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.7.2
github-actions[bot]b9f3f75cfcf1
diff --git a/plugins/omo/.codex-plugin/plugin.json b/plugins/omo/.codex-plugin/plugin.jsonindex 660b8467..f2d2e469 100644--- a/plugins/omo/.codex-plugin/plugin.json+++ b/plugins/omo/.codex-plugin/plugin.json@@ -7,8 +7,8 @@"email": "[email protected]","url": "https://github.com/code-yeongyu"},- "homepage": "https://github.com/code-yeongyu/omo",- "repository": "https://github.com/code-yeongyu/omo",+ "homepage": "https://github.com/sisyphuslabs/omo",+ "repository": "https://github.com/sisyphuslabs/omo","license": "MIT","keywords": ["codex", "codex-plugin", "omo", "hooks", "mcp", "skills"],"skills": "./skills/",@@ -17,13 +17,13 @@"interface": {"displayName": "OMO","shortDescription": "Unified local Codex components",- "longDescription": "OMO exposes the local Codex Rules, Comment Checker, LSP, Ultrawork, and Ultragoal components as one plugin namespace while keeping each component isolated under components/ for maintenance.",+ "longDescription": "OMO exposes the local Codex Rules, Comment Checker, LSP, Ultrawork, and ulw-loop components as one plugin namespace while keeping each component isolated under components/ for maintenance.","developerName": "Yeongyu Kim","category": "Developer Tools","capabilities": ["Hooks", "MCP Tools", "Code Intelligence", "Workflow", "Context Injection"],- "websiteURL": "https://github.com/code-yeongyu/omo",- "privacyPolicyURL": "https://github.com/code-yeongyu/omo#privacy",- "termsOfServiceURL": "https://github.com/code-yeongyu/omo#license",+ "websiteURL": "https://github.com/sisyphuslabs/omo",+ "privacyPolicyURL": "https://github.com/sisyphuslabs/omo#privacy",+ "termsOfServiceURL": "https://github.com/sisyphuslabs/omo#license","defaultPrompt": ["Use OMO LSP diagnostics on this workspace.","Show which OMO rules matched this file.",diff --git a/plugins/omo/.mcp.json b/plugins/omo/.mcp.jsonindex b36e4a79..45867b20 100644--- a/plugins/omo/.mcp.json+++ b/plugins/omo/.mcp.json@@ -1,8 +1,33 @@{"mcpServers": {+ "ast_grep": {+ "command": "node",+ "args": [+ "./components/ast-grep-mcp/dist/cli.js",+ "mcp"+ ],+ "cwd": "."+ },+ "grep_app": {+ "url": "https://mcp.grep.app"+ },+ "context7": {+ "url": "https://mcp.context7.com/mcp"+ },+ "git_bash": {+ "command": "node",+ "args": [+ "./components/git-bash-mcp/dist/cli.js",+ "mcp"+ ],+ "cwd": "."+ },"lsp": {"command": "node",- "args": ["./components/lsp/packages/lsp-tools-mcp/dist/cli.js", "mcp"],+ "args": [+ "./components/lsp-tools-mcp/dist/cli.js",+ "mcp"+ ],"cwd": "."}}diff --git a/plugins/omo/README.md b/plugins/omo/README.mdindex a5a9bdc7..f5144a26 100644--- a/plugins/omo/README.md+++ b/plugins/omo/README.md@@ -8,6 +8,6 @@ Internally each component remains isolated under `components/`:- `components/rules`- `components/lsp`- `components/ultrawork`-- `components/ultragoal`+- `components/ulw-loop`The root plugin manifest exports one Codex plugin named `omo`, with aggregate hooks, skills, and the LSP MCP server.diff --git a/plugins/omo/components/comment-checker/hooks/hooks.json b/plugins/omo/components/comment-checker/hooks/hooks.jsonindex 96fc9649..2f8db801 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": "checking comments"+ "statusMessage": "LazyCodex(0.1.1): Checking Comments"}]}diff --git a/plugins/omo/components/comment-checker/package.json b/plugins/omo/components/comment-checker/package.jsonindex 44f855e5..6fa96b41 100644--- a/plugins/omo/components/comment-checker/package.json+++ b/plugins/omo/components/comment-checker/package.json@@ -21,7 +21,7 @@"typescript"],"bin": {- "codex-comment-checker": "./dist/cli.js"+ "omo-comment-checker": "./dist/cli.js"},"files": ["dist",diff --git a/plugins/omo/components/comment-checker/src/cli.ts b/plugins/omo/components/comment-checker/src/cli.tsindex ca899182..bc16c1fb 100644--- a/plugins/omo/components/comment-checker/src/cli.ts+++ b/plugins/omo/components/comment-checker/src/cli.ts@@ -7,6 +7,6 @@ const [command, subcommand] = process.argv.slice(2);if (command === "hook" && subcommand === "post-tool-use") {await runCodexHookCli();} else {- process.stderr.write("Usage: codex-comment-checker hook post-tool-use\n");+ process.stderr.write("Usage: omo-comment-checker hook post-tool-use\n");process.exitCode = 2;}diff --git a/plugins/omo/components/comment-checker/src/codex-hook.ts b/plugins/omo/components/comment-checker/src/codex-hook.tsindex ae76cea5..ff1239ec 100644--- a/plugins/omo/components/comment-checker/src/codex-hook.ts+++ b/plugins/omo/components/comment-checker/src/codex-hook.ts@@ -1,3 +1,4 @@+import { readFileSync } from "node:fs";import { stdin as processStdin, stdout as processStdout } from "node:process";import {@@ -28,6 +29,18 @@ export type CodexHookOptions = {run?: CommentCheckerRunner;};+const DEFAULT_MAX_HOOK_FEEDBACK_CHARS = 8000;+const CONTEXT_PRESSURE_MAX_HOOK_FEEDBACK_CHARS = 1200;+const CONTEXT_PRESSURE_MARKERS = [+ "context compacted",+ "context_length_exceeded",+ "skill descriptions were shortened",+ "context_too_large",+ "codex ran out of room in the model's context window",+ "your input exceeds the context window",+ "long threads and multiple compactions",+] as const;+export function extractCodexCommentCheckRequests(input: CodexPostToolUseInput): CommentCheckRequest[] {return extractCommentCheckRequests(toToolResultLike(input));}@@ -51,7 +64,7 @@ export async function runCommentCheckerPostToolUse(const result = await runner(toHookInput(request, context));if (result.status === "missing" || result.status === "pass") continue;if (result.status === "error") continue;- const message = result.message.trim();+ const message = normalizeHookText(result.message);if (message.length > 0) {warnings.push({ filePath: request.filePath, message });}@@ -61,7 +74,7 @@ export async function runCommentCheckerPostToolUse(return JSON.stringify({decision: "block",- reason: formatWarnings(warnings),+ reason: limitHookText(formatWarnings(warnings), hookFeedbackLimit(input.transcript_path)),});}@@ -128,6 +141,39 @@ function formatWarnings(warnings: Array<{ filePath: string; message: string }>):.join("\n\n");}+function normalizeHookText(value: string): string {+ return value.replace(/\r\n/g, "\n").replace(/\r/g, "\n").trim();+}++function hookFeedbackLimit(transcriptPath: string | null): number {+ return isContextPressureTranscript(transcriptPath)+ ? CONTEXT_PRESSURE_MAX_HOOK_FEEDBACK_CHARS+ : DEFAULT_MAX_HOOK_FEEDBACK_CHARS;+}++function isContextPressureTranscript(transcriptPath: string | null): boolean {+ if (transcriptPath === null) return false;+ try {+ return hasContextPressureMarker(readFileSync(transcriptPath, "utf8"));+ } catch (error) {+ if (error instanceof Error) return false;+ throw error;+ }+}++function hasContextPressureMarker(text: string): boolean {+ const normalizedText = text.toLowerCase();+ return CONTEXT_PRESSURE_MARKERS.some((marker) => normalizedText.includes(marker));+}++function limitHookText(text: string, maxChars: number): string {+ if (text.length <= maxChars) return text;+ const marker = `\n\n[Truncated hook output to ${maxChars} chars to avoid Codex context overflow.]`;+ if (marker.length >= maxChars) return marker.slice(0, maxChars);+ const head = text.slice(0, maxChars - marker.length).replace(/[ \t\r\n]+$/, "");+ return `${head}${marker}`;+}+function isCodexPostToolUseInput(value: unknown): value is CodexPostToolUseInput {return (isRecord(value) &&diff --git a/plugins/omo/components/comment-checker/test/codex-hook-newline.test.ts b/plugins/omo/components/comment-checker/test/codex-hook-newline.test.tsnew file mode 100644index 00000000..b6dbfabf--- /dev/null+++ b/plugins/omo/components/comment-checker/test/codex-hook-newline.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest";++import { type CodexPostToolUseInput, runCommentCheckerPostToolUse } from "../src/codex-hook.ts";++function postToolUseInput(): CodexPostToolUseInput {+ return {+ session_id: "thread-1",+ turn_id: "turn-1",+ transcript_path: null,+ cwd: "/repo",+ hook_event_name: "PostToolUse",+ model: "gpt-5.5",+ permission_mode: "never",+ tool_name: "apply_patch",+ tool_input: {+ command: [+ "*** Begin Patch",+ "*** Update File: src/example.ts",+ "@@",+ "-const value = 1;",+ "+// explains value",+ "+const value = 2;",+ "*** End Patch",+ ].join("\n"),+ },+ tool_response: "Success. Updated files.",+ tool_use_id: "call-1",+ };+}++describe("comment-checker hook newline rendering", () => {+ it("#given checker warning with CRLF and bare CR #when hook runs #then returns normalized blocking feedback JSON", async () => {+ // given+ const output = await runCommentCheckerPostToolUse(postToolUseInput(), {+ run: async () => ({+ status: "warning",+ message: "\r\nfirst warning line\r\n indented detail\rthird warning line\r\n",+ }),+ });++ // when+ const parsed: unknown = JSON.parse(output);++ // then+ expect(parsed).toEqual({+ decision: "block",+ reason:+ "comment-checker found issues in src/example.ts:\nfirst warning line\n indented detail\nthird warning line",+ });+ expect(output).not.toContain("\r");+ });+});diff --git a/plugins/omo/components/comment-checker/test/codex-hook.test.ts b/plugins/omo/components/comment-checker/test/codex-hook.test.tsindex 7d12f7b3..83b74c3f 100644--- a/plugins/omo/components/comment-checker/test/codex-hook.test.ts+++ b/plugins/omo/components/comment-checker/test/codex-hook.test.ts@@ -1,6 +1,9 @@import { spawn } from "node:child_process";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";import { fileURLToPath } from "node:url";-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it } from "vitest";import {type CodexPostToolUseInput,@@ -15,6 +18,13 @@ type CliResult = {};const CLI_PATH = fileURLToPath(new URL("../dist/cli.js", import.meta.url));+const tempDirs: string[] = [];++afterEach(() => {+ for (const tempDir of tempDirs.splice(0)) {+ rmSync(tempDir, { recursive: true, force: true });+ }+});function runHookCli(input: string): Promise<CliResult> {return new Promise((resolve, reject) => {@@ -267,6 +277,34 @@ describe("runCommentCheckerPostToolUse", () => {expect(transcriptPath).toBe("");});++ it("#given Codex canonical context-window transcript and long checker warning #when hook blocks #then it caps feedback", async () => {+ const root = mkdtempSync(path.join(tmpdir(), "codex-comment-checker-context-pressure-"));+ tempDirs.push(root);+ const transcriptPath = path.join(root, "transcript.jsonl");+ writeFileSync(+ transcriptPath,+ [+ "context_length_exceeded",+ "Codex ran out of room in the model's context window. Start a new thread before retrying.",+ "",+ ].join("\n"),+ );++ const output = await runCommentCheckerPostToolUse(postToolUseInput({ transcript_path: transcriptPath }), {+ run: async () => ({+ status: "warning",+ message: `comment warning: explain less\n${"x".repeat(10_000)}`,+ }),+ });++ const parsed: unknown = JSON.parse(output);+ if (!isBlockingOutput(parsed)) throw new TypeError("Expected blocking output");++ expect(parsed.reason.length).toBeLessThanOrEqual(1200);+ expect(parsed.reason).toContain("comment-checker found issues in src/example.ts");+ expect(parsed.reason).toContain("[Truncated hook output");+ });});describe("runCodexHookCli", () => {@@ -315,3 +353,16 @@ describe("runCodexHookCli", () => {});});});++interface BlockingOutput {+ readonly decision: "block";+ readonly reason: string;+}++function isBlockingOutput(value: unknown): value is BlockingOutput {+ return isRecord(value) && value["decision"] === "block" && typeof value["reason"] === "string";+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/comment-checker/test/package-smoke.test.ts b/plugins/omo/components/comment-checker/test/package-smoke.test.tsindex 650cc580..668bae0f 100644--- a/plugins/omo/components/comment-checker/test/package-smoke.test.ts+++ b/plugins/omo/components/comment-checker/test/package-smoke.test.ts@@ -9,10 +9,6 @@ type PackageJson = {readonly optionalDependencies: Record<string, string>;};-type PluginJson = {- readonly hooks: string;-};-type HookCommand = {readonly command: string;};@@ -31,12 +27,6 @@ function readPackageJson(path: string): PackageJson {return parsed;}-function readPluginJson(path: string): PluginJson {- const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));- if (!isPluginJson(parsed)) throw new TypeError(`Invalid plugin metadata: ${path}`);- return parsed;-}-function readHooksJson(path: string): HooksJson {const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));if (!isHooksJson(parsed)) throw new TypeError(`Invalid hooks metadata: ${path}`);@@ -47,7 +37,6 @@ describe("plugin package metadata", () => {it("#given packaged plugin files #when validating entrypoints #then hook command uses portable plugin root interpolation", () => {// givenconst packageJson = readPackageJson("package.json");- const pluginJson = readPluginJson(".codex-plugin/plugin.json");const hooksJson = readHooksJson("hooks/hooks.json");const cliSource = readFileSync("src/cli.ts", "utf8");@@ -60,8 +49,7 @@ describe("plugin package metadata", () => {expect(packageJson.packageManager).toBe("[email protected]");expect(packageJson.dependencies ?? {}).not.toHaveProperty("@code-yeongyu/comment-checker");expect(packageJson.optionalDependencies).toHaveProperty("@code-yeongyu/comment-checker");- expect(packageJson.bin["codex-comment-checker"]).toBe("./dist/cli.js");- expect(pluginJson.hooks).toBe("./hooks/hooks.json");+ expect(packageJson.bin["omo-comment-checker"]).toBe("./dist/cli.js");expect(cliSource.startsWith("#!/usr/bin/env node")).toBe(true);expect(command).toBe(`node "${pluginRoot}/dist/cli.js" hook post-tool-use`);});@@ -79,10 +67,6 @@ function isPackageJson(value: unknown): value is PackageJson {);}-function isPluginJson(value: unknown): value is PluginJson {- return isRecord(value) && typeof value["hooks"] === "string";-}-function isHooksJson(value: unknown): value is HooksJson {if (!isRecord(value) || !isRecord(value["hooks"])) return false;return Object.values(value["hooks"]).every(isHookEntries);diff --git a/plugins/omo/components/git-bash/hooks/hooks.json b/plugins/omo/components/git-bash/hooks/hooks.jsonnew file mode 100644index 00000000..1224be0f--- /dev/null+++ b/plugins/omo/components/git-bash/hooks/hooks.json@@ -0,0 +1,29 @@+{+ "hooks": {+ "PreToolUse": [+ {+ "matcher": "^Bash$",+ "hooks": [+ {+ "type": "command",+ "command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use",+ "timeout": 5,+ "statusMessage": "LazyCodex(0.1.0): Recommending Git Bash Mcp"+ }+ ]+ }+ ],+ "PostCompact": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact",+ "timeout": 5,+ "statusMessage": "LazyCodex(0.1.0): Resetting Git Bash Mcp Reminder"+ }+ ]+ }+ ]+ }+}diff --git a/plugins/omo/components/git-bash/package.json b/plugins/omo/components/git-bash/package.jsonnew file mode 100644index 00000000..e154fa00--- /dev/null+++ b/plugins/omo/components/git-bash/package.json@@ -0,0 +1,23 @@+{+ "name": "@sisyphuslabs/codex-git-bash-hook",+ "version": "0.1.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"],+ "scripts": {+ "build": "tsc -p tsconfig.build.json",+ "test": "bun test test/*.test.ts",+ "typecheck": "tsc --noEmit"+ },+ "devDependencies": {+ "@types/node": "^25.7.0",+ "typescript": "^6.0.3"+ },+ "engines": {+ "node": ">=20.0.0"+ }+}diff --git a/plugins/omo/components/git-bash/src/cli.ts b/plugins/omo/components/git-bash/src/cli.tsnew file mode 100644index 00000000..4f26ceab--- /dev/null+++ b/plugins/omo/components/git-bash/src/cli.ts@@ -0,0 +1,33 @@+#!/usr/bin/env node+import { runGitBashHookCli } from "./codex-hook.js";++const TOP_LEVEL_HELP =+ "Usage:\n omo-git-bash-hook hook pre-tool-use\n omo-git-bash-hook hook post-compact\n omo-git-bash-hook help | --help | -h\n";++async function main(): Promise<number> {+ const argv = process.argv.slice(2);+ const command = argv[0];+ if (command === undefined || command === "help" || command === "--help" || command === "-h") {+ process.stdout.write(TOP_LEVEL_HELP);+ return 0;+ }+ if (command === "hook" && argv[1] === "pre-tool-use") {+ await runGitBashHookCli(process.stdin, process.stdout, "pre-tool-use");+ return 0;+ }+ if (command === "hook" && argv[1] === "post-compact") {+ await runGitBashHookCli(process.stdin, process.stdout, "post-compact");+ return 0;+ }+ process.stderr.write(`[omo-git-bash-hook] unknown command: ${argv.join(" ")}\n${TOP_LEVEL_HELP}`);+ return 1;+}++main()+ .then((code) => {+ process.exit(code);+ })+ .catch((error: unknown) => {+ process.stderr.write(`[omo-git-bash-hook] ${error instanceof Error ? error.message : String(error)}\n`);+ process.exit(1);+ });diff --git a/plugins/omo/components/git-bash/src/codex-hook.ts b/plugins/omo/components/git-bash/src/codex-hook.tsnew file mode 100644index 00000000..52deed2c--- /dev/null+++ b/plugins/omo/components/git-bash/src/codex-hook.ts@@ -0,0 +1,180 @@+import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";+import { homedir } from "node:os";+import { dirname, join } from "node:path";++export interface PreToolUsePayload {+ readonly cwd: string;+ readonly hook_event_name: "PreToolUse";+ readonly model: string;+ readonly permission_mode: string;+ readonly session_id: string;+ readonly tool_input: unknown;+ readonly tool_name: string;+ readonly tool_use_id: string;+ readonly transcript_path: string | null;+ readonly turn_id: string;+}++export interface GitBashHookOptions {+ readonly env?: NodeJS.ProcessEnv;+ readonly platform?: NodeJS.Platform | string;+ readonly pluginDataRoot?: string;+}++export interface PostCompactPayload {+ readonly hook_event_name: "PostCompact";+ readonly session_id: string;+ readonly transcript_path?: string | null;+ readonly trigger?: string;+}++interface PreToolUseHookOutput {+ readonly hookSpecificOutput: {+ readonly hookEventName: "PreToolUse";+ readonly additionalContext: string;+ };+}++const BASH_TOOL_NAME = "Bash";+const REMINDER =+ "On Windows, prefer the OMO git_bash MCP for shell commands before using built-in exec_command. Use exec_command only when git_bash is unavailable or for non-shell operations.";++export function parsePreToolUsePayload(raw: string): PreToolUsePayload | null {+ if (raw.trim().length === 0) return null;+ try {+ const parsed: unknown = JSON.parse(raw);+ return isPreToolUsePayload(parsed) ? parsed : null;+ } catch (error) {+ if (error instanceof SyntaxError) return null;+ return null;+ }+}++export function parsePostCompactPayload(raw: string): PostCompactPayload | null {+ if (raw.trim().length === 0) return null;+ try {+ const parsed: unknown = JSON.parse(raw);+ return isPostCompactPayload(parsed) ? parsed : null;+ } catch (error) {+ if (error instanceof SyntaxError) return null;+ return null;+ }+}++export function applyGitBashPreToolUseReminder(payload: PreToolUsePayload, options: GitBashHookOptions = {}): string {+ if (payload.hook_event_name !== "PreToolUse") return "";+ if (payload.tool_name !== BASH_TOOL_NAME) return "";+ if (!isWindowsHost(options)) return "";++ const markerPath = reminderMarkerPath(payload.session_id, options.pluginDataRoot);+ if (hasReminderMarker(markerPath)) return "";+ mkdirSync(dirname(markerPath), { recursive: true });+ writeFileSync(markerPath, `${new Date().toISOString()}\n`);++ const output: PreToolUseHookOutput = {+ hookSpecificOutput: {+ hookEventName: "PreToolUse",+ additionalContext: REMINDER,+ },+ };+ return `${JSON.stringify(output)}\n`;+}++export function applyGitBashPostCompactReset(payload: PostCompactPayload, options: GitBashHookOptions = {}): string {+ if (payload.hook_event_name !== "PostCompact") return "";+ rmSync(reminderMarkerPath(payload.session_id, options.pluginDataRoot), { force: true });+ return "";+}++export async function runGitBashHookCli(+ stdin: NodeJS.ReadableStream,+ stdout: NodeJS.WritableStream,+ eventName: "pre-tool-use" | "post-compact" = "pre-tool-use",+ options: GitBashHookOptions = {},+): Promise<void> {+ try {+ const raw = await readAll(stdin);+ const output =+ eventName === "post-compact" ? postCompactOutput(raw, options) : preToolUseOutput(raw, options);+ if (output.length > 0) stdout.write(output);+ } catch (error) {+ if (error instanceof Error) return;+ return;+ }+}++function preToolUseOutput(raw: string, options: GitBashHookOptions): string {+ const payload = parsePreToolUsePayload(raw);+ if (payload === null) return "";+ return applyGitBashPreToolUseReminder(payload, options);+}++function postCompactOutput(raw: string, options: GitBashHookOptions): string {+ const payload = parsePostCompactPayload(raw);+ if (payload === null) return "";+ return applyGitBashPostCompactReset(payload, options);+}++function isWindowsHost(options: GitBashHookOptions): boolean {+ const platform = options.platform ?? process.platform;+ if (platform === "win32") return true;+ const env = options.env ?? process.env;+ return env["OS"] === "Windows_NT" || env["ComSpec"] !== undefined || env["SystemRoot"] !== undefined;+}++function hasReminderMarker(path: string): boolean {+ return existsSync(path);+}++function reminderMarkerPath(sessionId: string, pluginDataRoot?: string): string {+ const root = pluginDataRoot ?? process.env["PLUGIN_DATA"] ?? join(homedir(), ".codex", "omo-git-bash");+ return join(root, "git-bash-reminder", `${safePathSegment(sessionId)}.seen`);+}++function safePathSegment(value: string): string {+ return value.replace(/[^A-Za-z0-9._-]/g, "_");+}++function isPreToolUsePayload(value: unknown): value is PreToolUsePayload {+ if (!isRecord(value)) return false;+ return (+ value["hook_event_name"] === "PreToolUse" &&+ typeof value["cwd"] === "string" &&+ typeof value["model"] === "string" &&+ typeof value["permission_mode"] === "string" &&+ typeof value["session_id"] === "string" &&+ typeof value["tool_name"] === "string" &&+ typeof value["tool_use_id"] === "string" &&+ (value["transcript_path"] === null || typeof value["transcript_path"] === "string") &&+ typeof value["turn_id"] === "string" &&+ Object.hasOwn(value, "tool_input")+ );+}++function isPostCompactPayload(value: unknown): value is PostCompactPayload {+ if (!isRecord(value)) return false;+ return (+ value["hook_event_name"] === "PostCompact" &&+ typeof value["session_id"] === "string" &&+ (value["transcript_path"] === undefined ||+ value["transcript_path"] === null ||+ typeof value["transcript_path"] === "string") &&+ (value["trigger"] === undefined || typeof value["trigger"] === "string")+ );+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function readAll(stdin: NodeJS.ReadableStream): Promise<string> {+ return new Promise((resolve, reject) => {+ let data = "";+ stdin.setEncoding("utf8");+ stdin.on("data", (chunk: unknown) => {+ data += chunk instanceof Buffer ? chunk.toString() : String(chunk);+ });+ stdin.once("error", reject);+ stdin.once("end", () => resolve(data));+ });+}diff --git a/plugins/omo/components/git-bash/src/index.ts b/plugins/omo/components/git-bash/src/index.tsnew file mode 100644index 00000000..f0801aa8--- /dev/null+++ b/plugins/omo/components/git-bash/src/index.ts@@ -0,0 +1,10 @@+export {+ applyGitBashPostCompactReset,+ applyGitBashPreToolUseReminder,+ parsePostCompactPayload,+ parsePreToolUsePayload,+ runGitBashHookCli,+ type GitBashHookOptions,+ type PostCompactPayload,+ type PreToolUsePayload,+} from "./codex-hook.js";diff --git a/plugins/omo/components/git-bash/test/codex-hook.test.ts b/plugins/omo/components/git-bash/test/codex-hook.test.tsnew file mode 100644index 00000000..97146e83--- /dev/null+++ b/plugins/omo/components/git-bash/test/codex-hook.test.ts@@ -0,0 +1,195 @@+import { afterEach, describe, expect, it } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Readable, Writable } from "node:stream";++import {+ applyGitBashPostCompactReset,+ applyGitBashPreToolUseReminder,+ runGitBashHookCli,+ type PostCompactPayload,+ type PreToolUsePayload,+} from "../src/codex-hook.js";++const temporaryDirectories: string[] = [];++function createTemporaryDirectory(prefix: string): string {+ const directory = mkdtempSync(join(tmpdir(), prefix));+ temporaryDirectories.push(directory);+ return directory;+}++afterEach(() => {+ for (const directory of temporaryDirectories.splice(0)) {+ rmSync(directory, { recursive: true, force: true });+ }+});++function preToolPayload(toolName: string, sessionId = "session-1"): PreToolUsePayload {+ return {+ cwd: "/repo",+ hook_event_name: "PreToolUse",+ model: "gpt-5.5",+ permission_mode: "default",+ session_id: sessionId,+ tool_input: { command: "pwd" },+ tool_name: toolName,+ tool_use_id: "call-1",+ transcript_path: null,+ turn_id: "turn-1",+ };+}++function postCompactPayload(sessionId = "session-1"): PostCompactPayload {+ return {+ hook_event_name: "PostCompact",+ session_id: sessionId,+ transcript_path: null,+ trigger: "manual",+ };+}++function windowsEnv(): NodeJS.ProcessEnv {+ return { OS: "Windows_NT", ComSpec: "C:\\Windows\\System32\\cmd.exe" };+}++function captureStdout(): { readonly stdout: Writable; readonly read: () => string } {+ let captured = "";+ const stdout = new Writable({+ write(chunk: unknown, _encoding: BufferEncoding, callback: (error?: Error | null) => void): void {+ captured += chunk instanceof Buffer ? chunk.toString() : String(chunk);+ callback();+ },+ });+ return { stdout, read: () => captured };+}++describe("applyGitBashPreToolUseReminder", () => {+ it("#given first Windows Bash call #when hook runs #then emits non-blocking git_bash guidance", () => {+ // given+ const pluginDataRoot = createTemporaryDirectory("omo-git-bash-hook-");++ // when+ const output = applyGitBashPreToolUseReminder(preToolPayload("Bash"), {+ env: windowsEnv(),+ platform: "linux",+ pluginDataRoot,+ });++ // then+ const parsed = JSON.parse(output);+ expect(parsed.hookSpecificOutput).toEqual({+ hookEventName: "PreToolUse",+ additionalContext:+ "On Windows, prefer the OMO git_bash MCP for shell commands before using built-in exec_command. Use exec_command only when git_bash is unavailable or for non-shell operations.",+ });+ });++ it("#given second Windows Bash call in same session #when hook runs #then it stays silent", () => {+ // given+ const pluginDataRoot = createTemporaryDirectory("omo-git-bash-hook-");+ const payload = preToolPayload("Bash");++ // when+ const first = applyGitBashPreToolUseReminder(payload, { env: windowsEnv(), platform: "linux", pluginDataRoot });+ const second = applyGitBashPreToolUseReminder(payload, { env: windowsEnv(), platform: "linux", pluginDataRoot });++ // then+ expect(first).toContain("git_bash");+ expect(second).toBe("");+ });++ it("#given non-Windows Bash call #when hook runs #then it stays silent", () => {+ // given+ const pluginDataRoot = createTemporaryDirectory("omo-git-bash-hook-");++ // when+ const output = applyGitBashPreToolUseReminder(preToolPayload("Bash"), {+ env: {},+ platform: "darwin",+ pluginDataRoot,+ });++ // then+ expect(output).toBe("");+ });++ it("#given non-Bash tool call #when hook runs #then it stays silent", () => {+ // given+ const pluginDataRoot = createTemporaryDirectory("omo-git-bash-hook-");++ // when+ const output = applyGitBashPreToolUseReminder(preToolPayload("exec_command"), {+ env: windowsEnv(),+ platform: "linux",+ pluginDataRoot,+ });++ // then+ expect(output).toBe("");+ });+});++describe("applyGitBashPostCompactReset", () => {+ it("#given reminder already emitted #when PostCompact runs #then next Windows Bash call emits reminder again", () => {+ // given+ const pluginDataRoot = createTemporaryDirectory("omo-git-bash-hook-");+ const payload = preToolPayload("Bash");+ const first = applyGitBashPreToolUseReminder(payload, { env: windowsEnv(), platform: "linux", pluginDataRoot });+ const second = applyGitBashPreToolUseReminder(payload, { env: windowsEnv(), platform: "linux", pluginDataRoot });++ // when+ applyGitBashPostCompactReset(postCompactPayload(), { pluginDataRoot });+ const afterCompact = applyGitBashPreToolUseReminder(payload, {+ env: windowsEnv(),+ platform: "linux",+ pluginDataRoot,+ });++ // then+ expect(first).toContain("git_bash");+ expect(second).toBe("");+ expect(afterCompact).toContain("git_bash");+ });+});++describe("runGitBashHookCli", () => {+ it("#given Codex PreToolUse stdin on Windows #when CLI hook runs #then it writes reminder JSON", async () => {+ // given+ const pluginDataRoot = createTemporaryDirectory("omo-git-bash-hook-");+ const stdin = Readable.from([JSON.stringify(preToolPayload("Bash"))]);+ const capture = captureStdout();++ // when+ await runGitBashHookCli(stdin, capture.stdout, "pre-tool-use", {+ env: windowsEnv(),+ platform: "linux",+ pluginDataRoot,+ });++ // then+ expect(capture.read()).toContain("git_bash MCP");+ });++ it("#given PostCompact stdin #when CLI hook runs #then it resets the one-shot reminder", async () => {+ // given+ const pluginDataRoot = createTemporaryDirectory("omo-git-bash-hook-");+ const payload = preToolPayload("Bash");+ applyGitBashPreToolUseReminder(payload, { env: windowsEnv(), platform: "linux", pluginDataRoot });+ const resetStdin = Readable.from([JSON.stringify(postCompactPayload())]);+ const capture = captureStdout();++ // when+ await runGitBashHookCli(resetStdin, capture.stdout, "post-compact", { pluginDataRoot });+ const afterCompact = applyGitBashPreToolUseReminder(payload, {+ env: windowsEnv(),+ platform: "linux",+ pluginDataRoot,+ });++ // then+ expect(capture.read()).toBe("");+ expect(afterCompact).toContain("git_bash");+ });+});diff --git a/plugins/omo/components/git-bash/tsconfig.build.json b/plugins/omo/components/git-bash/tsconfig.build.jsonnew file mode 100644index 00000000..d428d2a0--- /dev/null+++ b/plugins/omo/components/git-bash/tsconfig.build.json@@ -0,0 +1,13 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "allowImportingTsExtensions": false,+ "declaration": true,+ "outDir": "dist",+ "rootDir": "src",+ "noEmit": false,+ "types": ["node"]+ },+ "include": ["src/**/*"],+ "exclude": ["test/**/*"]+}diff --git a/plugins/omo/components/git-bash/tsconfig.json b/plugins/omo/components/git-bash/tsconfig.jsonnew file mode 100644index 00000000..3c017b67--- /dev/null+++ b/plugins/omo/components/git-bash/tsconfig.json@@ -0,0 +1,25 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "Node16",+ "moduleResolution": "Node16",+ "lib": ["ES2022"],+ "strict": true,+ "exactOptionalPropertyTypes": true,+ "noUncheckedIndexedAccess": true,+ "noPropertyAccessFromIndexSignature": true,+ "verbatimModuleSyntax": true,+ "noImplicitOverride": true,+ "noImplicitReturns": true,+ "noFallthroughCasesInSwitch": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "esModuleInterop": true,+ "allowImportingTsExtensions": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "types": ["node", "bun-types"],+ "noEmit": true+ },+ "include": ["src/**/*", "test/**/*"]+}diff --git a/plugins/omo/components/lsp/.gitmodules b/plugins/omo/components/lsp/.gitmodulesdeleted file mode 100644index f172b519..00000000--- a/plugins/omo/components/lsp/.gitmodules+++ /dev/null@@ -1,4 +0,0 @@-[submodule "packages/lsp-tools-mcp"]- path = packages/lsp-tools-mcp- url = https://github.com/code-yeongyu/lsp-tools-mcp.git- branch = maindiff --git a/plugins/omo/components/lsp/.mcp.json b/plugins/omo/components/lsp/.mcp.jsonindex 13ff674d..46ecc491 100644--- a/plugins/omo/components/lsp/.mcp.json+++ b/plugins/omo/components/lsp/.mcp.json@@ -2,7 +2,7 @@"mcpServers": {"lsp": {"command": "node",- "args": ["./packages/lsp-tools-mcp/dist/cli.js", "mcp"],+ "args": ["../../../../lsp-tools-mcp/dist/cli.js", "mcp"],"cwd": "."}}diff --git a/plugins/omo/components/lsp/CHANGELOG.md b/plugins/omo/components/lsp/CHANGELOG.mdindex 5853ed1f..31941445 100644--- a/plugins/omo/components/lsp/CHANGELOG.md+++ b/plugins/omo/components/lsp/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Reuse the repository-level `packages/lsp-tools-mcp` package instead of carrying a second copy under `components/lsp/packages`.+## 0.2.0- Extracted the LSP runtime and MCP server into [`@code-yeongyu/lsp-tools-mcp`](https://github.com/code-yeongyu/lsp-tools-mcp).diff --git a/plugins/omo/components/lsp/README.md b/plugins/omo/components/lsp/README.mdindex 237e8f4f..a0ca81cd 100644--- a/plugins/omo/components/lsp/README.md+++ b/plugins/omo/components/lsp/README.md@@ -6,7 +6,7 @@ Codex plugin that ports the standalone LSP runtime from [`pi-lsp-client`](https:## Architecture-The LSP runtime moved to [`lsp-tools-mcp`](https://github.com/code-yeongyu/lsp-tools-mcp) and is consumed here as a git submodule at `packages/lsp-tools-mcp/`.+The LSP runtime moved to [`lsp-tools-mcp`](https://github.com/code-yeongyu/lsp-tools-mcp) and is consumed from this repository's root `packages/lsp-tools-mcp/` package.- `codex-lsp` keeps Codex-specific integration (`hook post-tool-use`, plugin metadata, package wiring).- `lsp-tools-mcp` owns MCP runtime, LSP manager, and tool implementations.@@ -75,7 +75,7 @@ The plugin ships:- `hooks/hooks.json` for the `PostToolUse` diagnostics hook.- `skills/lsp/SKILL.md` with MCP usage guidance.-The runtime depends on `@code-yeongyu/lsp-tools-mcp` via `file:./packages/lsp-tools-mcp`, so marketplace builds must include submodule contents.+The runtime depends on `@code-yeongyu/lsp-tools-mcp` via `file:../../../../lsp-tools-mcp`, so marketplace builds reuse the root package instead of carrying a second copy under this component.The hook command is:@@ -86,14 +86,13 @@ node "${PLUGIN_ROOT}/dist/cli.js" hook post-tool-useThe MCP command is:```bash-node ./packages/lsp-tools-mcp/dist/cli.js mcp+node ../../../../lsp-tools-mcp/dist/cli.js mcp```## Local Development```bash-git submodule update --init --recursive-npm run bootstrap # installs + builds the lsp-tools-mcp submodule+npm run bootstrap # installs + builds the root packages/lsp-tools-mcp packagenpm installnpm testnpm run typecheck@@ -101,7 +100,7 @@ npm run checknpm pack --dry-run```-The `bootstrap` script installs and builds the `lsp-tools-mcp` git submodule so+The `bootstrap` script installs and builds the root `lsp-tools-mcp` package so`@code-yeongyu/lsp-tools-mcp/dist/*.js` is available for the codex-lsp build.Smoke-test the hook:diff --git a/plugins/omo/components/lsp/hooks/hooks.json b/plugins/omo/components/lsp/hooks/hooks.jsonindex afdfe34a..674c1223 100644--- a/plugins/omo/components/lsp/hooks/hooks.json+++ b/plugins/omo/components/lsp/hooks/hooks.json@@ -8,7 +8,20 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use","timeout": 60,- "statusMessage": "checking LSP diagnostics"+ "statusMessage": "LazyCodex(0.2.0): Checking LSP Diagnostics"+ }+ ]+ }+ ],+ "PostCompact": [+ {+ "matcher": "manual|auto",+ "hooks": [+ {+ "type": "command",+ "command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact",+ "timeout": 5,+ "statusMessage": "LazyCodex(0.2.0): Resetting LSP Diagnostics Cache"}]}diff --git a/plugins/omo/components/lsp/package.json b/plugins/omo/components/lsp/package.jsonindex 3a45e161..b6a9af59 100644--- a/plugins/omo/components/lsp/package.json+++ b/plugins/omo/components/lsp/package.json@@ -22,7 +22,7 @@"diagnostics"],"bin": {- "codex-lsp": "./dist/cli.js"+ "omo-lsp": "./dist/cli.js"},"files": ["dist",@@ -36,21 +36,21 @@"CHANGELOG.md"],"scripts": {- "bootstrap": "node scripts/bootstrap-submodule.mjs",- "prebuild": "node scripts/bootstrap-submodule.mjs",- "build": "tsc -p tsconfig.build.json",- "pretest": "node scripts/bootstrap-submodule.mjs",- "test": "vitest --run",+ "bootstrap": "node scripts/build-lsp-tools.mjs",+ "prebuild": "node scripts/build-lsp-tools.mjs",+ "build": "node scripts/clean-dist.mjs && tsc -p tsconfig.build.json",+ "pretest": "node scripts/build-lsp-tools.mjs",+ "test": "node scripts/test.mjs","test:watch": "vitest",- "pretypecheck": "node scripts/bootstrap-submodule.mjs",+ "pretypecheck": "node scripts/build-lsp-tools.mjs","typecheck": "tsc --noEmit","lint": "biome check src test","lint:fix": "biome check --write src test",- "precheck": "node scripts/bootstrap-submodule.mjs",+ "precheck": "node scripts/build-lsp-tools.mjs","check": "tsc --noEmit && biome check src test && tsc -p tsconfig.build.json"},"dependencies": {- "@code-yeongyu/lsp-tools-mcp": "file:./packages/lsp-tools-mcp"+ "@code-yeongyu/lsp-tools-mcp": "file:../../../../lsp-tools-mcp"},"devDependencies": {"@biomejs/biome": "2.4.15",diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/CODEOWNERS b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/CODEOWNERSdeleted file mode 100644index e2330ddf..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/CODEOWNERS+++ /dev/null@@ -1 +0,0 @@-* @code-yeongyudiff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/ISSUE_TEMPLATE/bug.yml b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/ISSUE_TEMPLATE/bug.ymldeleted file mode 100644index 206a5f9d..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/ISSUE_TEMPLATE/bug.yml+++ /dev/null@@ -1,26 +0,0 @@-name: Bug report-description: Report a reproducible lsp-tools-mcp bug.-title: "[bug]: "-labels: ["bug"]-body:- - type: textarea- id: summary- attributes:- label: Summary- description: What happened?- validations:- required: true- - type: textarea- id: reproduction- attributes:- label: Reproduction- description: Exact steps, config, command output, and affected MCP tool or language server.- validations:- required: true- - type: input- id: version- attributes:- label: Version- placeholder: 0.1.0- validations:- required: truediff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/ISSUE_TEMPLATE/feature.yml b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/ISSUE_TEMPLATE/feature.ymldeleted file mode 100644index 4f0042f6..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/ISSUE_TEMPLATE/feature.yml+++ /dev/null@@ -1,19 +0,0 @@-name: Feature request-description: Propose a focused lsp-tools-mcp improvement.-title: "[feature]: "-labels: ["enhancement"]-body:- - type: textarea- id: problem- attributes:- label: Problem- description: What workflow should improve?- validations:- required: true- - type: textarea- id: proposal- attributes:- label: Proposal- description: What should lsp-tools-mcp do?- validations:- required: truediff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/branch-ruleset.json b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/branch-ruleset.jsondeleted file mode 100644index 1f482bb6..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/branch-ruleset.json+++ /dev/null@@ -1,45 +0,0 @@-{- "name": "main protection",- "target": "branch",- "enforcement": "active",- "conditions": {- "ref_name": {- "include": ["~DEFAULT_BRANCH"],- "exclude": []- }- },- "rules": [- { "type": "deletion" },- { "type": "non_fast_forward" },- { "type": "required_linear_history" },- {- "type": "pull_request",- "parameters": {- "required_approving_review_count": 1,- "dismiss_stale_reviews_on_push": true,- "require_code_owner_review": true,- "require_last_push_approval": false,- "required_review_thread_resolution": true- }- },- {- "type": "required_status_checks",- "parameters": {- "strict_required_status_checks_policy": true,- "required_status_checks": [- { "context": "test (ubuntu-latest · node 20)" },- { "context": "test (ubuntu-latest · node 22)" },- { "context": "test (macos-latest · node 20)" },- { "context": "test (macos-latest · node 22)" }- ]- }- }- ],- "bypass_actors": [- {- "actor_id": 5,- "actor_type": "RepositoryRole",- "bypass_mode": "always"- }- ]-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/dependabot.yml b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/dependabot.ymldeleted file mode 100644index be719fac..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/dependabot.yml+++ /dev/null@@ -1,11 +0,0 @@-version: 2-updates:- - package-ecosystem: npm- directory: /- schedule:- interval: weekly- open-pull-requests-limit: 5- - package-ecosystem: github-actions- directory: /- schedule:- interval: weeklydiff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/pull_request_template.md b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/pull_request_template.mddeleted file mode 100644index 39f36ad4..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/pull_request_template.md+++ /dev/null@@ -1,11 +0,0 @@-## Summary-----## Validation-----## Notes---diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/workflows/ci.yml b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/workflows/ci.ymldeleted file mode 100644index 6cc7a165..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/workflows/ci.yml+++ /dev/null@@ -1,47 +0,0 @@-name: ci--on:- push:- branches: [main]- pull_request:- branches: [main]- workflow_dispatch:--concurrency:- group: ${{ github.workflow }}-${{ github.ref }}- cancel-in-progress: true--permissions:- contents: read--jobs:- test:- name: test (${{ matrix.os }} · node ${{ matrix.node }})- runs-on: ${{ matrix.os }}- timeout-minutes: 15- strategy:- fail-fast: false- matrix:- os: [ubuntu-latest, macos-latest, windows-latest]- node: ["20", "22"]- steps:- - name: Checkout- uses: actions/checkout@v6-- - name: Setup Node ${{ matrix.node }}- uses: actions/setup-node@v6- with:- node-version: ${{ matrix.node }}- cache: npm-- - name: Install dependencies- run: npm ci-- - name: Check- run: npm run check-- - name: Unit tests- run: npm test-- - name: Package smoke- run: npm pack --dry-rundiff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/workflows/publish.yml b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/workflows/publish.ymldeleted file mode 100644index 4214a99b..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/workflows/publish.yml+++ /dev/null@@ -1,51 +0,0 @@-name: publish--on:- release:- types: [published]- workflow_dispatch:--concurrency:- group: ${{ github.workflow }}-${{ github.ref }}- cancel-in-progress: false--permissions:- contents: read- id-token: write--jobs:- publish:- runs-on: ubuntu-latest- timeout-minutes: 15- steps:- - name: Checkout- uses: actions/checkout@v6-- - name: Setup Node 22- uses: actions/setup-node@v6- with:- node-version: "22"- registry-url: https://registry.npmjs.org- cache: npm-- - name: Install dependencies- run: npm ci-- - name: Check- run: npm run check-- - name: Unit tests- run: npm test-- - name: Package smoke- run: npm pack --dry-run-- - name: Publish to npm- run: |- if [ -z "$NODE_AUTH_TOKEN" ]; then- echo "NODE_AUTH_TOKEN is not configured; skipping npm publish."- exit 0- fi- npm publish --access public --provenance- env:- NODE_AUTH_TOKEN: ${{ secrets.NODE_AUTH_TOKEN }}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.gitignore b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.gitignoredeleted file mode 100644index 1bf09f16..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.gitignore+++ /dev/null@@ -1,6 +0,0 @@-node_modules/-*.log-.env-.DS_Store-coverage/-.vitest/diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/CHANGELOG.md b/plugins/omo/components/lsp/packages/lsp-tools-mcp/CHANGELOG.mddeleted file mode 100644index 4bff36af..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/CHANGELOG.md+++ /dev/null@@ -1,20 +0,0 @@-# Changelog--All notable changes to this project are documented in this file.--## [0.1.0] - 2026-05-18--### Added--- Initial standalone extraction from `codex-lsp`:- - LSP runtime (`src/lsp/*`)- - MCP server (`src/mcp.ts`)- - Tool definitions (`src/tools.ts`)- - Standalone CLI (`src/cli.ts`, `mcp` subcommand only)-- Config path override support:- - `LSP_TOOLS_MCP_PROJECT_CONFIG`- - `LSP_TOOLS_MCP_USER_CONFIG`-- Full test suite import (excluding Codex-specific hook tests)-- CI workflow matrix (ubuntu/macos/windows x node 20/22)-- Release-triggered npm publish workflow-- Repository governance files (ruleset, CODEOWNERS, dependabot, issue templates, PR template)diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/NOTICE b/plugins/omo/components/lsp/packages/lsp-tools-mcp/NOTICEdeleted file mode 100644index a3adc175..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/NOTICE+++ /dev/null@@ -1,3 +0,0 @@-lsp-tools-mcp extracts the standalone LSP runtime from codex-lsp into a reusable package.--The package includes adapted code originally developed for pi-lsp-client.diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/README.md b/plugins/omo/components/lsp/packages/lsp-tools-mcp/README.mddeleted file mode 100644index 906b7c61..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/README.md+++ /dev/null@@ -1,102 +0,0 @@-# lsp-tools-mcp--[](https://github.com/code-yeongyu/lsp-tools-mcp/actions/workflows/ci.yml) [](LICENSE)--Standalone Language Server Protocol tools exposed as a stdio MCP server.--## Used By--This repository is the upstream source of truth for two downstream plugins. Both consume it as a git submodule:--| Project | Path | Role |-|---------|------|------|-| **[codex-lsp](https://github.com/code-yeongyu/codex-lsp)** | `packages/lsp-tools-mcp/` | Codex plugin that ships these LSP MCP tools plus a Codex-specific PostToolUse diagnostics hook. |-| **[oh-my-openagent](https://github.com/code-yeongyu/oh-my-openagent)** (a.k.a. `oh-my-opencode`) | `vendor/lsp-tools-mcp/` | OpenCode plugin that registers this server as a built-in Tier-1 stdio MCP. Exposes `lsp_diagnostics`, `lsp_goto_definition`, `lsp_find_references`, `lsp_symbols`, `lsp_prepare_rename`, `lsp_rename`, and `lsp_status` to all agents. |--If you fix or extend the LSP runtime here, both downstreams pick up the change by bumping the submodule pointer. Do not fork the runtime into a downstream; land changes here instead.--## Quick Start--```bash-npm install-npm run check-npm test-npm run build-printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | node dist/cli.js mcp-```--## MCP Tools--This server exposes the following tools:--- `lsp.status`-- `lsp.diagnostics`-- `lsp.goto_definition`-- `lsp.find_references`-- `lsp.symbols`-- `lsp.prepare_rename`-- `lsp.rename`--Tool aliases are also available for compatibility:--- `lsp_status`-- `lsp_diagnostics`-- `lsp_goto_definition`-- `lsp_find_references`-- `lsp_symbols`-- `lsp_prepare_rename`-- `lsp_rename`--When an MCP host registers this server under the name `lsp` (the default in both downstreams), the tools are exposed to agents as `lsp_status`, `lsp_diagnostics`, and so on, matching the alias names above.--## Configuration--Default config paths (matches codex-lsp's historical layout):--- Project: `.codex/lsp-client.json`-- User: `~/.codex/lsp-client.json`--Path overrides via environment variables:--- `LSP_TOOLS_MCP_PROJECT_CONFIG`-- `LSP_TOOLS_MCP_USER_CONFIG`--Examples (oh-my-openagent points the project config at `.opencode/lsp.json` via the env var):--```bash-LSP_TOOLS_MCP_PROJECT_CONFIG=.opencode/lsp.json node dist/cli.js mcp-LSP_TOOLS_MCP_USER_CONFIG=.opencode/lsp.json node dist/cli.js mcp-```--Example config file:--```json-{- "lsp": {- "typescript": {- "command": ["typescript-language-server", "--stdio"],- "extensions": [".ts", ".tsx", ".js", ".jsx"]- }- }-}-```--## Architecture--- `src/lsp/*` standalone LSP runtime (process management, JSON-RPC transport, configuration, diagnostics, workspace edits)-- `src/tools.ts` MCP tool definitions and handlers-- `src/mcp.ts` stdio MCP server entry and registration-- `src/cli.ts` standalone CLI entry (`mcp` subcommand only)--## Local Development--```bash-npm install-npm run check-npm test-npm pack --dry-run-```--## License--[MIT](LICENSE)diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/cli.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/cli.tsdeleted file mode 100644index c0dc203d..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/cli.ts+++ /dev/null@@ -1,34 +0,0 @@-#!/usr/bin/env node-import { argv, stderr } from "node:process";--import { disposeDefaultLspManager } from "./lsp/manager.js";-import { runMcpStdioServer } from "./mcp.js";-import { writeMcpLifecycleLog } from "./mcp-lifecycle-log.js";--async function main(): Promise<void> {- const [command = "mcp"] = argv.slice(2);-- try {- if (command === "mcp") {- await runMcpStdioServer(process.stdin, process.stdout, {- log: writeMcpLifecycleLog,- onIdleTimeout: async () => {- await disposeDefaultLspManager();- process.exit(0);- },- });- return;- }-- stderr.write("Usage: lsp-tools-mcp [mcp]\n");- process.exitCode = 2;- } finally {- await disposeDefaultLspManager();- }-}--main().catch(async (error: unknown) => {- stderr.write(`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);- await disposeDefaultLspManager();- process.exitCode = 1;-});diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/cleanup-errors.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/cleanup-errors.tsdeleted file mode 100644index 30e7018b..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/cleanup-errors.ts+++ /dev/null@@ -1,5 +0,0 @@-export function reportBestEffortCleanupError(operation: string, error: unknown): void {- if (process.env["CODEX_LSP_DEBUG_CLEANUP"] !== "1") return;- const message = error instanceof Error ? error.message : String(error);- console.error(`[codex-lsp] ignored ${operation} failure during cleanup: ${message}`);-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/client-wrapper.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/client-wrapper.tsdeleted file mode 100644index 9e9d4bc8..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/client-wrapper.ts+++ /dev/null@@ -1,146 +0,0 @@-import { existsSync, statSync } from "node:fs";-import { dirname, extname, join, resolve } from "node:path";--import type { LspClient } from "./client.js";-import {- isLspDeadConnectionError,- LspInvalidPathError,- LspRequestTimeoutError,- LspServerInitializingError,- LspServerLookupError,-} from "./errors.js";-import { getLspManager, type LspManager } from "./manager.js";-import { findServerForExtension } from "./server-resolution.js";-import type { ServerLookupResult } from "./types.js";--const WORKSPACE_MARKERS = [".git", "package.json", "pyproject.toml", "Cargo.toml", "go.mod", "pom.xml", "build.gradle"];--export function isDirectoryPath(filePath: string): boolean {- try {- return statSync(filePath).isDirectory();- } catch {- return false;- }-}--export function findWorkspaceRoot(filePath: string): string {- const abs = resolve(filePath);- let dir = abs;-- if (!isDirectoryPath(dir)) {- dir = dirname(dir);- }-- let prevDir = "";- while (dir !== prevDir) {- for (const marker of WORKSPACE_MARKERS) {- if (existsSync(join(dir, marker))) {- return dir;- }- }- prevDir = dir;- dir = dirname(dir);- }-- return dirname(abs);-}--export function formatServerLookupError(result: Exclude<ServerLookupResult, { status: "found" }>): string {- if (result.status === "not_installed") {- const { server, installHint } = result;- return [- `LSP server '${server.id}' is configured but NOT INSTALLED.`,- "",- `Command not found: ${server.command[0]}`,- "",- "To install:",- ` ${installHint}`,- "",- `Supported extensions: ${server.extensions.join(", ")}`,- "",- "After installation, the server will be available automatically.",- ].join("\n");- }-- return [- `No LSP server configured for extension: ${result.extension}`,- "",- `Available servers: ${result.availableServers.slice(0, 10).join(", ")}${- result.availableServers.length > 10 ? "..." : ""- }`,- "",- "Configure a custom server in '.codex/lsp-client.json':",- " {",- ' "lsp": {',- ' "my-server": {',- ' "command": ["my-lsp", "--stdio"],',- ` "extensions": ["${result.extension}"]`,- " }",- " }",- " }",- ].join("\n");-}--export interface WithLspClientOptions {- signal?: AbortSignal;- manager?: LspManager;-}--const READ_ONLY_RETRY_TOOLS = new Set([- "diagnostics",- "definition",- "references",- "documentSymbols",- "workspaceSymbols",- "prepareRename",-]);--export async function withLspClient<T>(- filePath: string,- fn: (client: LspClient) => Promise<T>,- toolName: string,- options: WithLspClientOptions = {},-): Promise<T> {- const absPath = resolve(filePath);-- if (isDirectoryPath(absPath)) {- throw new LspInvalidPathError(- "Directory paths are not supported by this LSP tool. " +- "Use lsp.diagnostics with a directory path for directory diagnostics.",- );- }-- const ext = extname(absPath);- const result = findServerForExtension(ext);- if (result.status !== "found") {- throw new LspServerLookupError(formatServerLookupError(result));- }-- const server = result.server;- const root = findWorkspaceRoot(absPath);- const manager = options.manager ?? getLspManager();-- const acquireAndCall = async (allowRetry: boolean): Promise<T> => {- const client = await manager.getClient(root, server, options.signal);-- try {- return await fn(client);- } catch (err) {- if (allowRetry && READ_ONLY_RETRY_TOOLS.has(toolName) && isLspDeadConnectionError(err)) {- manager.invalidateClient(root, server.id, client);- return acquireAndCall(false);- }-- if (err instanceof LspRequestTimeoutError) {- if (manager.isServerInitializing(root, server.id)) {- throw new LspServerInitializingError(err);- }- }- throw err;- } finally {- manager.releaseClient(root, server.id);- }- };-- return acquireAndCall(true);-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/client.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/client.tsdeleted file mode 100644index 45dcf86f..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/client.ts+++ /dev/null@@ -1,170 +0,0 @@-import { readFileSync } from "node:fs";-import { extname, resolve } from "node:path";-import { pathToFileURL } from "node:url";--import { LspClientConnection } from "./connection.js";-import { getLanguageId } from "./language-mappings.js";-import type {- Diagnostic,- DocumentSymbol,- Location,- LocationLink,- PrepareRenameDefaultBehavior,- PrepareRenameResult,- Range,- SymbolInfo,- WorkspaceEdit,-} from "./types.js";--const POST_OPEN_DELAY_MS = 1000;-const POST_DIAGNOSTICS_WAIT_MS = 500;--export class LspClient extends LspClientConnection {- private readonly openedFiles = new Set<string>();- private readonly documentVersions = new Map<string, number>();- private readonly lastSyncedText = new Map<string, string>();- private readonly diagnosticPullErrors: Error[] = [];-- getDiagnosticPullErrors(): readonly Error[] {- return this.diagnosticPullErrors;- }-- async openFile(filePath: string): Promise<void> {- const absPath = resolve(filePath);- const uri = pathToFileURL(absPath).href;- const text = readFileSync(absPath, "utf-8");-- if (!this.openedFiles.has(absPath)) {- const ext = extname(absPath);- const languageId = getLanguageId(ext);- const version = 1;-- await this.sendNotification("textDocument/didOpen", {- textDocument: {- uri,- languageId,- version,- text,- },- });-- this.openedFiles.add(absPath);- this.documentVersions.set(uri, version);- this.lastSyncedText.set(uri, text);- await new Promise((r) => setTimeout(r, POST_OPEN_DELAY_MS));- return;- }-- const prevText = this.lastSyncedText.get(uri);- if (prevText === text) {- return;- }-- const nextVersion = (this.documentVersions.get(uri) ?? 1) + 1;- this.documentVersions.set(uri, nextVersion);- this.lastSyncedText.set(uri, text);-- await this.sendNotification("textDocument/didChange", {- textDocument: { uri, version: nextVersion },- contentChanges: [{ text }],- });-- await this.sendNotification("textDocument/didSave", {- textDocument: { uri },- text,- });- }-- async definition(- filePath: string,- line: number,- character: number,- ): Promise<Location | LocationLink | Array<Location | LocationLink> | null> {- const absPath = resolve(filePath);- await this.openFile(absPath);- return this.sendRequest<Location | LocationLink | Array<Location | LocationLink> | null>(- "textDocument/definition",- {- textDocument: { uri: pathToFileURL(absPath).href },- position: { line: line - 1, character },- },- );- }-- async references(filePath: string, line: number, character: number, includeDeclaration = true): Promise<Location[]> {- const absPath = resolve(filePath);- await this.openFile(absPath);- return this.sendRequest<Location[]>("textDocument/references", {- textDocument: { uri: pathToFileURL(absPath).href },- position: { line: line - 1, character },- context: { includeDeclaration },- });- }-- async documentSymbols(filePath: string): Promise<Array<DocumentSymbol | SymbolInfo>> {- const absPath = resolve(filePath);- await this.openFile(absPath);- return this.sendRequest<Array<DocumentSymbol | SymbolInfo>>("textDocument/documentSymbol", {- textDocument: { uri: pathToFileURL(absPath).href },- });- }-- async workspaceSymbols(query: string): Promise<SymbolInfo[]> {- return this.sendRequest<SymbolInfo[]>("workspace/symbol", { query });- }-- private isUnsupportedDiagnosticPullError(error: unknown): boolean {- if (!(error instanceof Error)) return false;- const code = "code" in error && typeof error.code === "number" ? error.code : undefined;- if (code === -32601) return true;- return /unsupported|not supported|method not found|unknown request/i.test(error.message);- }-- async diagnostics(filePath: string): Promise<{ items: Diagnostic[] }> {- const absPath = resolve(filePath);- const uri = pathToFileURL(absPath).href;- await this.openFile(absPath);- await new Promise((r) => setTimeout(r, POST_DIAGNOSTICS_WAIT_MS));-- try {- const result = await this.sendRequest<{ items?: Diagnostic[] }>("textDocument/diagnostic", {- textDocument: { uri },- });- if (result.items) {- return { items: result.items };- }- } catch (error) {- if (!this.isUnsupportedDiagnosticPullError(error)) {- this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));- }- }-- return { items: this.getStoredDiagnostics(uri) };- }-- async prepareRename(- filePath: string,- line: number,- character: number,- ): Promise<PrepareRenameResult | PrepareRenameDefaultBehavior | Range | null> {- const absPath = resolve(filePath);- await this.openFile(absPath);- return this.sendRequest<PrepareRenameResult | PrepareRenameDefaultBehavior | Range | null>(- "textDocument/prepareRename",- {- textDocument: { uri: pathToFileURL(absPath).href },- position: { line: line - 1, character },- },- );- }-- async rename(filePath: string, line: number, character: number, newName: string): Promise<WorkspaceEdit | null> {- const absPath = resolve(filePath);- await this.openFile(absPath);- return this.sendRequest<WorkspaceEdit | null>("textDocument/rename", {- textDocument: { uri: pathToFileURL(absPath).href },- position: { line: line - 1, character },- newName,- });- }-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/config-loader.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/config-loader.tsdeleted file mode 100644index 245938b9..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/config-loader.ts+++ /dev/null@@ -1,188 +0,0 @@-import { existsSync, readFileSync } from "node:fs";-import { homedir } from "node:os";-import { isAbsolute, join } from "node:path";--import { BUILTIN_SERVERS } from "./server-definitions.js";-import type { ResolvedServer } from "./types.js";--interface LspEntry {- disabled?: boolean;- command?: string[];- extensions?: string[];- priority?: number;- env?: Record<string, string>;- initialization?: Record<string, unknown>;-}--interface ConfigJson {- lsp?: Record<string, unknown>;-}--type ConfigSource = "project" | "user";--export interface ServerWithSource extends ResolvedServer {- source: "project" | "user" | "builtin";-}--export function getConfigPaths(): { project: string; user: string } {- const cwd = process.cwd();- const projectOverride = process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"];- const userOverride = process.env["LSP_TOOLS_MCP_USER_CONFIG"];- return {- project: projectOverride- ? isAbsolute(projectOverride)- ? projectOverride- : join(cwd, projectOverride)- : join(cwd, ".codex", "lsp-client.json"),- user: userOverride- ? isAbsolute(userOverride)- ? userOverride- : join(homedir(), userOverride)- : join(homedir(), ".codex", "lsp-client.json"),- };-}--function loadJsonFile(path: string): ConfigJson | null {- if (!existsSync(path)) return null;- try {- const parsed: unknown = JSON.parse(readFileSync(path, "utf-8"));- return isConfigJson(parsed) ? parsed : null;- } catch {- return null;- }-}--export function loadAllConfigs(): Map<ConfigSource, ConfigJson> {- const paths = getConfigPaths();- const configs = new Map<ConfigSource, ConfigJson>();-- const project = loadJsonFile(paths.project);- if (project) configs.set("project", project);-- const user = loadJsonFile(paths.user);- if (user) configs.set("user", user);-- return configs;-}--export function getMergedServers(): ServerWithSource[] {- const configs = loadAllConfigs();- const servers: ServerWithSource[] = [];- const disabled = new Set<string>();- const seen = new Set<string>();-- const sources: ConfigSource[] = ["project", "user"];-- for (const source of sources) {- const config = configs.get(source);- if (!config?.lsp) continue;-- for (const [id, rawEntry] of Object.entries(config.lsp)) {- const entry = parseLspEntry(rawEntry);- if (!entry) continue;- if (entry.disabled) {- disabled.add(id);- continue;- }-- if (seen.has(id)) continue;- if (!entry.command || !entry.extensions) continue;-- const server: ServerWithSource = {- id,- command: entry.command,- extensions: entry.extensions,- priority: entry.priority ?? 0,- source,- };- if (entry.env !== undefined) {- server.env = entry.env;- }- if (entry.initialization !== undefined) {- server.initialization = entry.initialization;- }- servers.push(server);- seen.add(id);- }- }-- for (const [id, config] of Object.entries(BUILTIN_SERVERS)) {- if (disabled.has(id) || seen.has(id)) continue;-- servers.push({- id,- command: config.command,- extensions: config.extensions,- priority: -100,- source: "builtin",- });- }-- return servers.sort((a, b) => {- if (a.source !== b.source) {- const order: Record<"project" | "user" | "builtin", number> = {- project: 0,- user: 1,- builtin: 2,- };- return order[a.source] - order[b.source];- }- return b.priority - a.priority;- });-}--function isConfigJson(value: unknown): value is ConfigJson {- if (!isRecord(value)) return false;- const lsp = value["lsp"];- return lsp === undefined || isRecord(lsp);-}--function parseLspEntry(value: unknown): LspEntry | null {- return isLspEntry(value) ? value : null;-}--function isLspEntry(value: unknown): value is LspEntry {- if (!isRecord(value)) return false;- const disabled = value["disabled"];- const command = value["command"];- const extensions = value["extensions"];- const priority = value["priority"];- const env = value["env"];- const initialization = value["initialization"];- return (- (disabled === undefined || typeof disabled === "boolean") &&- (command === undefined || isStringArray(command)) &&- (extensions === undefined || isStringArray(extensions)) &&- (priority === undefined || typeof priority === "number") &&- (env === undefined || isStringRecord(env)) &&- (initialization === undefined || isRecord(initialization))- );-}--function isStringArray(value: unknown): value is string[] {- return Array.isArray(value) && value.every((item) => typeof item === "string");-}--function isStringRecord(value: unknown): value is Record<string, string> {- return isRecord(value) && Object.values(value).every((item) => typeof item === "string");-}--function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === "object" && value !== null && !Array.isArray(value);-}--export function getDisabledServerIds(): Set<string> {- const configs = loadAllConfigs();- const disabled = new Set<string>();-- for (const config of configs.values()) {- if (!config.lsp) continue;- for (const [id, rawEntry] of Object.entries(config.lsp)) {- const entry = parseLspEntry(rawEntry);- if (!entry) continue;- if (entry.disabled) disabled.add(id);- }- }-- return disabled;-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/connection.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/connection.tsdeleted file mode 100644index 8cf905fc..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/connection.ts+++ /dev/null@@ -1,69 +0,0 @@-import { pathToFileURL } from "node:url";--import { LspClientTransport } from "./transport.js";--const INITIALIZE_SETTLE_MS = 300;--export class LspClientConnection extends LspClientTransport {- async initialize(): Promise<void> {- const rootUri = pathToFileURL(this.root).href;- await this.sendRequest("initialize", {- processId: process.pid,- rootUri,- rootPath: this.root,- workspaceFolders: [{ uri: rootUri, name: "workspace" }],- capabilities: {- textDocument: {- hover: { contentFormat: ["markdown", "plaintext"] },- definition: { linkSupport: true },- references: {},- documentSymbol: { hierarchicalDocumentSymbolSupport: true },- publishDiagnostics: {},- rename: {- prepareSupport: true,- prepareSupportDefaultBehavior: 1,- honorsChangeAnnotations: true,- },- codeAction: {- codeActionLiteralSupport: {- codeActionKind: {- valueSet: [- "quickfix",- "refactor",- "refactor.extract",- "refactor.inline",- "refactor.rewrite",- "source",- "source.organizeImports",- "source.fixAll",- ],- },- },- isPreferredSupport: true,- disabledSupport: true,- dataSupport: true,- resolveSupport: {- properties: ["edit", "command"],- },- },- },- workspace: {- symbol: {},- workspaceFolders: true,- configuration: true,- applyEdit: true,- workspaceEdit: {- documentChanges: true,- },- },- },- initializationOptions: this.server.initialization,- });- await this.sendNotification("initialized");- await this.sendNotification("workspace/didChangeConfiguration", {- settings: { json: { validate: { enable: true } } },- });- // Some servers accept initialized before their diagnostics/indexing handlers are ready.- await new Promise((r) => setTimeout(r, INITIALIZE_SETTLE_MS));- }-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/constants.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/constants.tsdeleted file mode 100644index 8dbddbbf..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/constants.ts+++ /dev/null@@ -1,11 +0,0 @@-export const DEFAULT_MAX_REFERENCES = 200;-export const DEFAULT_MAX_SYMBOLS = 200;-export const DEFAULT_MAX_DIAGNOSTICS = 200;-export const DEFAULT_MAX_DIRECTORY_FILES = 50;--export const REQUEST_TIMEOUT_MS = 15_000;-export const INIT_TIMEOUT_MS = 60_000;-export const IDLE_TIMEOUT_MS = 5 * 60_000;-export const REAPER_INTERVAL_MS = 60_000;-export const STOP_HARD_KILL_TIMEOUT_MS = 5_000;-export const STOP_SIGKILL_GRACE_MS = 1_000;diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/directory-diagnostics.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/directory-diagnostics.tsdeleted file mode 100644index 90e6849a..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/directory-diagnostics.ts+++ /dev/null@@ -1,152 +0,0 @@-import { existsSync, lstatSync, readdirSync, type Stats } from "node:fs";-import { extname, join, resolve } from "node:path";-import { findWorkspaceRoot, formatServerLookupError } from "./client-wrapper.js";-import { DEFAULT_MAX_DIAGNOSTICS, DEFAULT_MAX_DIRECTORY_FILES } from "./constants.js";-import { LspInvalidPathError, LspServerLookupError } from "./errors.js";-import { filterDiagnosticsBySeverity, formatDiagnostic } from "./formatters.js";-import { getLspManager } from "./manager.js";-import { findServerForExtension } from "./server-resolution.js";-import type { Diagnostic, SeverityFilter } from "./types.js";--const SKIP_DIRECTORIES = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);--interface FileDiagnostic {- filePath: string;- diagnostic: Diagnostic;-}--export function collectFilesWithExtension(dir: string, extension: string, maxFiles: number): string[] {- const files: string[] = [];-- function walk(currentDir: string): void {- if (files.length >= maxFiles) return;-- let entries: string[] = [];- try {- entries = readdirSync(currentDir);- } catch {- return;- }-- for (const entry of entries) {- if (files.length >= maxFiles) return;-- const fullPath = join(currentDir, entry);-- let stat: Stats | undefined;- try {- stat = lstatSync(fullPath);- } catch {- continue;- }-- if (!stat || stat.isSymbolicLink()) continue;-- if (stat.isDirectory()) {- if (!SKIP_DIRECTORIES.has(entry)) {- walk(fullPath);- }- } else if (stat.isFile() && extname(fullPath) === extension) {- files.push(fullPath);- }- }- }-- walk(dir);- return files;-}--export async function aggregateDiagnosticsForDirectory(- directory: string,- extension: string,- severity?: SeverityFilter,- maxFiles: number = DEFAULT_MAX_DIRECTORY_FILES,-): Promise<string> {- if (!extension.startsWith(".")) {- throw new LspInvalidPathError(- `Extension must start with a dot (e.g., ".ts", not "${extension}"). Use ".${extension}" instead.`,- );- }-- const absDir = resolve(directory);- if (!existsSync(absDir)) {- throw new LspInvalidPathError(`Directory does not exist: ${absDir}`);- }-- const serverResult = findServerForExtension(extension);- if (serverResult.status !== "found") {- throw new LspServerLookupError(formatServerLookupError(serverResult));- }-- const server = serverResult.server;- const allFiles = collectFilesWithExtension(absDir, extension, maxFiles + 1);- const wasCapped = allFiles.length > maxFiles;- const filesToProcess = allFiles.slice(0, maxFiles);-- if (filesToProcess.length === 0) {- return [- `Directory: ${absDir}`,- `Extension: ${extension}`,- "Files scanned: 0",- `No files found with extension "${extension}".`,- ].join("\n");- }-- const root = findWorkspaceRoot(absDir);- const manager = getLspManager();- const allDiagnostics: FileDiagnostic[] = [];- const fileErrors: { file: string; error: string }[] = [];-- const client = await manager.getClient(root, server);- try {- for (const file of filesToProcess) {- try {- const result = await client.diagnostics(file);- const filtered = filterDiagnosticsBySeverity(result.items, severity);- allDiagnostics.push(- ...filtered.map((diagnostic) => ({- filePath: file,- diagnostic,- })),- );- } catch (e) {- fileErrors.push({- file,- error: e instanceof Error ? e.message : String(e),- });- }- }- } finally {- manager.releaseClient(root, server.id);- }-- const displayDiagnostics = allDiagnostics.slice(0, DEFAULT_MAX_DIAGNOSTICS);- const wasDiagCapped = allDiagnostics.length > DEFAULT_MAX_DIAGNOSTICS;-- const lines: string[] = [- `Directory: ${absDir}`,- `Extension: ${extension}`,- `Files scanned: ${filesToProcess.length}${wasCapped ? ` (capped at ${maxFiles})` : ""}`,- `Files with errors: ${fileErrors.length}`,- `Total diagnostics: ${allDiagnostics.length}`,- ];-- if (fileErrors.length > 0) {- lines.push("", "File processing errors:");- for (const { file, error } of fileErrors) {- lines.push(` ${file}: ${error}`);- }- }-- if (displayDiagnostics.length > 0) {- lines.push("");- for (const { filePath, diagnostic } of displayDiagnostics) {- lines.push(`${filePath}: ${formatDiagnostic(diagnostic)}`);- }- if (wasDiagCapped) {- lines.push("", `... (${allDiagnostics.length - DEFAULT_MAX_DIAGNOSTICS} more diagnostics not shown)`);- }- }-- return lines.join("\n");-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/errors.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/errors.tsdeleted file mode 100644index 186c3c71..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/errors.ts+++ /dev/null@@ -1,63 +0,0 @@-export class LspConnectionClosedError extends Error {- override readonly name = "LspConnectionClosedError";-- constructor(- readonly serverId: string,- readonly root: string,- message?: string,- ) {- super(message ?? `LSP connection closed for ${serverId} at ${root}`);- }-}--export class LspProcessExitedError extends Error {- override readonly name = "LspProcessExitedError";-- constructor(- readonly serverId: string,- readonly root: string,- readonly exitCode: number | null,- readonly stderrTail?: string,- ) {- const stderrSuffix = stderrTail ? `\nstderr tail: ${stderrTail}` : "";- super(`LSP server ${serverId} at ${root} exited with code ${exitCode ?? "null"}${stderrSuffix}`);- }-}--export class LspRequestTimeoutError extends Error {- override readonly name = "LspRequestTimeoutError";-- constructor(- readonly method: string,- readonly stderrTail?: string,- ) {- const stderrSuffix = stderrTail ? `\nrecent stderr: ${stderrTail}` : "";- super(`LSP request timeout (method: ${method})${stderrSuffix}`);- }-}--export class LspInvalidPathError extends Error {- override readonly name = "LspInvalidPathError";-}--export class LspServerLookupError extends Error {- override readonly name = "LspServerLookupError";-}--export class LspServerInitializingError extends Error {- override readonly name = "LspServerInitializingError";-- constructor(readonly originalError: LspRequestTimeoutError) {- super(- `LSP server is still initializing. Please retry in a few seconds. Original error: ${originalError.message}`,- );- }-}--export class LspProcessSpawnError extends Error {- override readonly name = "LspProcessSpawnError";-}--export function isLspDeadConnectionError(err: unknown): err is LspConnectionClosedError | LspProcessExitedError {- return err instanceof LspConnectionClosedError || err instanceof LspProcessExitedError;-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/formatters.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/formatters.tsdeleted file mode 100644index 7f8e836a..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/formatters.ts+++ /dev/null@@ -1,141 +0,0 @@-import { fileURLToPath } from "node:url";--import { SEVERITY_MAP, SYMBOL_KIND_MAP } from "./language-mappings.js";-import type {- Diagnostic,- DocumentSymbol,- Location,- LocationLink,- PrepareRenameDefaultBehavior,- PrepareRenameResult,- Range,- SeverityFilter,- SymbolInfo,-} from "./types.js";-import type { ApplyResult } from "./workspace-edit.js";--type FilteredSeverity = Exclude<SeverityFilter, "all">;--const DIAGNOSTIC_SEVERITY_FILTERS = {- error: 1,- warning: 2,- information: 3,- hint: 4,-} as const satisfies Readonly<Record<FilteredSeverity, number>>;--export function uriToPath(uri: string): string {- return fileURLToPath(uri);-}--export function formatLocation(loc: Location | LocationLink): string {- if ("targetUri" in loc) {- const uri = uriToPath(loc.targetUri);- const line = loc.targetRange.start.line + 1;- const char = loc.targetRange.start.character;- return `${uri}:${line}:${char}`;- }-- const uri = uriToPath(loc.uri);- const line = loc.range.start.line + 1;- const char = loc.range.start.character;- return `${uri}:${line}:${char}`;-}--export function formatSymbolKind(kind: number): string {- return SYMBOL_KIND_MAP[kind] ?? `Unknown(${kind})`;-}--export function formatSeverity(severity: number | undefined): string {- if (!severity) return "unknown";- return SEVERITY_MAP[severity] ?? `unknown(${severity})`;-}--export function formatDocumentSymbol(symbol: DocumentSymbol, indent = 0): string {- const prefix = " ".repeat(indent);- const kind = formatSymbolKind(symbol.kind);- const line = symbol.range.start.line + 1;- let result = `${prefix}${symbol.name} (${kind}) - line ${line}`;-- if (symbol.children && symbol.children.length > 0) {- for (const child of symbol.children) {- result += `\n${formatDocumentSymbol(child, indent + 1)}`;- }- }-- return result;-}--export function formatSymbolInfo(symbol: SymbolInfo): string {- const kind = formatSymbolKind(symbol.kind);- const loc = formatLocation(symbol.location);- const container = symbol.containerName ? ` (in ${symbol.containerName})` : "";- return `${symbol.name} (${kind})${container} - ${loc}`;-}--export function formatDiagnostic(diag: Diagnostic): string {- const severity = formatSeverity(diag.severity);- const line = diag.range.start.line + 1;- const char = diag.range.start.character;- const source = diag.source ? `[${diag.source}]` : "";- const code = diag.code ? ` (${diag.code})` : "";- return `${severity}${source}${code} at ${line}:${char}: ${diag.message}`;-}--export function filterDiagnosticsBySeverity(diagnostics: Diagnostic[], severityFilter?: SeverityFilter): Diagnostic[] {- if (!severityFilter || severityFilter === "all") {- return diagnostics;- }-- const targetSeverity = DIAGNOSTIC_SEVERITY_FILTERS[severityFilter];- return diagnostics.filter((d) => d.severity === targetSeverity);-}--export function formatPrepareRenameResult(- result: PrepareRenameResult | PrepareRenameDefaultBehavior | Range | null,-): string {- if (!result) return "Cannot rename at this position";-- if ("defaultBehavior" in result) {- return result.defaultBehavior ? "Rename supported (using default behavior)" : "Cannot rename at this position";- }-- if ("range" in result && result.range) {- const startLine = result.range.start.line + 1;- const startChar = result.range.start.character;- const endLine = result.range.end.line + 1;- const endChar = result.range.end.character;- const placeholder = result.placeholder ? ` (current: "${result.placeholder}")` : "";- return `Rename available at ${startLine}:${startChar}-${endLine}:${endChar}${placeholder}`;- }-- if ("start" in result && "end" in result) {- const startLine = result.start.line + 1;- const startChar = result.start.character;- const endLine = result.end.line + 1;- const endChar = result.end.character;- return `Rename available at ${startLine}:${startChar}-${endLine}:${endChar}`;- }-- return "Cannot rename at this position";-}--export function formatApplyResult(result: ApplyResult): string {- const lines: string[] = [];-- if (result.success) {- lines.push(`Applied ${result.totalEdits} edit(s) to ${result.filesModified.length} file(s):`);- for (const file of result.filesModified) {- lines.push(` - ${file}`);- }- } else {- lines.push("Failed to apply some changes:");- for (const err of result.errors) {- lines.push(` Error: ${err}`);- }- if (result.filesModified.length > 0) {- lines.push(`Successfully modified: ${result.filesModified.join(", ")}`);- }- }-- return lines.join("\n");-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/infer-extension.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/infer-extension.tsdeleted file mode 100644index 31771cbc..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/infer-extension.ts+++ /dev/null@@ -1,65 +0,0 @@-import { lstatSync, readdirSync } from "node:fs";-import { extname, join } from "node:path";--import { EXT_TO_LANG } from "./language-mappings.js";--const SKIP_DIRECTORIES = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);-const MAX_SCAN_ENTRIES = 500;--export function inferExtensionFromDirectory(directory: string): string | null {- const extensionCounts = new Map<string, number>();- let scanned = 0;-- function walk(dir: string): void {- if (scanned >= MAX_SCAN_ENTRIES) return;-- let entries: string[];- try {- entries = readdirSync(dir);- } catch {- return;- }-- for (const entry of entries) {- if (scanned >= MAX_SCAN_ENTRIES) return;-- const fullPath = join(dir, entry);-- let stat: ReturnType<typeof lstatSync> | undefined;- try {- stat = lstatSync(fullPath);- } catch {- continue;- }-- if (stat.isSymbolicLink()) continue;- scanned++;-- if (stat.isDirectory()) {- if (!SKIP_DIRECTORIES.has(entry)) {- walk(fullPath);- }- } else if (stat.isFile()) {- const ext = extname(fullPath);- if (ext && ext in EXT_TO_LANG) {- extensionCounts.set(ext, (extensionCounts.get(ext) ?? 0) + 1);- }- }- }- }-- walk(directory);-- if (extensionCounts.size === 0) return null;-- let maxExt = "";- let maxCount = 0;- for (const [ext, count] of extensionCounts) {- if (count > maxCount) {- maxCount = count;- maxExt = ext;- }- }-- return maxExt || null;-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/json-rpc-connection.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/json-rpc-connection.tsdeleted file mode 100644index 2769466a..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/json-rpc-connection.ts+++ /dev/null@@ -1,296 +0,0 @@-type JsonRpcId = number | string | null;--interface PendingRequest {- resolve(result: unknown): void;- reject(error: Error): void;-}--type NotificationHandler = (params: unknown) => void;-type RequestHandler = (params: unknown) => Promise<unknown> | unknown;--const HEADER_SEPARATOR = "\r\n\r\n";-const PARSE_ERROR = -32700;-const INVALID_REQUEST = -32600;-const METHOD_NOT_FOUND = -32601;-const INTERNAL_ERROR = -32603;--export class JsonRpcConnection {- private readonly pendingRequests = new Map<string, PendingRequest>();- private readonly notificationHandlers = new Map<string, NotificationHandler>();- private readonly requestHandlers = new Map<string, RequestHandler>();- private readonly closeHandlers: Array<() => void> = [];- private readonly errorHandlers: Array<(error: Error) => void> = [];- private inputBuffer = Buffer.alloc(0);- private nextRequestId = 1;- private listening = false;- private disposed = false;-- constructor(- private readonly reader: NodeJS.ReadableStream,- private readonly writer: NodeJS.WritableStream,- ) {}-- listen(): void {- if (this.listening) return;- this.listening = true;- this.reader.on("data", this.handleData);- this.reader.on("close", this.handleClose);- this.reader.on("end", this.handleClose);- this.reader.on("error", this.handleStreamError);- this.writer.on("error", this.handleStreamError);- }-- onNotification(method: string, handler: NotificationHandler): void {- this.notificationHandlers.set(method, handler);- }-- onRequest(method: string, handler: RequestHandler): void {- this.requestHandlers.set(method, handler);- }-- onClose(handler: () => void): void {- this.closeHandlers.push(handler);- }-- onError(handler: (error: Error) => void): void {- this.errorHandlers.push(handler);- }-- async sendRequest<T>(method: string, params?: unknown): Promise<T> {- if (this.disposed) throw new Error("JSON-RPC connection is disposed");-- const id = this.nextRequestId;- this.nextRequestId += 1;- const message = params === undefined ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };-- const responsePromise = new Promise<T>((resolve, reject) => {- this.pendingRequests.set(String(id), {- resolve(result) {- resolve(result as T);- },- reject,- });- });-- try {- await this.writeMessage(message);- } catch (error) {- this.pendingRequests.delete(String(id));- throw error;- }-- return responsePromise;- }-- async sendNotification(method: string, params?: unknown): Promise<void> {- if (this.disposed) return;- const message = params === undefined ? { jsonrpc: "2.0", method } : { jsonrpc: "2.0", method, params };- await this.writeMessage(message);- }-- dispose(): void {- if (this.disposed) return;- this.disposed = true;- this.reader.off("data", this.handleData);- this.reader.off("close", this.handleClose);- this.reader.off("end", this.handleClose);- this.reader.off("error", this.handleStreamError);- this.writer.off("error", this.handleStreamError);- for (const pending of this.pendingRequests.values()) {- pending.reject(new Error("JSON-RPC connection disposed"));- }- this.pendingRequests.clear();- this.notificationHandlers.clear();- this.requestHandlers.clear();- }-- private readonly handleData = (chunk: Buffer | string): void => {- const chunkBuffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf8");- this.inputBuffer = Buffer.concat([this.inputBuffer, chunkBuffer]);- this.drainInputBuffer();- };-- private readonly handleClose = (): void => {- for (const handler of this.closeHandlers) {- handler();- }- };-- private readonly handleStreamError = (error: Error): void => {- this.emitError(error);- };-- private drainInputBuffer(): void {- while (true) {- const headerEnd = this.inputBuffer.indexOf(HEADER_SEPARATOR);- if (headerEnd === -1) return;-- const headers = this.inputBuffer.subarray(0, headerEnd).toString("ascii");- const contentLength = parseContentLength(headers);- if (contentLength === null) {- this.inputBuffer = Buffer.alloc(0);- this.emitError(new Error("JSON-RPC message is missing Content-Length header"));- return;- }-- const bodyStart = headerEnd + Buffer.byteLength(HEADER_SEPARATOR);- const bodyEnd = bodyStart + contentLength;- if (this.inputBuffer.length < bodyEnd) return;-- const body = this.inputBuffer.subarray(bodyStart, bodyEnd).toString("utf8");- this.inputBuffer = this.inputBuffer.subarray(bodyEnd);- this.dispatchBody(body);- }- }-- private dispatchBody(body: string): void {- let parsed: unknown;- try {- parsed = JSON.parse(body);- } catch (error) {- void this.writeError(null, PARSE_ERROR, error instanceof Error ? error.message : "Parse error").catch(- (writeError) => this.emitError(toError(writeError)),- );- return;- }-- if (!isJsonRpcObject(parsed)) {- void this.writeError(null, INVALID_REQUEST, "Invalid JSON-RPC message").catch((error) =>- this.emitError(toError(error)),- );- return;- }-- if ("id" in parsed && ("result" in parsed || "error" in parsed)) {- this.handleResponse(parsed);- return;- }-- if (typeof parsed["method"] !== "string") {- const id = getMessageId(parsed) ?? null;- void this.writeError(id, INVALID_REQUEST, "Invalid JSON-RPC method").catch((error) =>- this.emitError(toError(error)),- );- return;- }-- if ("id" in parsed) {- this.handleRequest(parsed);- return;- }-- this.handleNotification(parsed["method"], parsed["params"]);- }-- private handleResponse(message: Record<string, unknown>): void {- const id = getMessageId(message);- if (id === undefined) return;- const pending = this.pendingRequests.get(String(id));- if (!pending) return;- this.pendingRequests.delete(String(id));-- if ("error" in message) {- pending.reject(jsonRpcErrorToError(message["error"]));- return;- }-- pending.resolve(message["result"]);- }-- private handleNotification(method: string, params: unknown): void {- const handler = this.notificationHandlers.get(method);- if (!handler) return;- try {- handler(params);- } catch (error) {- this.emitError(toError(error));- }- }-- private handleRequest(message: Record<string, unknown>): void {- const id = getMessageId(message);- if (id === undefined) {- void this.writeError(null, INVALID_REQUEST, "Invalid JSON-RPC id").catch((error) =>- this.emitError(toError(error)),- );- return;- }-- const method = typeof message["method"] === "string" ? message["method"] : "";- const handler = this.requestHandlers.get(method);- if (!handler) {- void this.writeError(id, METHOD_NOT_FOUND, `Method not found: ${method}`).catch((error) =>- this.emitError(toError(error)),- );- return;- }-- Promise.resolve()- .then(() => handler(message["params"]))- .then(- (result) => this.writeMessage({ jsonrpc: "2.0", id, result }),- (error) => this.writeError(id, INTERNAL_ERROR, toError(error).message),- )- .catch((error) => this.emitError(toError(error)));- }-- private async writeError(id: JsonRpcId, code: number, message: string): Promise<void> {- await this.writeMessage({ jsonrpc: "2.0", id, error: { code, message } });- }-- private writeMessage(message: Record<string, unknown>): Promise<void> {- const body = JSON.stringify(message);- const payload = `Content-Length: ${Buffer.byteLength(body, "utf8")}\r\n\r\n${body}`;- return new Promise((resolve, reject) => {- this.writer.write(payload, (error?: Error | null) => {- if (error) {- reject(error);- return;- }- resolve();- });- });- }-- private emitError(error: Error): void {- for (const handler of this.errorHandlers) {- handler(error);- }- }-}--function parseContentLength(headers: string): number | null {- for (const line of headers.split("\r\n")) {- const separatorIndex = line.indexOf(":");- if (separatorIndex === -1) continue;- const name = line.slice(0, separatorIndex).trim().toLowerCase();- if (name !== "content-length") continue;- const value = Number.parseInt(line.slice(separatorIndex + 1).trim(), 10);- return Number.isFinite(value) && value >= 0 ? value : null;- }- return null;-}--function isJsonRpcObject(value: unknown): value is Record<string, unknown> {- return typeof value === "object" && value !== null && !Array.isArray(value);-}--function getMessageId(message: Record<string, unknown>): JsonRpcId | undefined {- const id = message["id"];- if (typeof id === "number" || typeof id === "string" || id === null) return id;- return undefined;-}--function jsonRpcErrorToError(value: unknown): Error {- if (!isJsonRpcObject(value)) return new Error("JSON-RPC request failed");- const message = typeof value["message"] === "string" ? value["message"] : "JSON-RPC request failed";- const error = new Error(message);- if (typeof value["code"] === "number") {- error.name = `JsonRpcError(${value["code"]})`;- }- return error;-}--function toError(error: unknown): Error {- return error instanceof Error ? error : new Error(String(error));-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/language-mappings.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/language-mappings.tsdeleted file mode 100644index ace3c234..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/language-mappings.ts+++ /dev/null@@ -1,172 +0,0 @@-export const SYMBOL_KIND_MAP: Record<number, string> = {- 1: "File",- 2: "Module",- 3: "Namespace",- 4: "Package",- 5: "Class",- 6: "Method",- 7: "Property",- 8: "Field",- 9: "Constructor",- 10: "Enum",- 11: "Interface",- 12: "Function",- 13: "Variable",- 14: "Constant",- 15: "String",- 16: "Number",- 17: "Boolean",- 18: "Array",- 19: "Object",- 20: "Key",- 21: "Null",- 22: "EnumMember",- 23: "Struct",- 24: "Event",- 25: "Operator",- 26: "TypeParameter",-};--export const SEVERITY_MAP: Record<number, string> = {- 1: "error",- 2: "warning",- 3: "information",- 4: "hint",-};--export const EXT_TO_LANG: Record<string, string> = {- ".abap": "abap",- ".bat": "bat",- ".bib": "bibtex",- ".bibtex": "bibtex",- ".clj": "clojure",- ".cljs": "clojure",- ".cljc": "clojure",- ".edn": "clojure",- ".coffee": "coffeescript",- ".c": "c",- ".cpp": "cpp",- ".cxx": "cpp",- ".cc": "cpp",- ".c++": "cpp",- ".cs": "csharp",- ".css": "css",- ".d": "d",- ".pas": "pascal",- ".pascal": "pascal",- ".diff": "diff",- ".patch": "diff",- ".dart": "dart",- ".dockerfile": "dockerfile",- ".ex": "elixir",- ".exs": "elixir",- ".erl": "erlang",- ".hrl": "erlang",- ".fs": "fsharp",- ".fsi": "fsharp",- ".fsx": "fsharp",- ".fsscript": "fsharp",- ".gitcommit": "git-commit",- ".gitrebase": "git-rebase",- ".go": "go",- ".groovy": "groovy",- ".gleam": "gleam",- ".hbs": "handlebars",- ".handlebars": "handlebars",- ".hs": "haskell",- ".html": "html",- ".htm": "html",- ".ini": "ini",- ".java": "java",- ".js": "javascript",- ".jsx": "javascriptreact",- ".json": "json",- ".jsonc": "jsonc",- ".tex": "latex",- ".latex": "latex",- ".less": "less",- ".lua": "lua",- ".makefile": "makefile",- makefile: "makefile",- ".md": "markdown",- ".markdown": "markdown",- ".m": "objective-c",- ".mm": "objective-cpp",- ".pl": "perl",- ".pm": "perl",- ".pm6": "perl6",- ".php": "php",- ".ps1": "powershell",- ".psm1": "powershell",- ".pug": "jade",- ".jade": "jade",- ".py": "python",- ".pyi": "python",- ".r": "r",- ".cshtml": "razor",- ".razor": "razor",- ".rb": "ruby",- ".rake": "ruby",- ".gemspec": "ruby",- ".ru": "ruby",- ".erb": "erb",- ".html.erb": "erb",- ".js.erb": "erb",- ".css.erb": "erb",- ".json.erb": "erb",- ".rs": "rust",- ".scss": "scss",- ".sass": "sass",- ".scala": "scala",- ".shader": "shaderlab",- ".sh": "shellscript",- ".bash": "shellscript",- ".zsh": "shellscript",- ".ksh": "shellscript",- ".sql": "sql",- ".svelte": "svelte",- ".swift": "swift",- ".ts": "typescript",- ".tsx": "typescriptreact",- ".mts": "typescript",- ".cts": "typescript",- ".mtsx": "typescriptreact",- ".ctsx": "typescriptreact",- ".xml": "xml",- ".xsl": "xsl",- ".yaml": "yaml",- ".yml": "yaml",- ".mjs": "javascript",- ".cjs": "javascript",- ".vue": "vue",- ".zig": "zig",- ".zon": "zig",- ".astro": "astro",- ".ml": "ocaml",- ".mli": "ocaml",- ".tf": "terraform",- ".tfvars": "terraform-vars",- ".hcl": "hcl",- ".nix": "nix",- ".typ": "typst",- ".typc": "typst",- ".ets": "typescript",- ".lhs": "haskell",- ".kt": "kotlin",- ".kts": "kotlin",- ".prisma": "prisma",- ".h": "c",- ".hpp": "cpp",- ".hh": "cpp",- ".hxx": "cpp",- ".h++": "cpp",- ".objc": "objective-c",- ".objcpp": "objective-cpp",- ".fish": "fish",- ".graphql": "graphql",- ".gql": "graphql",-};--export function getLanguageId(ext: string): string {- return EXT_TO_LANG[ext] ?? "plaintext";-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/manager.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/manager.tsdeleted file mode 100644index 6b2e95a5..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/manager.ts+++ /dev/null@@ -1,369 +0,0 @@-import { reportBestEffortCleanupError } from "./cleanup-errors.js";-import { LspClient } from "./client.js";-import { IDLE_TIMEOUT_MS, INIT_TIMEOUT_MS, REAPER_INTERVAL_MS } from "./constants.js";-import { installProcessSignalCleanup } from "./process-signal-cleanup.js";-import type { ResolvedServer } from "./types.js";--interface ManagedClient {- client: LspClient;- refCount: number;- pendingWaiters: number;- lastUsedAt: number;- initPromise: Promise<void> | null;- isInitializing: boolean;- initializingSince: number | null;-}--export interface ClientSnapshot {- root: string;- serverId: string;- refCount: number;- pendingWaiters: number;- lastUsedAt: number;- isInitializing: boolean;- alive: boolean;- command: string[];-}--export interface LspManagerOptions {- idleTimeoutMs?: number;- initTimeoutMs?: number;- reaperIntervalMs?: number;- clientFactory?: (root: string, server: ResolvedServer) => LspClient;- now?: () => number;-}--async function stopClientBestEffort(client: LspClient): Promise<void> {- try {- await client.stop();- } catch (error) {- reportBestEffortCleanupError("client stop", error);- }-}--function awaitWithSignal<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {- if (!signal) return promise;- return new Promise<T>((resolve, reject) => {- let settled = false;- const onAbort = () => {- if (settled) return;- settled = true;- reject(new DOMException("Aborted", "AbortError"));- };- if (signal.aborted) {- onAbort();- return;- }- signal.addEventListener("abort", onAbort, { once: true });- promise.then(- (value) => {- if (settled) return;- settled = true;- signal.removeEventListener("abort", onAbort);- resolve(value);- },- (err) => {- if (settled) return;- settled = true;- signal.removeEventListener("abort", onAbort);- reject(err);- },- );- });-}--export class LspManager {- private readonly clients = new Map<string, ManagedClient>();- private reaperHandle: NodeJS.Timeout | null = null;- private signalDisposer: (() => void) | null = null;- private disposed = false;-- private readonly idleTimeoutMs: number;- private readonly initTimeoutMs: number;- private readonly reaperIntervalMs: number;- private readonly clientFactory: (root: string, server: ResolvedServer) => LspClient;- private readonly now: () => number;-- constructor(options: LspManagerOptions = {}) {- this.idleTimeoutMs = options.idleTimeoutMs ?? IDLE_TIMEOUT_MS;- this.initTimeoutMs = options.initTimeoutMs ?? INIT_TIMEOUT_MS;- this.reaperIntervalMs = options.reaperIntervalMs ?? REAPER_INTERVAL_MS;- this.clientFactory = options.clientFactory ?? ((root, server) => new LspClient(root, server));- this.now = options.now ?? (() => Date.now());-- this.startReaper();- this.signalDisposer = installProcessSignalCleanup(() => this.stopAll());- }-- private startReaper(): void {- if (this.reaperHandle) return;- this.reaperHandle = setInterval(() => {- this.reapStale();- }, this.reaperIntervalMs);- if (typeof this.reaperHandle.unref === "function") {- this.reaperHandle.unref();- }- }-- private getKey(root: string, serverId: string): string {- return `${root}::${serverId}`;- }-- private reapStale(): void {- const t = this.now();- for (const [key, managed] of this.clients) {- if (- managed.isInitializing &&- managed.initializingSince !== null &&- t - managed.initializingSince > this.initTimeoutMs- ) {- void stopClientBestEffort(managed.client);- this.clients.delete(key);- continue;- }-- if (- !managed.isInitializing &&- managed.refCount === 0 &&- managed.pendingWaiters === 0 &&- t - managed.lastUsedAt > this.idleTimeoutMs- ) {- void stopClientBestEffort(managed.client);- this.clients.delete(key);- }- }- }-- private async tryDeleteIfOrphaned(key: string, managed: ManagedClient): Promise<void> {- if (- managed.refCount === 0 &&- managed.pendingWaiters === 0 &&- !managed.isInitializing &&- this.clients.get(key) === managed- ) {- this.clients.delete(key);- await stopClientBestEffort(managed.client);- }- }-- async getClient(root: string, server: ResolvedServer, signal?: AbortSignal): Promise<LspClient> {- if (this.disposed) {- throw new Error("LspManager has been disposed");- }- signal?.throwIfAborted();-- const key = this.getKey(root, server.id);- let managed = this.clients.get(key);-- if (managed) {- const t = this.now();- if (- managed.isInitializing &&- managed.initializingSince !== null &&- t - managed.initializingSince > this.initTimeoutMs- ) {- await stopClientBestEffort(managed.client);- this.clients.delete(key);- managed = undefined;- }- }-- if (managed) {- if (managed.initPromise) {- managed.pendingWaiters++;- try {- await awaitWithSignal(managed.initPromise, signal);- } catch (err) {- managed.pendingWaiters--;- await this.tryDeleteIfOrphaned(key, managed);- throw err;- }- managed.pendingWaiters--;- }-- if (signal?.aborted) {- await this.tryDeleteIfOrphaned(key, managed);- signal.throwIfAborted();- }-- if (!managed.client.isAlive()) {- await stopClientBestEffort(managed.client);- this.clients.delete(key);- return this.getClient(root, server, signal);- }-- managed.refCount++;- managed.lastUsedAt = this.now();- return managed.client;- }-- const client = this.clientFactory(root, server);- const initStartedAt = this.now();- const initPromise = (async () => {- await client.start();- await client.initialize();- })();-- const newManaged: ManagedClient = {- client,- refCount: 0,- pendingWaiters: 1,- lastUsedAt: initStartedAt,- initPromise,- isInitializing: true,- initializingSince: initStartedAt,- };- this.clients.set(key, newManaged);-- try {- await awaitWithSignal(initPromise, signal);- } catch (err) {- newManaged.pendingWaiters--;- if (this.clients.get(key) === newManaged) {- this.clients.delete(key);- }- await stopClientBestEffort(client);- throw err;- }-- newManaged.pendingWaiters--;- newManaged.isInitializing = false;- newManaged.initializingSince = null;- newManaged.initPromise = null;-- if (signal?.aborted) {- await this.tryDeleteIfOrphaned(key, newManaged);- signal.throwIfAborted();- }-- newManaged.refCount++;- newManaged.lastUsedAt = this.now();- return client;- }-- releaseClient(root: string, serverId: string): void {- const key = this.getKey(root, serverId);- const managed = this.clients.get(key);- if (managed && managed.refCount > 0) {- managed.refCount--;- managed.lastUsedAt = this.now();- }- }-- invalidateClient(root: string, serverId: string, client?: LspClient): void {- const key = this.getKey(root, serverId);- const managed = this.clients.get(key);- if (!managed) return;- if (client && managed.client !== client) return;- this.clients.delete(key);- void stopClientBestEffort(managed.client);- }-- warmupClient(root: string, server: ResolvedServer): void {- if (this.disposed) return;- const key = this.getKey(root, server.id);- if (this.clients.has(key)) return;-- const client = this.clientFactory(root, server);- const initStartedAt = this.now();- const initPromise = (async () => {- await client.start();- await client.initialize();- })();-- const managed: ManagedClient = {- client,- refCount: 0,- pendingWaiters: 0,- lastUsedAt: initStartedAt,- initPromise,- isInitializing: true,- initializingSince: initStartedAt,- };- this.clients.set(key, managed);-- initPromise.then(- () => {- managed.isInitializing = false;- managed.initializingSince = null;- managed.initPromise = null;- managed.lastUsedAt = this.now();- },- () => {- if (this.clients.get(key) === managed) {- this.clients.delete(key);- }- void stopClientBestEffort(client);- },- );- }-- isServerInitializing(root: string, serverId: string): boolean {- const managed = this.clients.get(this.getKey(root, serverId));- return managed?.isInitializing ?? false;- }-- getSnapshot(): ClientSnapshot[] {- const snapshots: ClientSnapshot[] = [];- for (const [key, managed] of this.clients) {- const [root, serverId] = key.split("::") as [string, string];- snapshots.push({- root,- serverId,- refCount: managed.refCount,- pendingWaiters: managed.pendingWaiters,- lastUsedAt: managed.lastUsedAt,- isInitializing: managed.isInitializing,- alive: managed.client.isAlive(),- command: managed.client.command(),- });- }- return snapshots;- }-- hasClient(root: string, serverId: string): boolean {- return this.clients.has(this.getKey(root, serverId));- }-- clientCount(): number {- return this.clients.size;- }-- async stopAll(): Promise<void> {- this.disposed = true;-- if (this.reaperHandle) {- clearInterval(this.reaperHandle);- this.reaperHandle = null;- }-- if (this.signalDisposer) {- this.signalDisposer();- this.signalDisposer = null;- }-- const stopPromises: Promise<void>[] = [];- for (const managed of this.clients.values()) {- stopPromises.push(stopClientBestEffort(managed.client));- }- this.clients.clear();- await Promise.allSettled(stopPromises);- }-}--let _defaultInstance: LspManager | null = null;--export function getLspManager(): LspManager {- if (!_defaultInstance) {- _defaultInstance = new LspManager();- }- return _defaultInstance;-}--export async function disposeDefaultLspManager(): Promise<void> {- if (_defaultInstance) {- const m = _defaultInstance;- _defaultInstance = null;- await m.stopAll();- }-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/process-signal-cleanup.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/process-signal-cleanup.tsdeleted file mode 100644index 9ab3a4ee..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/process-signal-cleanup.ts+++ /dev/null@@ -1,21 +0,0 @@-import { reportBestEffortCleanupError } from "./cleanup-errors.js";--export function installProcessSignalCleanup(cleanup: () => Promise<void>): () => void {- const signals: readonly NodeJS.Signals[] =- process.platform === "win32" ? ["SIGINT", "SIGTERM", "SIGBREAK"] : ["SIGINT", "SIGTERM"];- const handler = () => {- void cleanup().catch((error) => {- reportBestEffortCleanupError("signal cleanup", error);- });- };-- for (const signal of signals) {- process.on(signal, handler);- }-- return () => {- for (const signal of signals) {- process.removeListener(signal, handler);- }- };-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/process.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/process.tsdeleted file mode 100644index e059b141..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/process.ts+++ /dev/null@@ -1,202 +0,0 @@-import { type ChildProcess, spawn, spawnSync } from "node:child_process";-import { existsSync, statSync } from "node:fs";-import { delimiter, join } from "node:path";--import { reportBestEffortCleanupError } from "./cleanup-errors.js";-import { LspInvalidPathError, LspProcessSpawnError } from "./errors.js";--export interface SpawnedProcess {- stdin: NodeJS.WritableStream;- stdout: NodeJS.ReadableStream;- stderr: NodeJS.ReadableStream;- pid: number | undefined;- exitCode: number | null;- exited: Promise<number>;- kill(signal?: NodeJS.Signals): void;- killed: boolean;-}--export interface SpawnOptions {- cwd: string;- env: Record<string, string | undefined>;-}--export interface PreparedSpawnCommand {- command: string;- args: string[];- shell: false;-}--function isMissingProcessError(error: unknown): boolean {- if (!(error instanceof Error) || !("code" in error)) return false;- return error.code === "ESRCH";-}--function reportKillError(context: string, error: unknown): void {- if (!isMissingProcessError(error)) {- reportBestEffortCleanupError(context, error);- }-}--export function validateCwd(cwd: string): { valid: boolean; error?: string } {- try {- if (!existsSync(cwd)) {- return { valid: false, error: `Working directory does not exist: ${cwd}` };- }- const stats = statSync(cwd);- if (!stats.isDirectory()) {- return { valid: false, error: `Path is not a directory: ${cwd}` };- }- return { valid: true };- } catch (err) {- return {- valid: false,- error: `Cannot access working directory: ${cwd} (${err instanceof Error ? err.message : String(err)})`,- };- }-}--function wrap(proc: ChildProcess): SpawnedProcess {- const exitedPromise = new Promise<number>((resolve) => {- proc.once("close", (code) => resolve(code ?? 0));- proc.once("error", () => resolve(1));- });-- if (!proc.stdin || !proc.stdout || !proc.stderr) {- throw new LspProcessSpawnError("Spawned process is missing one of stdin/stdout/stderr pipes");- }-- return {- stdin: proc.stdin,- stdout: proc.stdout,- stderr: proc.stderr,- get pid() {- return proc.pid ?? undefined;- },- get exitCode() {- return proc.exitCode;- },- get killed() {- return proc.killed;- },- exited: exitedPromise,- kill(signal?: NodeJS.Signals) {- killProcessTree(proc, signal ?? "SIGTERM");- },- };-}--function killProcessTree(proc: ChildProcess, signal: NodeJS.Signals): void {- if (process.platform === "win32" && proc.pid) {- const result = spawnSync("taskkill", ["/pid", String(proc.pid), "/f", "/t"], { stdio: "ignore" });- if (!result.error && result.status === 0) return;- if (result.error) reportKillError("windows process tree kill", result.error);- }-- if (process.platform !== "win32" && proc.pid) {- try {- process.kill(-proc.pid, signal);- return;- } catch (error) {- reportKillError("process group kill", error);- }- }-- try {- proc.kill(signal);- } catch (error) {- reportKillError("process kill", error);- }-}--function isWindowsShellShim(command: string): boolean {- const lowerCommand = command.toLowerCase();- return lowerCommand.endsWith(".cmd") || lowerCommand.endsWith(".bat");-}--function splitPath(pathValue: string, platform: NodeJS.Platform): string[] {- const separator = platform === "win32" ? ";" : delimiter;- return pathValue.split(separator).filter(Boolean);-}--function getWindowsPathExtensions(env: Record<string, string | undefined>): string[] {- const rawExtensions = env["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD";- const extensions = rawExtensions- .split(";")- .map((extension) => extension.trim())- .filter(Boolean)- .map((extension) => (extension.startsWith(".") ? extension : `.${extension}`));- return [...new Set(["", ...extensions, ".exe", ".cmd", ".bat"])];-}--function resolveWindowsCommand(command: string, env: Record<string, string | undefined>): string {- const hasPathSeparator = command.includes("/") || command.includes("\\");- const pathValue = env["PATH"] ?? env["Path"] ?? "";- const baseDirectories = hasPathSeparator ? [""] : splitPath(pathValue, "win32");- const extensions = getWindowsPathExtensions(env);-- for (const baseDirectory of baseDirectories) {- for (const extension of extensions) {- const candidate = baseDirectory ? join(baseDirectory, `${command}${extension}`) : `${command}${extension}`;- if (existsSync(candidate)) return candidate;- }- }-- return command;-}--export function createSpawnCommand(- command: string[],- platform: NodeJS.Platform = process.platform,- commandProcessor: string = process.env["ComSpec"] ?? "cmd.exe",- env: Record<string, string | undefined> = process.env,-): PreparedSpawnCommand {- const [cmd, ...args] = command;- if (!cmd) {- throw new LspProcessSpawnError("[lsp] empty command");- }-- if (platform !== "win32") {- return { command: cmd, args, shell: false };- }-- const resolvedCommand = resolveWindowsCommand(cmd, env);- if (!isWindowsShellShim(resolvedCommand)) {- return { command: resolvedCommand, args, shell: false };- }-- return {- command: commandProcessor,- args: ["/d", "/s", "/c", resolvedCommand, ...args],- shell: false,- };-}--export function spawnProcess(command: string[], options: SpawnOptions): SpawnedProcess {- const cwdValidation = validateCwd(options.cwd);- if (!cwdValidation.valid) {- throw new LspInvalidPathError(`[lsp] ${cwdValidation.error}`);- }-- const [cmd] = command;- if (!cmd) {- throw new LspProcessSpawnError("[lsp] empty command");- }-- const preparedCommand = createSpawnCommand(- command,- process.platform,- process.env["ComSpec"] ?? "cmd.exe",- options.env,- );- const proc = spawn(preparedCommand.command, preparedCommand.args, {- cwd: options.cwd,- env: options.env,- stdio: ["pipe", "pipe", "pipe"],- windowsHide: true,- shell: preparedCommand.shell,- detached: process.platform !== "win32",- });-- return wrap(proc);-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-definitions.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-definitions.tsdeleted file mode 100644index b8e72864..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-definitions.ts+++ /dev/null@@ -1,163 +0,0 @@-import type { LspServerConfig } from "./types.js";--export const LSP_INSTALL_HINTS: Record<string, string> = {- typescript: "npm install -g typescript-language-server typescript",- deno: "Install Deno from https://deno.land",- vue: "npm install -g @vue/language-server",- eslint: "npm install -g vscode-langservers-extracted",- oxlint: "npm install -g oxlint",- biome: "npm install -g @biomejs/biome",- gopls: "go install golang.org/x/tools/gopls@latest",- "ruby-lsp": "gem install ruby-lsp",- basedpyright: "pip install basedpyright",- pyright: "pip install pyright",- ty: "pip install ty",- ruff: "pip install ruff",- "elixir-ls": "See https://github.com/elixir-lsp/elixir-ls",- zls: "See https://github.com/zigtools/zls",- csharp: "dotnet tool install -g csharp-ls",- fsharp: "dotnet tool install -g fsautocomplete",- "sourcekit-lsp": "Included with Xcode or Swift toolchain",- rust:- "Install rust-analyzer and ensure it is in PATH. If using rustup: rustup component add rust-analyzer. " +- "If rust-analyzer exits while loading rust-src: rustup component remove rust-src && rustup component add rust-src.",- clangd: "See https://clangd.llvm.org/installation",- svelte: "npm install -g svelte-language-server",- astro: "npm install -g @astrojs/language-server",- "bash-ls": "npm install -g bash-language-server",- jdtls: "See https://github.com/eclipse-jdtls/eclipse.jdt.ls",- "yaml-ls": "npm install -g yaml-language-server",- "lua-ls": "See https://github.com/LuaLS/lua-language-server",- php: "npm install -g intelephense",- dart: "Included with Dart SDK",- "terraform-ls": "See https://github.com/hashicorp/terraform-ls",- terraform: "See https://github.com/hashicorp/terraform-ls",- prisma: "npm install -g prisma",- "ocaml-lsp": "opam install ocaml-lsp-server",- texlab: "See https://github.com/latex-lsp/texlab",- dockerfile: "npm install -g dockerfile-language-server-nodejs",- gleam: "See https://gleam.run/getting-started/installing/",- "clojure-lsp": "See https://clojure-lsp.io/installation/",- nixd: "nix profile install nixpkgs#nixd",- tinymist: "See https://github.com/Myriad-Dreamin/tinymist",- "haskell-language-server": "ghcup install hls",- bash: "npm install -g bash-language-server",- "kotlin-ls": "See https://github.com/Kotlin/kotlin-lsp",-};--export const BUILTIN_SERVERS: Record<string, Omit<LspServerConfig, "id">> = {- typescript: {- command: ["typescript-language-server", "--stdio"],- extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"],- },- deno: { command: ["deno", "lsp"], extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs"] },- vue: { command: ["vue-language-server", "--stdio"], extensions: [".vue"] },- eslint: {- command: ["vscode-eslint-language-server", "--stdio"],- extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".vue"],- },- oxlint: {- command: ["oxlint", "--lsp"],- extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".vue", ".astro", ".svelte"],- },- biome: {- command: ["biome", "lsp-proxy", "--stdio"],- extensions: [- ".ts",- ".tsx",- ".js",- ".jsx",- ".mjs",- ".cjs",- ".mts",- ".cts",- ".json",- ".jsonc",- ".vue",- ".astro",- ".svelte",- ".css",- ".graphql",- ".gql",- ".html",- ],- },- gopls: { command: ["gopls"], extensions: [".go"] },- "ruby-lsp": {- command: ["rubocop", "--lsp"],- extensions: [".rb", ".rake", ".gemspec", ".ru"],- },- basedpyright: {- command: ["basedpyright-langserver", "--stdio"],- extensions: [".py", ".pyi"],- },- pyright: { command: ["pyright-langserver", "--stdio"], extensions: [".py", ".pyi"] },- ty: { command: ["ty", "server"], extensions: [".py", ".pyi"] },- ruff: { command: ["ruff", "server"], extensions: [".py", ".pyi"] },- "elixir-ls": { command: ["elixir-ls"], extensions: [".ex", ".exs"] },- zls: { command: ["zls"], extensions: [".zig", ".zon"] },- csharp: { command: ["csharp-ls"], extensions: [".cs"] },- fsharp: { command: ["fsautocomplete"], extensions: [".fs", ".fsi", ".fsx", ".fsscript"] },- "sourcekit-lsp": { command: ["sourcekit-lsp"], extensions: [".swift", ".objc", ".objcpp"] },- rust: { command: ["rust-analyzer"], extensions: [".rs"] },- clangd: {- command: ["clangd", "--background-index", "--clang-tidy"],- extensions: [".c", ".cpp", ".cc", ".cxx", ".c++", ".h", ".hpp", ".hh", ".hxx", ".h++"],- },- svelte: { command: ["svelteserver", "--stdio"], extensions: [".svelte"] },- astro: { command: ["astro-ls", "--stdio"], extensions: [".astro"] },- bash: {- command: ["bash-language-server", "start"],- extensions: [".sh", ".bash", ".zsh", ".ksh"],- },- "bash-ls": {- command: ["bash-language-server", "start"],- extensions: [".sh", ".bash", ".zsh", ".ksh"],- },- jdtls: { command: ["jdtls"], extensions: [".java"] },- "yaml-ls": { command: ["yaml-language-server", "--stdio"], extensions: [".yaml", ".yml"] },- "lua-ls": { command: ["lua-language-server"], extensions: [".lua"] },- php: { command: ["intelephense", "--stdio"], extensions: [".php"] },- dart: { command: ["dart", "language-server", "--lsp"], extensions: [".dart"] },- terraform: { command: ["terraform-ls", "serve"], extensions: [".tf", ".tfvars"] },- "terraform-ls": { command: ["terraform-ls", "serve"], extensions: [".tf", ".tfvars"] },- prisma: { command: ["prisma", "language-server"], extensions: [".prisma"] },- "ocaml-lsp": { command: ["ocamllsp"], extensions: [".ml", ".mli"] },- texlab: { command: ["texlab"], extensions: [".tex", ".bib"] },- dockerfile: { command: ["docker-langserver", "--stdio"], extensions: [".dockerfile"] },- gleam: { command: ["gleam", "lsp"], extensions: [".gleam"] },- "clojure-lsp": {- command: ["clojure-lsp", "listen"],- extensions: [".clj", ".cljs", ".cljc", ".edn"],- },- nixd: { command: ["nixd"], extensions: [".nix"] },- tinymist: { command: ["tinymist"], extensions: [".typ", ".typc"] },- "haskell-language-server": {- command: ["haskell-language-server-wrapper", "--lsp"],- extensions: [".hs", ".lhs"],- },- "kotlin-ls": { command: ["kotlin-lsp"], extensions: [".kt", ".kts"] },-};--export const AUTO_INSTALLABLE_SERVERS: Record<string, string[]> = {- typescript: ["npm", "install", "-g", "typescript-language-server", "typescript"],- vue: ["npm", "install", "-g", "@vue/language-server"],- eslint: ["npm", "install", "-g", "vscode-langservers-extracted"],- oxlint: ["npm", "install", "-g", "oxlint"],- biome: ["npm", "install", "-g", "@biomejs/biome"],- svelte: ["npm", "install", "-g", "svelte-language-server"],- astro: ["npm", "install", "-g", "@astrojs/language-server"],- "bash-ls": ["npm", "install", "-g", "bash-language-server"],- bash: ["npm", "install", "-g", "bash-language-server"],- "yaml-ls": ["npm", "install", "-g", "yaml-language-server"],- php: ["npm", "install", "-g", "intelephense"],- prisma: ["npm", "install", "-g", "prisma"],- dockerfile: ["npm", "install", "-g", "dockerfile-language-server-nodejs"],- gopls: ["go", "install", "golang.org/x/tools/gopls@latest"],- pyright: ["pip", "install", "pyright"],- basedpyright: ["pip", "install", "basedpyright"],- ruff: ["pip", "install", "ruff"],- ty: ["pip", "install", "ty"],- "ruby-lsp": ["gem", "install", "ruby-lsp"],- "ocaml-lsp": ["opam", "install", "ocaml-lsp-server"],-};diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-installation.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-installation.tsdeleted file mode 100644index 622a174d..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-installation.ts+++ /dev/null@@ -1,57 +0,0 @@-import { existsSync } from "node:fs";-import { delimiter, join } from "node:path";--export function getAdditionalPathBases(workingDirectory: string): string[] {- return [join(workingDirectory, "node_modules", ".bin")];-}--export function isServerInstalled(command: string[]): boolean {- if (command.length === 0) return false;-- const [cmd] = command;- if (!cmd) return false;-- if (cmd.includes("/") || cmd.includes("\\")) {- if (existsSync(cmd)) return true;- }-- const isWindows = process.platform === "win32";-- let exts = [""];- if (isWindows) {- const pathExt = process.env["PATHEXT"] ?? "";- if (pathExt) {- const systemExts = pathExt.split(";").filter(Boolean);- exts = [...new Set([...exts, ...systemExts, ".exe", ".cmd", ".bat", ".ps1"])];- } else {- exts = ["", ".exe", ".cmd", ".bat", ".ps1"];- }- }-- let pathEnv = process.env["PATH"] ?? "";- if (isWindows && !pathEnv) {- pathEnv = process.env["Path"] ?? "";- }-- const paths = pathEnv.split(delimiter);-- for (const p of paths) {- for (const suffix of exts) {- if (existsSync(join(p, cmd + suffix))) {- return true;- }- }- }-- for (const base of getAdditionalPathBases(process.cwd())) {- for (const suffix of exts) {- if (existsSync(join(base, cmd + suffix))) {- return true;- }- }- }-- if (cmd === "node") return true;-- return false;-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-resolution.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-resolution.tsdeleted file mode 100644index e08478c9..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-resolution.ts+++ /dev/null@@ -1,104 +0,0 @@-import { getDisabledServerIds, getMergedServers } from "./config-loader.js";-import { BUILTIN_SERVERS, LSP_INSTALL_HINTS } from "./server-definitions.js";-import { isServerInstalled } from "./server-installation.js";-import type { ServerLookupResult } from "./types.js";--export function findServerForExtension(ext: string): ServerLookupResult {- const servers = getMergedServers();-- for (const server of servers) {- if (server.extensions.includes(ext) && isServerInstalled(server.command)) {- const resolvedServer = {- id: server.id,- command: server.command,- extensions: server.extensions,- priority: server.priority,- };- if (server.env !== undefined) {- return {- status: "found",- server: {- ...resolvedServer,- env: server.env,- ...(server.initialization === undefined ? {} : { initialization: server.initialization }),- },- };- }- return {- status: "found",- server: {- ...resolvedServer,- ...(server.initialization === undefined ? {} : { initialization: server.initialization }),- },- };- }- }-- for (const server of servers) {- if (server.extensions.includes(ext)) {- const installHint =- LSP_INSTALL_HINTS[server.id] ?? `Install '${server.command[0]}' and ensure it's in your PATH`;- return {- status: "not_installed",- server: {- id: server.id,- command: server.command,- extensions: server.extensions,- },- installHint,- };- }- }-- const availableServers = [...new Set(servers.map((s) => s.id))];- return {- status: "not_configured",- extension: ext,- availableServers,- };-}--export interface ServerStatus {- id: string;- installed: boolean;- extensions: string[];- disabled: boolean;- source: string;- priority: number;-}--export function getAllServers(): ServerStatus[] {- const servers = getMergedServers();- const disabled = getDisabledServerIds();-- const result: ServerStatus[] = [];- const seen = new Set<string>();-- for (const server of servers) {- if (seen.has(server.id)) continue;- result.push({- id: server.id,- installed: isServerInstalled(server.command),- extensions: server.extensions,- disabled: false,- source: server.source,- priority: server.priority,- });- seen.add(server.id);- }-- for (const id of disabled) {- if (seen.has(id)) continue;- const builtin = BUILTIN_SERVERS[id];- result.push({- id,- installed: builtin ? isServerInstalled(builtin.command) : false,- extensions: builtin?.extensions ?? [],- disabled: true,- source: "disabled",- priority: 0,- });- }-- return result;-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/transport.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/transport.tsdeleted file mode 100644index 49ecf7ea..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/transport.ts+++ /dev/null@@ -1,285 +0,0 @@-import { delimiter } from "node:path";--import { reportBestEffortCleanupError } from "./cleanup-errors.js";-import { REQUEST_TIMEOUT_MS, STOP_HARD_KILL_TIMEOUT_MS, STOP_SIGKILL_GRACE_MS } from "./constants.js";-import { LspConnectionClosedError, LspProcessExitedError, LspRequestTimeoutError } from "./errors.js";-import { JsonRpcConnection } from "./json-rpc-connection.js";-import { type SpawnedProcess, spawnProcess } from "./process.js";-import { getAdditionalPathBases } from "./server-installation.js";-import type { Diagnostic, ResolvedServer } from "./types.js";--interface ConfigurationItem {- section?: string;-}--interface DiagnosticsParams {- uri: string;- diagnostics: Diagnostic[];-}--function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === "object" && value !== null && !Array.isArray(value);-}--function parseConfigurationItems(params: unknown): ConfigurationItem[] {- if (!isRecord(params) || !Array.isArray(params["items"])) return [];- const items: ConfigurationItem[] = [];- for (const item of params["items"]) {- if (!isRecord(item)) continue;- const section = item["section"];- items.push(section === undefined || typeof section !== "string" ? {} : { section });- }- return items;-}--function parseDiagnosticsParams(params: unknown): DiagnosticsParams | null {- if (!isRecord(params) || typeof params["uri"] !== "string") return null;- const diagnostics = Array.isArray(params["diagnostics"]) ? params["diagnostics"].filter(isDiagnostic) : [];- return { uri: params["uri"], diagnostics };-}--export class LspClientTransport {- protected proc: SpawnedProcess | null = null;- protected connection: JsonRpcConnection | null = null;- protected readonly stderrBuffer: string[] = [];- protected processExited = false;- protected readonly diagnosticsStore = new Map<string, Diagnostic[]>();-- constructor(- protected readonly root: string,- protected readonly server: ResolvedServer,- ) {}-- pid(): number | undefined {- return this.proc?.pid;- }-- command(): string[] {- return [...this.server.command];- }-- async start(): Promise<void> {- const env: Record<string, string | undefined> = {- ...process.env,- ...this.server.env,- };- const pathValue = process.platform === "win32" ? (env["PATH"] ?? env["Path"] ?? "") : (env["PATH"] ?? "");- const spawnPath = [pathValue, ...getAdditionalPathBases(this.root)].filter(Boolean).join(delimiter);- if (process.platform === "win32" && env["Path"] !== undefined) {- env["Path"] = spawnPath;- }- env["PATH"] = spawnPath;-- this.proc = spawnProcess(this.server.command, {- cwd: this.root,- env,- });- this.startStderrReading();-- await new Promise<void>((resolve) => setTimeout(resolve, 100));-- if (this.proc.exitCode !== null) {- const stderr = this.stderrBuffer.join("\n");- throw new LspProcessExitedError(this.server.id, this.root, this.proc.exitCode, stderr.slice(-2000));- }-- this.connection = new JsonRpcConnection(this.proc.stdout, this.proc.stdin);-- this.connection.onNotification("textDocument/publishDiagnostics", (params) => {- const diagnosticsParams = parseDiagnosticsParams(params);- if (diagnosticsParams?.uri) {- this.diagnosticsStore.set(diagnosticsParams.uri, diagnosticsParams.diagnostics);- }- });-- this.connection.onRequest("workspace/configuration", (params) => {- const items = parseConfigurationItems(params);- return items.map((item) => {- if (item.section === "json") return { validate: { enable: true } };- return {};- });- });-- this.connection.onRequest("client/registerCapability", () => null);- this.connection.onRequest("window/workDoneProgress/create", () => null);-- this.connection.onClose(() => {- this.processExited = true;- });-- this.connection.onError((error) => {- reportBestEffortCleanupError("connection error notification", error);- });-- this.connection.listen();- }-- protected startStderrReading(): void {- if (!this.proc) return;- this.proc.stderr.setEncoding("utf-8");- this.proc.stderr.on("data", (chunk: string) => {- this.stderrBuffer.push(chunk);- if (this.stderrBuffer.length > 100) {- this.stderrBuffer.shift();- }- });- }-- private isConnectionClosedError(error: unknown): error is Error {- if (!(error instanceof Error)) {- return false;- }- const code = "code" in error && typeof error.code === "string" ? error.code : undefined;- return (- code === "ERR_STREAM_DESTROYED" ||- /connection closed|connection is disposed|stream was destroyed/i.test(error.message)- );- }-- protected sendRequest<T>(method: string): Promise<T>;- protected sendRequest<T>(method: string, params: unknown): Promise<T>;- protected async sendRequest<T>(method: string, ...args: [] | [unknown]): Promise<T> {- if (!this.connection) throw new Error("LSP client not started");-- if (this.processExited || (this.proc && this.proc.exitCode !== null)) {- const stderrTail = this.stderrBuffer.slice(-10).join("\n");- throw new LspProcessExitedError(- this.server.id,- this.root,- this.proc?.exitCode ?? null,- stderrTail || undefined,- );- }-- let timeoutHandle: NodeJS.Timeout | null = null;- const timeoutPromise = new Promise<never>((_, reject) => {- timeoutHandle = setTimeout(() => {- const stderrTail = this.stderrBuffer.slice(-5).join("\n");- reject(new LspRequestTimeoutError(method, stderrTail || undefined));- }, REQUEST_TIMEOUT_MS);- });-- try {- const requestPromise =- args.length === 0- ? this.connection.sendRequest<T>(method)- : this.connection.sendRequest<T>(method, args[0]);- const result = await Promise.race([requestPromise, timeoutPromise]);- if (timeoutHandle !== null) clearTimeout(timeoutHandle);- return result;- } catch (error) {- if (timeoutHandle !== null) clearTimeout(timeoutHandle);- if (this.processExited || (this.proc && this.proc.exitCode !== null)) {- throw new LspProcessExitedError(- this.server.id,- this.root,- this.proc?.exitCode ?? null,- this.stderrBuffer.slice(-10).join("\n") || undefined,- );- }- if (this.isConnectionClosedError(error)) {- throw new LspConnectionClosedError(this.server.id, this.root, error.message);- }- throw error;- }- }-- protected sendNotification(method: string): Promise<void>;- protected sendNotification(method: string, params: unknown): Promise<void>;- protected async sendNotification(method: string, ...args: [] | [unknown]): Promise<void> {- if (!this.connection) return;- if (this.processExited || (this.proc && this.proc.exitCode !== null)) return;- try {- if (args.length === 0) {- await this.connection.sendNotification(method);- } else {- await this.connection.sendNotification(method, args[0]);- }- } catch (error) {- if (this.isConnectionClosedError(error)) {- throw new LspConnectionClosedError(this.server.id, this.root, error.message);- }- throw error;- }- }-- isAlive(): boolean {- return this.proc !== null && !this.processExited && this.proc.exitCode === null;- }-- async stop(): Promise<void> {- if (this.connection) {- try {- await this.sendRequest<null>("shutdown");- } catch (error) {- reportBestEffortCleanupError("shutdown request", error);- }- try {- await this.sendNotification("exit");- } catch (error) {- reportBestEffortCleanupError("exit notification", error);- }- try {- this.connection.dispose();- } catch (error) {- reportBestEffortCleanupError("connection dispose", error);- }- this.connection = null;- }-- const proc = this.proc;- if (proc) {- this.proc = null;- let exitedBeforeTimeout = false;- try {- proc.kill();- let timeoutId: NodeJS.Timeout | undefined;- const timeoutPromise = new Promise<void>((resolve) => {- timeoutId = setTimeout(resolve, STOP_HARD_KILL_TIMEOUT_MS);- });- await Promise.race([- proc.exited- .then(() => {- exitedBeforeTimeout = true;- })- .finally(() => {- if (timeoutId) clearTimeout(timeoutId);- }),- timeoutPromise,- ]);- if (!exitedBeforeTimeout) {- try {- proc.kill("SIGKILL");- await Promise.race([- proc.exited,- new Promise<void>((resolve) => setTimeout(resolve, STOP_SIGKILL_GRACE_MS)),- ]);- } catch (error) {- reportBestEffortCleanupError("hard process kill", error);- }- }- } catch (error) {- reportBestEffortCleanupError("process stop", error);- }- }-- this.processExited = true;- this.diagnosticsStore.clear();- }-- getStoredDiagnostics(uri: string): Diagnostic[] {- return this.diagnosticsStore.get(uri) ?? [];- }-}--function isDiagnostic(value: unknown): value is Diagnostic {- return isRecord(value) && isRange(value["range"]) && typeof value["message"] === "string";-}--function isRange(value: unknown): value is Diagnostic["range"] {- return isRecord(value) && isPosition(value["start"]) && isPosition(value["end"]);-}--function isPosition(value: unknown): value is Diagnostic["range"]["start"] {- return isRecord(value) && typeof value["line"] === "number" && typeof value["character"] === "number";-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/types.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/types.tsdeleted file mode 100644index 9fe67afe..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/types.ts+++ /dev/null@@ -1,126 +0,0 @@-export interface LspServerConfig {- id: string;- command: string[];- extensions: string[];- disabled?: boolean;- env?: Record<string, string>;- initialization?: Record<string, unknown>;-}--export interface ResolvedServer {- id: string;- command: string[];- extensions: string[];- priority: number;- env?: Record<string, string>;- initialization?: Record<string, unknown>;-}--export interface ServerLookupInfo {- id: string;- command: string[];- extensions: string[];-}--export type ServerLookupResult =- | { status: "found"; server: ResolvedServer }- | { status: "not_configured"; extension: string; availableServers: string[] }- | { status: "not_installed"; server: ServerLookupInfo; installHint: string };--export interface Position {- line: number;- character: number;-}--export interface Range {- start: Position;- end: Position;-}--export interface Location {- uri: string;- range: Range;-}--export interface LocationLink {- targetUri: string;- targetRange: Range;- targetSelectionRange: Range;- originSelectionRange?: Range;-}--export interface SymbolInfo {- name: string;- kind: number;- location: Location;- containerName?: string;-}--export interface DocumentSymbol {- name: string;- kind: number;- range: Range;- selectionRange: Range;- children?: DocumentSymbol[];-}--export interface Diagnostic {- range: Range;- severity?: number;- code?: string | number;- source?: string;- message: string;-}--export interface TextDocumentIdentifier {- uri: string;-}--export interface VersionedTextDocumentIdentifier extends TextDocumentIdentifier {- version: number | null;-}--export interface TextEdit {- range: Range;- newText: string;-}--export interface TextDocumentEdit {- textDocument: VersionedTextDocumentIdentifier;- edits: TextEdit[];-}--export interface CreateFile {- kind: "create";- uri: string;- options?: { overwrite?: boolean; ignoreIfExists?: boolean };-}--export interface RenameFile {- kind: "rename";- oldUri: string;- newUri: string;- options?: { overwrite?: boolean; ignoreIfExists?: boolean };-}--export interface DeleteFile {- kind: "delete";- uri: string;- options?: { recursive?: boolean; ignoreIfNotExists?: boolean };-}--export interface WorkspaceEdit {- changes?: { [uri: string]: TextEdit[] };- documentChanges?: (TextDocumentEdit | CreateFile | RenameFile | DeleteFile)[];-}--export interface PrepareRenameResult {- range: Range;- placeholder?: string;-}--export interface PrepareRenameDefaultBehavior {- defaultBehavior: boolean;-}--export type SeverityFilter = "error" | "warning" | "information" | "hint" | "all";diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/utils.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/utils.tsdeleted file mode 100644index 94428b2e..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/utils.ts+++ /dev/null@@ -1,40 +0,0 @@-import { LspProcessExitedError } from "./errors.js";--const RUST_SRC_REPAIR_MESSAGE = [- "rust-analyzer exited while loading Rust standard library sources.",- "",- "Repair rust-src for the active toolchain:",- " rustup component remove rust-src",- " rustup component add rust-src",-];--export function errorMessage(error: unknown): string {- return error instanceof Error ? error.message : String(error);-}--export function formatKnownLspStartupFailure(error: unknown): string | null {- if (!(error instanceof LspProcessExitedError)) return null;- if (error.serverId !== "rust") return null;-- const details = error.stderrTail ?? error.message;- const lowerDetails = details.toLowerCase();- const isRustSrcFailure =- lowerDetails.includes("rust-src") &&- (lowerDetails.includes("failed to install component") ||- lowerDetails.includes("detected conflict") ||- lowerDetails.includes("can't load standard library") ||- lowerDetails.includes("try installing") ||- lowerDetails.includes("sysroot"));-- if (!isRustSrcFailure) return null;-- return [...RUST_SRC_REPAIR_MESSAGE, "", "Original stderr tail:", details].join("\n");-}--export function handleMissingDependencyError(error: unknown): string | null {- const knownStartupFailure = formatKnownLspStartupFailure(error);- if (knownStartupFailure) return knownStartupFailure;-- const message = errorMessage(error);- return message.includes("NOT INSTALLED") || message.includes("No LSP server configured") ? message : null;-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/workspace-edit.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/workspace-edit.tsdeleted file mode 100644index fccf7bfb..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/workspace-edit.ts+++ /dev/null@@ -1,132 +0,0 @@-import { readFileSync, unlinkSync, writeFileSync } from "node:fs";--import { uriToPath } from "./formatters.js";-import type { TextEdit, WorkspaceEdit } from "./types.js";--export interface ApplyResult {- success: boolean;- filesModified: string[];- totalEdits: number;- errors: string[];-}--interface FileApplyResult {- success: boolean;- editCount: number;- error?: string;-}--function applyTextEditsToFile(filePath: string, edits: TextEdit[]): FileApplyResult {- try {- const content = readFileSync(filePath, "utf-8");- const lines = content.split("\n");-- const sortedEdits = [...edits].sort((a, b) => {- if (b.range.start.line !== a.range.start.line) {- return b.range.start.line - a.range.start.line;- }- return b.range.start.character - a.range.start.character;- });-- for (const edit of sortedEdits) {- const startLine = edit.range.start.line;- const startChar = edit.range.start.character;- const endLine = edit.range.end.line;- const endChar = edit.range.end.character;-- if (startLine === endLine) {- const line = lines[startLine] ?? "";- lines[startLine] = line.substring(0, startChar) + edit.newText + line.substring(endChar);- } else {- const firstLine = lines[startLine] ?? "";- const lastLine = lines[endLine] ?? "";- const newContent = firstLine.substring(0, startChar) + edit.newText + lastLine.substring(endChar);- lines.splice(startLine, endLine - startLine + 1, ...newContent.split("\n"));- }- }-- writeFileSync(filePath, lines.join("\n"), "utf-8");- return { success: true, editCount: edits.length };- } catch (err) {- return {- success: false,- editCount: 0,- error: err instanceof Error ? err.message : String(err),- };- }-}--export function applyWorkspaceEdit(edit: WorkspaceEdit | null): ApplyResult {- if (!edit) {- return { success: false, filesModified: [], totalEdits: 0, errors: ["No edit provided"] };- }-- const result: ApplyResult = { success: true, filesModified: [], totalEdits: 0, errors: [] };-- if (edit.changes) {- for (const [uri, edits] of Object.entries(edit.changes)) {- const filePath = uriToPath(uri);- const applyResult = applyTextEditsToFile(filePath, edits);-- if (applyResult.success) {- result.filesModified.push(filePath);- result.totalEdits += applyResult.editCount;- } else {- result.success = false;- result.errors.push(`${filePath}: ${applyResult.error}`);- }- }- }-- if (edit.documentChanges) {- for (const change of edit.documentChanges) {- if (!("kind" in change)) {- const filePath = uriToPath(change.textDocument.uri);- const applyResult = applyTextEditsToFile(filePath, change.edits);-- if (applyResult.success) {- result.filesModified.push(filePath);- result.totalEdits += applyResult.editCount;- } else {- result.success = false;- result.errors.push(`${filePath}: ${applyResult.error}`);- }- continue;- }-- if (change.kind === "create") {- try {- const filePath = uriToPath(change.uri);- writeFileSync(filePath, "", "utf-8");- result.filesModified.push(filePath);- } catch (err) {- result.success = false;- result.errors.push(`Create ${change.uri}: ${String(err)}`);- }- } else if (change.kind === "rename") {- try {- const oldPath = uriToPath(change.oldUri);- const newPath = uriToPath(change.newUri);- const content = readFileSync(oldPath, "utf-8");- writeFileSync(newPath, content, "utf-8");- unlinkSync(oldPath);- result.filesModified.push(newPath);- } catch (err) {- result.success = false;- result.errors.push(`Rename ${change.oldUri}: ${String(err)}`);- }- } else if (change.kind === "delete") {- try {- const filePath = uriToPath(change.uri);- unlinkSync(filePath);- result.filesModified.push(filePath);- } catch (err) {- result.success = false;- result.errors.push(`Delete ${change.uri}: ${String(err)}`);- }- }- }- }-- return result;-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/mcp-lifecycle-log.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/mcp-lifecycle-log.tsdeleted file mode 100644index 54101b7b..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/mcp-lifecycle-log.ts+++ /dev/null@@ -1,36 +0,0 @@-import { appendFileSync, renameSync, statSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";--type LogFieldValue = boolean | number | string | null;--const LOG_FILE_NAME = "omo-codex-lsp-mcp.log";-const MAX_LOG_BYTES = 5 * 1024 * 1024;--export function mcpLifecycleLogPath(): string {- return join(tmpdir(), LOG_FILE_NAME);-}--export function writeMcpLifecycleLog(event: string, fields: Record<string, LogFieldValue> = {}): void {- const path = mcpLifecycleLogPath();- try {- rotateLogIfNeeded(path);- appendFileSync(- path,- `${JSON.stringify({ ts: new Date().toISOString(), event, pid: process.pid, ppid: process.ppid, ...fields })}\n`,- );- } catch (error) {- if (error instanceof Error) return;- return;- }-}--function rotateLogIfNeeded(path: string): void {- try {- if (statSync(path).size < MAX_LOG_BYTES) return;- renameSync(path, `${path}.1`);- } catch (error) {- if (error instanceof Error) return;- return;- }-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/mcp.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/mcp.tsdeleted file mode 100644index 68fd9993..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/mcp.ts+++ /dev/null@@ -1,188 +0,0 @@-import { createInterface } from "node:readline";--import { coerceToolArguments, executeLspTool, LSP_MCP_TOOLS, type TextContent } from "./tools.js";--export type JsonRpcId = string | number | null;-export type McpLifecycleLog = (event: string, fields?: Record<string, boolean | number | string | null>) => void;--export interface McpToolDescriptor {- name: string;- title: string;- description: string;- inputSchema: unknown;-}--export interface JsonRpcError {- code: number;- message: string;- data?: unknown;-}--export interface JsonRpcResult {- capabilities?: Record<string, unknown>;- serverInfo?: Record<string, unknown>;- protocolVersion?: string;- tools?: McpToolDescriptor[];- content?: TextContent[];- isError?: boolean;- [key: string]: unknown;-}--export interface JsonRpcResponse {- jsonrpc: "2.0";- id: JsonRpcId;- result?: JsonRpcResult;- error?: JsonRpcError;-}--export interface McpStdioServerOptions {- readonly idleTimeoutMs?: number;- readonly onIdleTimeout?: () => void | Promise<void>;- readonly log?: McpLifecycleLog;-}--const SERVER_NAME = "lsp";-const SERVER_VERSION = "0.1.0";-const DEFAULT_IDLE_TIMEOUT_MS = 10 * 60_000;-const noopLog: McpLifecycleLog = () => {};--export async function handleLspMcpRequest(input: unknown): Promise<JsonRpcResponse | undefined> {- if (!isRecord(input)) {- return errorResponse(null, -32600, "Invalid Request");- }-- const id = jsonRpcId(input["id"]);- const method = input["method"];- if (method === "notifications/initialized") return undefined;- if (method === "ping") return successResponse(id, {});- if (method === "initialize") {- const protocolVersion = requestedProtocolVersion(input["params"]);- return successResponse(id, {- capabilities: { tools: { listChanged: false } },- serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },- protocolVersion,- });- }-- if (method === "tools/list") {- return successResponse(id, { tools: LSP_MCP_TOOLS.map(describeTool) });- }-- if (method === "tools/call") {- return handleToolCall(id, input["params"]);- }-- return errorResponse(id, -32601, `Method not found: ${String(method)}`);-}--export async function runMcpStdioServer(- input: NodeJS.ReadableStream = process.stdin,- output: NodeJS.WritableStream = process.stdout,- options: McpStdioServerOptions = {},-): Promise<void> {- const log = options.log ?? noopLog;- const idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;- let idleTimer: NodeJS.Timeout | null = null;- let closed = false;-- const clearIdleTimer = () => {- if (idleTimer === null) return;- clearTimeout(idleTimer);- idleTimer = null;- };- const armIdleTimer = () => {- clearIdleTimer();- if (idleTimeoutMs <= 0) return;- idleTimer = setTimeout(() => {- closed = true;- log("idle_timeout", { idle_timeout_ms: idleTimeoutMs });- void options.onIdleTimeout?.();- }, idleTimeoutMs);- idleTimer.unref();- };-- log("stdio_started", { cwd: process.cwd(), idle_timeout_ms: idleTimeoutMs });- armIdleTimer();- const lines = createInterface({ input, crlfDelay: Number.POSITIVE_INFINITY });- try {- for await (const line of lines) {- if (closed) break;- armIdleTimer();- if (!line.trim()) continue;- let parsed: unknown;- try {- parsed = JSON.parse(line);- } catch (error) {- log("parse_error", { message: messageFromError(error) });- output.write(`${JSON.stringify(errorResponse(null, -32700, "Parse error", messageFromError(error)))}\n`);- continue;- }-- const id = isRecord(parsed) ? jsonRpcId(parsed["id"]) : null;- const method = isRecord(parsed) && typeof parsed["method"] === "string" ? parsed["method"] : null;- log("request", { id: id === null ? null : String(id), method });- const response = await handleLspMcpRequest(parsed);- if (response) {- output.write(`${JSON.stringify(response)}\n`);- log("response", { id: String(response.id), method, is_error: response.error !== undefined });- }- }- } finally {- clearIdleTimer();- log("stdio_stopped");- }-}--async function handleToolCall(id: JsonRpcId, params: unknown): Promise<JsonRpcResponse> {- if (!isRecord(params) || typeof params["name"] !== "string") {- return errorResponse(id, -32602, "tools/call requires params.name");- }-- try {- const result = await executeLspTool(params["name"], coerceToolArguments(params["arguments"]));- return successResponse(id, {- content: result.content,- isError: result.isError ?? false,- details: result.details,- });- } catch (error) {- return successResponse(id, {- content: [{ type: "text", text: messageFromError(error) }],- isError: true,- });- }-}--function describeTool(tool: (typeof LSP_MCP_TOOLS)[number]): McpToolDescriptor {- return {- name: tool.name,- title: tool.title,- description: tool.description,- inputSchema: tool.inputSchema,- };-}--function successResponse(id: JsonRpcId, result: JsonRpcResult): JsonRpcResponse {- return { jsonrpc: "2.0", id, result };-}--function errorResponse(id: JsonRpcId, code: number, message: string, data?: unknown): JsonRpcResponse {- return { jsonrpc: "2.0", id, error: data === undefined ? { code, message } : { code, message, data } };-}--function requestedProtocolVersion(params: unknown): string {- if (!isRecord(params) || typeof params["protocolVersion"] !== "string") return "2024-11-05";- return params["protocolVersion"];-}--function jsonRpcId(value: unknown): JsonRpcId {- return typeof value === "string" || typeof value === "number" || value === null ? value : null;-}--function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === "object" && value !== null && !Array.isArray(value);-}--function messageFromError(error: unknown): string {- return error instanceof Error ? error.message : String(error);-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/tools.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/tools.tsdeleted file mode 100644index 87239239..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/tools.ts+++ /dev/null@@ -1,669 +0,0 @@-import { resolve } from "node:path";--import { isDirectoryPath, type WithLspClientOptions, withLspClient } from "./lsp/client-wrapper.js";-import { DEFAULT_MAX_DIAGNOSTICS, DEFAULT_MAX_REFERENCES, DEFAULT_MAX_SYMBOLS } from "./lsp/constants.js";-import { aggregateDiagnosticsForDirectory } from "./lsp/directory-diagnostics.js";-import {- filterDiagnosticsBySeverity,- formatApplyResult,- formatDiagnostic,- formatDocumentSymbol,- formatLocation,- formatPrepareRenameResult,- formatSymbolInfo,-} from "./lsp/formatters.js";-import { inferExtensionFromDirectory } from "./lsp/infer-extension.js";-import { getLspManager } from "./lsp/manager.js";-import { getAllServers } from "./lsp/server-resolution.js";-import type {- Diagnostic,- DocumentSymbol,- Location,- LocationLink,- PrepareRenameDefaultBehavior,- PrepareRenameResult,- Range,- SeverityFilter,- SymbolInfo,- WorkspaceEdit,-} from "./lsp/types.js";-import { handleMissingDependencyError } from "./lsp/utils.js";-import { type ApplyResult, applyWorkspaceEdit } from "./lsp/workspace-edit.js";--export interface TextContent {- type: "text";- text: string;-}--export interface ToolExecutionResult {- content: TextContent[];- isError?: boolean;- details?: unknown;-}--export interface JsonSchema {- type: string;- description?: string;- properties?: Record<string, JsonSchema>;- required?: string[];- items?: JsonSchema;- enum?: string[];-}--export interface LspMcpTool {- name: string;- aliases?: string[];- title: string;- description: string;- inputSchema: JsonSchema;- execute(params: Record<string, unknown>, signal?: AbortSignal): Promise<ToolExecutionResult>;-}--export interface LspDiagnosticsDetails {- filePath: string;- severity: SeverityFilter;- mode: "file" | "directory";- diagnostics: Array<{ file: string; diagnostic: Diagnostic }>;- totalDiagnostics: number;- truncated: boolean;- error?: string;- errorKind?: "missing_dependency" | "no_files" | "invalid_path";-}--export interface LspGotoDefinitionDetails {- filePath: string;- line: number;- character: number;- locations: Array<Location | LocationLink>;- error?: string;- errorKind?: "missing_dependency";-}--export interface LspFindReferencesDetails {- filePath: string;- line: number;- character: number;- references: Location[];- totalReferences: number;- truncated: boolean;- error?: string;- errorKind?: "missing_dependency";-}--export interface LspSymbolsDetails {- filePath: string;- scope: "document" | "workspace";- query?: string;- symbols: Array<DocumentSymbol | SymbolInfo>;- totalSymbols: number;- truncated: boolean;- error?: string;- errorKind?: "missing_dependency" | "missing_query";-}--export interface LspPrepareRenameDetails {- filePath: string;- line: number;- character: number;- result: PrepareRenameResult | PrepareRenameDefaultBehavior | Range | null;- error?: string;- errorKind?: "missing_dependency";-}--export interface LspRenameDetails {- filePath: string;- line: number;- character: number;- newName: string;- apply: ApplyResult | null;- edit: WorkspaceEdit | null;- error?: string;- errorKind?: "missing_dependency";-}--const objectSchema = (properties: Record<string, JsonSchema>, required: string[] = []): JsonSchema => ({- type: "object",- properties,- required,-});--function text(text: string, details?: unknown, isError = false): ToolExecutionResult {- return { content: [{ type: "text", text }], details, isError };-}--function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === "object" && value !== null && !Array.isArray(value);-}--function requireString(params: Record<string, unknown>, key: string): string {- const value = params[key];- if (typeof value !== "string" || value.length === 0) {- throw new Error(`Missing required string parameter '${key}'`);- }- return value;-}--function optionalString(params: Record<string, unknown>, key: string): string | undefined {- const value = params[key];- return typeof value === "string" ? value : undefined;-}--function requireNumber(params: Record<string, unknown>, key: string): number {- const value = params[key];- if (typeof value !== "number" || !Number.isFinite(value)) {- throw new Error(`Missing required number parameter '${key}'`);- }- return value;-}--function optionalNumber(params: Record<string, unknown>, key: string): number | undefined {- const value = params[key];- return typeof value === "number" && Number.isFinite(value) ? value : undefined;-}--function optionalBoolean(params: Record<string, unknown>, key: string): boolean | undefined {- const value = params[key];- return typeof value === "boolean" ? value : undefined;-}--function isSeverityFilter(value: unknown): value is SeverityFilter {- return value === "error" || value === "warning" || value === "information" || value === "hint" || value === "all";-}--function severityFilter(params: Record<string, unknown>): SeverityFilter {- const value = params["severity"];- if (isSeverityFilter(value)) return value;- return "all";-}--function clientOptions(signal: AbortSignal | undefined): WithLspClientOptions {- return signal === undefined ? {} : { signal };-}--function asDiagnosticArray(result: { items?: Diagnostic[] } | Diagnostic[] | null | undefined): Diagnostic[] {- if (!result) return [];- if (Array.isArray(result)) return result;- return result.items ?? [];-}--function isDocumentSymbol(symbol: DocumentSymbol | SymbolInfo): symbol is DocumentSymbol {- return "range" in symbol;-}--async function executeLspStatus(): Promise<ToolExecutionResult> {- const servers = getAllServers();- const snapshots = getLspManager().getSnapshot();- const installed = servers.filter((server) => server.installed && !server.disabled);- const configuredLines = servers.map((server) => {- const state = server.disabled ? "disabled" : server.installed ? "installed" : "missing";- return `- ${server.id}: ${state}; source=${server.source}; extensions=${server.extensions.join(", ")}`;- });- const activeLines = snapshots.map((snapshot) => {- const state = snapshot.alive ? (snapshot.isInitializing ? "initializing" : "alive") : "dead";- return `- ${snapshot.serverId}: ${state}; root=${snapshot.root}; refs=${snapshot.refCount}`;- });- const lines = [- `Configured LSP servers: ${servers.length}`,- `Installed LSP servers: ${installed.length}`,- "",- ...configuredLines,- "",- `Active LSP clients: ${snapshots.length}`,- ...activeLines,- ];- return text(lines.join("\n"), { servers, snapshots });-}--export async function executeLspDiagnostics(- params: Record<string, unknown>,- signal?: AbortSignal,-): Promise<ToolExecutionResult> {- const filePath = requireString(params, "filePath");- const severity = severityFilter(params);-- try {- const absPath = resolve(filePath);- if (isDirectoryPath(absPath)) {- const extension = inferExtensionFromDirectory(absPath);- if (!extension) {- const message = `No supported source files found in directory: ${absPath}`;- const details: LspDiagnosticsDetails = {- filePath,- severity,- mode: "directory",- diagnostics: [],- totalDiagnostics: 0,- truncated: false,- error: message,- errorKind: "no_files",- };- return text(message, details);- }-- const output = await aggregateDiagnosticsForDirectory(absPath, extension, severity);- const details: LspDiagnosticsDetails = {- filePath,- severity,- mode: "directory",- diagnostics: [],- totalDiagnostics: 0,- truncated: false,- };- return text(output, details);- }-- const result = await withLspClient(- filePath,- async (client) => client.diagnostics(filePath),- "diagnostics",- clientOptions(signal),- );- const diagnostics = filterDiagnosticsBySeverity(asDiagnosticArray(result), severity);- const total = diagnostics.length;- const truncated = total > DEFAULT_MAX_DIAGNOSTICS;- const limited = truncated ? diagnostics.slice(0, DEFAULT_MAX_DIAGNOSTICS) : diagnostics;- const output =- total === 0- ? "No diagnostics found"- : [- ...(truncated ? [`Found ${total} diagnostics (showing first ${DEFAULT_MAX_DIAGNOSTICS}):`] : []),- ...limited.map(formatDiagnostic),- ].join("\n");- const details: LspDiagnosticsDetails = {- filePath,- severity,- mode: "file",- diagnostics: diagnostics.map((diagnostic) => ({ file: absPath, diagnostic })),- totalDiagnostics: total,- truncated,- };- return text(output, details);- } catch (error) {- const message = handleMissingDependencyError(error);- if (message) {- const details: LspDiagnosticsDetails = {- filePath,- severity,- mode: "file",- diagnostics: [],- totalDiagnostics: 0,- truncated: false,- error: message,- errorKind: "missing_dependency",- };- return text(message, details);- }- throw error;- }-}--async function executeLspGotoDefinition(- params: Record<string, unknown>,- signal?: AbortSignal,-): Promise<ToolExecutionResult> {- const filePath = requireString(params, "filePath");- const line = requireNumber(params, "line");- const character = requireNumber(params, "character");-- try {- const result = await withLspClient(- filePath,- async (client) => client.definition(filePath, line, character),- "definition",- clientOptions(signal),- );- const locations = !result ? [] : Array.isArray(result) ? result : [result];- const details: LspGotoDefinitionDetails = { filePath, line, character, locations };- if (locations.length === 0) return text("No definition found", details);- return text(locations.map(formatLocation).join("\n"), details);- } catch (error) {- const message = handleMissingDependencyError(error);- if (message) {- return text(message, {- filePath,- line,- character,- locations: [],- error: message,- errorKind: "missing_dependency",- });- }- throw error;- }-}--async function executeLspFindReferences(- params: Record<string, unknown>,- signal?: AbortSignal,-): Promise<ToolExecutionResult> {- const filePath = requireString(params, "filePath");- const line = requireNumber(params, "line");- const character = requireNumber(params, "character");- const includeDeclaration = optionalBoolean(params, "includeDeclaration") ?? true;-- try {- const result = await withLspClient(- filePath,- async (client) => client.references(filePath, line, character, includeDeclaration),- "references",- clientOptions(signal),- );- const references = Array.isArray(result) ? result : [];- const total = references.length;- const truncated = total > DEFAULT_MAX_REFERENCES;- const limited = truncated ? references.slice(0, DEFAULT_MAX_REFERENCES) : references;- const details: LspFindReferencesDetails = {- filePath,- line,- character,- references,- totalReferences: total,- truncated,- };- if (total === 0) return text("No references found", details);- const output = [- ...(truncated ? [`Found ${total} references (showing first ${DEFAULT_MAX_REFERENCES}):`] : []),- ...limited.map(formatLocation),- ].join("\n");- return text(output, details);- } catch (error) {- const message = handleMissingDependencyError(error);- if (message) {- return text(message, {- filePath,- line,- character,- references: [],- totalReferences: 0,- truncated: false,- error: message,- errorKind: "missing_dependency",- });- }- throw error;- }-}--async function executeLspSymbols(params: Record<string, unknown>, signal?: AbortSignal): Promise<ToolExecutionResult> {- const filePath = requireString(params, "filePath");- const rawScope = optionalString(params, "scope") ?? "document";- const scope = rawScope === "workspace" ? "workspace" : "document";- const limit = Math.min(optionalNumber(params, "limit") ?? DEFAULT_MAX_SYMBOLS, DEFAULT_MAX_SYMBOLS);-- try {- if (scope === "workspace") {- const query = optionalString(params, "query");- if (!query) {- const message = "Error: 'query' is required for workspace scope";- return text(message, {- filePath,- scope,- symbols: [],- totalSymbols: 0,- truncated: false,- error: message,- errorKind: "missing_query",- });- }-- const symbols = await withLspClient(- filePath,- async (client) => client.workspaceSymbols(query),- "workspaceSymbols",- clientOptions(signal),- );- return formatSymbolsResult(filePath, scope, symbols, limit, query);- }-- const symbols = await withLspClient(- filePath,- async (client) => client.documentSymbols(filePath),- "documentSymbols",- clientOptions(signal),- );- return formatSymbolsResult(filePath, scope, symbols, limit);- } catch (error) {- const message = handleMissingDependencyError(error);- if (message) {- const query = optionalString(params, "query");- return text(message, {- filePath,- scope,- symbols: [],- totalSymbols: 0,- truncated: false,- error: message,- errorKind: "missing_dependency",- ...(query === undefined ? {} : { query }),- });- }- throw error;- }-}--function formatSymbolsResult(- filePath: string,- scope: "document" | "workspace",- symbols: Array<DocumentSymbol | SymbolInfo>,- limit: number,- query?: string,-): ToolExecutionResult {- const total = symbols.length;- const truncated = total > limit;- const limited = truncated ? symbols.slice(0, limit) : symbols;- const details: LspSymbolsDetails = {- filePath,- scope,- symbols,- totalSymbols: total,- truncated,- ...(query === undefined ? {} : { query }),- };- if (total === 0) return text("No symbols found", details);-- const lines: string[] = [];- if (truncated) lines.push(`Found ${total} symbols (showing first ${limit}):`);- const documentSymbols = limited.filter(isDocumentSymbol);- if (documentSymbols.length === limited.length) {- lines.push(...documentSymbols.map((symbol) => formatDocumentSymbol(symbol)));- } else {- lines.push(...limited.filter((symbol): symbol is SymbolInfo => !isDocumentSymbol(symbol)).map(formatSymbolInfo));- }- return text(lines.join("\n"), details);-}--async function executeLspPrepareRename(- params: Record<string, unknown>,- signal?: AbortSignal,-): Promise<ToolExecutionResult> {- const filePath = requireString(params, "filePath");- const line = requireNumber(params, "line");- const character = requireNumber(params, "character");-- try {- const result = await withLspClient(- filePath,- async (client) => client.prepareRename(filePath, line, character),- "prepareRename",- clientOptions(signal),- );- const details: LspPrepareRenameDetails = { filePath, line, character, result };- return text(formatPrepareRenameResult(result), details);- } catch (error) {- const message = handleMissingDependencyError(error);- if (message) {- return text(message, {- filePath,- line,- character,- result: null,- error: message,- errorKind: "missing_dependency",- });- }- throw error;- }-}--async function executeLspRename(params: Record<string, unknown>, signal?: AbortSignal): Promise<ToolExecutionResult> {- const filePath = requireString(params, "filePath");- const line = requireNumber(params, "line");- const character = requireNumber(params, "character");- const newName = requireString(params, "newName");-- try {- const edit = await withLspClient(- filePath,- async (client) => client.rename(filePath, line, character, newName),- "rename",- clientOptions(signal),- );- const apply = applyWorkspaceEdit(edit);- const details: LspRenameDetails = { filePath, line, character, newName, apply, edit };- return text(formatApplyResult(apply), details, !apply.success);- } catch (error) {- const message = handleMissingDependencyError(error);- if (message) {- return text(message, {- filePath,- line,- character,- newName,- apply: null,- edit: null,- error: message,- errorKind: "missing_dependency",- });- }- throw error;- }-}--export async function executeLspTool(- name: string,- params: Record<string, unknown>,- signal?: AbortSignal,-): Promise<ToolExecutionResult> {- const tool = LSP_MCP_TOOLS.find((candidate) => matchesToolName(candidate, name));- if (!tool) throw new Error(`Unknown LSP tool: ${name}`);- return tool.execute(params, signal);-}--function matchesToolName(tool: LspMcpTool, name: string): boolean {- return tool.name === name || (tool.aliases?.includes(name) ?? false);-}--export function coerceToolArguments(value: unknown): Record<string, unknown> {- return isRecord(value) ? value : {};-}--export const LSP_MCP_TOOLS: LspMcpTool[] = [- {- name: "status",- aliases: ["lsp_status"],- title: "LSP Status",- description: "List configured and active LSP servers without starting a new language server.",- inputSchema: objectSchema({}),- execute: executeLspStatus,- },- {- name: "diagnostics",- aliases: ["lsp_diagnostics"],- title: "LSP Diagnostics",- description: "Get errors, warnings, and hints for a source file or directory.",- inputSchema: objectSchema(- {- filePath: { type: "string", description: "File or directory path to check." },- severity: {- type: "string",- enum: ["error", "warning", "information", "hint", "all"],- description: "Severity filter. Defaults to all.",- },- },- ["filePath"],- ),- execute: executeLspDiagnostics,- },- {- name: "goto_definition",- aliases: ["lsp_goto_definition"],- title: "LSP Goto Definition",- description: "Find where a symbol is defined.",- inputSchema: objectSchema(- {- filePath: { type: "string", description: "Source file containing the symbol." },- line: { type: "number", description: "1-based line number." },- character: { type: "number", description: "0-based column." },- },- ["filePath", "line", "character"],- ),- execute: executeLspGotoDefinition,- },- {- name: "find_references",- aliases: ["lsp_find_references"],- title: "LSP Find References",- description: "Find references of a symbol across the workspace.",- inputSchema: objectSchema(- {- filePath: { type: "string", description: "Source file containing the symbol." },- line: { type: "number", description: "1-based line number." },- character: { type: "number", description: "0-based column." },- includeDeclaration: { type: "boolean", description: "Include the declaration. Defaults to true." },- },- ["filePath", "line", "character"],- ),- execute: executeLspFindReferences,- },- {- name: "symbols",- aliases: ["lsp_symbols"],- title: "LSP Symbols",- description: "List document symbols or search workspace symbols.",- inputSchema: objectSchema(- {- filePath: { type: "string", description: "File path used as LSP context." },- scope: {- type: "string",- enum: ["document", "workspace"],- description: "Use document for file outline or workspace for project-wide search.",- },- query: { type: "string", description: "Workspace symbol query." },- limit: { type: "number", description: "Maximum number of symbols to return." },- },- ["filePath", "scope"],- ),- execute: executeLspSymbols,- },- {- name: "prepare_rename",- aliases: ["lsp_prepare_rename"],- title: "LSP Prepare Rename",- description: "Check whether a symbol can be renamed at a position.",- inputSchema: objectSchema(- {- filePath: { type: "string", description: "Source file path." },- line: { type: "number", description: "1-based line number." },- character: { type: "number", description: "0-based column." },- },- ["filePath", "line", "character"],- ),- execute: executeLspPrepareRename,- },- {- name: "rename",- aliases: ["lsp_rename"],- title: "LSP Rename",- description: "Rename a symbol across the workspace and apply the returned workspace edit.",- inputSchema: objectSchema(- {- filePath: { type: "string", description: "Source file path." },- line: { type: "number", description: "1-based line number." },- character: { type: "number", description: "0-based column." },- newName: { type: "string", description: "New symbol name." },- },- ["filePath", "line", "character", "newName"],- ),- execute: executeLspRename,- },-];diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/config-loader.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/config-loader.test.tsdeleted file mode 100644index 1bffd6ce..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/config-loader.test.ts+++ /dev/null@@ -1,135 +0,0 @@-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { join, sep } from "node:path";-import { afterEach, describe, expect, it } from "vitest";--import { getConfigPaths, getMergedServers } from "../src/lsp/config-loader.js";--const tempDirectories: string[] = [];--afterEach(() => {- for (const directory of tempDirectories.splice(0)) {- rmSync(directory, { recursive: true, force: true });- }-});--describe("config loader", () => {- it("uses Codex config locations instead of pi config locations", () => {- const paths = getConfigPaths();- const expectedSuffix = join(".codex", "lsp-client.json");- const piMarker = `${sep}.pi${sep}`;-- expect(paths.project.endsWith(expectedSuffix)).toBe(true);- expect(paths.user.endsWith(expectedSuffix)).toBe(true);- expect(paths.project).not.toContain(piMarker);- expect(paths.user).not.toContain(piMarker);- });-- it("supports project and user config path overrides via environment variables", () => {- const previousProject = process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"];- const previousUser = process.env["LSP_TOOLS_MCP_USER_CONFIG"];-- process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"] = "config/lsp-opencode.json";- process.env["LSP_TOOLS_MCP_USER_CONFIG"] = ".opencode/lsp.json";-- try {- const paths = getConfigPaths();-- expect(paths.project).toBe(join(process.cwd(), "config", "lsp-opencode.json"));- expect(paths.user).toBe(join(process.env["HOME"] ?? "", ".opencode", "lsp.json"));- } finally {- if (previousProject === undefined) {- delete process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"];- } else {- process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"] = previousProject;- }-- if (previousUser === undefined) {- delete process.env["LSP_TOOLS_MCP_USER_CONFIG"];- } else {- process.env["LSP_TOOLS_MCP_USER_CONFIG"] = previousUser;- }- }- });-- it("keeps absolute override paths unchanged", () => {- const previousProject = process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"];- const previousUser = process.env["LSP_TOOLS_MCP_USER_CONFIG"];- const absoluteProject = join(process.cwd(), "overrides", "project.json");- const absoluteUser = join(process.cwd(), "overrides", "user.json");-- process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"] = absoluteProject;- process.env["LSP_TOOLS_MCP_USER_CONFIG"] = absoluteUser;-- try {- const paths = getConfigPaths();-- expect(paths.project).toBe(absoluteProject);- expect(paths.user).toBe(absoluteUser);- } finally {- if (previousProject === undefined) {- delete process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"];- } else {- process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"] = previousProject;- }-- if (previousUser === undefined) {- delete process.env["LSP_TOOLS_MCP_USER_CONFIG"];- } else {- process.env["LSP_TOOLS_MCP_USER_CONFIG"] = previousUser;- }- }- });-- it("#given one invalid LSP config entry #when merging servers #then keeps valid sibling entries", () => {- // given- const previousProject = process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"];- const previousUser = process.env["LSP_TOOLS_MCP_USER_CONFIG"];- const root = mkdtempSync(join(tmpdir(), "lsp-tools-config-"));- tempDirectories.push(root);- const projectConfig = join(root, "project.json");- const userConfig = join(root, "user.json");- mkdirSync(root, { recursive: true });- writeFileSync(- projectConfig,- JSON.stringify({- lsp: {- valid: { command: ["valid-lsp", "--stdio"], extensions: [".valid"], priority: 7 },- invalid: "not an object",- },- }),- );- writeFileSync(userConfig, JSON.stringify({ lsp: {} }));- process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"] = projectConfig;- process.env["LSP_TOOLS_MCP_USER_CONFIG"] = userConfig;-- try {- // when- const servers = getMergedServers();-- // then- expect(servers).toContainEqual(- expect.objectContaining({- id: "valid",- command: ["valid-lsp", "--stdio"],- extensions: [".valid"],- priority: 7,- source: "project",- }),- );- expect(servers.some((server) => server.id === "invalid")).toBe(false);- } finally {- if (previousProject === undefined) {- delete process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"];- } else {- process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"] = previousProject;- }-- if (previousUser === undefined) {- delete process.env["LSP_TOOLS_MCP_USER_CONFIG"];- } else {- process.env["LSP_TOOLS_MCP_USER_CONFIG"] = previousUser;- }- }- });-});diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/directory-diagnostics.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/directory-diagnostics.test.tsdeleted file mode 100644index cbd85cae..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/directory-diagnostics.test.ts+++ /dev/null@@ -1,32 +0,0 @@-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { afterEach, describe, expect, it } from "vitest";--import { collectFilesWithExtension } from "../src/lsp/directory-diagnostics.js";--const tempDirectories: string[] = [];--afterEach(() => {- for (const directory of tempDirectories.splice(0)) {- rmSync(directory, { recursive: true, force: true });- }-});--describe("collectFilesWithExtension", () => {- it("#given more matching files than max #when collecting diagnostics inputs #then traversal returns only capped files", () => {- // given- const root = mkdtempSync(join(tmpdir(), "codex-lsp-directory-"));- tempDirectories.push(root);- mkdirSync(join(root, "src"), { recursive: true });- for (let index = 0; index < 5; index += 1) {- writeFileSync(join(root, "src", `file-${index}.ts`), `export const value${index} = ${index};\n`);- }-- // when- const files = collectFilesWithExtension(root, ".ts", 2);-- // then- expect(files).toHaveLength(2);- });-});diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/fixtures/broken.py b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/fixtures/broken.pydeleted file mode 100644index 745b30da..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/fixtures/broken.py+++ /dev/null@@ -1 +0,0 @@-value: str = 1diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/formatters.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/formatters.test.tsdeleted file mode 100644index 61fbf636..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/formatters.test.ts+++ /dev/null@@ -1,43 +0,0 @@-import { describe, expect, it } from "vitest";--import { filterDiagnosticsBySeverity } from "../src/lsp/formatters.js";-import type { Diagnostic } from "../src/lsp/types.js";--const range = {- start: { line: 0, character: 0 },- end: { line: 0, character: 1 },-};--function diagnostic(message: string, severity?: number): Diagnostic {- return severity === undefined ? { range, message } : { range, message, severity };-}--describe("filterDiagnosticsBySeverity", () => {- it("#given all severity filter #when filtering diagnostics #then returns the original diagnostics", () => {- // given- const diagnostics = [diagnostic("syntax", 1), diagnostic("note", 3)];-- // when- const filtered = filterDiagnosticsBySeverity(diagnostics, "all");-- // then- expect(filtered).toBe(diagnostics);- });-- it("#given mixed severities #when filtering diagnostics #then returns only matching diagnostics", () => {- // given- const diagnostics = [- diagnostic("syntax", 1),- diagnostic("lint", 2),- diagnostic("note", 3),- diagnostic("hint", 4),- diagnostic("unknown"),- ];-- // when / then- expect(filterDiagnosticsBySeverity(diagnostics, "error")).toEqual([diagnostics[0]]);- expect(filterDiagnosticsBySeverity(diagnostics, "warning")).toEqual([diagnostics[1]]);- expect(filterDiagnosticsBySeverity(diagnostics, "information")).toEqual([diagnostics[2]]);- expect(filterDiagnosticsBySeverity(diagnostics, "hint")).toEqual([diagnostics[3]]);- });-});diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/helpers/fake-lsp-client.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/helpers/fake-lsp-client.tsdeleted file mode 100644index 6d199210..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/helpers/fake-lsp-client.ts+++ /dev/null@@ -1,74 +0,0 @@-import { LspClient } from "../../src/lsp/client.js";-import type { ResolvedServer } from "../../src/lsp/types.js";--export interface FakeLspClientOptions {- startDelayMs?: number;- initDelayMs?: number;- failStart?: boolean;- failInitialize?: boolean;- stopDelayMs?: number;- startsAlive?: boolean;-}--export class FakeLspClient extends LspClient {- private aliveFlag: boolean;- startCallCount = 0;- initializeCallCount = 0;- stopCallCount = 0;-- constructor(- root: string,- server: ResolvedServer,- private readonly opts: FakeLspClientOptions = {},- ) {- super(root, server);- this.aliveFlag = opts.startsAlive !== false;- }-- override async start(): Promise<void> {- this.startCallCount++;- if (this.opts.startDelayMs !== undefined) {- await new Promise((resolve) => setTimeout(resolve, this.opts.startDelayMs));- }- if (this.opts.failStart) {- this.aliveFlag = false;- throw new Error("fake start failed");- }- }-- override async initialize(): Promise<void> {- this.initializeCallCount++;- if (this.opts.initDelayMs !== undefined) {- await new Promise((resolve) => setTimeout(resolve, this.opts.initDelayMs));- }- if (this.opts.failInitialize) {- this.aliveFlag = false;- throw new Error("fake initialize failed");- }- }-- override isAlive(): boolean {- return this.aliveFlag;- }-- override command(): string[] {- return ["fake-server"];- }-- override async stop(): Promise<void> {- this.stopCallCount++;- if (this.opts.stopDelayMs !== undefined) {- await new Promise((resolve) => setTimeout(resolve, this.opts.stopDelayMs));- }- this.aliveFlag = false;- }-}--export function makeServer(id: string, extensions: string[] = [".ts"]): ResolvedServer {- return {- id,- command: ["fake-server", "--stdio"],- extensions,- priority: 0,- };-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/json-rpc-connection.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/json-rpc-connection.test.tsdeleted file mode 100644index 5b9e8d47..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/json-rpc-connection.test.ts+++ /dev/null@@ -1,69 +0,0 @@-import { PassThrough } from "node:stream";-import { describe, expect, it } from "vitest";--import { JsonRpcConnection } from "../src/lsp/json-rpc-connection.js";--function encodeMessage(message: Record<string, unknown>): string {- const body = JSON.stringify(message);- return `Content-Length: ${Buffer.byteLength(body, "utf8")}\r\n\r\n${body}`;-}--function readOneMessage(stream: PassThrough): Promise<Record<string, unknown>> {- return new Promise((resolve) => {- stream.once("data", (chunk: Buffer) => {- const text = chunk.toString("utf8");- const bodyStart = text.indexOf("\r\n\r\n") + 4;- resolve(JSON.parse(text.slice(bodyStart)) as Record<string, unknown>);- });- });-}--describe("JsonRpcConnection", () => {- it("#given a framed response #when sending request #then resolves the matching result", async () => {- // given- const serverOutput = new PassThrough();- const serverInput = new PassThrough();- const connection = new JsonRpcConnection(serverOutput, serverInput);- connection.listen();- const requestMessage = readOneMessage(serverInput);-- // when- const resultPromise = connection.sendRequest<{ capabilities: Record<string, unknown> }>("initialize", {- rootUri: "file:///tmp/project",- });- const request = await requestMessage;- serverOutput.write(encodeMessage({ jsonrpc: "2.0", id: request["id"], result: { capabilities: {} } }));-- // then- await expect(resultPromise).resolves.toEqual({ capabilities: {} });- connection.dispose();- });-- it("#given a server request #when handler returns #then writes a json-rpc response", async () => {- // given- const serverOutput = new PassThrough();- const serverInput = new PassThrough();- const connection = new JsonRpcConnection(serverOutput, serverInput);- connection.onRequest("workspace/configuration", () => [{ validate: { enable: true } }]);- connection.listen();-- // when- const responseMessage = readOneMessage(serverInput);- serverOutput.write(- encodeMessage({- jsonrpc: "2.0",- id: 7,- method: "workspace/configuration",- params: { items: [{ section: "json" }] },- }),- );-- // then- await expect(responseMessage).resolves.toMatchObject({- jsonrpc: "2.0",- id: 7,- result: [{ validate: { enable: true } }],- });- connection.dispose();- });-});diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/manager.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/manager.test.tsdeleted file mode 100644index 4242e262..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/manager.test.ts+++ /dev/null@@ -1,126 +0,0 @@-import { describe, expect, it } from "vitest";--import type { LspClient } from "../src/lsp/client.js";-import { LspManager } from "../src/lsp/manager.js";-import type { ResolvedServer } from "../src/lsp/types.js";--import { FakeLspClient, type FakeLspClientOptions, makeServer } from "./helpers/fake-lsp-client.js";--interface FakeContext {- manager: LspManager;- clients: FakeLspClient[];- now: { value: number };-}--function setupManager(options?: {- idleTimeoutMs?: number;- initTimeoutMs?: number;- reaperIntervalMs?: number;- clientFactoryOptions?: () => FakeLspClientOptions;-}): FakeContext {- const clients: FakeLspClient[] = [];- const now = { value: 1_000 };- const manager = new LspManager({- idleTimeoutMs: options?.idleTimeoutMs ?? 5_000,- initTimeoutMs: options?.initTimeoutMs ?? 1_000,- reaperIntervalMs: options?.reaperIntervalMs ?? 100,- now: () => now.value,- clientFactory: (root: string, server: ResolvedServer): LspClient => {- const client = new FakeLspClient(root, server, options?.clientFactoryOptions?.());- clients.push(client);- return client;- },- });- return { manager, clients, now };-}--type ProcessSignalListener = (...args: never[]) => unknown;--function findAddedListener(- signal: NodeJS.Signals,- before: readonly ProcessSignalListener[],-): ProcessSignalListener | undefined {- return process.listeners(signal).find((listener) => !before.includes(listener));-}--describe("LspManager", () => {- it("#given failed start #when later getClient #then failed client is stopped and a fresh client is built", async () => {- // given- let firstCall = true;- const failingFactory = () => {- if (firstCall) {- firstCall = false;- return { failStart: true };- }- return {};- };- const { manager, clients } = setupManager({ clientFactoryOptions: failingFactory });- const server = makeServer("typescript");-- // when- await expect(manager.getClient("/root/a", server)).rejects.toThrow("fake start failed");-- // then- expect(manager.getSnapshot()).toEqual([]);- expect(clients[0]?.stopCallCount).toBeGreaterThan(0);-- const fresh = await manager.getClient("/root/a", server);- expect(clients.length).toBe(2);- expect(fresh).toBe(clients[1]);-- await manager.stopAll();- });-- it("#given failed initialize #when later getClient #then failed client is stopped and a fresh client is built", async () => {- // given- let firstCall = true;- const failingFactory = () => {- if (firstCall) {- firstCall = false;- return { failInitialize: true };- }- return {};- };- const { manager, clients } = setupManager({ clientFactoryOptions: failingFactory });- const server = makeServer("typescript");-- // when- await expect(manager.getClient("/root/a", server)).rejects.toThrow("fake initialize failed");-- // then- expect(manager.getSnapshot()).toEqual([]);- expect(clients[0]?.stopCallCount).toBeGreaterThan(0);-- const fresh = await manager.getClient("/root/a", server);- expect(clients.length).toBe(2);- expect(fresh).toBe(clients[1]);-- await manager.stopAll();- });-- it("#given active client #when signal cleanup runs #then client is stopped and handlers unregister", async () => {- // given- const beforeSigterm = process.listeners("SIGTERM");- const { manager, clients } = setupManager();- const server = makeServer("typescript");-- try {- await manager.getClient("/root/a", server);- manager.releaseClient("/root/a", server.id);-- // when- const listener = findAddedListener("SIGTERM", beforeSigterm);-- // then- expect(listener).toBeDefined();- listener?.();- await new Promise((resolve) => setTimeout(resolve, 0));-- expect(clients[0]?.stopCallCount).toBe(1);- expect(manager.clientCount()).toBe(0);- expect(process.listeners("SIGTERM")).toEqual(beforeSigterm);- } finally {- await manager.stopAll();- }- });-});diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/mcp.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/mcp.test.tsdeleted file mode 100644index fce1bf57..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/mcp.test.ts+++ /dev/null@@ -1,103 +0,0 @@-import { PassThrough } from "node:stream";--import { describe, expect, it } from "vitest";--import { handleLspMcpRequest, runMcpStdioServer } from "../src/mcp.js";--describe("lsp MCP server", () => {- it("responds to initialize with tool capabilities", async () => {- const response = await handleLspMcpRequest({- jsonrpc: "2.0",- id: 1,- method: "initialize",- params: {- protocolVersion: "2024-11-05",- capabilities: {},- clientInfo: { name: "test", version: "0.0.0" },- },- });-- expect(response).toMatchObject({- jsonrpc: "2.0",- id: 1,- result: {- capabilities: { tools: { listChanged: false } },- serverInfo: { name: "lsp", version: "0.1.0" },- },- });- });-- it("lists LSP MCP tools", async () => {- const response = await handleLspMcpRequest({- jsonrpc: "2.0",- id: 2,- method: "tools/list",- });-- const tools = response?.result?.tools as Array<{ name: string }>;- expect(tools.map((tool) => tool.name)).toEqual([- "status",- "diagnostics",- "goto_definition",- "find_references",- "symbols",- "prepare_rename",- "rename",- ]);- });-- it("calls status without starting a language server", async () => {- const response = await handleLspMcpRequest({- jsonrpc: "2.0",- id: 3,- method: "tools/call",- params: { name: "status", arguments: {} },- });-- expect(response).toMatchObject({- jsonrpc: "2.0",- id: 3,- result: {- isError: false,- },- });- expect(response?.result?.content?.[0]?.text).toContain("Configured LSP servers");- });-- it("accepts legacy lsp-prefixed tool names without listing them", async () => {- const response = await handleLspMcpRequest({- jsonrpc: "2.0",- id: 4,- method: "tools/call",- params: { name: "lsp_status", arguments: {} },- });-- expect(response).toMatchObject({- jsonrpc: "2.0",- id: 4,- result: {- isError: false,- },- });- expect(response?.result?.content?.[0]?.text).toContain("Configured LSP servers");- });-- it("#given idle stdio connection #when no request arrives before timeout #then server exits through idle callback", async () => {- // given- const input = new PassThrough();- const output = new PassThrough();- let idleCallCount = 0;-- // when- await runMcpStdioServer(input, output, {- idleTimeoutMs: 1,- onIdleTimeout: () => {- idleCallCount++;- input.end();- },- });-- // then- expect(idleCallCount).toBe(1);- });-});diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/package-smoke.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/package-smoke.test.tsdeleted file mode 100644index bc6196fc..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/package-smoke.test.ts+++ /dev/null@@ -1,63 +0,0 @@-import { readFileSync } from "node:fs";-import { describe, expect, it } from "vitest";--type PackageJson = {- readonly type: string;- readonly packageManager: string;- readonly name: string;- readonly license: string;- readonly bin: Record<string, string>;- readonly files: readonly string[];- readonly dependencies?: Record<string, unknown>;-};--function readPackageJson(path: string): PackageJson {- const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));- if (!isPackageJson(parsed)) throw new TypeError(`Invalid package metadata: ${path}`);- return parsed;-}--describe("package metadata", () => {- it("#given packaged files #when validating entrypoints #then package metadata is consistent", () => {- // given- const packageJson = readPackageJson("package.json");- const cliSource = readFileSync("src/cli.ts", "utf8");-- // then- expect(packageJson.type).toBe("module");- expect(packageJson.packageManager).toBe("[email protected]");- expect(packageJson.name).toBe("@code-yeongyu/lsp-tools-mcp");- expect(packageJson.license).toBe("MIT");- expect(packageJson.dependencies ?? {}).toEqual({});- expect(packageJson.bin["lsp-tools-mcp"]).toBe("./dist/cli.js");- expect(packageJson.files).toEqual(["dist", "LICENSE", "NOTICE", "README.md", "CHANGELOG.md"]);- expect(cliSource.startsWith("#!/usr/bin/env node")).toBe(true);- expect(cliSource).toContain("Usage: lsp-tools-mcp [mcp]");- });-});--function isPackageJson(value: unknown): value is PackageJson {- const dependencies = isRecord(value) ? value["dependencies"] : undefined;- return (- isRecord(value) &&- value["type"] === "module" &&- value["packageManager"] === "[email protected]" &&- value["name"] === "@code-yeongyu/lsp-tools-mcp" &&- value["license"] === "MIT" &&- isStringRecord(value["bin"]) &&- isStringArray(value["files"]) &&- (dependencies === undefined || isRecord(dependencies))- );-}--function isStringRecord(value: unknown): value is Record<string, string> {- return isRecord(value) && Object.values(value).every((item) => typeof item === "string");-}--function isStringArray(value: unknown): value is readonly string[] {- return Array.isArray(value) && value.every((item) => typeof item === "string");-}--function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === "object" && value !== null && !Array.isArray(value);-}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/process.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/process.test.tsdeleted file mode 100644index c71a0c0d..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/process.test.ts+++ /dev/null@@ -1,151 +0,0 @@-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";--import { afterEach, describe, expect, it } from "vitest";--import { createSpawnCommand, spawnProcess } from "../src/lsp/process.js";--const tempDirectories: string[] = [];--afterEach(() => {- for (const directory of tempDirectories.splice(0)) {- rmSync(directory, { recursive: true, force: true });- }-});--function readFirstLine(stream: NodeJS.ReadableStream): Promise<string> {- return new Promise((resolve, reject) => {- let buffer = "";-- const cleanup = () => {- stream.off("data", onData);- stream.off("error", onError);- };-- const onData = (chunk: Buffer | string) => {- buffer += Buffer.isBuffer(chunk) ? chunk.toString("utf8") : chunk;- const newlineIndex = buffer.indexOf("\n");- if (newlineIndex === -1) return;- cleanup();- resolve(buffer.slice(0, newlineIndex).trim());- };-- const onError = (error: Error) => {- cleanup();- reject(error);- };-- stream.on("data", onData);- stream.on("error", onError);- });-}--function sleep(ms: number): Promise<void> {- return new Promise((resolve) => setTimeout(resolve, ms));-}--function isPidAlive(pid: number): boolean {- try {- process.kill(pid, 0);- return true;- } catch {- return false;- }-}--function killPidBestEffort(pid: number): void {- try {- process.kill(pid, "SIGKILL");- } catch {- // Already exited.- }-}--describe("createSpawnCommand", () => {- it("#given windows executable command #when building spawn command #then it avoids shell mode", () => {- // given- const command = ["typescript-language-server", "--stdio"];-- // when- const prepared = createSpawnCommand(command, "win32", "cmd.exe");-- // then- expect(prepared).toEqual({- command: "typescript-language-server",- args: ["--stdio"],- shell: false,- });- });-- it("#given windows cmd shim #when building spawn command #then it uses cmd only for the shim", () => {- // given- const command = ["typescript-language-server.cmd", "--stdio"];-- // when- const prepared = createSpawnCommand(command, "win32", "cmd.exe");-- // then- expect(prepared).toEqual({- command: "cmd.exe",- args: ["/d", "/s", "/c", "typescript-language-server.cmd", "--stdio"],- shell: false,- });- });-- it("#given windows PATH shim #when resolving spawn command #then it executes the shim without shell mode", () => {- // given- const binaryDirectory = mkdtempSync(join(tmpdir(), "codex-lsp-bin-"));- tempDirectories.push(binaryDirectory);- mkdirSync(binaryDirectory, { recursive: true });- const shimPath = join(binaryDirectory, "typescript-language-server.cmd");- writeFileSync(shimPath, "@echo off\n");-- // when- const prepared = createSpawnCommand(["typescript-language-server", "--stdio"], "win32", "cmd.exe", {- PATH: binaryDirectory,- PATHEXT: ".cmd;.exe",- });-- // then- expect(prepared).toEqual({- command: "cmd.exe",- args: ["/d", "/s", "/c", shimPath, "--stdio"],- shell: false,- });- });-});--describe("spawnProcess", () => {- it.skipIf(process.platform === "win32")(- "#given child process tree #when killing spawned wrapper #then descendant process exits too",- async () => {- // given- const directory = mkdtempSync(join(tmpdir(), "lsp-tools-process-tree-"));- tempDirectories.push(directory);- const script = [- "const { spawn } = require('node:child_process')",- "const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })",- "console.error(String(child.pid))",- "process.on('SIGTERM', () => process.exit(0))",- "setInterval(() => {}, 1000)",- ].join(";");- const proc = spawnProcess([process.execPath, "-e", script], { cwd: directory, env: process.env });- const childPid = Number(await readFirstLine(proc.stderr));-- try {- // when- proc.kill("SIGTERM");- await Promise.race([proc.exited, sleep(2_000)]);- await sleep(200);-- // then- expect(Number.isInteger(childPid)).toBe(true);- expect(isPidAlive(childPid)).toBe(false);- } finally {- killPidBestEffort(childPid);- proc.kill("SIGKILL");- }- },- );-});diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/server-definitions.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/server-definitions.test.tsdeleted file mode 100644index 5fb9bdba..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/server-definitions.test.ts+++ /dev/null@@ -1,27 +0,0 @@-import { describe, expect, it } from "vitest";--import { AUTO_INSTALLABLE_SERVERS, BUILTIN_SERVERS, LSP_INSTALL_HINTS } from "../src/lsp/server-definitions.js";--describe("BUILTIN_SERVERS", () => {- it("#given rust #when looking it up #then maps to rust-analyzer", () => {- // given- const rust = BUILTIN_SERVERS["rust"];-- // when / then- expect(rust).toBeDefined();- expect(rust?.command[0]).toBe("rust-analyzer");- expect(rust?.extensions).toEqual([".rs"]);- });-- it("#given rust install guidance #when inspecting registry #then rust is manual install only", () => {- // given- const hint = LSP_INSTALL_HINTS["rust"];-- // when / then- expect(AUTO_INSTALLABLE_SERVERS["rust"]).toBeUndefined();- expect(hint).toContain("rust-analyzer");- expect(hint).toContain("rustup component add rust-analyzer");- expect(hint).toContain("rustup component remove rust-src");- expect(hint).toContain("rustup component add rust-src");- });-});diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/utils.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/utils.test.tsdeleted file mode 100644index 614743d1..00000000--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/utils.test.ts+++ /dev/null@@ -1,72 +0,0 @@-import { describe, expect, it } from "vitest";--import { LspProcessExitedError } from "../src/lsp/errors.js";-import { formatKnownLspStartupFailure, handleMissingDependencyError } from "../src/lsp/utils.js";--describe("formatKnownLspStartupFailure", () => {- it("#given rust-src component conflict #when formatting startup failure #then returns repair guidance", () => {- // given- const error = new LspProcessExitedError(- "rust",- "/repo",- 1,- "failed to install component: 'rust-src', detected conflict: 'lib/rustlib/src/rust/library/Cargo.lock'",- );-- // when- const message = formatKnownLspStartupFailure(error);-- // then- expect(message).toContain("rust-analyzer");- expect(message).toContain("rustup component remove rust-src");- expect(message).toContain("rustup component add rust-src");- expect(message).toContain("detected conflict");- expect(message).toContain("Cargo.lock");- expect(message).not.toContain("automatic repair");- });-- it("#given rust-analyzer sysroot error #when handling missing dependency #then returns repair guidance", () => {- // given- const error = new LspProcessExitedError(- "rust",- "/repo",- 1,- "can't load standard library from sysroot\ntry installing `rust-src` the same way you installed `rustc`",- );-- // when- const message = handleMissingDependencyError(error);-- // then- expect(message).toContain("rustup component remove rust-src");- expect(message).toContain("rustup component add rust-src");- expect(message).toContain("can't load standard library");- });-- it("#given unrelated process exits #when formatting startup failure #then returns null", () => {- // given- const typescriptError = new LspProcessExitedError(- "typescript",- "/repo",- 1,- "failed to install component: 'rust-src', detected conflict",- );- const rustPanic = new LspProcessExitedError("rust", "/repo", 1, "thread panicked while loading crate graph");-- // when / then- expect(formatKnownLspStartupFailure(typescriptError)).toBeNull();- expect(formatKnownLspStartupFailure(rustPanic)).toBeNull();- });-});--describe("handleMissingDependencyError", () => {- it("#given existing dependency messages #when handling error #then preserves current messages", () => {- // given- const notInstalled = new Error("LSP server 'typescript' is configured but NOT INSTALLED.");- const notConfigured = new Error("No LSP server configured for extension: .md");-- // when / then- expect(handleMissingDependencyError(notInstalled)).toBe(notInstalled.message);- expect(handleMissingDependencyError(notConfigured)).toBe(notConfigured.message);- });-});diff --git a/plugins/omo/components/lsp/scripts/bootstrap-submodule.mjs b/plugins/omo/components/lsp/scripts/bootstrap-submodule.mjsdeleted file mode 100644index a1b45e3d..00000000--- a/plugins/omo/components/lsp/scripts/bootstrap-submodule.mjs+++ /dev/null@@ -1,38 +0,0 @@-#!/usr/bin/env node-// Bootstrap the lsp-tools-mcp git submodule for local development.-// CI runs the install+build steps explicitly in the workflow, so this-// script is mostly for `npm run bootstrap` after a fresh clone and as a-// chained pre-step before typecheck / test / check so contributors do not-// have to remember it.-//-// Idempotent: skips when dist/cli.js already exists, unless --force is passed.-import { existsSync } from "node:fs";-import { execSync } from "node:child_process";-import { dirname, join } from "node:path";-import { fileURLToPath } from "node:url";--const __dirname = dirname(fileURLToPath(import.meta.url));-const submoduleDir = join(__dirname, "..", "packages", "lsp-tools-mcp");-const submodulePackageJson = join(submoduleDir, "package.json");-const submoduleDistCli = join(submoduleDir, "dist", "cli.js");-const force = process.argv.includes("--force");--if (!existsSync(submodulePackageJson)) {- console.error(- "lsp-tools-mcp submodule is missing. Run: git submodule update --init --recursive",- );- process.exit(1);-}--if (!force && existsSync(submoduleDistCli)) {- // Already built; nothing to do.- process.exit(0);-}--console.log("Installing lsp-tools-mcp dependencies...");-execSync("npm ci", { cwd: submoduleDir, stdio: "inherit" });--console.log("Building lsp-tools-mcp...");-execSync("npm run build", { cwd: submoduleDir, stdio: "inherit" });--console.log("Done.");diff --git a/plugins/omo/components/lsp/scripts/build-lsp-tools.mjs b/plugins/omo/components/lsp/scripts/build-lsp-tools.mjsnew file mode 100644index 00000000..390ffe06--- /dev/null+++ b/plugins/omo/components/lsp/scripts/build-lsp-tools.mjs@@ -0,0 +1,46 @@+#!/usr/bin/env node+// Build the repository-level lsp-tools-mcp package used by codex-lsp.+import { execSync } from "node:child_process";+import { existsSync, statSync } from "node:fs";+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);+}++if (!existsSync(packageJson)) {+ if (!force && requiredOutputs.every((path) => existsSync(path))) {+ console.log("Using bundled lsp-tools-mcp dist.");+ 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" });++console.log("Done.");++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.test.mjs b/plugins/omo/components/lsp/scripts/build-lsp-tools.test.mjsnew file mode 100644index 00000000..6848a2f8--- /dev/null+++ b/plugins/omo/components/lsp/scripts/build-lsp-tools.test.mjs@@ -0,0 +1,104 @@+import assert from "node:assert/strict";+import { chmod, copyFile, mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { spawnSync } from "node:child_process";+import test from "node:test";++async function makeFixture() {+ const root = await mkdtemp(join(tmpdir(), "codex-lsp-build-"));+ await mkdir(join(root, "packages", "omo-codex", "plugin", "components", "lsp", "scripts"), { recursive: true });+ await mkdir(join(root, "packages", "lsp-tools-mcp", "dist"), { recursive: true });+ await copyFile(+ new URL("./build-lsp-tools.mjs", import.meta.url),+ join(root, "packages", "omo-codex", "plugin", "components", "lsp", "scripts", "build-lsp-tools.mjs"),+ );+ await writeFile(join(root, "packages", "lsp-tools-mcp", "package.json"), "{}\n");+ await writeFile(join(root, "packages", "lsp-tools-mcp", "dist", "cli.js"), "cli\n");+ const fakeBin = join(root, "bin");+ await mkdir(fakeBin, { recursive: true });+ const npmLog = join(root, "npm.log");+ await writeFile(+ join(fakeBin, "npm"),+ `#!/usr/bin/env node\nconst { appendFileSync } = require("node:fs");\nappendFileSync(${JSON.stringify(npmLog)}, process.argv.slice(2).join(" ") + "\\n");\n`,+ );+ await chmod(join(fakeBin, "npm"), 0o755);+ return { root, npmLog, script: join(root, "packages", "omo-codex", "plugin", "components", "lsp", "scripts", "build-lsp-tools.mjs"), fakeBin };+}++function runScript(script, fakeBin, args = []) {+ return spawnSync(process.execPath, [script, ...args], {+ encoding: "utf8",+ env: { ...process.env, PATH: `${fakeBin}:${process.env.PATH ?? ""}` },+ });+}++test("#given dist cli exists but required hook outputs are missing #when bootstrapping #then it rebuilds", async () => {+ // given+ const fixture = await makeFixture();++ // when+ const result = runScript(fixture.script, fixture.fakeBin);++ // then+ assert.equal(result.status, 0);+ assert.match(await readFile(fixture.npmLog, "utf8"), /ci\nrun build\n/u);+});++test("#given package metadata is newer than required outputs #when bootstrapping #then it rebuilds", async () => {+ // given+ const fixture = await makeFixture();+ await mkdir(join(fixture.root, "packages", "lsp-tools-mcp", "dist", "lsp"), { recursive: true });+ await writeFile(join(fixture.root, "packages", "lsp-tools-mcp", "dist", "lsp", "manager.js"), "manager\n");+ await writeFile(join(fixture.root, "packages", "lsp-tools-mcp", "dist", "tools.js"), "tools\n");+ const older = new Date("2026-01-01T00:00:00.000Z");+ const newer = new Date("2026-01-02T00:00:00.000Z");+ for (const path of [+ join(fixture.root, "packages", "lsp-tools-mcp", "dist", "cli.js"),+ join(fixture.root, "packages", "lsp-tools-mcp", "dist", "tools.js"),+ join(fixture.root, "packages", "lsp-tools-mcp", "dist", "lsp", "manager.js"),+ ]) {+ await utimes(path, older, older);+ }+ await utimes(join(fixture.root, "packages", "lsp-tools-mcp", "package.json"), newer, newer);++ // when+ const result = runScript(fixture.script, fixture.fakeBin);++ // then+ assert.equal(result.status, 0);+ assert.match(await readFile(fixture.npmLog, "utf8"), /ci\nrun build\n/u);+});++test("#given force flag #when bootstrapping #then it rebuilds even when dist exists", async () => {+ // given+ const fixture = await makeFixture();+ await mkdir(join(fixture.root, "packages", "lsp-tools-mcp", "dist", "lsp"), { recursive: true });+ await writeFile(join(fixture.root, "packages", "lsp-tools-mcp", "dist", "lsp", "manager.js"), "manager\n");+ await writeFile(join(fixture.root, "packages", "lsp-tools-mcp", "dist", "tools.js"), "tools\n");++ // when+ const result = runScript(fixture.script, fixture.fakeBin, ["--force"]);++ // then+ assert.equal(result.status, 0);+ assert.match(await readFile(fixture.npmLog, "utf8"), /ci\nrun build\n/u);+});++test("#given packaged dist without package metadata #when bootstrapping #then it uses bundled runtime", async () => {+ // given+ const fixture = await makeFixture();+ await mkdir(join(fixture.root, "packages", "lsp-tools-mcp", "dist", "lsp"), { recursive: true });+ await writeFile(join(fixture.root, "packages", "lsp-tools-mcp", "dist", "lsp", "manager.js"), "manager\n");+ await writeFile(join(fixture.root, "packages", "lsp-tools-mcp", "dist", "tools.js"), "tools\n");+ await writeFile(fixture.npmLog, "");+ await rm(join(fixture.root, "packages", "lsp-tools-mcp", "package.json"));++ // when+ const result = runScript(fixture.script, fixture.fakeBin);++ // then+ assert.equal(result.status, 0, result.stderr);+ assert.match(result.stdout, /Using bundled lsp-tools-mcp dist/);+ assert.equal(await readFile(fixture.npmLog, "utf8"), "");+});diff --git a/plugins/omo/components/lsp/scripts/clean-dist.mjs b/plugins/omo/components/lsp/scripts/clean-dist.mjsnew file mode 100644index 00000000..630de3ab--- /dev/null+++ b/plugins/omo/components/lsp/scripts/clean-dist.mjs@@ -0,0 +1,5 @@+#!/usr/bin/env node+import { rm } from "node:fs/promises";+import { fileURLToPath } from "node:url";++await rm(fileURLToPath(new URL("../dist/", import.meta.url)), { recursive: true, force: true });diff --git a/plugins/omo/components/lsp/scripts/test.mjs b/plugins/omo/components/lsp/scripts/test.mjsnew file mode 100644index 00000000..3956f62e--- /dev/null+++ b/plugins/omo/components/lsp/scripts/test.mjs@@ -0,0 +1,8 @@+#!/usr/bin/env node+import { spawnSync } from "node:child_process";++const vitest = spawnSync("vitest", ["--run", ...process.argv.slice(2)], { stdio: "inherit" });+if (vitest.status !== 0) process.exit(vitest.status ?? 1);++const nodeTest = spawnSync(process.execPath, ["--test", "scripts/*.test.mjs"], { stdio: "inherit" });+process.exit(nodeTest.status ?? 1);diff --git a/plugins/omo/components/lsp/src/cli.ts b/plugins/omo/components/lsp/src/cli.tsindex 9373ad7d..aa1ca150 100644--- a/plugins/omo/components/lsp/src/cli.ts+++ b/plugins/omo/components/lsp/src/cli.ts@@ -1,33 +1,48 @@#!/usr/bin/env node-import { argv, stderr } from "node:process";+import { spawn } from "node:child_process";+import { createRequire } from "node:module";+import { argv, execPath, stderr } from "node:process";-import { disposeDefaultLspManager } from "@code-yeongyu/lsp-tools-mcp/dist/lsp/manager.js";-import { runMcpStdioServer } from "@code-yeongyu/lsp-tools-mcp/dist/mcp.js";-import { runPostToolUseHookCli } from "./codex-hook.js";+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";async function main(): Promise<void> {const [command = "mcp", subcommand = ""] = argv.slice(2);- try {- if (command === "hook" && subcommand === "post-tool-use") {- await runPostToolUseHookCli();- return;- }-- if (command === "mcp") {- await runMcpStdioServer();- return;- }-- stderr.write("Usage: codex-lsp [mcp | hook post-tool-use]\n");- process.exitCode = 2;- } finally {- await disposeDefaultLspManager();+ if (command === "hook" && subcommand === "post-tool-use") {+ await runPostToolUseHookCli();+ return;+ }+ if (command === "hook" && subcommand === "post-compact") {+ await runPostCompactHookCli();+ return;+ }++ if (command === "mcp") {+ await runPackageLspMcpCli();+ return;}++ stderr.write("Usage: omo-lsp [mcp | hook post-tool-use | hook post-compact]\n");+ process.exitCode = 2;}-main().catch(async (error: unknown) => {+main().catch((error: unknown) => {stderr.write(`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);- await disposeDefaultLspManager();process.exitCode = 1;});++async function runPackageLspMcpCli(): Promise<void> {+ const cliPath = require.resolve(PACKAGE_LSP_MCP_CLI);+ const child = spawn(execPath, [cliPath, "mcp"], { stdio: "inherit" });+ await new Promise<void>((resolve, reject) => {+ child.once("error", reject);+ child.once("exit", (code, signal) => {+ if (code !== null && code !== 0) process.exitCode = code;+ if (code === null && signal !== null) process.exitCode = 1;+ resolve();+ });+ });+}diff --git a/plugins/omo/components/lsp/src/codex-hook-cli.ts b/plugins/omo/components/lsp/src/codex-hook-cli.tsnew file mode 100644index 00000000..f99cd3ef--- /dev/null+++ b/plugins/omo/components/lsp/src/codex-hook-cli.ts@@ -0,0 +1,44 @@+import { stdin as processStdin } from "node:process";++import { disposeDefaultLspManager } from "@code-yeongyu/lsp-tools-mcp/dist/lsp/manager.js";++import { isRecord, runLspPostCompactHook, runLspPostToolUseHook } from "./codex-hook.js";++export async function runPostToolUseHookCli(stdin: NodeJS.ReadStream = processStdin): Promise<void> {+ await runHookCli((input) => runLspPostToolUseHook(input), stdin);+}++export async function runPostCompactHookCli(stdin: NodeJS.ReadStream = processStdin): Promise<void> {+ await runHookCli((input) => runLspPostCompactHook(input), stdin);+}++async function runHookCli(+ runHook: (input: Record<string, unknown>) => Promise<string>,+ stdin: NodeJS.ReadStream,+): Promise<void> {+ try {+ const raw = await readStdin(stdin);+ if (!raw.trim()) return;+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch (error) {+ if (error instanceof SyntaxError) return;+ throw error;+ }+ const input = isRecord(parsed) ? parsed : {};+ const output = await runHook(input);+ if (output) process.stdout.write(output);+ } finally {+ await disposeDefaultLspManager();+ }+}++async function readStdin(stdin: NodeJS.ReadStream): Promise<string> {+ stdin.setEncoding("utf8");+ let raw = "";+ for await (const chunk of stdin) {+ raw += chunk;+ }+ return raw;+}diff --git a/plugins/omo/components/lsp/src/codex-hook.ts b/plugins/omo/components/lsp/src/codex-hook.tsindex c5ea956f..138c2d1d 100644--- a/plugins/omo/components/lsp/src/codex-hook.ts+++ b/plugins/omo/components/lsp/src/codex-hook.ts@@ -1,13 +1,30 @@-import { stdin as processStdin } from "node:process";+import { readFileSync } from "node:fs";import { executeLspDiagnostics } from "@code-yeongyu/lsp-tools-mcp/dist/tools.js";+import {+ isUnavailableLspDiagnostics,+ markLspSessionCompacted,+ recordLspDiagnosticsObservations,+ sessionIdFrom,+ shouldSkipUnavailableLspDiagnostics,+} from "./lsp-session-state.js";+import { extractMutatedFilePaths } from "./mutated-file-paths.js";++export { extractMutatedFilePaths } from "./mutated-file-paths.js";+export type DiagnosticsRunner = (filePath: string) => Promise<string>;export interface CodexPostToolUseInput {+ session_id?: unknown;tool_name?: unknown;tool_input?: unknown;tool_response?: unknown;+ transcript_path?: unknown;+}++export interface CodexPostCompactInput {+ session_id?: unknown;}interface DiagnosticBlock {@@ -24,9 +41,22 @@ interface PostToolUseHookOutput {};}-const MUTATION_TOOL_NAMES = new Set(["apply_patch", "write", "edit", "multiedit", "multi_edit"]);const CLEAN_DIAGNOSTICS_TEXT = "No diagnostics found";const UNSUPPORTED_EXTENSION_TEXT = "No LSP server configured for extension:";+const DIAGNOSTIC_START_PATTERN = /(?:error|warning|information|hint)\[[^\]\r\n]+\] \(\d+\) at \d+:\d+:/g;+const DIAGNOSTIC_CHUNK_PATTERN = /^(?:error|warning|information|hint)\[[^\]\r\n]+\] \(\d+\) at \d+:\d+:/;+const DEFAULT_MAX_HOOK_FEEDBACK_CHARS = 8000;+const CONTEXT_PRESSURE_MAX_HOOK_FEEDBACK_CHARS = 1200;+const MAX_CONCURRENT_DIAGNOSTICS = 4;+const CONTEXT_PRESSURE_MARKERS = [+ "context compacted",+ "context_length_exceeded",+ "skill descriptions were shortened",+ "context_too_large",+ "codex ran out of room in the model's context window",+ "your input exceeds the context window",+ "long threads and multiple compactions",+] as const;export async function runLspDiagnosticsText(filePath: string): Promise<string> {const result = await executeLspDiagnostics({ filePath, severity: "error" });@@ -37,21 +67,27 @@ export async function runLspPostToolUseHook(input: CodexPostToolUseInput,runDiagnostics: DiagnosticsRunner = runLspDiagnosticsText,): Promise<string> {- const filePaths = extractMutatedFilePaths(input);+ const sessionId = sessionIdFrom(input);+ const filePaths = extractMutatedFilePaths(input).filter(+ (filePath) => !shouldSkipUnavailableLspDiagnostics(filePath, sessionId),+ );if (filePaths.length === 0) return "";const blocks: DiagnosticBlock[] = [];- for (const filePath of filePaths) {- const diagnostics = (await runDiagnostics(filePath)).trim();+ const observations: Array<{ filePath: string; unavailable: boolean }> = [];+ for (const { filePath, diagnostics } of await collectDiagnostics(filePaths, runDiagnostics)) {+ const unavailable = isUnavailableLspDiagnostics(diagnostics);+ observations.push({ filePath, unavailable });if (isCleanDiagnostics(diagnostics)) continue;+ if (unavailable) continue;blocks.push({ filePath, diagnostics });}+ recordLspDiagnosticsObservations(sessionId, observations);if (blocks.length === 0) return "";- const reason = blocks- .map(({ filePath, diagnostics }) => `LSP diagnostics after editing ${filePath}:\n${diagnostics}`)- .join("\n\n");+ const rawReason = blocks.map(formatDiagnosticBlock).join("\n\n");+ const reason = limitHookText(rawReason, hookFeedbackLimit(input.transcript_path));const output: PostToolUseHookOutput = {decision: "block",reason,@@ -63,109 +99,130 @@ export async function runLspPostToolUseHook(return `${JSON.stringify(output)}\n`;}-export function extractMutatedFilePaths(input: CodexPostToolUseInput): string[] {- if (!isMutationTool(input.tool_name)) return [];- if (isFailedToolResponse(input.tool_response)) return [];-- const toolInput = isRecord(input.tool_input) ? input.tool_input : {};- const paths = new Set<string>();- addStringValue(paths, toolInput["path"]);- addStringValue(paths, toolInput["filePath"]);- addStringValue(paths, toolInput["file_path"]);- addStringArray(paths, toolInput["paths"]);- addStringArray(paths, toolInput["filePaths"]);- addStringArray(paths, toolInput["file_paths"]);- addPatchPayloads(paths, toolInput);- addPatchFiles(paths, toolInput["files"]);- addPatchFiles(paths, toolInput["changes"]);- return [...paths];+export async function runLspPostCompactHook(input: CodexPostCompactInput): Promise<string> {+ markLspSessionCompacted(sessionIdFrom(input));+ return "";+}++async function collectDiagnostics(+ filePaths: readonly string[],+ runDiagnostics: DiagnosticsRunner,+): Promise<DiagnosticBlock[]> {+ const results: DiagnosticBlock[] = [];+ let nextIndex = 0;+ const workerCount = Math.min(MAX_CONCURRENT_DIAGNOSTICS, filePaths.length);+ async function worker(): Promise<void> {+ for (;;) {+ const index = nextIndex;+ nextIndex += 1;+ const filePath = filePaths[index];+ if (filePath === undefined) return;+ results[index] = { filePath, diagnostics: await collectFileDiagnostics(filePath, runDiagnostics) };+ }+ }+ await Promise.all(Array.from({ length: workerCount }, () => worker()));+ return results;}-export async function runPostToolUseHookCli(stdin: NodeJS.ReadStream = processStdin): Promise<void> {- const raw = await readStdin(stdin);- if (!raw.trim()) return;- const parsed: unknown = JSON.parse(raw);- const input = isRecord(parsed) ? parsed : {};- const output = await runLspPostToolUseHook(input);- if (output) process.stdout.write(output);+async function collectFileDiagnostics(filePath: string, runDiagnostics: DiagnosticsRunner): Promise<string> {+ try {+ return (await runDiagnostics(filePath)).trim();+ } catch (error) {+ return formatDiagnosticsError(error);+ }}-function isMutationTool(value: unknown): boolean {- if (typeof value !== "string") return false;- return MUTATION_TOOL_NAMES.has(value.toLowerCase());+function formatDiagnosticsError(error: unknown): string {+ if (error instanceof Error) {+ const message = error.message.trim();+ if (message.length > 0) return message;+ }+ return String(error).trim();}-function isCleanDiagnostics(diagnostics: string): boolean {- return (- diagnostics.length === 0 ||- diagnostics === CLEAN_DIAGNOSTICS_TEXT ||- diagnostics.startsWith(UNSUPPORTED_EXTENSION_TEXT)- );+function formatDiagnosticBlock({ filePath, diagnostics }: DiagnosticBlock): string {+ return `LSP diagnostics after editing ${filePath}:\n\n${formatDiagnosticsForDisplay(diagnostics)}`;}-function isFailedToolResponse(value: unknown): boolean {- if (!isRecord(value)) return false;- return (- value["isError"] === true || value["is_error"] === true || value["error"] === true || value["status"] === "error"- );+function formatDiagnosticsForDisplay(diagnostics: string): string {+ const chunks = splitDiagnosticChunks(diagnostics);+ if (!chunks.some(isDiagnosticChunk)) return chunks.join("\n").trim();+ return chunks.map(formatDiagnosticChunk).join("\n");}-function addStringValue(paths: Set<string>, value: unknown): void {- if (typeof value === "string" && value.length > 0) {- paths.add(value);+function splitDiagnosticChunks(diagnostics: string): string[] {+ const normalized = diagnostics.replace(/\r\n/g, "\n").replace(/\r/g, "\n").trim();+ if (normalized.length === 0) return [];++ const matches = Array.from(normalized.matchAll(DIAGNOSTIC_START_PATTERN));+ const firstMatch = matches[0];+ if (firstMatch?.index === undefined) return [normalized];++ const chunks: string[] = [];+ const leadingText = normalized.slice(0, firstMatch.index).trim();+ if (leadingText.length > 0) chunks.push(leadingText);++ for (const [index, match] of matches.entries()) {+ if (match.index === undefined) continue;+ const nextMatch = matches[index + 1];+ const end = nextMatch?.index ?? normalized.length;+ const chunk = normalized.slice(match.index, end).trim();+ if (chunk.length > 0) chunks.push(chunk);}++ return chunks;}-function addStringArray(paths: Set<string>, value: unknown): void {- if (!Array.isArray(value)) return;- for (const item of value) {- addStringValue(paths, item);- }+function formatDiagnosticChunk(chunk: string): string {+ const lines = chunk.split("\n");+ const firstLine = lines[0];+ if (firstLine === undefined) return "";+ if (!isDiagnosticChunk(firstLine)) return chunk;+ const followingLines = lines.slice(1).map((line) => ` ${line}`);+ return [`- ${firstLine}`, ...followingLines].join("\n");}-function addPatchPayloads(paths: Set<string>, input: Record<string, unknown>): void {- addPatchInput(paths, input["input"]);- addPatchInput(paths, input["patch"]);- addPatchInput(paths, input["command"]);+function isDiagnosticChunk(chunk: string): boolean {+ return DIAGNOSTIC_CHUNK_PATTERN.test(chunk);}-function addPatchInput(paths: Set<string>, value: unknown): void {- if (typeof value !== "string") return;- for (const line of value.split("\n")) {- const path = extractPatchHeaderPath(line);- if (path !== undefined) paths.add(path);- }+function hookFeedbackLimit(transcriptPath: unknown): number {+ return isContextPressureTranscript(transcriptPath)+ ? CONTEXT_PRESSURE_MAX_HOOK_FEEDBACK_CHARS+ : DEFAULT_MAX_HOOK_FEEDBACK_CHARS;}-function extractPatchHeaderPath(line: string): string | undefined {- const prefixes = ["*** Add File: ", "*** Update File: ", "*** Move to: "] as const;- for (const prefix of prefixes) {- if (line.startsWith(prefix)) return line.slice(prefix.length).trim();- }- return undefined;-}--function addPatchFiles(paths: Set<string>, value: unknown): void {- if (!Array.isArray(value)) return;- for (const item of value) {- if (!isRecord(item)) continue;- addStringValue(paths, item["path"]);- addStringValue(paths, item["filePath"]);- addStringValue(paths, item["file_path"]);- addStringValue(paths, item["movePath"]);- addStringValue(paths, item["move_path"]);+function isContextPressureTranscript(transcriptPath: unknown): boolean {+ if (typeof transcriptPath !== "string") return false;+ try {+ return hasContextPressureMarker(readFileSync(transcriptPath, "utf8"));+ } catch (error) {+ if (error instanceof Error) return false;+ throw error;}}-function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === "object" && value !== null && !Array.isArray(value);+function hasContextPressureMarker(text: string): boolean {+ const normalizedText = text.toLowerCase();+ return CONTEXT_PRESSURE_MARKERS.some((marker) => normalizedText.includes(marker));}-async function readStdin(stdin: NodeJS.ReadStream): Promise<string> {- stdin.setEncoding("utf8");- let raw = "";- for await (const chunk of stdin) {- raw += chunk;- }- return raw;+function limitHookText(text: string, maxChars: number): string {+ if (text.length <= maxChars) return text;+ const marker = `\n\n[Truncated hook output to ${maxChars} chars to avoid Codex context overflow.]`;+ if (marker.length >= maxChars) return marker.slice(0, maxChars);+ const head = text.slice(0, maxChars - marker.length).replace(/[ \t\r\n]+$/, "");+ return `${head}${marker}`;+}++function isCleanDiagnostics(diagnostics: string): boolean {+ return (+ diagnostics.length === 0 ||+ diagnostics === CLEAN_DIAGNOSTICS_TEXT ||+ diagnostics.startsWith(UNSUPPORTED_EXTENSION_TEXT)+ );+}++export function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);}diff --git a/plugins/omo/components/lsp/src/lsp-session-state.ts b/plugins/omo/components/lsp/src/lsp-session-state.tsnew file mode 100644index 00000000..9cbc5ca8--- /dev/null+++ b/plugins/omo/components/lsp/src/lsp-session-state.ts@@ -0,0 +1,116 @@+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { homedir } from "node:os";+import { dirname, extname, join } from "node:path";++interface LspSessionState {+ readonly unavailableExtensions: readonly string[];+ readonly postCompactProbePending?: boolean;+}++export interface DiagnosticsObservation {+ readonly filePath: string;+ readonly unavailable: boolean;+}++export function sessionIdFrom(input: { readonly session_id?: unknown }): string | undefined {+ return typeof input.session_id === "string" && input.session_id.length > 0 ? input.session_id : undefined;+}++export function shouldSkipUnavailableLspDiagnostics(filePath: string, sessionId: string | undefined): boolean {+ if (sessionId === undefined) return false;+ const state = readSessionState(sessionStatePath(sessionId));+ const extension = extensionKey(filePath);+ return (+ extension !== undefined &&+ state.postCompactProbePending !== true &&+ state.unavailableExtensions.includes(extension)+ );+}++export function recordLspDiagnosticsObservations(+ sessionId: string | undefined,+ observations: readonly DiagnosticsObservation[],+): void {+ if (sessionId === undefined || observations.length === 0) return;+ const state = readSessionState(sessionStatePath(sessionId));+ const unavailableExtensions = new Set(state.unavailableExtensions);++ for (const observation of observations) {+ const extension = extensionKey(observation.filePath);+ if (extension === undefined) continue;+ if (observation.unavailable) {+ unavailableExtensions.add(extension);+ } else {+ unavailableExtensions.delete(extension);+ }+ }++ writeSessionState(sessionStatePath(sessionId), { unavailableExtensions: [...unavailableExtensions].sort() });+}++export function markLspSessionCompacted(sessionId: string | undefined): void {+ if (sessionId === undefined) return;+ const state = readSessionState(sessionStatePath(sessionId));+ if (state.unavailableExtensions.length === 0) return;+ writeSessionState(sessionStatePath(sessionId), {+ unavailableExtensions: state.unavailableExtensions,+ postCompactProbePending: true,+ });+}++export function isUnavailableLspDiagnostics(diagnostics: string): boolean {+ const normalized = diagnostics.trim();+ return (+ normalized.includes("LSP request timeout (method: initialize)") ||+ normalized.includes("LSP server is still initializing") ||+ normalized.includes("NOT INSTALLED") ||+ normalized.includes("Command not found:")+ );+}++function sessionStatePath(sessionId: string): string {+ const root = process.env["PLUGIN_DATA"] ?? join(homedir(), ".codex", "codex-lsp");+ return join(root, "sessions", `${safePathSegment(sessionId)}.json`);+}++function readSessionState(path: string): LspSessionState {+ try {+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));+ if (isLspSessionState(parsed)) return parsed;+ return emptyState();+ } catch (error) {+ if (error instanceof SyntaxError || (isRecord(error) && error["code"] === "ENOENT")) return emptyState();+ throw error;+ }+}++function writeSessionState(path: string, state: LspSessionState): void {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, `${JSON.stringify(state)}\n`);+}++function emptyState(): LspSessionState {+ return { unavailableExtensions: [] };+}++function extensionKey(filePath: string): string | undefined {+ const extension = extname(filePath).toLowerCase();+ return extension.length === 0 ? undefined : extension;+}++function safePathSegment(value: string): string {+ return value.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 120) || "unknown-session";+}++function isLspSessionState(value: unknown): value is LspSessionState {+ if (!isRecord(value) || !Array.isArray(value["unavailableExtensions"])) return false;+ const postCompactProbePending = value["postCompactProbePending"];+ return (+ value["unavailableExtensions"].every((item) => typeof item === "string") &&+ (postCompactProbePending === undefined || typeof postCompactProbePending === "boolean")+ );+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/lsp/src/mutated-file-paths.ts b/plugins/omo/components/lsp/src/mutated-file-paths.tsnew file mode 100644index 00000000..31daca2c--- /dev/null+++ b/plugins/omo/components/lsp/src/mutated-file-paths.ts@@ -0,0 +1,88 @@+const MUTATION_TOOL_NAMES = new Set(["apply_patch", "write", "edit", "multiedit", "multi_edit"]);++export interface MutatedFileInput {+ readonly tool_name?: unknown;+ readonly tool_input?: unknown;+ readonly tool_response?: unknown;+}++export function extractMutatedFilePaths(input: MutatedFileInput): string[] {+ if (!isMutationTool(input.tool_name)) return [];+ if (isFailedToolResponse(input.tool_response)) return [];++ const toolInput = isRecord(input.tool_input) ? input.tool_input : {};+ const paths = new Set<string>();+ addStringValue(paths, toolInput["path"]);+ addStringValue(paths, toolInput["filePath"]);+ addStringValue(paths, toolInput["file_path"]);+ addStringArray(paths, toolInput["paths"]);+ addStringArray(paths, toolInput["filePaths"]);+ addStringArray(paths, toolInput["file_paths"]);+ addPatchPayloads(paths, toolInput);+ addPatchFiles(paths, toolInput["files"]);+ addPatchFiles(paths, toolInput["changes"]);+ return [...paths];+}++function isMutationTool(value: unknown): boolean {+ if (typeof value !== "string") return false;+ return MUTATION_TOOL_NAMES.has(value.toLowerCase());+}++function isFailedToolResponse(value: unknown): boolean {+ if (!isRecord(value)) return false;+ return (+ value["isError"] === true || value["is_error"] === true || value["error"] === true || value["status"] === "error"+ );+}++function addStringValue(paths: Set<string>, value: unknown): void {+ if (typeof value === "string" && value.length > 0) {+ paths.add(value);+ }+}++function addStringArray(paths: Set<string>, value: unknown): void {+ if (!Array.isArray(value)) return;+ for (const item of value) {+ addStringValue(paths, item);+ }+}++function addPatchPayloads(paths: Set<string>, input: Record<string, unknown>): void {+ addPatchInput(paths, input["input"]);+ addPatchInput(paths, input["patch"]);+ addPatchInput(paths, input["command"]);+}++function addPatchInput(paths: Set<string>, value: unknown): void {+ if (typeof value !== "string") return;+ for (const line of value.split("\n")) {+ const path = extractPatchHeaderPath(line);+ if (path !== undefined) paths.add(path);+ }+}++function extractPatchHeaderPath(line: string): string | undefined {+ const prefixes = ["*** Add File: ", "*** Update File: ", "*** Move to: "] as const;+ for (const prefix of prefixes) {+ if (line.startsWith(prefix)) return line.slice(prefix.length).trim();+ }+ return undefined;+}++function addPatchFiles(paths: Set<string>, value: unknown): void {+ if (!Array.isArray(value)) return;+ for (const item of value) {+ if (!isRecord(item)) continue;+ addStringValue(paths, item["path"]);+ addStringValue(paths, item["filePath"]);+ addStringValue(paths, item["file_path"]);+ addStringValue(paths, item["movePath"]);+ addStringValue(paths, item["move_path"]);+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/lsp/test/codex-hook-cli.test.ts b/plugins/omo/components/lsp/test/codex-hook-cli.test.tsnew file mode 100644index 00000000..7d8ff7ad--- /dev/null+++ b/plugins/omo/components/lsp/test/codex-hook-cli.test.ts@@ -0,0 +1,28 @@+import { spawnSync } from "node:child_process";+import path from "node:path";+import { fileURLToPath } from "node:url";++import { describe, expect, it } from "vitest";++describe("codex PostToolUse hook CLI", () => {+ it("#given malformed post-tool-use stdin #when hook CLI runs #then it no-ops without stderr", () => {+ // given+ const input = "break;\n";++ // when+ const result = runBuiltHookCli(input);++ // then+ expect(result.status).toBe(0);+ expect(result.stderr).toBe("");+ expect(result.stdout).toBe("");+ });+});++function runBuiltHookCli(input: string): ReturnType<typeof spawnSync> {+ const cliPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../dist/cli.js");+ return spawnSync(process.execPath, [cliPath, "hook", "post-tool-use"], {+ input,+ encoding: "utf8",+ });+}diff --git a/plugins/omo/components/lsp/test/codex-hook-errors.test.ts b/plugins/omo/components/lsp/test/codex-hook-errors.test.tsnew file mode 100644index 00000000..076dfc33--- /dev/null+++ b/plugins/omo/components/lsp/test/codex-hook-errors.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from "vitest";++import { runLspPostToolUseHook } from "../src/codex-hook.js";++describe("codex PostToolUse diagnostics errors", () => {+ it("#given diagnostics runner throws for a mutated file #when the hook evaluates diagnostics #then it returns blocked output with the thrown message", async () => {+ // given+ const output = await runLspPostToolUseHook(+ {+ tool_name: "write",+ tool_input: { path: "src/missing.ts" },+ tool_response: { ok: true },+ },+ async (filePath) => {+ expect(filePath).toBe("src/missing.ts");+ throw new Error("ENOENT: no such file or directory, open 'src/missing.ts'");+ },+ );++ // when+ const parsed: unknown = JSON.parse(output);+ if (!isPostToolUseHookOutput(parsed)) throw new TypeError("Expected PostToolUse hook output");++ // then+ expect(parsed.reason).toBe(+ "LSP diagnostics after editing src/missing.ts:\n\nENOENT: no such file or directory, open 'src/missing.ts'",+ );+ expect(parsed.hookSpecificOutput.additionalContext).toBe(parsed.reason);+ });+});++interface PostToolUseHookOutput {+ readonly decision: "block";+ readonly reason: string;+ readonly hookSpecificOutput: {+ readonly hookEventName: "PostToolUse";+ readonly additionalContext: string;+ };+}++function isPostToolUseHookOutput(value: unknown): value is PostToolUseHookOutput {+ if (!isRecord(value)) return false;+ const hookSpecificOutput = value["hookSpecificOutput"];+ return (+ value["decision"] === "block" &&+ typeof value["reason"] === "string" &&+ isRecord(hookSpecificOutput) &&+ hookSpecificOutput["hookEventName"] === "PostToolUse" &&+ typeof hookSpecificOutput["additionalContext"] === "string"+ );+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/lsp/test/codex-hook-unavailable.test.ts b/plugins/omo/components/lsp/test/codex-hook-unavailable.test.tsnew file mode 100644index 00000000..7c4371f0--- /dev/null+++ b/plugins/omo/components/lsp/test/codex-hook-unavailable.test.ts@@ -0,0 +1,206 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";++import { afterEach, describe, expect, it } from "vitest";++import { runLspPostCompactHook, runLspPostToolUseHook } from "../src/codex-hook.js";++const MARKSMAN_INITIALIZE_TIMEOUT = [+ "LSP request timeout (method: initialize)",+ 'recent stderr: [01:16:41 INF] <LSP Entry> Starting Marksman LSP server: {"arch":"Arm64"}',+ '[01:16:41 INF] <Folder> Loading folder documents: {"uri":"file:///repo"}',+].join("\n");++const tempDirs: string[] = [];++afterEach(() => {+ for (const tempDir of tempDirs.splice(0)) {+ rmSync(tempDir, { recursive: true, force: true });+ }+});++describe("codex PostToolUse unavailable LSP suppression", () => {+ it("#given unavailable markdown LSP in one session #when PostToolUse repeats #then suppresses feedback and skips the cached extension", async () => {+ // given+ const pluginData = tempPluginData();+ const input = postToolUseInput("session-unavailable", ".omo/ulw-loop/evidence/note.md");+ let calls = 0;++ await withPluginData(pluginData, async () => {+ // when+ const firstOutput = await runLspPostToolUseHook(input, async () => {+ calls += 1;+ return MARKSMAN_INITIALIZE_TIMEOUT;+ });+ const secondOutput = await runLspPostToolUseHook(input, async () => {+ calls += 1;+ return "error[markdown] (1000) at 1:1: second call should have been skipped.";+ });++ // then+ expect(firstOutput).toBe("");+ expect(secondOutput).toBe("");+ expect(calls).toBe(1);+ });+ });++ it("#given cached unavailable LSP after PostCompact #when the next PostToolUse runs #then probes once and suppresses again", async () => {+ // given+ const pluginData = tempPluginData();+ const input = postToolUseInput("session-compact", ".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.";+ });++ // when+ const compactInput = {+ cwd: "/repo",+ hook_event_name: "PostCompact",+ model: "gpt-5.5",+ session_id: "session-compact",+ transcript_path: null,+ trigger: "manual",+ turn_id: "turn-compact",+ };+ const compactOutput = await runLspPostCompactHook(compactInput);+ const afterCompactOutput = await runLspPostToolUseHook(input, async () => {+ calls += 1;+ return MARKSMAN_INITIALIZE_TIMEOUT;+ });+ await runLspPostToolUseHook(input, async () => {+ calls += 1;+ return "error[markdown] (1000) at 1:1: post-compact cached call should have been skipped.";+ });++ // then+ expect(compactOutput).toBe("");+ expect(afterCompactOutput).toBe("");+ expect(calls).toBe(2);+ });+ });++ it("#given cached unavailable LSP after PostCompact #when the probe is clean #then clears the unavailable cache", async () => {+ // given+ const pluginData = tempPluginData();+ const input = postToolUseInput("session-compact-clean", ".omo/ulw-loop/evidence/note.md");+ let calls = 0;++ await withPluginData(pluginData, async () => {+ await runLspPostToolUseHook(input, async () => {+ calls += 1;+ return MARKSMAN_INITIALIZE_TIMEOUT;+ });+ await runLspPostCompactHook({ session_id: "session-compact-clean" });++ // when+ const cleanProbeOutput = await runLspPostToolUseHook(input, async () => {+ calls += 1;+ return "No diagnostics found";+ });+ const laterDiagnosticOutput = await runLspPostToolUseHook(input, async () => {+ calls += 1;+ return "error[markdown] (1000) at 1:1: recovered markdown diagnostic.";+ });++ // then+ expect(cleanProbeOutput).toBe("");+ expect(laterDiagnosticOutput).toContain("recovered markdown diagnostic");+ expect(calls).toBe(3);+ });+ });++ it("#given markdown LSP is cached unavailable #when TypeScript diagnostics run #then real diagnostics still block", async () => {+ // given+ const pluginData = tempPluginData();+ const markdownInput = postToolUseInput("session-real-diagnostics", "README.md");+ const typescriptInput = postToolUseInput("session-real-diagnostics", "src/broken.ts");++ await withPluginData(pluginData, async () => {+ await runLspPostToolUseHook(markdownInput, async () => MARKSMAN_INITIALIZE_TIMEOUT);++ // when+ const output = await runLspPostToolUseHook(+ typescriptInput,+ async () => "error[typescript] (2304) at 1:1: Cannot find name 'missing'.",+ );++ // then+ const parsed: unknown = JSON.parse(output);+ if (!isPostToolUseHookOutput(parsed)) throw new TypeError("Expected PostToolUse hook output");+ expect(parsed.reason).toBe(+ "LSP diagnostics after editing src/broken.ts:\n\n" ++ "- error[typescript] (2304) at 1:1: Cannot find name 'missing'.",+ );+ });+ });+});++function postToolUseInput(sessionId: string, filePath: string) {+ return {+ cwd: "/repo",+ hook_event_name: "PostToolUse",+ model: "gpt-5.5",+ permission_mode: "default",+ session_id: sessionId,+ tool_input: { path: filePath },+ tool_name: "write",+ tool_response: { ok: true },+ tool_use_id: "tool-use-1",+ transcript_path: null,+ turn_id: "turn-1",+ };+}++async function withPluginData(pluginData: string, fn: () => Promise<void>): Promise<void> {+ const previous = process.env["PLUGIN_DATA"];+ process.env["PLUGIN_DATA"] = pluginData;+ try {+ await fn();+ } finally {+ if (previous === undefined) {+ delete process.env["PLUGIN_DATA"];+ } else {+ process.env["PLUGIN_DATA"] = previous;+ }+ }+}++function tempPluginData(): string {+ const dir = mkdtempSync(path.join(tmpdir(), "codex-lsp-unavailable-"));+ tempDirs.push(dir);+ return dir;+}++interface PostToolUseHookOutput {+ readonly decision: "block";+ readonly reason: string;+ readonly hookSpecificOutput: {+ readonly hookEventName: "PostToolUse";+ readonly additionalContext: string;+ };+}++function isPostToolUseHookOutput(value: unknown): value is PostToolUseHookOutput {+ if (!isRecord(value)) return false;+ const hookSpecificOutput = value["hookSpecificOutput"];+ return (+ value["decision"] === "block" &&+ typeof value["reason"] === "string" &&+ isRecord(hookSpecificOutput) &&+ hookSpecificOutput["hookEventName"] === "PostToolUse" &&+ typeof hookSpecificOutput["additionalContext"] === "string"+ );+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/lsp/test/codex-hook.test.ts b/plugins/omo/components/lsp/test/codex-hook.test.tsindex 0bda45d1..0b34e163 100644--- a/plugins/omo/components/lsp/test/codex-hook.test.ts+++ b/plugins/omo/components/lsp/test/codex-hook.test.ts@@ -1,7 +1,19 @@-import { describe, expect, it } from "vitest";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";++import { afterEach, describe, expect, it } from "vitest";import { extractMutatedFilePaths, runLspPostToolUseHook } from "../src/codex-hook.js";+const tempDirs: string[] = [];++afterEach(() => {+ for (const tempDir of tempDirs.splice(0)) {+ rmSync(tempDir, { recursive: true, force: true });+ }+});+describe("codex PostToolUse hook", () => {it("extracts files from Codex apply_patch command payloads", () => {const paths = extractMutatedFilePaths({@@ -34,7 +46,8 @@ describe("codex PostToolUse hook", () => {expect(paths).toEqual(["src/edit.ts"]);});- it("returns blocking feedback when post-edit diagnostics contain errors", async () => {+ it("#given post-edit diagnostics contain one error #when the hook blocks #then it keeps the blocked output shape", async () => {+ // givenconst output = await runLspPostToolUseHook({tool_name: "apply_patch",@@ -49,21 +62,103 @@ describe("codex PostToolUse hook", () => {},);+ // when+ const parsed: unknown = JSON.parse(output);++ // thenexpect(JSON.parse(output)).toEqual({decision: "block",hookSpecificOutput: {hookEventName: "PostToolUse",additionalContext:- "LSP diagnostics after editing src/broken.ts:\n" +- "error[typescript] (2304) at 1:1: Cannot find name 'missing'.",+ "LSP diagnostics after editing src/broken.ts:\n\n" ++ "- error[typescript] (2304) at 1:1: Cannot find name 'missing'.",},reason:- "LSP diagnostics after editing src/broken.ts:\n" +- "error[typescript] (2304) at 1:1: Cannot find name 'missing'.",+ "LSP diagnostics after editing src/broken.ts:\n\n" ++ "- error[typescript] (2304) at 1:1: Cannot find name 'missing'.",});+ expect(parsed).toHaveProperty("decision", "block");+ });++ it("#given adjacent TypeScript diagnostics #when the hook blocks #then it renders each diagnostic on its own bullet line", async () => {+ // given+ const output = await runLspPostToolUseHook(+ {+ tool_name: "apply_patch",+ tool_input: {+ command: "*** Begin Patch\n*** Update File: src/broken.ts\n@@\n+missing();\n*** End Patch\n",+ },+ tool_response: "Success. Updated files.",+ },+ async () =>+ "error[typescript] (2307) at 5:7: Cannot find module 'openclaw/plugin-sdk/config-runtime' or its corresponding type declarations.error[typescript] (2307) at 6:49: Cannot find module 'openclaw/plugin-sdk/config-runtime' or its corresponding type declarations.error[typescript] (2307) at 10:7: Cannot find module 'openclaw/plugin-sdk/config-runtime' or its corresponding type declarations.",+ );++ // when+ const parsed: unknown = JSON.parse(output);+ if (!isPostToolUseHookOutput(parsed)) throw new TypeError("Expected PostToolUse hook output");++ // then+ expect(parsed.reason).toBe(+ [+ "LSP diagnostics after editing src/broken.ts:",+ "",+ "- error[typescript] (2307) at 5:7: Cannot find module 'openclaw/plugin-sdk/config-runtime' or its corresponding type declarations.",+ "- error[typescript] (2307) at 6:49: Cannot find module 'openclaw/plugin-sdk/config-runtime' or its corresponding type declarations.",+ "- error[typescript] (2307) at 10:7: Cannot find module 'openclaw/plugin-sdk/config-runtime' or its corresponding type declarations.",+ ].join("\n"),+ );+ expect(parsed.hookSpecificOutput.additionalContext).toBe(parsed.reason);+ });++ it("#given plain non-diagnostic feedback #when the hook blocks #then it preserves the text after the readable header", async () => {+ // given+ const output = await runLspPostToolUseHook(+ {+ tool_name: "write",+ tool_input: { path: "src/broken.ts" },+ tool_response: { ok: true },+ },+ async () => "language server failed before diagnostics could be collected",+ );++ // when+ const parsed: unknown = JSON.parse(output);+ if (!isPostToolUseHookOutput(parsed)) throw new TypeError("Expected PostToolUse hook output");++ // then+ expect(parsed.reason).toBe(+ "LSP diagnostics after editing src/broken.ts:\n\nlanguage server failed before diagnostics could be collected",+ );+ expect(parsed.hookSpecificOutput.additionalContext).toBe(parsed.reason);+ });++ it("#given plain non-diagnostic feedback with CRLF and bare CR #when the hook blocks #then it normalizes line endings", async () => {+ // given+ const output = await runLspPostToolUseHook(+ {+ tool_name: "write",+ tool_input: { path: "src/broken.ts" },+ tool_response: { ok: true },+ },+ async () => "\r\nlanguage server failed\r\n retry detail\rbefore diagnostics could be collected\r\n",+ );++ // when+ const parsed: unknown = JSON.parse(output);+ if (!isPostToolUseHookOutput(parsed)) throw new TypeError("Expected PostToolUse hook output");++ // then+ expect(parsed.reason).toBe(+ "LSP diagnostics after editing src/broken.ts:\n\nlanguage server failed\n retry detail\nbefore diagnostics could be collected",+ );+ expect(parsed.reason).not.toContain("\r");+ expect(parsed.hookSpecificOutput.additionalContext).toBe(parsed.reason);});- it("injects only files with diagnostics when multiple files are edited", async () => {+ it("#given multiple edited files #when only one file has diagnostics #then it injects only files with diagnostics", async () => {+ // givenconst checkedFilePaths: string[] = [];const output = await runLspPostToolUseHook({@@ -85,10 +180,12 @@ describe("codex PostToolUse hook", () => {},);+ // whenconst expectedDiagnostics =- "LSP diagnostics after editing src/broken.ts:\n" +- "error[typescript] (2322) at 1:7: Type 'number' is not assignable to type 'string'.";+ "LSP diagnostics after editing src/broken.ts:\n\n" ++ "- error[typescript] (2322) at 1:7: Type 'number' is not assignable to type 'string'.";+ // thenexpect(checkedFilePaths).toEqual(["src/clean.ts", "README.md", "src/broken.ts"]);expect(JSON.parse(output)).toEqual({decision: "block",@@ -100,6 +197,69 @@ describe("codex PostToolUse hook", () => {});});+ it("#given multiple edited files #when diagnostics resolve out of order #then starts bounded concurrent diagnostics and preserves output order", async () => {+ // given+ const calls: string[] = [];+ const resolvers = new Map<string, (value: string) => void>();+ const outputPromise = runLspPostToolUseHook(+ {+ tool_name: "MultiEdit",+ tool_input: { file_paths: ["src/a.ts", "src/b.ts"] },+ tool_response: { ok: true },+ },+ (filePath) =>+ new Promise<string>((resolve) => {+ calls.push(filePath);+ resolvers.set(filePath, resolve);+ }),+ );++ // when+ const startedBeforeRelease = [...calls];+ const resolveB = resolvers.get("src/b.ts");+ const resolveA = resolvers.get("src/a.ts");+ if (resolveB === undefined || resolveA === undefined) throw new TypeError("Expected both diagnostics to start");+ resolveB("error[typescript] (1000) at 1:1: src/b.ts failed.");+ await Promise.resolve();+ resolveA("error[typescript] (1000) at 1:1: src/a.ts failed.");+ const parsed: unknown = JSON.parse(await outputPromise);+ if (!isPostToolUseHookOutput(parsed)) throw new TypeError("Expected PostToolUse hook output");++ // then+ expect(startedBeforeRelease).toEqual(["src/a.ts", "src/b.ts"]);+ expect(parsed.reason.indexOf("src/a.ts")).toBeLessThan(parsed.reason.indexOf("src/b.ts"));+ });++ it("#given six edited files #when diagnostics run #then at most four are active concurrently", async () => {+ // given+ const calls: string[] = [];+ const resolvers = new Map<string, (value: string) => void>();+ const filePaths = ["src/a.ts", "src/b.ts", "src/c.ts", "src/d.ts", "src/e.ts", "src/f.ts"];+ const outputPromise = runLspPostToolUseHook(+ {+ tool_name: "MultiEdit",+ tool_input: { file_paths: filePaths },+ tool_response: { ok: true },+ },+ (filePath) =>+ new Promise<string>((resolve) => {+ calls.push(filePath);+ resolvers.set(filePath, resolve);+ }),+ );++ // when+ const initialCalls = [...calls];+ for (const filePath of filePaths) {+ resolvers.get(filePath)?.("No diagnostics found");+ await Promise.resolve();+ }+ await outputPromise;++ // then+ expect(initialCalls).toEqual(["src/a.ts", "src/b.ts", "src/c.ts", "src/d.ts"]);+ });+it("does not run diagnostics for failed mutation tool responses", async () => {const output = await runLspPostToolUseHook({@@ -131,4 +291,68 @@ describe("codex PostToolUse hook", () => {expect(output).toBe("");});++ it("#given Codex canonical context-window transcript and large diagnostics #when the hook blocks #then it caps injected feedback", async () => {+ const root = mkdtempSync(path.join(tmpdir(), "codex-lsp-context-pressure-"));+ tempDirs.push(root);+ const transcriptPath = path.join(root, "transcript.jsonl");+ writeFileSync(+ transcriptPath,+ [+ "context_length_exceeded",+ "Codex ran out of room in the model's context window. Start a new thread before retrying.",+ "",+ ].join("\n"),+ );+ const largeDiagnostics = [+ "error[typescript] (2322) at 1:1: Type 'number' is not assignable to type 'string'.",+ "x".repeat(10_000),+ ].join("\n");++ const output = await runLspPostToolUseHook(+ {+ tool_name: "apply_patch",+ tool_input: {+ command:+ "*** Begin Patch\n*** Update File: src/broken.ts\n@@\n+const value: string = 1;\n*** End Patch\n",+ },+ tool_response: "Success. Updated files.",+ transcript_path: transcriptPath,+ },+ async () => largeDiagnostics,+ );++ const parsed: unknown = JSON.parse(output);+ if (!isPostToolUseHookOutput(parsed)) throw new TypeError("Expected PostToolUse hook output");++ expect(parsed.reason.length).toBeLessThanOrEqual(1200);+ expect(parsed.reason).toContain("LSP diagnostics after editing src/broken.ts");+ expect(parsed.reason).toContain("[Truncated hook output");+ expect(parsed.hookSpecificOutput.additionalContext).toBe(parsed.reason);+ });});++interface PostToolUseHookOutput {+ readonly decision: "block";+ readonly reason: string;+ readonly hookSpecificOutput: {+ readonly hookEventName: "PostToolUse";+ readonly additionalContext: string;+ };+}++function isPostToolUseHookOutput(value: unknown): value is PostToolUseHookOutput {+ if (!isRecord(value)) return false;+ const hookSpecificOutput = value["hookSpecificOutput"];+ return (+ value["decision"] === "block" &&+ typeof value["reason"] === "string" &&+ isRecord(hookSpecificOutput) &&+ hookSpecificOutput["hookEventName"] === "PostToolUse" &&+ typeof hookSpecificOutput["additionalContext"] === "string"+ );+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/lsp/test/package-smoke.test.ts b/plugins/omo/components/lsp/test/package-smoke.test.tsindex 260a745b..72c02471 100644--- a/plugins/omo/components/lsp/test/package-smoke.test.ts+++ b/plugins/omo/components/lsp/test/package-smoke.test.ts@@ -1,4 +1,4 @@-import { readFileSync } from "node:fs";+import { readdirSync, readFileSync } from "node:fs";import { describe, expect, it } from "vitest";type PackageJson = {@@ -7,12 +7,7 @@ type PackageJson = {readonly packageManager: string;readonly bin: Record<string, string>;readonly dependencies: Record<string, string>;-};--type PluginJson = {- readonly version: string;- readonly hooks: string;- readonly mcpServers: string;+ readonly scripts: Record<string, string>;};type HookCommand = {@@ -42,12 +37,6 @@ function readPackageJson(path: string): PackageJson {return parsed;}-function readPluginJson(path: string): PluginJson {- const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));- if (!isPluginJson(parsed)) throw new TypeError(`Invalid plugin metadata: ${path}`);- return parsed;-}-function readHooksJson(path: string): HooksJson {const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));if (!isHooksJson(parsed)) throw new TypeError(`Invalid hooks metadata: ${path}`);@@ -61,33 +50,45 @@ function readMcpJson(path: string): McpJson {}describe("plugin package metadata", () => {- it("#given packaged plugin files #when validating entrypoints #then hook command uses portable plugin root interpolation", () => {+ it("#given packaged component files #when validating entrypoints #then hook command stays local and MCP command references the package", () => {// givenconst packageJson = readPackageJson("package.json");- const pluginJson = readPluginJson(".codex-plugin/plugin.json");const hooksJson = readHooksJson("hooks/hooks.json");const mcpJson = readMcpJson(".mcp.json");const cliSource = readFileSync("src/cli.ts", "utf8");+ const codexHookCliSource = readFileSync("src/codex-hook-cli.ts", "utf8");+ const codexHookSource = readFileSync("src/codex-hook.ts", "utf8");+ const sourceFiles = readdirSync("src");// when- const command = hooksJson.hooks["PostToolUse"]?.[0]?.hooks[0]?.command;+ const postToolUseCommand = hooksJson.hooks["PostToolUse"]?.[0]?.hooks[0]?.command;+ const postCompactCommand = hooksJson.hooks["PostCompact"]?.[0]?.hooks[0]?.command;const lspServer = mcpJson.mcpServers["lsp"];const pluginRoot = ["$", "{PLUGIN_ROOT}"].join("");// then- expect(pluginJson.version).toBe(packageJson.version);expect(packageJson.type).toBe("module");expect(packageJson.packageManager).toBe("[email protected]");expect(packageJson.dependencies).toEqual({- "@code-yeongyu/lsp-tools-mcp": "file:./packages/lsp-tools-mcp",+ "@code-yeongyu/lsp-tools-mcp": "file:../../../../lsp-tools-mcp",});- expect(packageJson.bin["codex-lsp"]).toBe("./dist/cli.js");- expect(pluginJson.hooks).toBe("./hooks/hooks.json");- expect(pluginJson.mcpServers).toBe("./.mcp.json");+ expect(packageJson.bin["omo-lsp"]).toBe("./dist/cli.js");+ expect(packageJson.bin["codex-lsp"]).toBeUndefined();+ expect(packageJson.scripts["build"]).toBe("node scripts/clean-dist.mjs && tsc -p tsconfig.build.json");expect(cliSource.startsWith("#!/usr/bin/env node")).toBe(true);- expect(command).toBe(`node "${pluginRoot}/dist/cli.js" hook post-tool-use`);+ expect(cliSource).toContain("Usage: omo-lsp [mcp | hook post-tool-use | hook post-compact]");+ 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(["./packages/lsp-tools-mcp/dist/cli.js", "mcp"]);+ expect(lspServer?.args).toEqual(["../../../../lsp-tools-mcp/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(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", () => {@@ -111,16 +112,8 @@ function isPackageJson(value: unknown): value is PackageJson {value["type"] === "module" &&value["packageManager"] === "[email protected]" &&isStringRecord(value["bin"]) &&- isStringRecord(value["dependencies"])- );-}--function isPluginJson(value: unknown): value is PluginJson {- return (- isRecord(value) &&- typeof value["version"] === "string" &&- typeof value["hooks"] === "string" &&- typeof value["mcpServers"] === "string"+ isStringRecord(value["dependencies"]) &&+ isStringRecord(value["scripts"]));}diff --git a/plugins/omo/components/rules/bundled-rules/hephaestus.md b/plugins/omo/components/rules/bundled-rules/hephaestus.mdindex 345b5e02..5ec76694 100644--- a/plugins/omo/components/rules/bundled-rules/hephaestus.md+++ b/plugins/omo/components/rules/bundled-rules/hephaestus.md@@ -79,13 +79,15 @@ omo-codex bundles three read-only Codex subagent roles in `CODEX_HOME/agents/`:**Routing:**-- "Where is X?" / "Find code that does Y" -> `spawn_agent(agent_type="explorer", ...)`-- "How does library Z work?" / "What's the API contract?" -> `spawn_agent(agent_type="librarian", ...)`-- 5+ interdependent steps, ambiguous scope, multi-module work -> `spawn_agent(agent_type="plan", ...)`-- Heavy verification of a finished change -> `spawn_agent(agent_type="codex-ultrawork-reviewer", ...)`+- "Where is X?" / "Find code that does Y" -> `spawn_agent(agent_type="explorer", fork_turns="none", ...)`+- "How does library Z work?" / "What's the API contract?" -> `spawn_agent(agent_type="librarian", fork_turns="none", ...)`+- 5+ interdependent steps, ambiguous scope, multi-module work -> `spawn_agent(agent_type="plan", fork_turns="none", ...)`+- Heavy verification of a finished change -> `spawn_agent(agent_type="codex-ultrawork-reviewer", fork_turns="none", ...)`**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.+**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, last heartbeat, 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.+# 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.@@ -158,7 +160,7 @@ AGENTS.md files in your context carry directory-scoped conventions. Obey them fo- Multi-line code in fenced blocks with a language tag.- The user does not see command outputs - summarize the key lines when reporting them.- No emojis or em dashes unless the user explicitly requests them.-- Never output broken inline citations like `[F:README.md L5-L14]` - they break the CLI.+- Never output broken inline citations like `【F:README.md†L5-L14】` - they break the CLI.# Success Criteriadiff --git a/plugins/omo/components/rules/bundled-rules/windows-git-bash.md b/plugins/omo/components/rules/bundled-rules/windows-git-bash.mdnew file mode 100644index 00000000..71b2f263--- /dev/null+++ b/plugins/omo/components/rules/bundled-rules/windows-git-bash.md@@ -0,0 +1,10 @@+---+description: Windows Git Bash guidance for Codex+alwaysApply: true+---++On Windows native Codex sessions, prefer Git Bash for shell commands.++Use `shell: "bash"` when `bash.exe` is on PATH. Otherwise use the absolute Git Bash path from `OMO_CODEX_GIT_BASH_PATH` or `C:\Program Files\Git\bin\bash.exe`.++Use PowerShell only for Windows-native operations that need PowerShell.diff --git a/plugins/omo/components/rules/hooks/hooks.json b/plugins/omo/components/rules/hooks/hooks.jsonindex a6e2f1ab..46831e87 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": "loading project rules"+ "statusMessage": "LazyCodex(0.1.0): Loading Project Rules"}]}@@ -19,7 +19,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit","timeout": 10,- "statusMessage": "loading project rules"+ "statusMessage": "LazyCodex(0.1.0): Loading Project Rules"}]}@@ -32,7 +32,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use","timeout": 10,- "statusMessage": "matching project rules"+ "statusMessage": "LazyCodex(0.1.0): Matching Project Rules"}]}@@ -45,7 +45,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact","timeout": 10,- "statusMessage": "resetting project rule cache"+ "statusMessage": "LazyCodex(0.1.0): Resetting Project Rule Cache"}]}diff --git a/plugins/omo/components/rules/package.json b/plugins/omo/components/rules/package.jsonindex 31a304e1..422bc80f 100644--- a/plugins/omo/components/rules/package.json+++ b/plugins/omo/components/rules/package.json@@ -23,7 +23,7 @@"typescript"],"bin": {- "codex-rules": "./dist/cli.js"+ "omo-rules": "./dist/cli.js"},"files": ["bundled-rules",diff --git a/plugins/omo/components/rules/src/cli.ts b/plugins/omo/components/rules/src/cli.tsindex 64fa4ddf..dfa2ce2e 100644--- a/plugins/omo/components/rules/src/cli.ts+++ b/plugins/omo/components/rules/src/cli.ts@@ -26,7 +26,7 @@ if (command === "hook" && subcommand === "session-start") {} else if (command === "hook" && subcommand === "post-compact") {await runHookCli("PostCompact");} else {- process.stderr.write("Usage: codex-rules hook [session-start|user-prompt-submit|post-tool-use|post-compact]\n");+ process.stderr.write("Usage: omo-rules hook [session-start|user-prompt-submit|post-tool-use|post-compact]\n");process.exitCode = 1;}diff --git a/plugins/omo/components/rules/src/codex-hook-options.ts b/plugins/omo/components/rules/src/codex-hook-options.tsnew file mode 100644index 00000000..ef5b3f73--- /dev/null+++ b/plugins/omo/components/rules/src/codex-hook-options.ts@@ -0,0 +1,5 @@+export interface CodexRulesHookOptions {+ env?: NodeJS.ProcessEnv;+ pluginDataRoot?: string;+ platform?: NodeJS.Platform;+}diff --git a/plugins/omo/components/rules/src/codex-hook.ts b/plugins/omo/components/rules/src/codex-hook.tsindex 8a29d245..84d0f94c 100644--- a/plugins/omo/components/rules/src/codex-hook.ts+++ b/plugins/omo/components/rules/src/codex-hook.ts@@ -1,27 +1,28 @@-import { readFileSync, statSync } from "node:fs";-import { isAbsolute, relative, resolve } from "node:path";-+import type { CodexRulesHookOptions } from "./codex-hook-options.js";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 { formatAdditionalContextOutput } from "./hook-output.js";+import { displayPath, uniqueStrings } from "./path-utils.js";import {+ claimPostCompactPending,clearSessionState,hasPostCompactPending,hydrateEngineState,- isPostCompactPending,+ isPostCompactRecoveryInProgress,markSessionCompacted,persistEngineState,sessionCachePath,} from "./persistent-cache.js";-import { SOURCE_PRIORITY } from "./rules/constants.js";-import { createEngine } from "./rules/engine.js";-import { createRuleDiscoveryCache, findRuleCandidates } from "./rules/finder.js";-import { hashContent } from "./rules/matcher.js";-import { sortCandidates } from "./rules/ordering.js";-import { findProjectRoot } from "./rules/project-root.js";-import type { LoadedRule, PiRulesConfig, RuleCandidate } from "./rules/types.js";+import { withPostCompactBudget } from "./post-compact-budget.js";+import { claimedPostCompactKind, shouldSkipPostCompactClaim } from "./post-compact-claim.js";+import { createRulesEngine } from "./rules-engine-factory.js";+import { runStaticInjection } from "./static-injection.js";import { extractCodexToolPaths } from "./tool-paths.js";+import { filterRulesAlreadyInTranscript } from "./transcript-rule-filter.js";-type ContextInjectionHookEventName = "SessionStart" | "UserPromptSubmit" | "PostToolUse";+export type { CodexRulesHookOptions } from "./codex-hook-options.js";export type CodexSessionStartInput = {session_id: string;@@ -30,7 +31,7 @@ export type CodexSessionStartInput = {hook_event_name: "SessionStart";model: string;permission_mode: string;- source: "startup" | "resume" | "clear";+ source: "startup" | "resume" | "clear" | "compact";};export type CodexUserPromptSubmitInput = {@@ -68,17 +69,6 @@ export type CodexPostCompactInput = {trigger: "manual" | "auto";};-export interface CodexRulesHookOptions {- env?: NodeJS.ProcessEnv;- pluginDataRoot?: string;-}--interface DynamicTargetFingerprint {- targetPath: string;- cacheKey: string;- fingerprint: string;-}-export async function runSessionStartHook(input: CodexSessionStartInput,options: CodexRulesHookOptions = {},@@ -86,18 +76,31 @@ export async function runSessionStartHook(const cachePath = sessionCachePath(input.session_id, options.pluginDataRoot);if (input.source === "clear") {clearSessionState(cachePath);- } else if (input.source !== "resume" && !hasPostCompactPending(cachePath)) {+ } else if (input.source !== "resume" && input.source !== "compact" && !hasPostCompactPending(cachePath)) {clearSessionState(cachePath);}- const postCompactPending = input.source !== "clear" && isPostCompactPending(cachePath, "static");- const transcriptPath = input.source === "clear" || postCompactPending ? null : input.transcript_path;+ const postCompactClaim = input.source === "clear" ? "not-pending" : claimPostCompactPending(cachePath, "static");+ const completedPostCompactKind =+ claimedPostCompactKind(postCompactClaim, "static") ??+ (input.source === "compact" && postCompactClaim === "not-pending" ? "static" : undefined);+ if (+ shouldSkipPostCompactClaim(+ postCompactClaim,+ input.source === "compact" && isPostCompactRecoveryInProgress(cachePath, "static"),+ )+ ) {+ return "";+ }+ const transcriptPath = input.source === "clear" ? null : input.transcript_path;return runStaticInjection(input.cwd,transcriptPath,"SessionStart",cachePath,options,- postCompactPending ? "static" : undefined,+ completedPostCompactKind,+ { latestCompactedReplacementOnly: completedPostCompactKind !== undefined },+ input.model,);}@@ -113,16 +116,27 @@ export async function runUserPromptSubmitHook(input: CodexUserPromptSubmitInput,options: CodexRulesHookOptions = {},): Promise<string> {+ if (hasContextPressureMarker(input.prompt)) {+ return "";+ }const cachePath = sessionCachePath(input.session_id, options.pluginDataRoot);- const postCompactPending = isPostCompactPending(cachePath, "static");- const transcriptPath = postCompactPending ? null : input.transcript_path;+ const postCompactClaim = claimPostCompactPending(cachePath, "static");+ if (postCompactClaim === "not-pending" && transcriptHasContextPressureMarker(input.transcript_path)) {+ return "";+ }+ const completedPostCompactKind = claimedPostCompactKind(postCompactClaim, "static");+ if (shouldSkipPostCompactClaim(postCompactClaim, isPostCompactRecoveryInProgress(cachePath, "static"))) {+ return "";+ }return runStaticInjection(input.cwd,- transcriptPath,+ input.transcript_path,"UserPromptSubmit",cachePath,options,- postCompactPending ? "static" : undefined,+ completedPostCompactKind,+ { latestCompactedReplacementOnly: completedPostCompactKind !== undefined },+ input.model,);}@@ -151,9 +165,22 @@ export async function runPostToolUseHook(}const cachePath = sessionCachePath(input.session_id, options.pluginDataRoot);- const postCompactPending = isPostCompactPending(cachePath, "dynamic");- const transcriptPath = postCompactPending ? null : input.transcript_path;- const engine = createRulesEngine(options);+ const postCompactClaim = claimPostCompactPending(cachePath, "dynamic");+ if (postCompactClaim === "not-pending" && transcriptHasContextPressureMarker(input.transcript_path)) {+ debugTimer.done({ outputBytes: 0, reason: "context-pressure-transcript" });+ return "";+ }+ const completedPostCompactKind = claimedPostCompactKind(postCompactClaim, "dynamic");+ if (shouldSkipPostCompactClaim(postCompactClaim, isPostCompactRecoveryInProgress(cachePath, "dynamic"))) {+ debugTimer.done({ outputBytes: 0, reason: "post-compact-recovery-in-progress" });+ return "";+ }+ const engine = createRulesEngine(+ options,+ completedPostCompactKind !== undefined+ ? withPostCompactBudget(config, { model: input.model, transcriptPath: input.transcript_path })+ : config,+ );hydrateEngineState(engine, cachePath);debugTimer.lap("hydrate", {dynamicDedupScopes: engine.state.dynamicDedup.size,@@ -167,7 +194,7 @@ export async function runPostToolUseHook();debugTimer.lap("pending", { pending: pendingTargetFingerprints.length });if (pendingTargetFingerprints.length === 0) {- persistEngineState(engine, cachePath, postCompactPending ? "dynamic" : undefined);+ persistEngineState(engine, cachePath, completedPostCompactKind);debugTimer.lap("persist", { reason: "no-pending" });debugTimer.done({ outputBytes: 0, reason: "no-pending" });return "";@@ -180,17 +207,18 @@ export async function runPostToolUseHook(debugTimer.lap("load", { diagnostics: loaded.diagnostics.length, loadedRules: loaded.rules.length });const rules = filterRulesAlreadyInTranscript(loaded.rules.filter((rule) => !engine.isStaticInjected(rule) && !engine.isDynamicInjected(rule)),- transcriptPath,+ input.transcript_path,(rule) => {engine.markDynamicInjected(rule);},+ { latestCompactedReplacementOnly: completedPostCompactKind !== undefined },);debugTimer.lap("filter", { rules: rules.length });for (const target of pendingTargetFingerprints) {engine.state.dynamicTargetFingerprints.set(target.cacheKey, target.fingerprint);}if (rules.length === 0) {- persistEngineState(engine, cachePath, postCompactPending ? "dynamic" : undefined);+ persistEngineState(engine, cachePath, completedPostCompactKind);debugTimer.lap("persist", { reason: "no-rules" });debugTimer.done({ outputBytes: 0, reason: "no-rules" });return "";@@ -202,274 +230,9 @@ export async function runPostToolUseHook(for (const rule of rules) {engine.markDynamicInjected(rule);}- persistEngineState(engine, cachePath, postCompactPending ? "dynamic" : undefined);+ persistEngineState(engine, cachePath, completedPostCompactKind);debugTimer.lap("persist", { reason: "emit" });const output = formatAdditionalContextOutput("PostToolUse", block);debugTimer.done({ outputBytes: Buffer.byteLength(output), reason: "emit" });return output;}--function runStaticInjection(- cwd: string,- transcriptPath: string | null,- eventName: "SessionStart" | "UserPromptSubmit",- cachePath: string,- options: CodexRulesHookOptions,- completedPostCompactChannel?: "static",-): string {- const config = configFromEnvironment(options.env);- if (config.disabled || config.mode === "off" || config.mode === "dynamic") {- return "";- }-- const engine = createRulesEngine(options);- hydrateEngineState(engine, cachePath);- engine.state.cwd = cwd;-- const loaded = engine.loadStaticRules(cwd);- const rules = filterRulesAlreadyInTranscript(- loaded.rules.filter((rule) => !engine.isStaticInjected(rule)),- transcriptPath,- (rule) => {- engine.markStaticInjected(rule);- },- );- if (rules.length === 0) {- persistEngineState(engine, cachePath, completedPostCompactChannel);- return "";- }-- const block = engine.formatStatic(rules);- for (const rule of rules) {- engine.markStaticInjected(rule);- }- persistEngineState(engine, cachePath, completedPostCompactChannel);- return formatAdditionalContextOutput(eventName, block);-}--function filterRulesAlreadyInTranscript(- rules: ReadonlyArray<LoadedRule>,- transcriptPath: string | null,- markInjected: (rule: LoadedRule) => void,-): LoadedRule[] {- if (rules.length === 0 || transcriptPath === null) {- return [...rules];- }-- const transcriptText = readTranscriptSearchText(transcriptPath);- if (transcriptText === null) {- return [...rules];- }-- const pendingRules: LoadedRule[] = [];- for (const rule of rules) {- if (isRuleAlreadyInTranscript(rule, transcriptText)) {- markInjected(rule);- continue;- }-- pendingRules.push(rule);- }- return pendingRules;-}--function isRuleAlreadyInTranscript(rule: LoadedRule, transcriptText: string): boolean {- const bodyNeedle = rule.body.trim().slice(0, 2_000);- if (bodyNeedle.length === 0 || !transcriptText.includes(bodyNeedle)) {- return false;- }-- const markers = [- `Instructions from: ${rule.path}`,- `Instructions from: ${rule.realPath}`,- rule.relativePath.length === 0 ? null : rule.relativePath,- ].filter((marker): marker is string => marker !== null);- return markers.some((marker) => transcriptText.includes(marker));-}--function readTranscriptSearchText(transcriptPath: string): string | null {- try {- const rawTranscript = readFileSync(transcriptPath, "utf8");- return [rawTranscript, ...collectJsonLineStrings(rawTranscript)].join("\n");- } catch {- return null;- }-}--function collectJsonLineStrings(rawTranscript: string): string[] {- const values: string[] = [];- for (const line of rawTranscript.split(/\r?\n/)) {- if (line.trim().length === 0) {- continue;- }-- try {- const parsed: unknown = JSON.parse(line);- collectStrings(parsed, values);- } catch {- // Non-JSON transcript lines are still covered by the raw transcript text.- }- }- return values;-}--function collectStrings(value: unknown, output: string[]): void {- if (typeof value === "string") {- output.push(value);- return;- }-- if (Array.isArray(value)) {- for (const item of value) {- collectStrings(item, output);- }- return;- }-- if (typeof value !== "object" || value === null) {- return;- }-- for (const item of Object.values(value)) {- collectStrings(item, output);- }-}--function createRulesEngine(options: CodexRulesHookOptions) {- const config = configFromEnvironment(options.env);- return createEngine(config, {- findCandidates: findRuleCandidates,- findProjectRoot,- readFile: (path) => {- try {- return readFileSync(path, "utf8");- } catch {- return null;- }- },- });-}--function fingerprintDynamicTargets(- cwd: string,- targetPaths: ReadonlyArray<string>,- config: PiRulesConfig,-): DynamicTargetFingerprint[] {- const disabledSources = disabledSourcesFor(config);- const discoveryCache = createRuleDiscoveryCache();- const cwdProjectRoot = findProjectRoot(cwd);- const fingerprints: DynamicTargetFingerprint[] = [];-- for (const targetPath of uniqueStrings(targetPaths)) {- const projectRoot =- cwdProjectRoot !== null && isSameOrChildPath(targetPath, cwdProjectRoot)- ? cwdProjectRoot- : findProjectRoot(targetPath);- const findOptions: {- projectRoot: string | null;- targetFile: string;- disabledSources?: ReadonlySet<string>;- cache: ReturnType<typeof createRuleDiscoveryCache>;- } = {- projectRoot,- targetFile: targetPath,- cache: discoveryCache,- };- if (disabledSources !== undefined) {- findOptions.disabledSources = disabledSources;- }- const candidates = findRuleCandidates(findOptions);- const candidateFingerprint = sortCandidates(candidates).map(fingerprintCandidate).join("\u0001");- const cacheKey = dynamicTargetCacheKey(targetPath);- fingerprints.push({- targetPath,- cacheKey,- fingerprint: hashContent(- [- "v1",- config.enabledSources === "auto" ? "auto" : config.enabledSources.join(","),- projectRoot ?? "",- cacheKey,- candidateFingerprint,- ].join("\u0000"),- ),- });- }-- return fingerprints;-}--function fingerprintCandidate(candidate: RuleCandidate): string {- return [- candidate.realPath,- candidate.relativePath,- candidate.source,- candidate.isGlobal ? "global" : "project",- candidate.isSingleFile ? "single" : "multi",- String(candidate.distance),- fileFingerprint(candidate.path),- ].join("\u0000");-}--function fileFingerprint(filePath: string): string {- try {- const stats = statSync(filePath, { bigint: true });- return `${stats.mtimeNs}:${stats.ctimeNs}:${stats.size}`;- } catch {- return "missing";- }-}--function disabledSourcesFor(config: PiRulesConfig): ReadonlySet<string> | undefined {- if (config.enabledSources === "auto") {- return undefined;- }-- const enabledSources = new Set(config.enabledSources);- return new Set([...SOURCE_PRIORITY.keys()].filter((source) => !enabledSources.has(source)));-}--function dynamicTargetCacheKey(targetPath: string): string {- return toPosixPath(resolve(targetPath));-}--function isSameOrChildPath(childPath: string, parentPath: string): boolean {- const childRelativePath = relative(parentPath, resolve(childPath));- return childRelativePath === "" || (!childRelativePath.startsWith("..") && !isAbsolute(childRelativePath));-}--function uniqueStrings(values: ReadonlyArray<string>): string[] {- const uniqueValues: string[] = [];- const seenValues = new Set<string>();- for (const value of values) {- if (seenValues.has(value)) {- continue;- }-- seenValues.add(value);- uniqueValues.push(value);- }- return uniqueValues;-}--function formatAdditionalContextOutput(eventName: ContextInjectionHookEventName, additionalContext: string): string {- if (additionalContext.trim().length === 0) return "";- return `${JSON.stringify({- hookSpecificOutput: {- hookEventName: eventName,- additionalContext,- },- })}\n`;-}--function displayPath(cwd: string, filePath: string): string {- const rel = isAbsolute(filePath) ? relative(cwd, filePath) : filePath;- // Normalize to POSIX separators so injected rule context renders the same- // path string on Linux/macOS and Windows (Codex feeds this verbatim into- // the model prompt, and the existing engine already emits POSIX paths).- return toPosixPath(rel);-}--function toPosixPath(path: string): string {- return path.replaceAll("\\", "/");-}diff --git a/plugins/omo/components/rules/src/config.ts b/plugins/omo/components/rules/src/config.tsindex 146ba964..8db63e7b 100644--- a/plugins/omo/components/rules/src/config.ts+++ b/plugins/omo/components/rules/src/config.ts@@ -13,6 +13,14 @@ export function configFromEnvironment(env: NodeJS.ProcessEnv = process.env): PiRconfig.maxResultChars =parsePositiveInteger(firstEnv(env, "CODEX_RULES_MAX_RESULT_CHARS", "PI_RULES_MAX_RESULT_CHARS")) ??config.maxResultChars;+ config.postCompactMaxRuleChars =+ parsePositiveInteger(+ firstEnv(env, "CODEX_RULES_POST_COMPACT_MAX_RULE_CHARS", "PI_RULES_POST_COMPACT_MAX_RULE_CHARS"),+ ) ?? config.postCompactMaxRuleChars;+ config.postCompactMaxResultChars =+ parsePositiveInteger(+ firstEnv(env, "CODEX_RULES_POST_COMPACT_MAX_RESULT_CHARS", "PI_RULES_POST_COMPACT_MAX_RESULT_CHARS"),+ ) ?? config.postCompactMaxResultChars;config.enabledSources = parseEnabledSources(firstEnv(env, "CODEX_RULES_ENABLED_SOURCES", "PI_RULES_ENABLED_SOURCES"),disableBundledRules,diff --git a/plugins/omo/components/rules/src/context-pressure.ts b/plugins/omo/components/rules/src/context-pressure.tsnew file mode 100644index 00000000..f880a0a0--- /dev/null+++ b/plugins/omo/components/rules/src/context-pressure.ts@@ -0,0 +1,26 @@+import { readFileSync } from "node:fs";++const CONTEXT_PRESSURE_MARKERS = [+ "context compacted",+ "context_length_exceeded",+ "skill descriptions were shortened",+ "context_too_large",+ "codex ran out of room in the model's context window",+ "your input exceeds the context window",+ "long threads and multiple compactions",+] as const;++export function hasContextPressureMarker(text: string): boolean {+ const normalizedText = text.toLowerCase();+ return CONTEXT_PRESSURE_MARKERS.some((marker) => normalizedText.includes(marker));+}++export function transcriptHasContextPressureMarker(transcriptPath: string | null | undefined): boolean {+ if (transcriptPath === undefined || transcriptPath === null) return false;+ try {+ return hasContextPressureMarker(readFileSync(transcriptPath, "utf8"));+ } catch (error) {+ if (error instanceof Error) return false;+ throw error;+ }+}diff --git a/plugins/omo/components/rules/src/dynamic-target-fingerprints.ts b/plugins/omo/components/rules/src/dynamic-target-fingerprints.tsnew file mode 100644index 00000000..32a8cb6c--- /dev/null+++ b/plugins/omo/components/rules/src/dynamic-target-fingerprints.ts@@ -0,0 +1,98 @@+import { statSync } from "node:fs";+import { resolve } from "node:path";+import { isSameOrChildPath, toPosixPath, uniqueStrings } from "./path-utils.js";+import { SOURCE_PRIORITY } from "./rules/constants.js";+import { createRuleDiscoveryCache, findRuleCandidates } from "./rules/finder.js";+import { hashContent } from "./rules/matcher.js";+import { sortCandidates } from "./rules/ordering.js";+import { findProjectRoot } from "./rules/project-root.js";+import type { PiRulesConfig, RuleCandidate } from "./rules/types.js";++export interface DynamicTargetFingerprint {+ targetPath: string;+ cacheKey: string;+ fingerprint: string;+}++export function fingerprintDynamicTargets(+ cwd: string,+ targetPaths: ReadonlyArray<string>,+ config: PiRulesConfig,+): DynamicTargetFingerprint[] {+ const disabledSources = disabledSourcesFor(config);+ const discoveryCache = createRuleDiscoveryCache();+ const cwdProjectRoot = findProjectRoot(cwd);+ const fingerprints: DynamicTargetFingerprint[] = [];++ for (const targetPath of uniqueStrings(targetPaths)) {+ const projectRoot =+ cwdProjectRoot !== null && isSameOrChildPath(targetPath, cwdProjectRoot)+ ? cwdProjectRoot+ : findProjectRoot(targetPath);+ const findOptions: {+ projectRoot: string | null;+ targetFile: string;+ disabledSources?: ReadonlySet<string>;+ cache: ReturnType<typeof createRuleDiscoveryCache>;+ } = {+ projectRoot,+ targetFile: targetPath,+ cache: discoveryCache,+ };+ if (disabledSources !== undefined) {+ findOptions.disabledSources = disabledSources;+ }+ const candidates = findRuleCandidates(findOptions);+ const candidateFingerprint = sortCandidates(candidates).map(fingerprintCandidate).join("\u0001");+ const cacheKey = dynamicTargetCacheKey(targetPath);+ fingerprints.push({+ targetPath,+ cacheKey,+ fingerprint: hashContent(+ [+ "v1",+ config.enabledSources === "auto" ? "auto" : config.enabledSources.join(","),+ projectRoot ?? "",+ cacheKey,+ candidateFingerprint,+ ].join("\u0000"),+ ),+ });+ }++ return fingerprints;+}++function fingerprintCandidate(candidate: RuleCandidate): string {+ return [+ candidate.realPath,+ candidate.relativePath,+ candidate.source,+ candidate.isGlobal ? "global" : "project",+ candidate.isSingleFile ? "single" : "multi",+ String(candidate.distance),+ fileFingerprint(candidate.path),+ ].join("\u0000");+}++function fileFingerprint(filePath: string): string {+ try {+ const stats = statSync(filePath, { bigint: true });+ return `${stats.mtimeNs}:${stats.ctimeNs}:${stats.size}`;+ } catch {+ return "missing";+ }+}++function disabledSourcesFor(config: PiRulesConfig): ReadonlySet<string> | undefined {+ if (config.enabledSources === "auto") {+ return undefined;+ }++ const enabledSources = new Set(config.enabledSources);+ return new Set([...SOURCE_PRIORITY.keys()].filter((source) => !enabledSources.has(source)));+}++function dynamicTargetCacheKey(targetPath: string): string {+ return toPosixPath(resolve(targetPath));+}diff --git a/plugins/omo/components/rules/src/hook-output.ts b/plugins/omo/components/rules/src/hook-output.tsnew file mode 100644index 00000000..b60a9488--- /dev/null+++ b/plugins/omo/components/rules/src/hook-output.ts@@ -0,0 +1,19 @@+export type ContextInjectionHookEventName = "SessionStart" | "UserPromptSubmit" | "PostToolUse";++export function formatAdditionalContextOutput(+ eventName: ContextInjectionHookEventName,+ additionalContext: string,+): string {+ const normalizedContext = normalizeAdditionalContext(additionalContext);+ if (normalizedContext.length === 0) return "";+ return `${JSON.stringify({+ hookSpecificOutput: {+ hookEventName: eventName,+ additionalContext: normalizedContext,+ },+ })}\n`;+}++function normalizeAdditionalContext(additionalContext: string): string {+ return additionalContext.replace(/\r\n/g, "\n").replace(/\r/g, "\n").trim();+}diff --git a/plugins/omo/components/rules/src/path-utils.ts b/plugins/omo/components/rules/src/path-utils.tsnew file mode 100644index 00000000..8f60449c--- /dev/null+++ b/plugins/omo/components/rules/src/path-utils.ts@@ -0,0 +1,29 @@+import { isAbsolute, relative, resolve } from "node:path";++export function displayPath(cwd: string, filePath: string): string {+ const rel = isAbsolute(filePath) ? relative(cwd, filePath) : filePath;+ return toPosixPath(rel);+}++export function isSameOrChildPath(childPath: string, parentPath: string): boolean {+ const childRelativePath = relative(parentPath, resolve(childPath));+ return childRelativePath === "" || (!childRelativePath.startsWith("..") && !isAbsolute(childRelativePath));+}++export function toPosixPath(path: string): string {+ return path.replaceAll("\\", "/");+}++export function uniqueStrings(values: ReadonlyArray<string>): string[] {+ const uniqueValues: string[] = [];+ const seenValues = new Set<string>();+ for (const value of values) {+ if (seenValues.has(value)) {+ continue;+ }++ seenValues.add(value);+ uniqueValues.push(value);+ }+ return uniqueValues;+}diff --git a/plugins/omo/components/rules/src/persistent-cache.ts b/plugins/omo/components/rules/src/persistent-cache.tsindex d95caeed..9e24a0be 100644--- a/plugins/omo/components/rules/src/persistent-cache.ts+++ b/plugins/omo/components/rules/src/persistent-cache.ts@@ -2,20 +2,24 @@ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import { dirname, join } from "node:path";+import {+ type PostCompactPendingKind,+ type PostCompactPendingState,+ postCompactKindState,+ postCompactPendingKinds,+ postCompactRecoveringKinds,+} from "./post-compact-state.js";import type { Engine } from "./rules/engine.js";+import { SESSION_STATE_LOCK_CONTENDED, withSessionStateLock } from "./session-state-lock.js";-export type PostCompactPendingKind = "static" | "dynamic";--interface PostCompactPendingState {- static?: boolean;- dynamic?: boolean;-}+export type PostCompactClaimResult = "claimed" | "not-pending" | "contended";interface SerializedSessionState {staticDedup: string[];dynamicDedup: Record<string, string[]>;dynamicTargetFingerprints?: Record<string, string>;postCompactPending?: PostCompactPendingState;+ postCompactRecovering?: PostCompactPendingState;compacted?: boolean;}@@ -48,11 +52,13 @@ export function persistEngineState(}const postCompactPending = nextPostCompactPending(currentState, completedPostCompactKind);+ const postCompactRecovering = nextPostCompactRecovering(currentState, completedPostCompactKind);writeSessionState(cachePath, {staticDedup: [...engine.state.staticDedup],dynamicDedup,dynamicTargetFingerprints: Object.fromEntries(engine.state.dynamicTargetFingerprints.entries()),...(postCompactPending === undefined ? {} : { postCompactPending }),+ ...(postCompactRecovering === undefined ? {} : { postCompactRecovering }),});}@@ -61,17 +67,57 @@ export function clearSessionState(cachePath: string): void {}export function markSessionCompacted(cachePath: string): void {- writeSessionState(cachePath, { ...emptyState(), postCompactPending: { static: true, dynamic: true } });+ const state = readSessionState(cachePath);+ writeSessionState(cachePath, {+ staticDedup: state.staticDedup,+ dynamicDedup: state.dynamicDedup,+ ...(state.dynamicTargetFingerprints === undefined+ ? {}+ : { dynamicTargetFingerprints: state.dynamicTargetFingerprints }),+ postCompactPending: { static: true, dynamic: true },+ });}export function hasPostCompactPending(cachePath: string): boolean {- return postCompactPendingKinds(readSessionState(cachePath)).size > 0;+ const state = readSessionState(cachePath);+ return postCompactPendingKinds(state).size > 0 || postCompactRecoveringKinds(state).size > 0;}export function isPostCompactPending(cachePath: string, kind: PostCompactPendingKind): boolean {return postCompactPendingKinds(readSessionState(cachePath)).has(kind);}+export function claimPostCompactPending(cachePath: string, kind: PostCompactPendingKind): PostCompactClaimResult {+ const result = withSessionStateLock(cachePath, () => {+ const state = readSessionState(cachePath);+ const pendingKinds = postCompactPendingKinds(state);+ if (!pendingKinds.has(kind)) {+ return "not-pending";+ }++ pendingKinds.delete(kind);+ const recoveringKinds = postCompactRecoveringKinds(state);+ recoveringKinds.add(kind);+ writeSessionState(cachePath, stateWithPostCompactKinds(state, pendingKinds, recoveringKinds));+ return "claimed";+ });+ return result === SESSION_STATE_LOCK_CONTENDED ? "contended" : result;+}++export function isPostCompactRecoveryInProgress(cachePath: string, kind: PostCompactPendingKind): boolean {+ return postCompactRecoveringKinds(readSessionState(cachePath)).has(kind);+}++export function completePostCompactRecovery(cachePath: string, kind: PostCompactPendingKind): void {+ withSessionStateLock(cachePath, () => {+ const state = readSessionState(cachePath);+ const pendingKinds = postCompactPendingKinds(state);+ const recoveringKinds = postCompactRecoveringKinds(state);+ recoveringKinds.delete(kind);+ writeSessionState(cachePath, stateWithPostCompactKinds(state, pendingKinds, recoveringKinds));+ });+}+export function sessionCachePath(sessionId: string, pluginDataRoot: string | undefined): string {const root = pluginDataRoot ?? process.env["PLUGIN_DATA"] ?? join(homedir(), ".codex", "codex-rules");return join(root, "sessions", `${safePathSegment(sessionId)}.json`);@@ -115,15 +161,34 @@ function nextPostCompactPending(};}-function postCompactPendingKinds(state: SerializedSessionState): Set<PostCompactPendingKind> {- const pendingKinds = new Set<PostCompactPendingKind>();- if (state.compacted === true || state.postCompactPending?.static === true) {- pendingKinds.add("static");- }- if (state.compacted === true || state.postCompactPending?.dynamic === true) {- pendingKinds.add("dynamic");+function nextPostCompactRecovering(+ state: SerializedSessionState,+ completedKind: PostCompactPendingKind | undefined,+): PostCompactPendingState | undefined {+ const recoveringKinds = postCompactRecoveringKinds(state);+ if (completedKind !== undefined) {+ recoveringKinds.delete(completedKind);}- return pendingKinds;++ return postCompactKindState(recoveringKinds);+}++function stateWithPostCompactKinds(+ state: SerializedSessionState,+ pendingKinds: ReadonlySet<PostCompactPendingKind>,+ recoveringKinds: ReadonlySet<PostCompactPendingKind>,+): SerializedSessionState {+ const postCompactPending = postCompactKindState(pendingKinds);+ const postCompactRecovering = postCompactKindState(recoveringKinds);+ return {+ staticDedup: state.staticDedup,+ dynamicDedup: state.dynamicDedup,+ ...(state.dynamicTargetFingerprints === undefined+ ? {}+ : { dynamicTargetFingerprints: state.dynamicTargetFingerprints }),+ ...(postCompactPending === undefined ? {} : { postCompactPending }),+ ...(postCompactRecovering === undefined ? {} : { postCompactRecovering }),+ };}function safePathSegment(value: string): string {@@ -138,6 +203,7 @@ function isSerializedSessionState(value: unknown): value is SerializedSessionStaconst dynamicDedup = value["dynamicDedup"];const dynamicTargetFingerprints = value["dynamicTargetFingerprints"];const postCompactPending = value["postCompactPending"];+ const postCompactRecovering = value["postCompactRecovering"];const compacted = value["compacted"];return (staticDedup.every((item) => typeof item === "string") &&@@ -150,6 +216,7 @@ function isSerializedSessionState(value: unknown): value is SerializedSessionSta([targetKey, fingerprint]) => typeof targetKey === "string" && typeof fingerprint === "string",))) &&(postCompactPending === undefined || isPostCompactPendingState(postCompactPending)) &&+ (postCompactRecovering === undefined || isPostCompactPendingState(postCompactRecovering)) &&(compacted === undefined || typeof compacted === "boolean"));}diff --git a/plugins/omo/components/rules/src/post-compact-budget.ts b/plugins/omo/components/rules/src/post-compact-budget.tsnew file mode 100644index 00000000..348c3743--- /dev/null+++ b/plugins/omo/components/rules/src/post-compact-budget.ts@@ -0,0 +1,102 @@+import { hasContextPressureMarker } from "./context-pressure.js";+import type { PiRulesConfig } from "./rules/types.js";+import { readTranscriptSearchText } from "./transcript-search.js";++export interface PostCompactBudgetContext {+ readonly model: string;+ readonly transcriptPath: string | null;+}++interface ModelContextBudget {+ readonly slug: string;+ readonly contextWindowTokens: number;+ readonly effectivePercent: number;+}++const DEFAULT_EFFECTIVE_CONTEXT_WINDOW_PERCENT = 95;+const ESTIMATED_TRANSCRIPT_CHARS_PER_TOKEN = 3;+const PROJECTED_INJECTION_CHARS_PER_TOKEN = 2;+const POST_COMPACT_RESERVED_CONTEXT_PERCENT = 5;+const POST_COMPACT_MIN_RESERVED_TOKENS = 8_000;+const POST_COMPACT_MIN_GUIDE_CHARS = 500;+const FALLBACK_CONTEXT_WINDOW_TOKENS = 200_000;+const MODEL_CONTEXT_BUDGETS: readonly ModelContextBudget[] = [+ { slug: "gpt-5.5", contextWindowTokens: 272_000, effectivePercent: DEFAULT_EFFECTIVE_CONTEXT_WINDOW_PERCENT },+ { slug: "gpt-5.4", contextWindowTokens: 272_000, effectivePercent: DEFAULT_EFFECTIVE_CONTEXT_WINDOW_PERCENT },+ { slug: "gpt-5.4-mini", contextWindowTokens: 272_000, effectivePercent: DEFAULT_EFFECTIVE_CONTEXT_WINDOW_PERCENT },+ {+ slug: "codex-auto-review",+ contextWindowTokens: 272_000,+ effectivePercent: DEFAULT_EFFECTIVE_CONTEXT_WINDOW_PERCENT,+ },+];++export function withPostCompactBudget(config: PiRulesConfig, context?: PostCompactBudgetContext): PiRulesConfig {+ const postCompactMaxResultChars = dynamicPostCompactMaxResultChars(context) ?? config.postCompactMaxResultChars;+ const maxResultChars = Math.min(config.maxResultChars, config.postCompactMaxResultChars, postCompactMaxResultChars);+ const maxRuleChars = Math.min(config.maxRuleChars, config.postCompactMaxRuleChars, maxResultChars);+ return {+ ...config,+ maxRuleChars,+ maxResultChars,+ };+}++function dynamicPostCompactMaxResultChars(context: PostCompactBudgetContext | undefined): number | undefined {+ if (context === undefined || context.transcriptPath === null) {+ return undefined;+ }++ const transcript = estimateTranscript(context.transcriptPath);+ if (transcript === undefined) {+ return undefined;+ }++ if (hasContextPressureMarker(transcript.text)) {+ return POST_COMPACT_MIN_GUIDE_CHARS;+ }++ const modelBudget = modelContextBudgetFor(context.model) ?? fallbackModelContextBudget();+ const effectiveContextWindow = Math.floor((modelBudget.contextWindowTokens * modelBudget.effectivePercent) / 100);+ const reservedTokens = Math.max(+ POST_COMPACT_MIN_RESERVED_TOKENS,+ Math.floor((effectiveContextWindow * POST_COMPACT_RESERVED_CONTEXT_PERCENT) / 100),+ );+ const injectableTokens = Math.max(0, effectiveContextWindow - reservedTokens - transcript.tokens);+ return Math.max(POST_COMPACT_MIN_GUIDE_CHARS, Math.floor(injectableTokens * PROJECTED_INJECTION_CHARS_PER_TOKEN));+}++function modelContextBudgetFor(model: string): ModelContextBudget | undefined {+ const normalizedModel = model.trim().toLowerCase();+ for (const budget of MODEL_CONTEXT_BUDGETS) {+ if (+ normalizedModel === budget.slug ||+ normalizedModel.endsWith(`.${budget.slug}`) ||+ normalizedModel.endsWith(`/${budget.slug}`)+ ) {+ return budget;+ }+ }+ return undefined;+}++function fallbackModelContextBudget(): ModelContextBudget {+ return {+ slug: "unknown",+ contextWindowTokens: FALLBACK_CONTEXT_WINDOW_TOKENS,+ effectivePercent: DEFAULT_EFFECTIVE_CONTEXT_WINDOW_PERCENT,+ };+}++function estimateTranscript(transcriptPath: string): { readonly text: string; readonly tokens: number } | undefined {+ const transcriptText =+ readTranscriptSearchText(transcriptPath, { latestCompactedReplacementOnly: true }) ??+ readTranscriptSearchText(transcriptPath);+ if (transcriptText === null) {+ return undefined;+ }+ return {+ text: transcriptText,+ tokens: Math.ceil(Buffer.byteLength(transcriptText, "utf8") / ESTIMATED_TRANSCRIPT_CHARS_PER_TOKEN),+ };+}diff --git a/plugins/omo/components/rules/src/post-compact-claim.ts b/plugins/omo/components/rules/src/post-compact-claim.tsnew file mode 100644index 00000000..834d92a6--- /dev/null+++ b/plugins/omo/components/rules/src/post-compact-claim.ts@@ -0,0 +1,13 @@+import type { PostCompactClaimResult } from "./persistent-cache.js";+import type { PostCompactPendingKind } from "./post-compact-state.js";++export function claimedPostCompactKind<T extends PostCompactPendingKind>(+ result: PostCompactClaimResult,+ kind: T,+): T | undefined {+ return result === "claimed" ? kind : undefined;+}++export function shouldSkipPostCompactClaim(result: PostCompactClaimResult, recoveryInProgress: boolean): boolean {+ return result === "contended" || (result === "not-pending" && recoveryInProgress);+}diff --git a/plugins/omo/components/rules/src/post-compact-state.ts b/plugins/omo/components/rules/src/post-compact-state.tsnew file mode 100644index 00000000..a04a4668--- /dev/null+++ b/plugins/omo/components/rules/src/post-compact-state.ts@@ -0,0 +1,45 @@+export type PostCompactPendingKind = "static" | "dynamic";++export interface PostCompactPendingState {+ static?: boolean;+ dynamic?: boolean;+}++export interface PostCompactStateFields {+ readonly postCompactPending?: PostCompactPendingState;+ readonly postCompactRecovering?: PostCompactPendingState;+ readonly compacted?: boolean;+}++export function postCompactKindState(kinds: ReadonlySet<PostCompactPendingKind>): PostCompactPendingState | undefined {+ if (kinds.size === 0) {+ return undefined;+ }++ return {+ ...(kinds.has("static") ? { static: true } : {}),+ ...(kinds.has("dynamic") ? { dynamic: true } : {}),+ };+}++export function postCompactPendingKinds(state: PostCompactStateFields): Set<PostCompactPendingKind> {+ const pendingKinds = new Set<PostCompactPendingKind>();+ if (state.compacted === true || state.postCompactPending?.static === true) {+ pendingKinds.add("static");+ }+ if (state.compacted === true || state.postCompactPending?.dynamic === true) {+ pendingKinds.add("dynamic");+ }+ return pendingKinds;+}++export function postCompactRecoveringKinds(state: PostCompactStateFields): Set<PostCompactPendingKind> {+ const recoveringKinds = new Set<PostCompactPendingKind>();+ if (state.postCompactRecovering?.static === true) {+ recoveringKinds.add("static");+ }+ if (state.postCompactRecovering?.dynamic === true) {+ recoveringKinds.add("dynamic");+ }+ return recoveringKinds;+}diff --git a/plugins/omo/components/rules/src/rules-engine-factory.ts b/plugins/omo/components/rules/src/rules-engine-factory.tsnew file mode 100644index 00000000..92630678--- /dev/null+++ b/plugins/omo/components/rules/src/rules-engine-factory.ts@@ -0,0 +1,27 @@+import { readFileSync } from "node:fs";++import { configFromEnvironment } from "./config.js";+import { createEngine } from "./rules/engine.js";+import { findRuleCandidates } from "./rules/finder.js";+import { findProjectRoot } from "./rules/project-root.js";++interface RulesEngineFactoryOptions {+ env?: NodeJS.ProcessEnv;+ platform?: NodeJS.Platform;+}++export function createRulesEngine(options: RulesEngineFactoryOptions, config = configFromEnvironment(options.env)) {+ const platform = options.platform ?? process.platform;++ return createEngine(config, {+ findCandidates: (finderOptions) => findRuleCandidates({ ...finderOptions, platform }),+ findProjectRoot,+ readFile: (path) => {+ try {+ return readFileSync(path, "utf8");+ } catch {+ return null;+ }+ },+ });+}diff --git a/plugins/omo/components/rules/src/rules/constants.ts b/plugins/omo/components/rules/src/rules/constants.tsindex 38baef52..97459275 100644--- a/plugins/omo/components/rules/src/rules/constants.ts+++ b/plugins/omo/components/rules/src/rules/constants.ts@@ -92,10 +92,14 @@ export const DEFAULT_MAX_SCAN_FILES = 1000;*/export const DEFAULT_MAX_RESULT_CHARS = 40000;+export const DEFAULT_POST_COMPACT_MAX_RULE_CHARS = 3500;++export const DEFAULT_POST_COMPACT_MAX_RESULT_CHARS = 4000;+/*** Truncation marker template. `{path}` is replaced with the relative path.*/-export const TRUNCATION_NOTICE = "\n\n[Rule truncated. Read full rule: {path}]";+export const TRUNCATION_NOTICE = "\n\n[Truncated. Full: {path}]";/*** Directories excluded by the recursive scanner regardless of glob settings.diff --git a/plugins/omo/components/rules/src/rules/engine.ts b/plugins/omo/components/rules/src/rules/engine.tsindex 84ad3471..8634e729 100644--- a/plugins/omo/components/rules/src/rules/engine.ts+++ b/plugins/omo/components/rules/src/rules/engine.ts@@ -12,6 +12,8 @@ import {import {DEFAULT_MAX_RESULT_CHARS,DEFAULT_MAX_RULE_CHARS,+ DEFAULT_POST_COMPACT_MAX_RESULT_CHARS,+ DEFAULT_POST_COMPACT_MAX_RULE_CHARS,PROJECT_SINGLE_FILES,SOURCE_PRIORITY,} from "./constants.js";@@ -74,6 +76,8 @@ export function defaultConfig(): PiRulesConfig {mode: "both",maxRuleChars: DEFAULT_MAX_RULE_CHARS,maxResultChars: DEFAULT_MAX_RESULT_CHARS,+ postCompactMaxRuleChars: DEFAULT_POST_COMPACT_MAX_RULE_CHARS,+ postCompactMaxResultChars: DEFAULT_POST_COMPACT_MAX_RESULT_CHARS,enabledSources: "auto",};}diff --git a/plugins/omo/components/rules/src/rules/finder.ts b/plugins/omo/components/rules/src/rules/finder.tsindex bbe01a9b..89229a70 100644--- a/plugins/omo/components/rules/src/rules/finder.ts+++ b/plugins/omo/components/rules/src/rules/finder.ts@@ -36,6 +36,7 @@ export interface FinderOptions {skipUserHome?: boolean;/** Plugin root directory. Defaults to PLUGIN_ROOT env or this package root. */pluginRoot?: string;+ platform?: NodeJS.Platform;cache?: RuleDiscoveryCache;}@@ -43,8 +44,11 @@ interface PluginBundledFinderOptions {readonly disabledSources?: ReadonlySet<string>;readonly cache?: RuleDiscoveryCache;readonly pluginRoot?: string;+ readonly platform?: NodeJS.Platform;}+const WINDOWS_GIT_BASH_BUNDLED_RULE_PATH = "bundled-rules/windows-git-bash.md";+export function findRuleCandidates(options: FinderOptions): RuleCandidate[] {const skipUserHome = options.skipUserHome ?? false;const disabledSources = options.disabledSources ?? new Set<string>();@@ -61,6 +65,7 @@ export function findRuleCandidates(options: FinderOptions): RuleCandidate[] {disabledSources,...(options.cache === undefined ? {} : { cache: options.cache }),...(options.pluginRoot === undefined ? {} : { pluginRoot: options.pluginRoot }),+ ...(options.platform === undefined ? {} : { platform: options.platform }),};candidates.push(...findPluginBundledCandidates(pluginBundledOptions));@@ -78,9 +83,10 @@ export function findPluginBundledCandidates(options: PluginBundledFinderOptionsconst pluginRoot = resolvePluginRulesRoot(options.pluginRoot);const ruleDirectory = join(pluginRoot, BUNDLED_RULE_SUBDIR);+ const platform = options.platform ?? process.platform;const candidates: RuleCandidate[] = [];for (const scannedFile of scanRuleFilesCached(ruleDirectory, options.cache)) {- candidates.push({+ const candidate: RuleCandidate = {path: scannedFile.path,realPath: scannedFile.realPath,source: "plugin-bundled",@@ -88,11 +94,18 @@ export function findPluginBundledCandidates(options: PluginBundledFinderOptionsisGlobal: true,isSingleFile: false,relativePath: toRelativePath(pluginRoot, scannedFile.path),- });+ };+ if (isPluginBundledCandidateEnabled(candidate, platform)) {+ candidates.push(candidate);+ }}return candidates;}+function isPluginBundledCandidateEnabled(candidate: RuleCandidate, platform: NodeJS.Platform): boolean {+ return candidate.relativePath !== WINDOWS_GIT_BASH_BUNDLED_RULE_PATH || platform === "win32";+}+function findProjectCandidates(projectRoot: string,targetFile: string | null,diff --git a/plugins/omo/components/rules/src/rules/formatter.ts b/plugins/omo/components/rules/src/rules/formatter.tsindex 92305a7b..2f96db9a 100644--- a/plugins/omo/components/rules/src/rules/formatter.ts+++ b/plugins/omo/components/rules/src/rules/formatter.ts@@ -12,31 +12,45 @@ type TruncatedRule = {body: string;};+type NormalizedRule = TruncatedRule & {+ source: LoadedRule["source"];+};+function formatRule(rule: TruncatedRule): string {- return `Instructions from: ${rule.path}\n${rule.body}`;+ const body = normalizeRuleBody(rule.body);+ if (body.length === 0) {+ return `Instructions from: ${rule.path}`;+ }+ return `Instructions from: ${rule.path}\n\n${body}`;}function truncateRules(rules: ReadonlyArray<LoadedRule>, options: FormatOptions): TruncatedRule[] {- const perRuleTruncated = rules.map((rule) => ({+ const perRuleNormalized: NormalizedRule[] = rules.map((rule) => ({+ path: rule.path,+ relativePath: rule.relativePath,+ body: normalizeRuleBody(rule.body),+ source: rule.source,+ }));+ const perRuleResultChars = Math.floor(options.maxResultChars / Math.max(1, perRuleNormalized.length));+ const perRuleBudgeted = perRuleNormalized.map((rule) => ({path: rule.path,relativePath: rule.relativePath,- // Plugin-bundled rules ship as-is. The per-rule cap exists to guard against absurd- // user-authored AGENTS.md files; bundled rules are author-controlled and silent- // mid-section truncation would break the contract that the rule landed in full.- // The overall maxResultChars budget still applies via truncateBudget below.body:rule.source === "plugin-bundled"- ? rule.body- : truncateRule(rule.body, { maxChars: options.maxRuleChars, relativePath: rule.relativePath }).body,+ ? truncateRule(rule.body, { maxChars: perRuleResultChars, relativePath: rule.relativePath }).body+ : truncateRule(rule.body, {+ maxChars: Math.min(options.maxRuleChars, perRuleResultChars),+ relativePath: rule.relativePath,+ }).body,}));const budgetedRules = truncateBudget({- rules: perRuleTruncated.map((rule) => ({ body: rule.body, relativePath: rule.relativePath })),+ rules: perRuleBudgeted.map((rule) => ({ body: rule.body, relativePath: rule.relativePath })),maxResultChars: options.maxResultChars,});const truncatedRules: TruncatedRule[] = [];for (let index = 0; index < budgetedRules.length; index += 1) {- const sourceRule = perRuleTruncated[index];+ const sourceRule = perRuleBudgeted[index];const budgetedRule = budgetedRules[index];if (sourceRule === undefined || budgetedRule === undefined) {continue;@@ -57,7 +71,11 @@ export function formatStaticBlock(rules: ReadonlyArray<LoadedRule>, options: Forreturn "";}- return `\n\n## Project Instructions\n${truncateRules(uniqueRulesByBody(rules), options).map(formatRule).join("\n\n")}`;+ return [+ "## Project Instructions",+ "",+ truncateRules(uniqueRulesByBody(rules), options).map(formatRule).join("\n\n"),+ ].join("\n");}function uniqueRulesByBody(rules: ReadonlyArray<LoadedRule>): LoadedRule[] {@@ -70,7 +88,7 @@ function uniqueRulesByBody(rules: ReadonlyArray<LoadedRule>): LoadedRule[] {continue;}- const bodyKey = rule.body.trim();+ const bodyKey = normalizeRuleBody(rule.body);if (seenBodies.has(bodyKey)) {continue;}@@ -93,7 +111,13 @@ export function formatDynamicBlock(return "";}- return `\n\nAdditional project instructions matched for ${targetRelativePath}:\n\n${truncateRules(rules, options)- .map(formatRule)- .join("\n\n")}`;+ return [+ `Additional project instructions matched for ${targetRelativePath}:`,+ "",+ truncateRules(rules, options).map(formatRule).join("\n\n"),+ ].join("\n");+}++function normalizeRuleBody(body: string): string {+ return body.replace(/\r\n/g, "\n").replace(/\r/g, "\n").trim();}diff --git a/plugins/omo/components/rules/src/rules/types.ts b/plugins/omo/components/rules/src/rules/types.tsindex f24f046d..bb914bb1 100644--- a/plugins/omo/components/rules/src/rules/types.ts+++ b/plugins/omo/components/rules/src/rules/types.ts@@ -114,6 +114,8 @@ export interface PiRulesConfig {mode: "static" | "dynamic" | "both" | "off";maxRuleChars: number;maxResultChars: number;+ postCompactMaxRuleChars: number;+ postCompactMaxResultChars: number;enabledSources: RuleSource[] | "auto";}diff --git a/plugins/omo/components/rules/src/session-state-lock.ts b/plugins/omo/components/rules/src/session-state-lock.tsnew file mode 100644index 00000000..479ee60c--- /dev/null+++ b/plugins/omo/components/rules/src/session-state-lock.ts@@ -0,0 +1,47 @@+import { mkdirSync, rmSync } from "node:fs";+import { dirname } from "node:path";++export const SESSION_STATE_LOCK_CONTENDED = Symbol("session-state-lock-contended");++export type SessionStateLockResult<T> = T | typeof SESSION_STATE_LOCK_CONTENDED;++const LOCK_RETRY_COUNT = 20;+const LOCK_RETRY_DELAY_MS = 5;+const LOCK_SLEEP_VIEW = new Int32Array(new SharedArrayBuffer(4));++export function withSessionStateLock<T>(cachePath: string, callback: () => T): SessionStateLockResult<T> {+ const lockPath = `${cachePath}.lock`;+ mkdirSync(dirname(cachePath), { recursive: true });+ for (let attempt = 0; attempt < LOCK_RETRY_COUNT; attempt += 1) {+ try {+ mkdirSync(lockPath);+ try {+ return callback();+ } finally {+ rmSync(lockPath, { recursive: true, force: true });+ }+ } catch (error) {+ if (errorCode(error) === "EEXIST") {+ sleepSync(LOCK_RETRY_DELAY_MS);+ continue;+ }+ throw error;+ }+ }+ return SESSION_STATE_LOCK_CONTENDED;+}++function errorCode(error: unknown): unknown {+ if (!isRecord(error)) {+ return undefined;+ }+ return Reflect.get(error, "code");+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function sleepSync(milliseconds: number): void {+ Atomics.wait(LOCK_SLEEP_VIEW, 0, 0, milliseconds);+}diff --git a/plugins/omo/components/rules/src/static-injection.ts b/plugins/omo/components/rules/src/static-injection.tsnew file mode 100644index 00000000..36d14c48--- /dev/null+++ b/plugins/omo/components/rules/src/static-injection.ts@@ -0,0 +1,56 @@+import type { CodexRulesHookOptions } from "./codex-hook-options.js";+import { configFromEnvironment } from "./config.js";+import { formatAdditionalContextOutput } from "./hook-output.js";+import { completePostCompactRecovery, hydrateEngineState, persistEngineState } from "./persistent-cache.js";+import { withPostCompactBudget } from "./post-compact-budget.js";+import { createRulesEngine } from "./rules-engine-factory.js";+import { filterRulesAlreadyInTranscript } from "./transcript-rule-filter.js";+import type { TranscriptSearchOptions } from "./transcript-search.js";++export function runStaticInjection(+ cwd: string,+ transcriptPath: string | null,+ eventName: "SessionStart" | "UserPromptSubmit",+ cachePath: string,+ options: CodexRulesHookOptions,+ completedPostCompactChannel?: "static",+ transcriptSearchOptions: TranscriptSearchOptions = {},+ model?: string,+): string {+ const config = configFromEnvironment(options.env);+ if (config.disabled || config.mode === "off" || config.mode === "dynamic") {+ if (completedPostCompactChannel !== undefined) {+ completePostCompactRecovery(cachePath, completedPostCompactChannel);+ }+ return "";+ }++ const effectiveConfig =+ completedPostCompactChannel === undefined+ ? config+ : withPostCompactBudget(config, { model: model ?? "", transcriptPath });+ const engine = createRulesEngine(options, effectiveConfig);+ hydrateEngineState(engine, cachePath);+ engine.state.cwd = cwd;++ const loaded = engine.loadStaticRules(cwd);+ const rules = filterRulesAlreadyInTranscript(+ loaded.rules.filter((rule) => !engine.isStaticInjected(rule)),+ transcriptPath,+ (rule) => {+ engine.markStaticInjected(rule);+ },+ transcriptSearchOptions,+ );+ if (rules.length === 0) {+ persistEngineState(engine, cachePath, completedPostCompactChannel);+ return "";+ }++ const block = engine.formatStatic(rules);+ for (const rule of rules) {+ engine.markStaticInjected(rule);+ }+ persistEngineState(engine, cachePath, completedPostCompactChannel);+ return formatAdditionalContextOutput(eventName, block);+}diff --git a/plugins/omo/components/rules/src/transcript-rule-filter.ts b/plugins/omo/components/rules/src/transcript-rule-filter.tsnew file mode 100644index 00000000..c657f6e1--- /dev/null+++ b/plugins/omo/components/rules/src/transcript-rule-filter.ts@@ -0,0 +1,44 @@+import type { LoadedRule } from "./rules/types.js";+import type { TranscriptSearchOptions } from "./transcript-search.js";+import { readTranscriptSearchText } from "./transcript-search.js";++export function filterRulesAlreadyInTranscript(+ rules: ReadonlyArray<LoadedRule>,+ transcriptPath: string | null,+ markInjected: (rule: LoadedRule) => void,+ options: TranscriptSearchOptions = {},+): LoadedRule[] {+ if (rules.length === 0 || transcriptPath === null) {+ return [...rules];+ }++ const transcriptText = readTranscriptSearchText(transcriptPath, options);+ if (transcriptText === null) {+ return [...rules];+ }++ const pendingRules: LoadedRule[] = [];+ for (const rule of rules) {+ if (isRuleAlreadyInTranscript(rule, transcriptText)) {+ markInjected(rule);+ continue;+ }++ pendingRules.push(rule);+ }+ return pendingRules;+}++function isRuleAlreadyInTranscript(rule: LoadedRule, transcriptText: string): boolean {+ const bodyNeedle = rule.body.trim().slice(0, 2_000);+ if (bodyNeedle.length === 0 || !transcriptText.includes(bodyNeedle)) {+ return false;+ }++ const markers = [+ `Instructions from: ${rule.path}`,+ `Instructions from: ${rule.realPath}`,+ rule.relativePath.length === 0 ? null : rule.relativePath,+ ].filter((marker): marker is string => marker !== null);+ return markers.some((marker) => transcriptText.includes(marker));+}diff --git a/plugins/omo/components/rules/src/transcript-search.ts b/plugins/omo/components/rules/src/transcript-search.tsnew file mode 100644index 00000000..94dd73ff--- /dev/null+++ b/plugins/omo/components/rules/src/transcript-search.ts@@ -0,0 +1,108 @@+import { readFileSync } from "node:fs";++export interface TranscriptSearchOptions {+ readonly latestCompactedReplacementOnly?: boolean;+}++export function readTranscriptSearchText(transcriptPath: string, options: TranscriptSearchOptions = {}): string | null {+ try {+ const rawTranscript = readFileSync(transcriptPath, "utf8");+ if (options.latestCompactedReplacementOnly === true) {+ return latestCompactedReplacementSearchText(rawTranscript);+ }+ return [rawTranscript, ...collectJsonLineStrings(rawTranscript)].join("\n");+ } catch (error) {+ if (!(error instanceof Error)) {+ throw error;+ }+ return null;+ }+}++function latestCompactedReplacementSearchText(rawTranscript: string): string | null {+ const lines = rawTranscript.split(/\r?\n/);+ let latestCompactedLineIndex = -1;+ let replacementHistory: unknown[] | null = null;+ for (const [index, line] of lines.entries()) {+ const parsed = parseJsonLine(line);+ if (!isRecord(parsed) || parsed["type"] !== "compacted") {+ continue;+ }++ const payload = parsed["payload"];+ if (!isRecord(payload)) {+ continue;+ }++ const candidateReplacementHistory = payload["replacement_history"];+ if (!Array.isArray(candidateReplacementHistory)) {+ continue;+ }++ latestCompactedLineIndex = index;+ replacementHistory = candidateReplacementHistory;+ }++ if (replacementHistory === null) {+ return null;+ }++ const values: string[] = [];+ collectStrings(replacementHistory, values);+ const laterTranscript = lines.slice(latestCompactedLineIndex + 1).join("\n");+ values.push(laterTranscript, ...collectJsonLineStrings(laterTranscript));+ return values.join("\n");+}++function collectJsonLineStrings(rawTranscript: string): string[] {+ const values: string[] = [];+ for (const line of rawTranscript.split(/\r?\n/)) {+ const parsed = parseJsonLine(line);+ if (parsed !== null) {+ collectStrings(parsed, values);+ }+ }+ return values;+}++function parseJsonLine(line: string): unknown | null {+ if (line.trim().length === 0) {+ return null;+ }++ try {+ const parsed: unknown = JSON.parse(line);+ return parsed;+ } catch (error) {+ if (!(error instanceof Error)) {+ throw error;+ }+ return null;+ }+}++function collectStrings(value: unknown, output: string[]): void {+ if (typeof value === "string") {+ output.push(value);+ return;+ }++ if (Array.isArray(value)) {+ for (const item of value) {+ collectStrings(item, output);+ }+ return;+ }++ if (!isRecord(value)) {+ return;+ }++ for (const item of Object.values(value)) {+ collectStrings(item, output);+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/rules/test/bundled-rules.test.ts b/plugins/omo/components/rules/test/bundled-rules.test.tsindex 7da2d5a9..80f60bd4 100644--- a/plugins/omo/components/rules/test/bundled-rules.test.ts+++ b/plugins/omo/components/rules/test/bundled-rules.test.ts@@ -192,7 +192,7 @@ describe("plugin bundled rules", () => {expect(output).toBe("");});- it("#given PostCompact pending flag #when UserPromptSubmit runs #then bundled static context re-injects", async () => {+ it("#given bundled static context already injected #when UserPromptSubmit runs after PostCompact #then it emits no duplicate bundled context", async () => {// givenconst { root, pluginData } = makeFixture();const firstOutput = await runSessionStartHook(sessionStartInput(root), {@@ -210,7 +210,7 @@ describe("plugin bundled rules", () => {// thenexpect(compactOutput).toBe("");- expect(output).toContain(BUNDLED_BODY);+ expect(output).toBe("");});it("#given bundled rule body exceeds per-rule cap #when SessionStart runs #then bundled body lands in full without truncation", async () => {@@ -236,7 +236,7 @@ describe("plugin bundled rules", () => {// thenexpect(output).toContain(tailMarker);- expect(output).not.toContain("[Rule truncated. Read full rule:");+ expect(output).not.toContain("[Truncated. Full:");});it("#given project rule body exceeds per-rule cap #when SessionStart runs #then project body is truncated", async () => {@@ -262,7 +262,7 @@ describe("plugin bundled rules", () => {});// then- expect(output).toContain("[Rule truncated. Read full rule: .omo/rules/oversized.md]");+ expect(output).toContain("[Truncated. Full: .omo/rules/oversized.md]");expect(output).not.toContain(tailMarker);});});diff --git a/plugins/omo/components/rules/test/codex-hook-context-pressure.test.ts b/plugins/omo/components/rules/test/codex-hook-context-pressure.test.tsnew file mode 100644index 00000000..6e7f81dd--- /dev/null+++ b/plugins/omo/components/rules/test/codex-hook-context-pressure.test.ts@@ -0,0 +1,243 @@+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 { runPostToolUseHook, runUserPromptSubmitHook } from "../src/codex-hook.js";++const tempDirectories: string[] = [];+const PROJECT_ONLY_ENV = {+ CODEX_RULES_ENABLED_SOURCES: "AGENTS.md,.omo/rules",+};++afterEach(() => {+ for (const directory of tempDirectories.splice(0)) {+ rmSync(directory, { recursive: true, force: true });+ }+});++describe("codex rules context-pressure recovery", () => {+ it("#given context-pressure recovery prompt and empty static cache #when UserPromptSubmit runs #then it emits no static context", async () => {+ // given+ const { root, pluginData } = makeTempProject();++ // when+ const output = await runUserPromptSubmitHook(+ {+ ...userPromptSubmitInput(root),+ prompt: [+ "Context compacted",+ "error context_too_large: Your input exceeds the context window of this model.",+ "Please adjust your input and try again.",+ ].join("\n"),+ },+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },+ );++ // then+ expect(output).toBe("");+ });++ it("#given Codex canonical context-window prompt and empty static cache #when UserPromptSubmit runs #then it emits no static context", async () => {+ // given+ const { root, pluginData } = makeTempProject();++ // when+ const output = await runUserPromptSubmitHook(+ {+ ...userPromptSubmitInput(root),+ prompt: [+ "error context_length_exceeded",+ "Codex ran out of room in the model's context window. Start a new thread before retrying.",+ ].join("\n"),+ },+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },+ );++ // then+ expect(output).toBe("");+ });++ it("#given context-pressure transcript and empty static cache #when UserPromptSubmit runs #then it emits no static context", async () => {+ // given+ const { root, pluginData } = makeTempProject();+ const transcriptPath = writeContextPressureTranscript(root);++ // when+ const output = await runUserPromptSubmitHook(+ {+ ...userPromptSubmitInput(root),+ transcript_path: transcriptPath,+ prompt: "continue",+ },+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },+ );++ // then+ expect(output).toBe("");+ });++ it("#given Codex canonical context-window transcript and empty static cache #when UserPromptSubmit runs #then it emits no static context", async () => {+ // given+ const { root, pluginData } = makeTempProject();+ const transcriptPath = writeCodexContextWindowTranscript(root);++ // when+ const output = await runUserPromptSubmitHook(+ {+ ...userPromptSubmitInput(root),+ transcript_path: transcriptPath,+ prompt: "continue",+ },+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },+ );++ // then+ expect(output).toBe("");+ });++ it("#given context-pressure transcript and empty dynamic cache #when PostToolUse runs #then it emits no dynamic context", async () => {+ // given+ const { root, pluginData } = makeTempProject();+ const transcriptPath = writeContextPressureTranscript(root);+ const filePath = path.join(root, "src", "app.ts");+ mkdirSync(path.dirname(filePath), { recursive: true });+ writeFileSync(filePath, "export const answer = 42;\n");++ // when+ const output = await runPostToolUseHook(+ {+ session_id: "session-context-pressure",+ turn_id: "turn-1",+ transcript_path: transcriptPath,+ cwd: root,+ hook_event_name: "PostToolUse",+ model: "gpt-5.5",+ permission_mode: "default",+ tool_name: "mcp__filesystem__read_file",+ tool_input: { path: filePath },+ tool_response: { text: "export const answer = 42;" },+ tool_use_id: "call-1",+ },+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },+ );++ // then+ expect(output).toBe("");+ });++ it("#given Codex canonical context-window transcript and empty dynamic cache #when PostToolUse runs #then it emits no dynamic context", async () => {+ // given+ const { root, pluginData } = makeTempProject();+ const transcriptPath = writeCodexContextWindowTranscript(root);+ const filePath = path.join(root, "src", "app.ts");+ mkdirSync(path.dirname(filePath), { recursive: true });+ writeFileSync(filePath, "export const answer = 42;\n");++ // when+ const output = await runPostToolUseHook(+ {+ session_id: "session-context-pressure",+ turn_id: "turn-1",+ transcript_path: transcriptPath,+ cwd: root,+ hook_event_name: "PostToolUse",+ model: "gpt-5.5",+ permission_mode: "default",+ tool_name: "mcp__filesystem__read_file",+ tool_input: { path: filePath },+ tool_response: { text: "export const answer = 42;" },+ tool_use_id: "call-1",+ },+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },+ );++ // then+ expect(output).toBe("");+ });+});++function makeTempProject(): { readonly root: string; readonly pluginData: string } {+ const root = mkdtempSync(path.join(tmpdir(), "codex-rules-context-pressure-project-"));+ const pluginData = mkdtempSync(path.join(tmpdir(), "codex-rules-context-pressure-data-"));+ tempDirectories.push(root, pluginData);+ writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "fixture" }));+ writeFileSync(path.join(root, "AGENTS.md"), "Always wear safety goggles when refactoring.");+ mkdirSync(path.join(root, ".omo", "rules"), { recursive: true });+ writeFileSync(+ path.join(root, ".omo", "rules", "typescript.md"),+ [+ "---",+ "description: TypeScript",+ 'globs: ["**/*.ts", "**/*.tsx"]',+ "---",+ "",+ "Prefer strict TypeScript for all source files.",+ ].join("\n"),+ );+ return { root, pluginData };+}++function userPromptSubmitInput(root: string): Parameters<typeof runUserPromptSubmitHook>[0] {+ return {+ session_id: "session-context-pressure",+ turn_id: "turn-1",+ transcript_path: null,+ cwd: root,+ hook_event_name: "UserPromptSubmit",+ model: "gpt-5.5",+ permission_mode: "default",+ prompt: "read src/app.ts",+ };+}++function writeContextPressureTranscript(root: string): string {+ const transcriptPath = path.join(root, "transcript-context-pressure.jsonl");+ writeFileSync(+ transcriptPath,+ [+ JSON.stringify({+ type: "message",+ payload: {+ content: "Context compacted",+ },+ }),+ JSON.stringify({+ type: "message",+ payload: {+ content: "Your input exceeds the context window of this model.",+ },+ }),+ "",+ ].join("\n"),+ );+ return transcriptPath;+}++function writeCodexContextWindowTranscript(root: string): string {+ const transcriptPath = path.join(root, "transcript-codex-context-window.jsonl");+ writeFileSync(+ transcriptPath,+ [+ JSON.stringify({+ type: "message",+ payload: {+ content: {+ error: {+ code: "context_length_exceeded",+ },+ },+ },+ }),+ JSON.stringify({+ type: "message",+ payload: {+ content:+ "Codex ran out of room in the model's context window. Start a new thread or clear earlier history before retrying.",+ },+ }),+ "",+ ].join("\n"),+ );+ return transcriptPath;+}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.tsnew file mode 100644index 00000000..a674fc33--- /dev/null+++ b/plugins/omo/components/rules/test/codex-hook-post-compact-budget.test.ts@@ -0,0 +1,132 @@+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 CodexSessionStartInput,+ runPostCompactHook,+ runSessionStartHook,+ runUserPromptSubmitHook,+} from "../src/codex-hook.js";++const tempDirectories: string[] = [];+const PROJECT_RULES_ENV = {+ CODEX_RULES_ENABLED_SOURCES: "AGENTS.md,.omo/rules",+ CODEX_RULES_MAX_RESULT_CHARS: "50000",+ CODEX_RULES_MAX_RULE_CHARS: "30000",+};++afterEach(() => {+ for (const directory of tempDirectories.splice(0)) {+ rmSync(directory, { recursive: true, force: true });+ }+});++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 budget block", async () => {+ // given+ const { root, pluginData } = makeOversizedProject();+ const firstOutput = await runSessionStartHook(sessionStartInput(root), {+ pluginDataRoot: pluginData,+ env: PROJECT_RULES_ENV,+ });+ const firstContext = readAdditionalContext(firstOutput);+ const transcriptPath = writeCompactedTranscript(root, "summary dropped injected rules");+ await runPostCompactHook(+ { ...postCompactInput(root), transcript_path: transcriptPath },+ { pluginDataRoot: pluginData },+ );++ // when+ const output = await runUserPromptSubmitHook(userPromptSubmitInput(root, transcriptPath), {+ pluginDataRoot: pluginData,+ env: PROJECT_RULES_ENV,+ });++ // then+ expect(firstContext.length).toBeGreaterThan(20_000);+ expect(output).toBe("");+ });+});++function makeOversizedProject(): { root: string; pluginData: string } {+ const root = mkdtempSync(path.join(tmpdir(), "codex-rules-post-compact-budget-project-"));+ const pluginData = mkdtempSync(path.join(tmpdir(), "codex-rules-post-compact-budget-data-"));+ tempDirectories.push(root, pluginData);+ writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "fixture" }));+ writeFileSync(path.join(root, "AGENTS.md"), `Project rule\n${"A".repeat(30_000)}`);+ mkdirSync(path.join(root, ".omo", "rules"), { recursive: true });+ writeFileSync(+ path.join(root, ".omo", "rules", "typescript.md"),+ ["---", 'globs: "**/*.ts"', "---", "", `TypeScript rule\n${"B".repeat(30_000)}`].join("\n"),+ );+ return { root, pluginData };+}++function sessionStartInput(root: string): CodexSessionStartInput {+ return {+ session_id: "session-post-compact-budget",+ transcript_path: null,+ cwd: root,+ hook_event_name: "SessionStart",+ model: "gpt-5.5",+ permission_mode: "default",+ source: "startup",+ };+}++function postCompactInput(root: string): CodexPostCompactInput {+ return {+ session_id: "session-post-compact-budget",+ 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): Parameters<typeof runUserPromptSubmitHook>[0] {+ return {+ session_id: "session-post-compact-budget",+ turn_id: "turn-after-compact",+ transcript_path: transcriptPath,+ cwd: root,+ hook_event_name: "UserPromptSubmit",+ model: "gpt-5.5",+ permission_mode: "default",+ prompt: "continue",+ };+}++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 {+ expect(output.trim().length).toBeGreaterThan(0);+ const parsed: unknown = JSON.parse(output);+ if (!isRecord(parsed)) return "";+ const hookSpecificOutput = parsed["hookSpecificOutput"];+ if (!isRecord(hookSpecificOutput)) return "";+ const additionalContext = hookSpecificOutput["additionalContext"];+ return typeof additionalContext === "string" ? additionalContext : "";+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/rules/test/codex-hook-post-compact-context.test.ts b/plugins/omo/components/rules/test/codex-hook-post-compact-context.test.tsnew file mode 100644index 00000000..dd20c24a--- /dev/null+++ b/plugins/omo/components/rules/test/codex-hook-post-compact-context.test.ts@@ -0,0 +1,156 @@+import { afterEach, describe, expect, it } from "vitest";++import { runPostCompactHook, runSessionStartHook } from "../src/codex-hook.js";+import {+ cleanupPostCompactFixtures,+ compactSessionStartInput,+ EXPANDED_POST_COMPACT_ENV,+ makeOversizedProject,+ PROJECT_RULES_ENV,+ postCompactInput,+ readAdditionalContext,+ readOptionalAdditionalContext,+ writeCompactedTranscript,+ writeCompactedWarningTranscript,+ writeMalformedContextTooLargeTranscript,+} from "./post-compact-test-fixture.ts";++afterEach(() => {+ cleanupPostCompactFixtures();+});++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 () => {+ // given+ const { root, pluginData } = makeOversizedProject("compact-source");+ const transcriptPath = writeCompactedTranscript(root, "summary dropped injected rules");+ await runPostCompactHook(+ { ...postCompactInput(root), transcript_path: transcriptPath },+ { pluginDataRoot: pluginData },+ );++ // when+ const output = await runSessionStartHook(compactSessionStartInput(root, transcriptPath), {+ pluginDataRoot: pluginData,+ env: PROJECT_RULES_ENV,+ });++ // then+ const postCompactContext = readAdditionalContext(output);+ expect(postCompactContext.length).toBeLessThan(5_000);+ expect(postCompactContext).toContain("Instructions from:");+ });++ it("#given compacted context warning and near-full transcript #when compact source starts twice #then handles compacted context warning once", async () => {+ // given+ const { root, pluginData } = makeOversizedProject("warning-once");+ const transcriptPath = writeCompactedWarningTranscript(root, "C".repeat(760_000));+ await runPostCompactHook(+ { ...postCompactInput(root), transcript_path: transcriptPath },+ { pluginDataRoot: pluginData },+ );++ // when+ const firstOutput = await runSessionStartHook(compactSessionStartInput(root, transcriptPath), {+ pluginDataRoot: pluginData,+ env: EXPANDED_POST_COMPACT_ENV,+ });+ const secondOutput = await runSessionStartHook(compactSessionStartInput(root, transcriptPath), {+ pluginDataRoot: pluginData,+ env: EXPANDED_POST_COMPACT_ENV,+ });++ // then+ const firstContext = readOptionalAdditionalContext(firstOutput);+ expect(firstContext.length).toBeLessThan(1_000);+ expect(firstContext).toContain("[Truncated. Full:");+ expect(secondOutput).toBe("");+ });++ it("#given context-too-large marker with compacted small summary #when compact source starts #then emits emergency-sized context", async () => {+ // given+ const { root, pluginData } = makeOversizedProject("warning-small");+ const transcriptPath = writeCompactedWarningTranscript(root, "small compacted summary");+ await runPostCompactHook(+ { ...postCompactInput(root), transcript_path: transcriptPath },+ { pluginDataRoot: pluginData },+ );++ // when+ const output = await runSessionStartHook(compactSessionStartInput(root, transcriptPath), {+ pluginDataRoot: pluginData,+ env: EXPANDED_POST_COMPACT_ENV,+ });++ // then+ const context = readOptionalAdditionalContext(output);+ expect(context.length).toBeLessThan(1_000);+ expect(context).toContain("[Truncated. Full:");+ });++ it("#given compact SessionStart without prior PostCompact state #when context-pressure transcript is present #then emits emergency-sized context", async () => {+ // given+ const { root, pluginData } = makeOversizedProject("compact-no-state");+ const transcriptPath = writeCompactedWarningTranscript(root, "small compacted summary");++ // when+ const output = await runSessionStartHook(compactSessionStartInput(root, transcriptPath), {+ pluginDataRoot: pluginData,+ env: EXPANDED_POST_COMPACT_ENV,+ });++ // then+ const context = readOptionalAdditionalContext(output);+ expect(context.length).toBeLessThan(1_000);+ expect(context).toContain("[Truncated. Full:");+ });++ it("#given malformed context-too-large transcript and empty session data #when compact source starts #then ignores malformed oversize markers safely", async () => {+ // given+ const { root, pluginData } = makeOversizedProject("malformed");+ const transcriptPath = writeMalformedContextTooLargeTranscript(root, "D".repeat(760_000));+ await runPostCompactHook(+ { ...postCompactInput(root), transcript_path: transcriptPath },+ { pluginDataRoot: pluginData },+ );++ // when+ const output = await runSessionStartHook(compactSessionStartInput(root, transcriptPath), {+ pluginDataRoot: pluginData,+ env: EXPANDED_POST_COMPACT_ENV,+ });++ // then+ const context = readOptionalAdditionalContext(output);+ expect(context.length).toBeLessThan(1_000);+ expect(context).toContain("[Truncated. Full:");+ });++ it("#given concurrent compact SessionStart triggers #when both recover context-too-large state #then deduplicates concurrent context-too-large recovery", async () => {+ // given+ const { root, pluginData } = makeOversizedProject("concurrent");+ const transcriptPath = writeCompactedWarningTranscript(root, "E".repeat(760_000));+ await runPostCompactHook(+ { ...postCompactInput(root), transcript_path: transcriptPath },+ { pluginDataRoot: pluginData },+ );++ // when+ const outputs = await Promise.all([+ runSessionStartHook(compactSessionStartInput(root, transcriptPath), {+ pluginDataRoot: pluginData,+ env: EXPANDED_POST_COMPACT_ENV,+ }),+ runSessionStartHook(compactSessionStartInput(root, transcriptPath), {+ pluginDataRoot: pluginData,+ env: EXPANDED_POST_COMPACT_ENV,+ }),+ ]);++ // then+ 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("[Truncated. Full:");+ });+});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.tsnew file mode 100644index 00000000..87d76327--- /dev/null+++ b/plugins/omo/components/rules/test/codex-hook-post-compact-dedup.test.ts@@ -0,0 +1,299 @@+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,+ runPostCompactHook,+ runPostToolUseHook,+ runSessionStartHook,+ runUserPromptSubmitHook,+} from "../src/codex-hook.js";++const tempDirectories: string[] = [];+const PROJECT_ONLY_ENV = {+ CODEX_RULES_ENABLED_SOURCES: "AGENTS.md,.omo/rules",+};++afterEach(() => {+ for (const directory of tempDirectories.splice(0)) {+ rmSync(directory, { recursive: true, force: true });+ }+});++describe("codex rules PostCompact deduplication", () => {+ it("#given compacted replacement already retained static context #when UserPromptSubmit runs after PostCompact #then it emits no duplicate static context", async () => {+ // given+ const { root, pluginData } = makeTempProject();+ const firstOutput = await runSessionStartHook(sessionStartInput(root), {+ pluginDataRoot: pluginData,+ env: PROJECT_ONLY_ENV,+ });+ const transcriptPath = writeTranscriptWithCompactedReplacement(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 compacted replacement already retained dynamic context #when PostToolUse runs after PostCompact #then it emits no duplicate dynamic context", async () => {+ // given+ const { root, pluginData } = makeTempProject();+ const filePath = path.join(root, "src", "app.ts");+ const input = postToolUseInput(root, filePath);+ const firstOutput = await runPostToolUseHook(input, { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV });+ const transcriptPath = writeTranscriptWithCompactedReplacement(root, readAdditionalContext(firstOutput));+ await runPostCompactHook(+ { ...postCompactInput(root), transcript_path: transcriptPath },+ { pluginDataRoot: pluginData },+ );++ // when+ const output = await runPostToolUseHook(+ { ...input, transcript_path: transcriptPath },+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },+ );++ // then+ expect(output).toBe("");+ });++ it("#given malformed transcript with repeated compactions retaining context #when UserPromptSubmit runs after PostCompact #then it emits no duplicate static context", async () => {+ // given+ const { root, pluginData } = makeTempProject();+ const firstOutput = await runSessionStartHook(sessionStartInput(root), {+ pluginDataRoot: pluginData,+ env: PROJECT_ONLY_ENV,+ });+ const transcriptPath = writeTranscriptWithRepeatedCompactions(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 startup already injected static context #when UserPromptSubmit runs after PostCompact #then it emits no duplicate static context", async () => {+ // given+ const { root, pluginData } = makeTempProject();+ await runSessionStartHook(sessionStartInput(root), {+ pluginDataRoot: pluginData,+ env: PROJECT_ONLY_ENV,+ });+ const transcriptPath = writeTranscriptWithCompactedReplacement(root, "summary without project instructions");+ 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 startup already injected static context #when compact SessionStart runs after PostCompact #then it emits no duplicate static context", async () => {+ // given+ const { root, pluginData } = makeTempProject();+ await runSessionStartHook(sessionStartInput(root), {+ pluginDataRoot: pluginData,+ env: PROJECT_ONLY_ENV,+ });+ const transcriptPath = writeTranscriptWithCompactedReplacement(root, "summary without project instructions");+ await runPostCompactHook(+ { ...postCompactInput(root), transcript_path: transcriptPath },+ { pluginDataRoot: pluginData },+ );++ // when+ const output = await runSessionStartHook(compactSessionStartInput(root, transcriptPath), {+ pluginDataRoot: pluginData,+ env: PROJECT_ONLY_ENV,+ });++ // then+ expect(output).toBe("");+ });+});++function makeTempProject(): { root: string; pluginData: string } {+ const root = mkdtempSync(path.join(tmpdir(), "codex-rules-compact-dedup-project-"));+ const pluginData = mkdtempSync(path.join(tmpdir(), "codex-rules-compact-dedup-data-"));+ tempDirectories.push(root, pluginData);+ writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "fixture" }));+ writeFileSync(path.join(root, "AGENTS.md"), "Always wear safety goggles when refactoring.");+ mkdirSync(path.join(root, ".omo", "rules"), { recursive: true });+ writeFileSync(+ path.join(root, ".omo", "rules", "typescript.md"),+ [+ "---",+ "description: TypeScript",+ 'globs: ["**/*.ts", "**/*.tsx"]',+ "---",+ "",+ "Prefer strict TypeScript for all source files.",+ ].join("\n"),+ );+ mkdirSync(path.join(root, "src"), { recursive: true });+ writeFileSync(path.join(root, "src", "app.ts"), "export const app = true;\n");+ return { root, pluginData };+}++function sessionStartInput(root: string): CodexSessionStartInput {+ return {+ session_id: "session-compact-dedup",+ 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 {+ ...sessionStartInput(root),+ transcript_path: transcriptPath,+ source: "compact",+ };+}++function postCompactInput(root: string): CodexPostCompactInput {+ return {+ session_id: "session-compact-dedup",+ turn_id: "turn-compact",+ transcript_path: null,+ cwd: root,+ hook_event_name: "PostCompact",+ model: "gpt-5.5",+ trigger: "manual",+ };+}++function userPromptSubmitInput(root: string, transcriptPath: string): Parameters<typeof runUserPromptSubmitHook>[0] {+ return {+ session_id: "session-compact-dedup",+ turn_id: "turn-after-compact",+ transcript_path: transcriptPath,+ cwd: root,+ hook_event_name: "UserPromptSubmit",+ model: "gpt-5.5",+ permission_mode: "default",+ prompt: "read src/app.ts",+ };+}++function postToolUseInput(root: string, filePath: string): CodexPostToolUseInput {+ return {+ session_id: "session-compact-dedup",+ turn_id: "turn-after-compact",+ transcript_path: null,+ cwd: root,+ hook_event_name: "PostToolUse",+ model: "gpt-5.5",+ permission_mode: "default",+ tool_name: "mcp__filesystem__read_file",+ tool_input: { path: filePath },+ tool_response: { text: "file contents" },+ tool_use_id: "call-1",+ };+}++function writeTranscriptWithCompactedReplacement(root: string, ...replacementTexts: string[]): string {+ const transcriptPath = path.join(root, "transcript-compacted.jsonl");+ const replacementHistory = replacementTexts.map((text) => ({+ type: "message",+ role: "user",+ content: [{ type: "input_text", text }],+ }));+ writeFileSync(+ transcriptPath,+ `${JSON.stringify({+ type: "compacted",+ payload: {+ message: "summary",+ replacement_history: replacementHistory,+ },+ })}\n`,+ );+ return transcriptPath;+}++function writeTranscriptWithRepeatedCompactions(root: string, retainedText: string): string {+ const transcriptPath = path.join(root, "transcript-repeated-compacted.jsonl");+ writeFileSync(+ transcriptPath,+ [+ "{not json",+ JSON.stringify({+ type: "compacted",+ payload: {+ message: "older summary",+ replacement_history: [{ type: "message", role: "user", content: "old summary without rules" }],+ },+ }),+ JSON.stringify({+ type: "message",+ payload: { content: "x".repeat(10_000) },+ }),+ JSON.stringify({+ type: "compacted",+ payload: {+ message: "latest summary",+ replacement_history: [+ {+ type: "message",+ role: "user",+ content: [{ type: "input_text", text: retainedText }],+ },+ ],+ },+ }),+ JSON.stringify({+ type: "message",+ payload: { content: "later prompt after compact" },+ }),+ "",+ ].join("\n"),+ );+ return transcriptPath;+}++function readAdditionalContext(output: string): string {+ expect(output.trim().length).toBeGreaterThan(0);+ const parsed: unknown = JSON.parse(output);+ if (!isRecord(parsed)) return "";+ const hookSpecificOutput = parsed["hookSpecificOutput"];+ if (!isRecord(hookSpecificOutput)) return "";+ const additionalContext = hookSpecificOutput["additionalContext"];+ return typeof additionalContext === "string" ? additionalContext : "";+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/rules/test/codex-hook-post-compact-lock.test.ts b/plugins/omo/components/rules/test/codex-hook-post-compact-lock.test.tsnew file mode 100644index 00000000..d621fb71--- /dev/null+++ b/plugins/omo/components/rules/test/codex-hook-post-compact-lock.test.ts@@ -0,0 +1,46 @@+import { mkdirSync, rmSync } from "node:fs";+import { afterEach, describe, expect, it } from "vitest";++import { runPostCompactHook, runSessionStartHook } from "../src/codex-hook.js";+import { sessionCachePath } from "../src/persistent-cache.js";+import {+ cleanupPostCompactFixtures,+ compactSessionStartInput,+ EXPANDED_POST_COMPACT_ENV,+ makeOversizedProject,+ postCompactInput,+ writeCompactedWarningTranscript,+} from "./post-compact-test-fixture.ts";++const SESSION_ID = "session-post-compact-lock";++afterEach(() => {+ cleanupPostCompactFixtures();+});++describe("codex rules post-compact lock contention", () => {+ it("#given compacted session state while cache lock is contended #when compact source starts #then skips fail-open rule injection", async () => {+ // given+ const { root, pluginData } = makeOversizedProject("lock");+ const transcriptPath = writeCompactedWarningTranscript(root, "F".repeat(760_000));+ await runPostCompactHook(+ { ...postCompactInput(root, SESSION_ID), transcript_path: transcriptPath },+ { pluginDataRoot: pluginData },+ );+ const lockPath = `${sessionCachePath(SESSION_ID, pluginData)}.lock`;+ mkdirSync(lockPath);++ try {+ // when+ const output = await runSessionStartHook(compactSessionStartInput(root, transcriptPath, SESSION_ID), {+ pluginDataRoot: pluginData,+ env: EXPANDED_POST_COMPACT_ENV,+ });++ // then+ expect(output).toBe("");+ } finally {+ rmSync(lockPath, { recursive: true, force: true });+ }+ });+});diff --git a/plugins/omo/components/rules/test/codex-hook-post-compact-process.test.ts b/plugins/omo/components/rules/test/codex-hook-post-compact-process.test.tsnew file mode 100644index 00000000..e8e199e7--- /dev/null+++ b/plugins/omo/components/rules/test/codex-hook-post-compact-process.test.ts@@ -0,0 +1,83 @@+import { execFileSync, spawn } from "node:child_process";+import { fileURLToPath } from "node:url";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { runPostCompactHook } from "../src/codex-hook.js";+import {+ cleanupPostCompactFixtures,+ compactSessionStartInput,+ EXPANDED_POST_COMPACT_ENV,+ makeOversizedProject,+ postCompactInput,+ readOptionalAdditionalContext,+ writeCompactedWarningTranscript,+} from "./post-compact-test-fixture.ts";++type CliResult = {+ readonly exitCode: number | null;+ readonly stdout: string;+ readonly stderr: string;+};++const PLUGIN_ROOT = fileURLToPath(new URL("..", import.meta.url));+const CLI_PATH = fileURLToPath(new URL("../dist/cli.js", import.meta.url));++beforeAll(() => {+ execFileSync("npm", ["run", "build", "--silent"], { cwd: PLUGIN_ROOT, stdio: "pipe" });+});++afterAll(() => {+ cleanupPostCompactFixtures();+});++describe("codex rules post-compact cross-process recovery", () => {+ it("#given two compact hook processes share session state #when both start concurrently #then only one emits the budgeted recovery context", async () => {+ // given+ const { root, pluginData } = makeOversizedProject("process");+ const transcriptPath = writeCompactedWarningTranscript(root, "G".repeat(760_000));+ await runPostCompactHook(+ { ...postCompactInput(root), transcript_path: transcriptPath },+ { pluginDataRoot: pluginData },+ );+ const input = `${JSON.stringify(compactSessionStartInput(root, transcriptPath))}\n`;++ // when+ const [first, second] = await Promise.all([+ runHookCli(input, "session-start", { ...EXPANDED_POST_COMPACT_ENV, PLUGIN_DATA: pluginData }),+ runHookCli(input, "session-start", { ...EXPANDED_POST_COMPACT_ENV, PLUGIN_DATA: pluginData }),+ ]);++ // then+ expect(first.exitCode).toBe(0);+ expect(second.exitCode).toBe(0);+ expect(first.stderr).toBe("");+ expect(second.stderr).toBe("");+ const contexts = [first.stdout, second.stdout].map(readOptionalAdditionalContext);+ expect(contexts.filter((context) => context.length > 0)).toHaveLength(1);+ expect(contexts.join("").length).toBeLessThan(1_000);+ });+});++function runHookCli(input: string, subcommand: string, env: NodeJS.ProcessEnv): Promise<CliResult> {+ return new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [CLI_PATH, "hook", subcommand], {+ env: { ...process.env, ...env },+ stdio: ["pipe", "pipe", "pipe"],+ });+ let stdout = "";+ let stderr = "";+ child.stdout.setEncoding("utf8");+ child.stderr.setEncoding("utf8");+ child.stdout.on("data", (chunk: string) => {+ stdout += chunk;+ });+ child.stderr.on("data", (chunk: string) => {+ stderr += chunk;+ });+ child.once("error", reject);+ child.once("close", (exitCode) => {+ resolve({ exitCode, stdout, stderr });+ });+ child.stdin.end(input);+ });+}diff --git a/plugins/omo/components/rules/test/codex-hook.test.ts b/plugins/omo/components/rules/test/codex-hook.test.tsindex b05dbdb8..5659e1f5 100644--- a/plugins/omo/components/rules/test/codex-hook.test.ts+++ b/plugins/omo/components/rules/test/codex-hook.test.ts@@ -407,7 +407,7 @@ describe("codex rules hooks", () => {);});- it("#given cached dynamic context #when PostCompact runs #then PostToolUse can re-inject after compaction", async () => {+ it("#given cached dynamic context #when PostCompact runs #then PostToolUse emits no duplicate dynamic context", async () => {// givenconst { root, pluginData } = makeTempProject();const filePath = path.join(root, "src", "app.ts");@@ -434,10 +434,10 @@ describe("codex rules hooks", () => {// thenexpect(compactOutput).toBe("");- expect(parseHookOutput(output).hookSpecificOutput?.additionalContext).toContain("Prefer strict TypeScript");+ expect(output).toBe("");});- it("#given compacted transcript #when static re-injects before dynamic #then dynamic still re-injects", async () => {+ it("#given cached static and dynamic context #when static recovery runs before dynamic #then neither emits duplicate context", async () => {// givenconst { root, pluginData } = makeTempProject();const filePath = path.join(root, "src", "app.ts");@@ -470,15 +470,11 @@ describe("codex rules hooks", () => {);// then- expect(parseHookOutput(staticReinjectOutput).hookSpecificOutput?.additionalContext).toContain(- "Always wear safety goggles",- );- expect(parseHookOutput(dynamicReinjectOutput).hookSpecificOutput?.additionalContext).toContain(- "Prefer strict TypeScript",- );+ expect(staticReinjectOutput).toBe("");+ expect(dynamicReinjectOutput).toBe("");});- it("#given compacted transcript #when dynamic re-injects before static #then static still re-injects", async () => {+ it("#given cached static and dynamic context #when dynamic recovery runs before static #then neither emits duplicate context", async () => {// givenconst { root, pluginData } = makeTempProject();const filePath = path.join(root, "src", "app.ts");@@ -511,12 +507,8 @@ describe("codex rules hooks", () => {});// then- expect(parseHookOutput(dynamicReinjectOutput).hookSpecificOutput?.additionalContext).toContain(- "Prefer strict TypeScript",- );- expect(parseHookOutput(staticReinjectOutput).hookSpecificOutput?.additionalContext).toContain(- "Always wear safety goggles",- );+ expect(dynamicReinjectOutput).toBe("");+ expect(staticReinjectOutput).toBe("");});it("#given legacy session cache #when PostToolUse hydrates state #then it accepts the old shape", async () => {diff --git a/plugins/omo/components/rules/test/formatter.test.ts b/plugins/omo/components/rules/test/formatter.test.tsnew file mode 100644index 00000000..903974c0--- /dev/null+++ b/plugins/omo/components/rules/test/formatter.test.ts@@ -0,0 +1,168 @@+import { describe, expect, it } from "vitest";++import { formatDynamicBlock, formatStaticBlock } from "../src/rules/formatter.js";+import type { LoadedRule, MatchReason, RuleSource } from "../src/rules/types.js";++const FORMAT_OPTIONS = {+ maxRuleChars: 10_000,+ maxResultChars: 10_000,+};++describe("rules formatter hook context", () => {+ it("#given multiline dynamic rules #when formatting PostToolUse context #then labels and bodies render on separate lines", () => {+ // given+ const rule = loadedRule({+ path: "/repo/packages/AGENTS.md",+ relativePath: "packages/AGENTS.md",+ body: ["# packages", "", "## OVERVIEW", "23 sibling packages.", "", "## CONVENTIONS", "Use npm."].join("\n"),+ });++ // when+ const block = formatDynamicBlock(+ [rule],+ "packages/omo-codex/plugin/components/ulw-loop/src/paths.ts",+ FORMAT_OPTIONS,+ );++ // then+ expect(block).toBe(+ [+ "Additional project instructions matched for packages/omo-codex/plugin/components/ulw-loop/src/paths.ts:",+ "",+ "Instructions from: /repo/packages/AGENTS.md",+ "",+ "# packages",+ "",+ "## OVERVIEW",+ "23 sibling packages.",+ "",+ "## CONVENTIONS",+ "Use npm.",+ ].join("\n"),+ );+ });++ it("#given static rules #when formatting SessionStart context #then it avoids leading blank lines", () => {+ // given+ const rule = loadedRule({+ path: "/repo/AGENTS.md",+ relativePath: "AGENTS.md",+ body: "Keep generated hook context readable.",+ });++ // when+ const block = formatStaticBlock([rule], FORMAT_OPTIONS);++ // then+ expect(block).toBe(+ [+ "## Project Instructions",+ "",+ "Instructions from: /repo/AGENTS.md",+ "",+ "Keep generated hook context readable.",+ ].join("\n"),+ );+ });++ it("#given CRLF and bare CR rule bodies #when formatting context #then it normalizes line endings", () => {+ // given+ const rule = loadedRule({+ body: "First line\r\n indented second line\rThird line",+ });++ // when+ const block = formatDynamicBlock([rule], "src/app.ts", FORMAT_OPTIONS);++ // then+ expect(block).toContain("First line\n indented second line\nThird line");+ expect(block).not.toContain("\r");+ });++ it("#given duplicate static rules with different line endings #when formatting context #then it renders one copy", () => {+ // given+ const lfRule = loadedRule({+ path: "/repo/AGENTS.md",+ relativePath: "AGENTS.md",+ body: "Shared rule\nKeep one copy.",+ });+ const crlfRule = loadedRule({+ path: "/repo/packages/AGENTS.md",+ relativePath: "packages/AGENTS.md",+ body: "Shared rule\r\nKeep one copy.",+ });++ // when+ const block = formatStaticBlock([lfRule, crlfRule], FORMAT_OPTIONS);++ // then+ expect(occurrenceCount(block, "Shared rule\nKeep one copy.")).toBe(1);+ expect(block).not.toContain("/repo/packages/AGENTS.md");+ });++ 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", () => {+ // given+ const rules = [+ loadedRule({ path: "/repo/alpha.md", relativePath: "alpha.md", body: `alpha-${"A".repeat(500)}` }),+ loadedRule({ path: "/repo/beta.md", relativePath: "beta.md", body: `beta-${"B".repeat(500)}` }),+ loadedRule({ path: "/repo/gamma.md", relativePath: "gamma.md", body: `gamma-${"C".repeat(500)}` }),+ ];++ // when+ const block = formatDynamicBlock(rules, "src/app.ts", {+ maxRuleChars: 10_000,+ maxResultChars: 900,+ });++ // then+ expect(block).toContain("Instructions from: /repo/alpha.md");+ expect(block).toContain("Instructions from: /repo/beta.md");+ expect(block).toContain("Instructions from: /repo/gamma.md");+ expect(block).toContain("[Truncated. Full: alpha.md]");+ expect(block).toContain("[Truncated. Full: beta.md]");+ expect(block).toContain("[Truncated. Full: gamma.md]");+ expect(occurrenceCount(block, "[Truncated. Full:")).toBe(3);+ });++ it("#given no matching rules #when formatting hook context #then it emits no context", () => {+ // given+ const rules: LoadedRule[] = [];++ // when+ const dynamicBlock = formatDynamicBlock(rules, "src/app.ts", FORMAT_OPTIONS);+ const staticBlock = formatStaticBlock(rules, FORMAT_OPTIONS);++ // then+ expect(dynamicBlock).toBe("");+ expect(staticBlock).toBe("");+ });+});++function loadedRule(input: {+ readonly body: string;+ readonly path?: string;+ readonly relativePath?: string;+ readonly source?: RuleSource;+ readonly matchReason?: MatchReason;+}): LoadedRule {+ const path = input.path ?? "/repo/AGENTS.md";+ const relativePath = input.relativePath ?? "AGENTS.md";+ const source = input.source ?? "AGENTS.md";+ return {+ path,+ realPath: path,+ source,+ distance: 0,+ isGlobal: false,+ isSingleFile: true,+ relativePath,+ frontmatter: {},+ body: input.body,+ contentHash: "hash",+ matchReason: input.matchReason ?? "single-file",+ };+}++function occurrenceCount(value: string, search: string): number {+ return value.split(search).length - 1;+}diff --git a/plugins/omo/components/rules/test/hook-output.test.ts b/plugins/omo/components/rules/test/hook-output.test.tsnew file mode 100644index 00000000..aa022863--- /dev/null+++ b/plugins/omo/components/rules/test/hook-output.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from "vitest";++import { formatAdditionalContextOutput } from "../src/hook-output.js";++describe("formatAdditionalContextOutput", () => {+ it("#given context with outer whitespace and CRLF #when serializing hook JSON #then additional context is newline-normalized", () => {+ // given+ const context = "\r\n\r\nFirst line\r\nSecond line\rThird line\r\n";++ // when+ const output = formatAdditionalContextOutput("PostToolUse", context);+ const parsed: unknown = JSON.parse(output);++ // then+ expect(readAdditionalContext(parsed)).toBe("First line\nSecond line\nThird line");+ expect(output.endsWith("\n")).toBe(true);+ });++ it("#given blank context #when serializing hook JSON #then it emits no hook output", () => {+ // given+ const context = "\r\n \n";++ // when+ const output = formatAdditionalContextOutput("SessionStart", context);++ // then+ expect(output).toBe("");+ });+});++function readAdditionalContext(value: unknown): string {+ if (!isRecord(value)) throw new TypeError("Expected hook output object");+ const hookSpecificOutput = value["hookSpecificOutput"];+ if (!isRecord(hookSpecificOutput)) throw new TypeError("Expected hookSpecificOutput object");+ const additionalContext = hookSpecificOutput["additionalContext"];+ if (typeof additionalContext !== "string") throw new TypeError("Expected additionalContext string");+ return additionalContext;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/rules/test/package-smoke.test.ts b/plugins/omo/components/rules/test/package-smoke.test.tsindex 186e8ab5..afa67eec 100644--- a/plugins/omo/components/rules/test/package-smoke.test.ts+++ b/plugins/omo/components/rules/test/package-smoke.test.ts@@ -1,4 +1,4 @@-import { readFileSync } from "node:fs";+import { readdirSync, readFileSync } from "node:fs";import { describe, expect, it } from "vitest";type PackageJson = {@@ -51,6 +51,7 @@ describe("plugin package metadata", () => {const pluginJson = readPluginJson(".codex-plugin/plugin.json");const hooksJson = readHooksJson("hooks/hooks.json");const cliSource = readFileSync("src/cli.ts", "utf8");+ const bundledRules = readdirSync("bundled-rules").sort();// whenconst hookConfig = hooksJson.hooks;@@ -67,8 +68,9 @@ describe("plugin package metadata", () => {expect(packageJson.type).toBe("module");expect(packageJson.packageManager).toBe("[email protected]");expect(packageJson.dependencies ?? {}).toEqual({ picomatch: "^4.0.3" });- expect(packageJson.bin["codex-rules"]).toBe("./dist/cli.js");+ expect(packageJson.bin["omo-rules"]).toBe("./dist/cli.js");expect(packageJson.files).toContain("bundled-rules");+ expect(bundledRules).toContain("windows-git-bash.md");expect(pluginJson.hooks).toBe("./hooks/hooks.json");expect(cliSource.startsWith("#!/usr/bin/env node")).toBe(true);expect(commands).toEqual([diff --git a/plugins/omo/components/rules/test/persistent-cache.test.ts b/plugins/omo/components/rules/test/persistent-cache.test.tsnew file mode 100644index 00000000..4581a1e1--- /dev/null+++ b/plugins/omo/components/rules/test/persistent-cache.test.ts@@ -0,0 +1,63 @@+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import {+ claimPostCompactPending,+ isPostCompactPending,+ isPostCompactRecoveryInProgress,+ markSessionCompacted,+ sessionCachePath,+} from "../src/persistent-cache.js";++const tempDirectories: string[] = [];++afterEach(() => {+ for (const directory of tempDirectories.splice(0)) {+ rmSync(directory, { recursive: true, force: true });+ }+});++describe("persistent post-compact state", () => {+ it("#given post-compact pending state #when static recovery is claimed twice #then only the first caller proceeds", () => {+ // given+ const pluginData = mkdtempSync(path.join(tmpdir(), "codex-rules-cache-"));+ tempDirectories.push(pluginData);+ const cachePath = sessionCachePath("session-cache-claim", pluginData);+ markSessionCompacted(cachePath);++ // when+ const firstClaim = claimPostCompactPending(cachePath, "static");+ const secondClaim = claimPostCompactPending(cachePath, "static");++ // then+ expect(firstClaim).toBe("claimed");+ expect(secondClaim).toBe("not-pending");+ expect(isPostCompactPending(cachePath, "static")).toBe(false);+ expect(isPostCompactRecoveryInProgress(cachePath, "static")).toBe(true);+ expect(isPostCompactPending(cachePath, "dynamic")).toBe(true);+ });++ it("#given post-compact pending state and contended lock #when static recovery is claimed #then reports contention without consuming pending state", () => {+ // given+ const pluginData = mkdtempSync(path.join(tmpdir(), "codex-rules-cache-"));+ tempDirectories.push(pluginData);+ const cachePath = sessionCachePath("session-cache-contended", pluginData);+ markSessionCompacted(cachePath);+ const lockPath = `${cachePath}.lock`;+ mkdirSync(lockPath);++ try {+ // when+ const claim = claimPostCompactPending(cachePath, "static");++ // then+ expect(claim).toBe("contended");+ expect(isPostCompactPending(cachePath, "static")).toBe(true);+ expect(isPostCompactRecoveryInProgress(cachePath, "static")).toBe(false);+ } finally {+ rmSync(lockPath, { recursive: true, force: true });+ }+ });+});diff --git a/plugins/omo/components/rules/test/post-compact-budget.test.ts b/plugins/omo/components/rules/test/post-compact-budget.test.tsnew file mode 100644index 00000000..0c462b27--- /dev/null+++ b/plugins/omo/components/rules/test/post-compact-budget.test.ts@@ -0,0 +1,172 @@+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { withPostCompactBudget } from "../src/post-compact-budget.js";+import type { PiRulesConfig } from "../src/rules/types.js";++const tempDirectories: string[] = [];+const CONFIG: PiRulesConfig = {+ disabled: false,+ mode: "both",+ maxRuleChars: 30_000,+ maxResultChars: 50_000,+ postCompactMaxRuleChars: 12_000,+ postCompactMaxResultChars: 20_000,+ enabledSources: "auto",+};++afterEach(() => {+ for (const directory of tempDirectories.splice(0)) {+ rmSync(directory, { recursive: true, force: true });+ }+});++describe("post-compact context budget", () => {+ it("#given known model near its context window #when resolving post-compact budget #then shrinks projected rule injection", () => {+ // given+ const transcriptPath = writeCompactedTranscript("A".repeat(760_000));++ // when+ const budget = withPostCompactBudget(CONFIG, { model: "gpt-5.5", transcriptPath });++ // then+ expect(budget.maxResultChars).toBeLessThan(1_000);+ expect(budget.maxRuleChars).toBeLessThanOrEqual(budget.maxResultChars);+ });++ it("#given unknown model near its context window #when resolving post-compact budget #then shrinks projected rule injection conservatively", () => {+ // given+ const transcriptPath = writeCompactedTranscript("A".repeat(760_000));++ // when+ const budget = withPostCompactBudget(CONFIG, { model: "unknown-model", transcriptPath });++ // then+ expect(budget.maxResultChars).toBeLessThan(1_000);+ expect(budget.maxRuleChars).toBeLessThanOrEqual(budget.maxResultChars);+ });++ it("#given known roomy model #when resolving post-compact budget #then keeps configured post-compact cap", () => {+ // given+ const transcriptPath = writeCompactedTranscript("small compacted summary");++ // when+ const budget = withPostCompactBudget(CONFIG, { model: "openai.gpt-5.5", transcriptPath });++ // then+ expect(budget.maxRuleChars).toBe(CONFIG.postCompactMaxRuleChars);+ expect(budget.maxResultChars).toBe(CONFIG.postCompactMaxResultChars);+ });++ it("#given context pressure marker after compaction #when resolving post-compact budget #then shrinks projected rule injection", () => {+ // given+ const transcriptPath = writeCompactedPressureTranscript("small compacted summary");++ // when+ const budget = withPostCompactBudget(CONFIG, { model: "gpt-5.5", transcriptPath });++ // then+ expect(budget.maxResultChars).toBeLessThan(1_000);+ expect(budget.maxRuleChars).toBeLessThanOrEqual(budget.maxResultChars);+ });++ it("#given Codex canonical context-window marker after compaction #when resolving post-compact budget #then shrinks projected rule injection", () => {+ // given+ const transcriptPath = writeCompactedCodexContextWindowTranscript("small compacted summary");++ // when+ const budget = withPostCompactBudget(CONFIG, { model: "gpt-5.5", transcriptPath });++ // then+ expect(budget.maxResultChars).toBeLessThan(1_000);+ expect(budget.maxRuleChars).toBeLessThanOrEqual(budget.maxResultChars);+ });+});++function writeCompactedTranscript(retainedText: string): string {+ const root = mkdtempSync(path.join(tmpdir(), "post-compact-budget-"));+ tempDirectories.push(root);+ const transcriptPath = path.join(root, "transcript.jsonl");+ writeFileSync(+ transcriptPath,+ `${JSON.stringify({+ type: "compacted",+ payload: {+ message: "summary",+ replacement_history: [{ type: "message", role: "user", content: retainedText }],+ },+ })}\n`,+ );+ return transcriptPath;+}++function writeCompactedPressureTranscript(retainedText: string): string {+ const root = mkdtempSync(path.join(tmpdir(), "post-compact-budget-"));+ tempDirectories.push(root);+ const transcriptPath = path.join(root, "transcript-pressure.jsonl");+ writeFileSync(+ transcriptPath,+ [+ JSON.stringify({+ type: "compacted",+ payload: {+ message: "summary",+ replacement_history: [{ type: "message", role: "user", content: retainedText }],+ },+ }),+ JSON.stringify({+ type: "message",+ payload: {+ content: {+ error: {+ code: "context_too_large",+ message:+ "Your input exceeds the context window of this model. Please adjust your input and try again.",+ },+ },+ },+ }),+ "",+ ].join("\n"),+ );+ return transcriptPath;+}++function writeCompactedCodexContextWindowTranscript(retainedText: string): string {+ const root = mkdtempSync(path.join(tmpdir(), "post-compact-budget-"));+ tempDirectories.push(root);+ const transcriptPath = path.join(root, "transcript-codex-context-window.jsonl");+ writeFileSync(+ transcriptPath,+ [+ JSON.stringify({+ type: "compacted",+ payload: {+ message: "summary",+ replacement_history: [{ type: "message", role: "user", content: retainedText }],+ },+ }),+ JSON.stringify({+ type: "message",+ payload: {+ content: {+ error: {+ code: "context_length_exceeded",+ },+ },+ },+ }),+ JSON.stringify({+ type: "message",+ payload: {+ content:+ "Codex ran out of room in the model's context window. Start a new thread or clear earlier history before retrying.",+ },+ }),+ "",+ ].join("\n"),+ );+ return transcriptPath;+}diff --git a/plugins/omo/components/rules/test/post-compact-test-fixture.ts b/plugins/omo/components/rules/test/post-compact-test-fixture.tsnew file mode 100644index 00000000..c34d54b0--- /dev/null+++ b/plugins/omo/components/rules/test/post-compact-test-fixture.ts@@ -0,0 +1,196 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";++import type { CodexPostCompactInput, CodexSessionStartInput, CodexUserPromptSubmitInput } from "../src/codex-hook.js";++export const PROJECT_RULES_ENV = {+ CODEX_RULES_ENABLED_SOURCES: "AGENTS.md,.omo/rules",+ CODEX_RULES_MAX_RESULT_CHARS: "50000",+ CODEX_RULES_MAX_RULE_CHARS: "30000",+};++export const EXPANDED_POST_COMPACT_ENV = {+ ...PROJECT_RULES_ENV,+ CODEX_RULES_POST_COMPACT_MAX_RESULT_CHARS: "20000",+ CODEX_RULES_POST_COMPACT_MAX_RULE_CHARS: "12000",+};++const tempDirectories: string[] = [];+const DEFAULT_SESSION_ID = "session-post-compact-budget";++export function cleanupPostCompactFixtures(): void {+ for (const directory of tempDirectories.splice(0)) {+ rmSync(directory, { recursive: true, force: true });+ }+}++export function makeOversizedProject(prefix = "budget"): { root: string; pluginData: string } {+ const root = mkdtempSync(path.join(tmpdir(), `codex-rules-post-compact-${prefix}-project-`));+ const pluginData = mkdtempSync(path.join(tmpdir(), `codex-rules-post-compact-${prefix}-data-`));+ tempDirectories.push(root, pluginData);+ writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "fixture" }));+ writeFileSync(path.join(root, "AGENTS.md"), `Project rule\n${"A".repeat(30_000)}`);+ mkdirSync(path.join(root, ".omo", "rules"), { recursive: true });+ writeFileSync(+ path.join(root, ".omo", "rules", "typescript.md"),+ ["---", 'globs: "**/*.ts"', "---", "", `TypeScript rule\n${"B".repeat(30_000)}`].join("\n"),+ );+ return { root, pluginData };+}++export function sessionStartInput(root: string, sessionId = DEFAULT_SESSION_ID): CodexSessionStartInput {+ return {+ session_id: sessionId,+ transcript_path: null,+ cwd: root,+ hook_event_name: "SessionStart",+ model: "gpt-5.5",+ permission_mode: "default",+ source: "startup",+ };+}++export function compactSessionStartInput(+ root: string,+ transcriptPath: string,+ sessionId = DEFAULT_SESSION_ID,+): CodexSessionStartInput {+ return {+ session_id: sessionId,+ transcript_path: transcriptPath,+ cwd: root,+ hook_event_name: "SessionStart",+ model: "gpt-5.5",+ permission_mode: "default",+ source: "compact",+ };+}++export function postCompactInput(root: string, sessionId = DEFAULT_SESSION_ID): CodexPostCompactInput {+ return {+ session_id: sessionId,+ turn_id: "turn-compact",+ transcript_path: null,+ cwd: root,+ hook_event_name: "PostCompact",+ model: "gpt-5.5",+ trigger: "auto",+ };+}++export function userPromptSubmitInput(+ root: string,+ transcriptPath: string,+ sessionId = DEFAULT_SESSION_ID,+): CodexUserPromptSubmitInput {+ return {+ session_id: sessionId,+ turn_id: "turn-after-compact",+ transcript_path: transcriptPath,+ cwd: root,+ hook_event_name: "UserPromptSubmit",+ model: "gpt-5.5",+ permission_mode: "default",+ prompt: "continue",+ };+}++export 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;+}++export function writeCompactedWarningTranscript(root: string, retainedText: string): string {+ const transcriptPath = path.join(root, "transcript-compacted-warning.jsonl");+ writeFileSync(+ transcriptPath,+ [+ JSON.stringify({+ type: "message",+ payload: {+ content: "Skill descriptions were shortened to fit the 2% skills context budget. Context compacted.",+ },+ }),+ JSON.stringify({+ type: "compacted",+ payload: {+ message: "summary",+ replacement_history: [{ type: "message", role: "user", content: retainedText }],+ },+ }),+ JSON.stringify({+ type: "message",+ payload: {+ content: "Your input exceeds the context window of this model. Please adjust your input and try again.",+ },+ }),+ "",+ ].join("\n"),+ );+ return transcriptPath;+}++export function writeMalformedContextTooLargeTranscript(root: string, retainedText = ""): string {+ const transcriptPath = path.join(root, "transcript-context-too-large.jsonl");+ writeFileSync(+ transcriptPath,+ [+ "{not json",+ retainedText,+ JSON.stringify({+ type: "message",+ payload: {+ content: "Skill descriptions were shortened to fit the 2% skills context budget. Context compacted.",+ },+ }),+ JSON.stringify({+ type: "message",+ payload: {+ content: {+ error: {+ code: "context_too_large",+ message:+ "Your input exceeds the context window of this model. Please adjust your input and try again.",+ },+ },+ },+ }),+ "",+ ].join("\n"),+ );+ return transcriptPath;+}++export function readOptionalAdditionalContext(output: string): string {+ if (output.trim().length === 0) {+ return "";+ }+ return readAdditionalContext(output);+}++export 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 (!isRecord(parsed)) return "";+ const hookSpecificOutput = parsed["hookSpecificOutput"];+ if (!isRecord(hookSpecificOutput)) return "";+ const additionalContext = hookSpecificOutput["additionalContext"];+ return typeof additionalContext === "string" ? additionalContext : "";+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/rules/test/windows-git-bash-bundled-rule.test.ts b/plugins/omo/components/rules/test/windows-git-bash-bundled-rule.test.tsnew file mode 100644index 00000000..d0994f9b--- /dev/null+++ b/plugins/omo/components/rules/test/windows-git-bash-bundled-rule.test.ts@@ -0,0 +1,120 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { type CodexSessionStartInput, runSessionStartHook } from "../src/codex-hook.js";+import { findPluginBundledCandidates } from "../src/rules/finder.js";++const WINDOWS_RULE_DESCRIPTION = "Windows Git Bash guidance for Codex";+const WINDOWS_RULE_PATH = "bundled-rules/windows-git-bash.md";+const WINDOWS_GUIDANCE = "On Windows native Codex sessions, prefer Git Bash for shell commands.";+const BUNDLED_ONLY_ENV = {+ CODEX_RULES_ENABLED_SOURCES: "plugin-bundled",+};+const PROJECT_AND_BUNDLED_ENV = {+ CODEX_RULES_ENABLED_SOURCES: ".omo/rules,plugin-bundled",+};+const tempDirectories: string[] = [];+let originalPluginRoot: string | undefined;++afterEach(() => {+ restoreEnv("PLUGIN_ROOT", originalPluginRoot);+ for (const directory of tempDirectories.splice(0)) {+ rmSync(directory, { recursive: true, force: true });+ }+});++function makeProject(): { readonly root: string; readonly pluginData: string } {+ originalPluginRoot = process.env["PLUGIN_ROOT"];+ process.env["PLUGIN_ROOT"] = process.cwd();+ const root = mkdtempSync(join(tmpdir(), "codex-rules-windows-git-bash-project-"));+ const pluginData = mkdtempSync(join(tmpdir(), "codex-rules-windows-git-bash-data-"));+ tempDirectories.push(root, pluginData);+ writeFileSync(join(root, "package.json"), JSON.stringify({ name: "fixture" }));+ return { root, pluginData };+}++function sessionStartInput(root: string): CodexSessionStartInput {+ return {+ session_id: "session-1",+ transcript_path: null,+ cwd: root,+ hook_event_name: "SessionStart",+ model: "gpt-5.5",+ permission_mode: "default",+ source: "startup",+ };+}++function restoreEnv(name: string, value: string | undefined): void {+ if (value === undefined) {+ delete process.env[name];+ return;+ }+ process.env[name] = value;+}++function occurrenceCount(value: string, search: string): number {+ return value.split(search).length - 1;+}++describe("Windows Git Bash bundled rule", () => {+ it("#given packaged bundled rules #when discovering plugin-bundled candidates #then Windows Git Bash rule is included", () => {+ const candidates = findPluginBundledCandidates({ pluginRoot: process.cwd(), platform: "win32" });++ expect(candidates.map((candidate) => candidate.relativePath)).toContain(WINDOWS_RULE_PATH);+ });++ it("#given packaged bundled rules off Windows #when discovering plugin-bundled candidates #then Windows Git Bash rule is excluded", () => {+ const candidates = findPluginBundledCandidates({ pluginRoot: process.cwd(), platform: "darwin" });++ expect(candidates.map((candidate) => candidate.relativePath)).not.toContain(WINDOWS_RULE_PATH);+ });++ it("#given bundled rules enabled on Windows #when SessionStart runs #then Windows Git Bash guidance is injected once", async () => {+ const { root, pluginData } = makeProject();++ const output = await runSessionStartHook(sessionStartInput(root), {+ pluginDataRoot: pluginData,+ env: BUNDLED_ONLY_ENV,+ platform: "win32",+ });++ expect(occurrenceCount(output, WINDOWS_GUIDANCE)).toBe(1);+ });++ it("#given bundled rules enabled off Windows #when SessionStart runs #then Windows Git Bash guidance is not injected", async () => {+ const { root, pluginData } = makeProject();++ const output = await runSessionStartHook(sessionStartInput(root), {+ pluginDataRoot: pluginData,+ env: BUNDLED_ONLY_ENV,+ platform: "darwin",+ });++ expect(output).not.toContain(WINDOWS_GUIDANCE);+ expect(output).not.toContain(WINDOWS_RULE_PATH);+ });++ it("#given project rule with same description on Windows #when static rules load #then project guidance overrides bundled guidance", async () => {+ const { root, pluginData } = makeProject();+ const projectGuidance = "Project-specific Windows shell policy.";+ mkdirSync(join(root, ".omo", "rules"), { recursive: true });+ writeFileSync(+ join(root, ".omo", "rules", "windows-git-bash.md"),+ ["---", `description: ${WINDOWS_RULE_DESCRIPTION}`, "alwaysApply: true", "---", "", projectGuidance].join(+ "\n",+ ),+ );++ const output = await runSessionStartHook(sessionStartInput(root), {+ pluginDataRoot: pluginData,+ env: PROJECT_AND_BUNDLED_ENV,+ platform: "win32",+ });++ expect(output).toContain(projectGuidance);+ expect(output).not.toContain(WINDOWS_GUIDANCE);+ });+});diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.gitattributes b/plugins/omo/components/start-work-continuation/.gitattributessimilarity index 100%rename from plugins/omo/components/lsp/packages/lsp-tools-mcp/.gitattributesrename to plugins/omo/components/start-work-continuation/.gitattributesdiff --git a/plugins/omo/components/start-work-continuation/.gitignore b/plugins/omo/components/start-work-continuation/.gitignorenew file mode 100644index 00000000..746087d3--- /dev/null+++ b/plugins/omo/components/start-work-continuation/.gitignore@@ -0,0 +1,3 @@+dist/+node_modules/+*.logdiff --git a/plugins/omo/components/start-work-continuation/AGENTS.md b/plugins/omo/components/start-work-continuation/AGENTS.mdnew file mode 100644index 00000000..7c8528b5--- /dev/null+++ b/plugins/omo/components/start-work-continuation/AGENTS.md@@ -0,0 +1,43 @@+# Repository Conventions++Conventions for human contributors and AI agents working on this repository.++## Stack++- Node >=20 runtime.+- npm package manager.+- TypeScript 6 strict mode.+- Biome 2 linting and formatting.+- Vitest 4 test runner.++## Forbidden++- No `as any` or `as unknown`.+- No `@ts-ignore` or `@ts-expect-error`.+- No enums.+- No non-null assertions.+- No default exports. `vitest.config.ts` is exempt because the framework requires that shape.++## File Ceiling++- Keep each `src/` TypeScript file under 250 pure LOC.+- Split by responsibility before a file reaches the ceiling.++## Test Discipline++- Use Vitest with nested `describe` names in `#given`, `#when`, and `#then` form, or inline `// given`, `// when`, and `// then` comments.+- Never use Arrange-Act-Assert comments.+- Keep fixtures in `test/fixtures/`.++## Build and Hooks++- Build output goes to `dist/`.+- `hooks/hooks.json` registers Codex `Stop` and `SubagentStop` hooks.+- Hook commands run `node ${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js hook stop` and `node ${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js hook subagent-stop`.++## Constraints++- Never let the hook block a Codex turn because of malformed input.+- Never make a network call from the hook.+- Keep the directive in `directive.md`. Do not inline it into TypeScript files.+- The hook only continues sessions listed in `.omo/boulder.json` as `codex:<session_id>`.diff --git a/plugins/omo/components/start-work-continuation/CHANGELOG.md b/plugins/omo/components/start-work-continuation/CHANGELOG.mdnew file mode 100644index 00000000..72bf8e5e--- /dev/null+++ b/plugins/omo/components/start-work-continuation/CHANGELOG.md@@ -0,0 +1,5 @@+# Changelog++## 0.1.0 - 2026-05-28++- Initial release: Stop and SubagentStop continuation injection.diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/LICENSE b/plugins/omo/components/start-work-continuation/LICENSEsimilarity index 100%rename from plugins/omo/components/lsp/packages/lsp-tools-mcp/LICENSErename to plugins/omo/components/start-work-continuation/LICENSEdiff --git a/plugins/omo/components/start-work-continuation/NOTICE b/plugins/omo/components/start-work-continuation/NOTICEnew file mode 100644index 00000000..5195cba8--- /dev/null+++ b/plugins/omo/components/start-work-continuation/NOTICE@@ -0,0 +1,5 @@+codex-start-work-continuation+Copyright (c) 2026 Yeongyu Kim++This product includes software released under the MIT License.+See LICENSE for the full text.diff --git a/plugins/omo/components/start-work-continuation/README.md b/plugins/omo/components/start-work-continuation/README.mdnew file mode 100644index 00000000..12500f3a--- /dev/null+++ b/plugins/omo/components/start-work-continuation/README.md@@ -0,0 +1,55 @@+# codex-start-work-continuation++Codex Stop-hook continuation injector for the omo-codex `start-work` skill.++It reads `.omo/boulder.json` in the hook payload `cwd`, resolves the active work, inspects the active plan for incomplete top-level checkboxes, and emits Codex Stop-hook JSON when the plan still has work:++```json+{"decision":"block","reason":"<directive>"}+```++The `reason` is loaded from `directive.md` on every invocation and filled with current plan state. The hook returns no output when `stop_hook_active` is `true`, when no active Boulder work exists, when the work is completed, when the active work is not tied to `codex:<session_id>`, or when all top-level plan checkboxes are complete.++This pairs with the `start-work` skill at `plugin/skills/start-work/SKILL.md`. That skill writes `.omo/boulder.json` with Codex session ids prefixed as `codex:` so the hook can continue only its own active Codex session.++## Counted plan checkboxes++Only column-0 checkboxes under these sections are counted:++- `## TODOs`+- `## Final Verification Wave`++Nested checkboxes under `### Acceptance Criteria`, `### Evidence`, and `### Definition of Done` are ignored.++## Smoke test++```bash+TMP=$(mktemp -d)+mkdir -p "$TMP/.omo/plans"+cat > "$TMP/.omo/plans/test.md" <<EOF+## TODOs+- [ ] Task one+- [ ] Task two+EOF+cat > "$TMP/.omo/boulder.json" <<EOF+{"schema_version":2,"active_work_id":"w1","works":{"w1":{"work_id":"w1","active_plan":".omo/plans/test.md","plan_name":"test","session_ids":["codex:smoke-session"],"status":"active"}}}+EOF+PAYLOAD='{"session_id":"smoke-session","turn_id":"t1","transcript_path":"","cwd":"'"$TMP"'","hook_event_name":"Stop","model":"gpt-5.5","permission_mode":"default","stop_hook_active":false}'+npm run build+echo "$PAYLOAD" | node dist/cli.js hook stop++PAYLOAD_LOOP='{"session_id":"smoke-session","turn_id":"t1","transcript_path":"","cwd":"'"$TMP"'","hook_event_name":"Stop","model":"gpt-5.5","permission_mode":"default","stop_hook_active":true}'+echo "$PAYLOAD_LOOP" | node dist/cli.js hook stop++rm -rf "$TMP"+```++Expect the first command to print JSON containing `"decision":"block"`; expect the anti-loop command to print nothing.++## License++MIT. See `LICENSE`.++## Privacy++This plugin only reads local hook payloads, `.omo/boulder.json`, the active plan, and the bundled directive. It makes no network calls and stores no telemetry.diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/biome.json b/plugins/omo/components/start-work-continuation/biome.jsonsimilarity index 100%rename from plugins/omo/components/lsp/packages/lsp-tools-mcp/biome.jsonrename to plugins/omo/components/start-work-continuation/biome.jsondiff --git a/plugins/omo/components/start-work-continuation/directive.md b/plugins/omo/components/start-work-continuation/directive.mdnew file mode 100644index 00000000..c1c9b7e0--- /dev/null+++ b/plugins/omo/components/start-work-continuation/directive.md@@ -0,0 +1,52 @@+<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]`.++# State++- Plan: `{{PLAN_NAME}}`+- Plan file: `{{PLAN_PATH}}`+- Boulder state: `{{BOULDER_PATH}}`+- Remaining top-level checkboxes: `{{REMAINING_COUNT}}` of `{{TOTAL_COUNT}}`+- Next incomplete task: `{{NEXT_TASK_LABEL}}`+{{WORKTREE_BLOCK}}+- Ledger: `{{LEDGER_PATH}}`+- Your session id in boulder.json: `codex:{{SESSION_ID}}`++# 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.+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. Every dispatch sets `agent_type`; `model` + `reasoning_effort` alone creates a default agent, not the requested role.+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. Use `wait_agent` for completion signals, but treat `wait_agent` as a mailbox signal, not proof of completion, content, or errors. After two waits with no substantive result, send one targeted followup: `TASK STILL ACTIVE: return <deliverable> or BLOCKED: <reason>`. If 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.+7. 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.+8. 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>`.++# 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 `--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.+- 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:`.++# 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(agent_type="codex-ultrawork-reviewer", fork_turns="none", ...)` and stop dispatch.+- Safety boundary (destructive command, secret exfiltration, production write) → stop and surface a safe substitute.+- All top-level checkboxes `- [x]` AND (if gate triggered) `codex-ultrawork-reviewer` approved unconditionally → 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.++Begin now. Pick the next checkbox, dispatch the parallel sub-agents, verify, mark, continue.++</start-work-continuation>diff --git a/plugins/omo/components/start-work-continuation/hooks/hooks.json b/plugins/omo/components/start-work-continuation/hooks/hooks.jsonnew file mode 100644index 00000000..fa7febb5--- /dev/null+++ b/plugins/omo/components/start-work-continuation/hooks/hooks.json@@ -0,0 +1,28 @@+{+ "hooks": {+ "Stop": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "node \"${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js\" hook stop",+ "timeout": 10,+ "statusMessage": "LazyCodex(0.1.0): Checking Start-Work Continuation"+ }+ ]+ }+ ],+ "SubagentStop": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "node \"${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js\" hook subagent-stop",+ "timeout": 10,+ "statusMessage": "LazyCodex(0.1.0): Checking Start-Work Continuation"+ }+ ]+ }+ ]+ }+}diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/package.json b/plugins/omo/components/start-work-continuation/package.jsonsimilarity index 54%rename from plugins/omo/components/lsp/packages/lsp-tools-mcp/package.jsonrename to plugins/omo/components/start-work-continuation/package.jsonindex 52a344d0..251463ba 100644--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/package.json+++ b/plugins/omo/components/start-work-continuation/package.json@@ -1,36 +1,29 @@{- "name": "@code-yeongyu/lsp-tools-mcp",+ "name": "@code-yeongyu/codex-start-work-continuation","version": "0.1.0",- "description": "Standalone Language Server Protocol tools exposed as a stdio MCP server.",+ "description": "Codex Stop hook continuation injector for omo-codex start-work plans.","type": "module","packageManager": "[email protected]","license": "MIT",- "homepage": "https://github.com/code-yeongyu/lsp-tools-mcp",+ "homepage": "https://github.com/code-yeongyu/codex-start-work-continuation","repository": {"type": "git",- "url": "git+https://github.com/code-yeongyu/lsp-tools-mcp.git"+ "url": "git+https://github.com/code-yeongyu/codex-start-work-continuation.git"},"bugs": {- "url": "https://github.com/code-yeongyu/lsp-tools-mcp/issues"+ "url": "https://github.com/code-yeongyu/codex-start-work-continuation/issues"},"keywords": [- "mcp",- "lsp",- "language-server-protocol",- "model-context-protocol",- "typescript",- "nodejs"+ "codex",+ "codex-plugin",+ "start-work",+ "continuation",+ "hooks",+ "boulder"],"bin": {- "lsp-tools-mcp": "./dist/cli.js"+ "omo-start-work-continuation": "./dist/cli.js"},- "files": [- "dist",- "LICENSE",- "NOTICE",- "README.md",- "CHANGELOG.md"- ],"scripts": {"build": "tsc -p tsconfig.build.json","test": "vitest --run",@@ -40,6 +33,14 @@"lint:fix": "biome check --write .","check": "tsc --noEmit && biome check . && npm run build"},+ "files": [+ "dist",+ "directive.md",+ "hooks",+ "README.md",+ "LICENSE",+ "NOTICE"+ ],"devDependencies": {"@biomejs/biome": "2.4.15","@types/node": "^25.7.0",diff --git a/plugins/omo/components/start-work-continuation/src/boulder-reader.ts b/plugins/omo/components/start-work-continuation/src/boulder-reader.tsnew file mode 100644index 00000000..6e371f0f--- /dev/null+++ b/plugins/omo/components/start-work-continuation/src/boulder-reader.ts@@ -0,0 +1,167 @@+import { isAbsolute, join, resolve } from "node:path";++import type { ReadonlyFileSystem } from "./types.js";++const CHECKBOX_PATTERN = /^- \[[ xX]\] /;+const UNCHECKED_PATTERN = /^- \[ \] /;+const TODO_HEADING = "TODOs";+const FINAL_VERIFICATION_HEADING = "Final Verification Wave";++type WorkStatus = "active" | "completed" | "paused" | "abandoned";++type BoulderWork = {+ readonly activePlan: string;+ readonly planName: string;+ readonly status: WorkStatus;+ readonly sessionIds: readonly string[];+ readonly worktreePath: string | null;+};++export type PlanChecklist = {+ readonly remaining: number;+ readonly total: number;+ readonly nextTaskLabel: string | null;+};++export type ContinuationState = {+ readonly planName: string;+ readonly planPath: string;+ readonly boulderPath: string;+ readonly ledgerPath: string;+ readonly worktreePath: string | null;+ readonly checklist: PlanChecklist;+};++export function parsePlanChecklist(markdown: string): PlanChecklist {+ const lines = markdown.split(/\r?\n/);+ const hasCountedSections = lines.some(hasCountedSectionHeading);+ let remaining = 0;+ let total = 0;+ let nextTaskLabel: string | null = null;+ let isCountedSection = !hasCountedSections;+ for (const line of lines) {+ const heading = parseLevelTwoHeading(line);+ if (heading !== null) isCountedSection = isCountedHeading(heading);+ if (!isCountedSection) continue;+ if (!CHECKBOX_PATTERN.test(line)) continue;+ total += 1;+ if (!UNCHECKED_PATTERN.test(line)) continue;+ remaining += 1;+ if (nextTaskLabel === null) nextTaskLabel = line.slice("- [ ] ".length);+ }+ return { remaining, total, nextTaskLabel };+}++function hasCountedSectionHeading(line: string): boolean {+ const heading = parseLevelTwoHeading(line);+ return heading !== null && isCountedHeading(heading);+}++export function readContinuationState(+ cwd: string,+ sessionId: string,+ fs: ReadonlyFileSystem,+): ContinuationState | null {+ const boulderPath = join(cwd, ".omo", "boulder.json");+ const boulderText = readTextFile(fs, boulderPath);+ if (boulderText === null) return null;+ const parsed = parseJsonObject(boulderText);+ if (parsed === null) return null;+ const work = findMatchingWork(parsed, `codex:${sessionId}`);+ if (work === null) return null;+ const planPath = resolvePlanPath(cwd, work.activePlan);+ const planText = readTextFile(fs, planPath);+ if (planText === null) return null;+ const checklist = parsePlanChecklist(planText);+ if (checklist.remaining === 0) return null;+ return {+ planName: work.planName,+ planPath,+ boulderPath,+ ledgerPath: join(cwd, ".omo", "start-work", "ledger.jsonl"),+ worktreePath: work.worktreePath,+ checklist,+ };+}++function findMatchingWork(state: Record<string, unknown>, prefixedSessionId: string): BoulderWork | null {+ const worksValue = state["works"];+ const candidates = isRecord(worksValue) ? Object.values(worksValue) : [state];+ for (const candidate of candidates) {+ const work = parseBoulderWork(candidate);+ if (work === null) continue;+ if (!isContinuableStatus(work.status)) continue;+ if (work.sessionIds.includes(prefixedSessionId)) return work;+ }+ return null;+}++function parseBoulderWork(value: unknown): BoulderWork | null {+ if (!isRecord(value)) return null;+ const activePlan = value["active_plan"];+ const planName = value["plan_name"];+ const status = parseWorkStatus(value["status"]);+ const sessionIds = value["session_ids"];+ const worktreePath = value["worktree_path"];+ if (typeof activePlan !== "string") return null;+ if (typeof planName !== "string") return null;+ if (status === null) return null;+ if (!isStringArray(sessionIds)) return null;+ return {+ activePlan,+ planName,+ status,+ sessionIds,+ worktreePath: typeof worktreePath === "string" ? worktreePath : null,+ };+}++function parseWorkStatus(value: unknown): WorkStatus | null {+ if (value === "active" || value === "completed" || value === "paused" || value === "abandoned") return value;+ return null;+}++function isContinuableStatus(status: WorkStatus): boolean {+ return status === "active" || status === "paused";+}++function parseLevelTwoHeading(line: string): string | null {+ if (!line.startsWith("## ")) return null;+ if (line.startsWith("### ")) return null;+ return line.slice("## ".length).trim();+}++function isCountedHeading(heading: string): boolean {+ return heading === TODO_HEADING || heading === FINAL_VERIFICATION_HEADING;+}++function resolvePlanPath(cwd: string, activePlan: string): string {+ return isAbsolute(activePlan) ? activePlan : resolve(cwd, activePlan);+}++function readTextFile(fs: ReadonlyFileSystem, path: string): string | null {+ try {+ return fs.readFileSync(path, "utf8");+ } catch (error) {+ if (error instanceof Error) return null;+ throw error;+ }+}++function parseJsonObject(json: string): Record<string, unknown> | null {+ try {+ const parsed: unknown = JSON.parse(json);+ return isRecord(parsed) ? parsed : null;+ } catch (error) {+ if (error instanceof SyntaxError) return null;+ throw error;+ }+}++function isStringArray(value: unknown): value is readonly string[] {+ return Array.isArray(value) && value.every((item) => typeof item === "string");+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/start-work-continuation/src/cli.ts b/plugins/omo/components/start-work-continuation/src/cli.tsnew file mode 100644index 00000000..b0548fe9--- /dev/null+++ b/plugins/omo/components/start-work-continuation/src/cli.ts@@ -0,0 +1,52 @@+#!/usr/bin/env node+import { readFileSync } from "node:fs";+import { stdin as processStdin, stdout as processStdout } from "node:process";++import { runStopHook } from "./codex-hook.js";+import type { ReadonlyFileSystem } from "./types.js";++const nodeFileSystem: ReadonlyFileSystem = {+ readFileSync(path, encoding) {+ return readFileSync(path, encoding);+ },+};++const command = process.argv[2];+const subcommand = process.argv[3];++if (command === "hook" && (subcommand === "stop" || subcommand === "subagent-stop")) {+ await runHookCli();+} else {+ process.stderr.write("Usage: omo-start-work-continuation hook <stop|subagent-stop>\n");+ process.exitCode = 1;+}++async function runHookCli(): Promise<void> {+ const raw = await readStdin();+ if (raw.trim().length === 0) return;+ const parsed = parseHookInput(raw);+ const output = runStopHook(parsed, nodeFileSystem);+ if (output.length > 0) processStdout.write(output);+}++function parseHookInput(raw: string): unknown | undefined {+ try {+ const parsed: unknown = JSON.parse(raw);+ return parsed;+ } catch (error) {+ if (error instanceof SyntaxError) return undefined;+ throw error;+ }+}++function readStdin(): Promise<string> {+ return new Promise((resolve) => {+ let data = "";+ processStdin.setEncoding("utf8");+ processStdin.on("data", (chunk: string) => {+ data += chunk;+ });+ processStdin.once("error", () => resolve(data));+ processStdin.once("end", () => resolve(data));+ });+}diff --git a/plugins/omo/components/start-work-continuation/src/codex-hook.ts b/plugins/omo/components/start-work-continuation/src/codex-hook.tsnew file mode 100644index 00000000..7717809f--- /dev/null+++ b/plugins/omo/components/start-work-continuation/src/codex-hook.ts@@ -0,0 +1,66 @@+import type { ContinuationState } from "./boulder-reader.js";+import { readContinuationState } from "./boulder-reader.js";+import { START_WORK_CONTINUATION_DIRECTIVE } from "./directive.js";+import type { ReadonlyFileSystem, StopHookEventName, StopHookOutput, StopInput } from "./types.js";++export function runStopHook(input: unknown, fs: ReadonlyFileSystem): string {+ if (!isStopInput(input)) return "";+ if (input.stop_hook_active) return "";+ const state = readContinuationState(input.cwd, input.session_id, fs);+ if (state === null) return "";+ return JSON.stringify({+ decision: "block",+ reason: renderDirective(state, input.session_id),+ } satisfies StopHookOutput);+}++function renderDirective(state: ContinuationState, sessionId: string): string {+ const lineBreak = String.fromCharCode(10);+ const worktreeBlock =+ state.worktreePath === null+ ? ""+ : `${lineBreak}- Worktree: \`${state.worktreePath}\` (all edits, tests, and commands run inside this directory)`;+ const replacements = {+ PLAN_NAME: state.planName,+ PLAN_PATH: state.planPath,+ BOULDER_PATH: state.boulderPath,+ REMAINING_COUNT: String(state.checklist.remaining),+ TOTAL_COUNT: String(state.checklist.total),+ NEXT_TASK_LABEL: state.checklist.nextTaskLabel ?? "",+ WORKTREE_BLOCK: worktreeBlock,+ LEDGER_PATH: state.ledgerPath,+ SESSION_ID: sessionId,+ } as const;+ let rendered = START_WORK_CONTINUATION_DIRECTIVE;+ for (const [placeholder, value] of Object.entries(replacements)) {+ rendered = rendered.replaceAll(`{{${placeholder}}}`, value);+ }+ return rendered;+}++function isStopInput(value: unknown): value is StopInput {+ return (+ isRecord(value) &&+ isStopHookEventName(value["hook_event_name"]) &&+ typeof value["session_id"] === "string" &&+ typeof value["turn_id"] === "string" &&+ typeof value["transcript_path"] === "string" &&+ typeof value["cwd"] === "string" &&+ typeof value["model"] === "string" &&+ typeof value["permission_mode"] === "string" &&+ typeof value["stop_hook_active"] === "boolean" &&+ optionalString(value["last_assistant_message"])+ );+}++function isStopHookEventName(value: unknown): value is StopHookEventName {+ return value === "Stop" || value === "SubagentStop";+}++function optionalString(value: unknown): boolean {+ return value === undefined || typeof value === "string";+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/start-work-continuation/src/directive.ts b/plugins/omo/components/start-work-continuation/src/directive.tsnew file mode 100644index 00000000..12fe3af2--- /dev/null+++ b/plugins/omo/components/start-work-continuation/src/directive.ts@@ -0,0 +1,6 @@+import { readFileSync } from "node:fs";++export const START_WORK_CONTINUATION_DIRECTIVE: string = readFileSync(+ new URL("../directive.md", import.meta.url),+ "utf8",+);diff --git a/plugins/omo/components/start-work-continuation/src/index.ts b/plugins/omo/components/start-work-continuation/src/index.tsnew file mode 100644index 00000000..fd51acd0--- /dev/null+++ b/plugins/omo/components/start-work-continuation/src/index.ts@@ -0,0 +1,5 @@+export type { ContinuationState, PlanChecklist } from "./boulder-reader.js";+export { parsePlanChecklist, readContinuationState } from "./boulder-reader.js";+export { runStopHook } from "./codex-hook.js";+export { START_WORK_CONTINUATION_DIRECTIVE } from "./directive.js";+export type { ReadonlyFileSystem, StopHookEventName, StopHookOutput, StopInput } from "./types.js";diff --git a/plugins/omo/components/start-work-continuation/src/types.ts b/plugins/omo/components/start-work-continuation/src/types.tsnew file mode 100644index 00000000..01f74b59--- /dev/null+++ b/plugins/omo/components/start-work-continuation/src/types.ts@@ -0,0 +1,23 @@+export const STOP_HOOK_EVENTS = ["Stop", "SubagentStop"] as const;+export type StopHookEventName = (typeof STOP_HOOK_EVENTS)[number];++export type StopInput = {+ readonly hook_event_name: StopHookEventName;+ readonly session_id: string;+ readonly turn_id: string;+ readonly transcript_path: string;+ readonly cwd: string;+ readonly model: string;+ readonly permission_mode: string;+ readonly stop_hook_active: boolean;+ readonly last_assistant_message?: string;+};++export type StopHookOutput = {+ readonly decision: "block";+ readonly reason: string;+};++export type ReadonlyFileSystem = {+ readFileSync(path: string, encoding: "utf8"): string;+};diff --git a/plugins/omo/components/start-work-continuation/test/boulder-reader.test.ts b/plugins/omo/components/start-work-continuation/test/boulder-reader.test.tsnew file mode 100644index 00000000..f4ba8739--- /dev/null+++ b/plugins/omo/components/start-work-continuation/test/boulder-reader.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from "vitest";++import { parsePlanChecklist } from "../src/boulder-reader.js";++describe("start-work plan checklist parser", () => {+ it("#given top-level completed and incomplete checkboxes #when parsed #then counts remaining and total", () => {+ // given+ const markdown = ["# Plan", "", "## TODOs", "- [ ] First", "- [x] Done", "- [X] Also done", "- [ ] Second"].join(+ "\n",+ );++ // when+ const checklist = parsePlanChecklist(markdown);++ // then+ expect(checklist).toEqual({ remaining: 2, total: 4, nextTaskLabel: "First" });+ });++ it("#given nested checkboxes #when parsed #then ignores non-column-zero items", () => {+ // given+ const markdown = ["## TODOs", "- [ ] Top-level", " - [ ] Nested", "\t- [ ] Tab nested", "- [x] Complete"].join(+ "\n",+ );++ // when+ const checklist = parsePlanChecklist(markdown);++ // then+ expect(checklist).toEqual({ remaining: 1, total: 2, nextTaskLabel: "Top-level" });+ });++ it("#given checkboxes outside counted sections #when parsed #then ignores unrelated top-level tasks", () => {+ // given+ const markdown = [+ "# Plan",+ "- [ ] Preamble task",+ "## TODOs",+ "- [ ] Build hook",+ "## Acceptance Criteria",+ "- [ ] Acceptance item",+ "## Final Verification Wave",+ "- [x] Run tests",+ "- [ ] Run smoke",+ ].join("\n");++ // when+ const checklist = parsePlanChecklist(markdown);++ // then+ expect(checklist).toEqual({ remaining: 2, total: 3, nextTaskLabel: "Build hook" });+ });++ it("#given all top-level tasks complete #when parsed #then next task is null", () => {+ // given+ const markdown = ["## TODOs", "- [x] First", "- [X] Second"].join("\n");++ // when+ const checklist = parsePlanChecklist(markdown);++ // then+ expect(checklist).toEqual({ remaining: 0, total: 2, nextTaskLabel: null });+ });+});diff --git a/plugins/omo/components/start-work-continuation/test/cli.test.ts b/plugins/omo/components/start-work-continuation/test/cli.test.tsnew file mode 100644index 00000000..6d6fd65d--- /dev/null+++ b/plugins/omo/components/start-work-continuation/test/cli.test.ts@@ -0,0 +1,124 @@+import { spawnSync } from "node:child_process";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { execPath } from "node:process";+import { afterEach, describe, expect, it } from "vitest";++const cleanupRoots: string[] = [];++afterEach(() => {+ for (const root of cleanupRoots.splice(0)) rmSync(root, { recursive: true, force: true });+});++describe("start-work continuation CLI", () => {+ it("#given valid Stop stdin #when CLI runs #then stdout contains block JSON", () => {+ // given+ const cwd = createWorkspace(["codex:s1"]);+ const payload = JSON.stringify(makePayload(cwd, false, "Stop"));++ // when+ const result = runCli("stop", payload);++ // then+ if (result.error !== undefined) throw result.error;+ expect(result.status).toBe(0);+ expect(result.stdout).toContain('"decision":"block"');+ });++ it("#given valid SubagentStop stdin #when CLI runs #then stdout contains block JSON", () => {+ // given+ const cwd = createWorkspace(["codex:s1"]);+ const payload = JSON.stringify(makePayload(cwd, false, "SubagentStop"));++ // when+ const result = runCli("subagent-stop", payload);++ // then+ if (result.error !== undefined) throw result.error;+ expect(result.status).toBe(0);+ expect(result.stdout).toContain('"decision":"block"');+ });++ it("#given active stop hook stdin #when CLI runs #then stdout is empty and exit is zero", () => {+ // given+ const cwd = createWorkspace(["codex:s1"]);+ const payload = JSON.stringify(makePayload(cwd, true, "Stop"));++ // when+ const result = runCli("stop", payload);++ // then+ if (result.error !== undefined) throw result.error;+ expect(result.status).toBe(0);+ expect(result.stdout).toBe("");+ });++ it("#given unrelated session stdin #when CLI runs #then stdout is empty and exit is zero", () => {+ // given+ const cwd = createWorkspace(["codex:other"]);+ const payload = JSON.stringify(makePayload(cwd, false, "Stop"));++ // when+ const result = runCli("stop", payload);++ // then+ if (result.error !== undefined) throw result.error;+ expect(result.status).toBe(0);+ expect(result.stdout).toBe("");+ });++ it("#given malformed stdin #when CLI runs #then stdout is empty and exit is zero", () => {+ // given+ const payload = "{not-json";++ // when+ const result = runCli("stop", payload);++ // then+ if (result.error !== undefined) throw result.error;+ expect(result.status).toBe(0);+ expect(result.stdout).toBe("");+ });+});++function runCli(subcommand: "stop" | "subagent-stop", input: string) {+ return spawnSync(execPath, [join(process.cwd(), "dist", "cli.js"), "hook", subcommand], { input, encoding: "utf8" });+}++function createWorkspace(sessionIds: readonly string[]): string {+ const root = mkdtempSync(join(tmpdir(), "codex-continuation-cli-"));+ cleanupRoots.push(root);+ mkdirSync(join(root, ".omo", "plans"), { recursive: true });+ writeFileSync(join(root, ".omo", "plans", "plan.md"), "## TODOs\n\n- [ ] Task one\n");+ const work = {+ work_id: "w1",+ active_plan: ".omo/plans/plan.md",+ plan_name: "cli plan",+ session_ids: sessionIds,+ status: "active",+ };+ writeFileSync(+ join(root, ".omo", "boulder.json"),+ `${JSON.stringify({ schema_version: 2, active_work_id: "w1", works: { w1: work } })}\n`,+ );+ return root;+}++function makePayload(+ cwd: string,+ stopHookActive: boolean,+ eventName: "Stop" | "SubagentStop",+): Record<string, string | boolean> {+ return {+ session_id: "s1",+ turn_id: "t1",+ transcript_path: "",+ cwd,+ hook_event_name: eventName,+ model: "gpt-5.5",+ permission_mode: "default",+ stop_hook_active: stopHookActive,+ last_assistant_message: "done",+ };+}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.tsnew file mode 100644index 00000000..5de59abd--- /dev/null+++ b/plugins/omo/components/start-work-continuation/test/codex-hook.test.ts@@ -0,0 +1,182 @@+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { runStopHook } from "../src/codex-hook.js";+import type { ReadonlyFileSystem, StopInput } from "../src/types.js";++const WORKSPACE = "/repo";+const BOULDER_PATH = join(WORKSPACE, ".omo", "boulder.json");+const PLAN_PATH = join(WORKSPACE, ".omo", "plans", "plan.md");+const LEDGER_PATH = join(WORKSPACE, ".omo", "start-work", "ledger.jsonl");++describe("start-work Stop hook", () => {+ it("#given stop hook is already active #when hook runs #then returns empty output", () => {+ // given+ const fs = createMemoryFs();+ const input = { ...createStopInput(), stop_hook_active: true };++ // when+ const output = runStopHook(input, fs);++ // then+ expect(output).toBe("");+ });++ it("#given active codex work with remaining top-level tasks #when hook runs #then returns block JSON", () => {+ // given+ const fs = createMemoryFs({+ [BOULDER_PATH]: createBoulderJson({+ sessionIds: ["codex:sess_abc"],+ status: "active",+ worktreePath: "/tmp/worktree",+ }),+ [PLAN_PATH]: ["# Plan", "", "## TODOs", "- [ ] First", "- [x] Done", "- [ ] Second"].join("\n"),+ });++ // when+ const output = runStopHook(createStopInput(), fs);++ // then+ const parsed = parseBlockOutput(output);+ expect(parsed.decision).toBe("block");+ expect(parsed.reason).toContain("- Plan: `launch-plan`");+ expect(parsed.reason).toContain(`- Plan file: \`${PLAN_PATH}\``);+ expect(parsed.reason).toContain(`- Boulder state: \`${BOULDER_PATH}\``);+ expect(parsed.reason).toContain("- Remaining top-level checkboxes: `2` of `3`");+ expect(parsed.reason).toContain("- Next incomplete task: `First`");+ expect(parsed.reason).toContain("- Worktree: `/tmp/worktree`");+ expect(parsed.reason).toContain(`- Ledger: \`${LEDGER_PATH}\``);+ expect(parsed.reason).toContain("- Your session id in boulder.json: `codex:sess_abc`");+ });++ it("#given active codex work #when continuation directive is emitted #then subagent guidance is reliable", () => {+ // 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(/TASK:/);+ expect(parsed.reason).toMatch(/fork_turns:\s*"none"/);+ expect(parsed.reason).toMatch(/wait_agent.*signal, not proof/);+ expect(parsed.reason).toMatch(/one targeted followup/);+ expect(parsed.reason).toMatch(/respawn.*smaller/);+ });++ it("#given active work belongs to another harness #when hook runs #then returns empty output", () => {+ // given+ const fs = createMemoryFs({+ [BOULDER_PATH]: createBoulderJson({ sessionIds: ["opencode:sess_abc"], status: "active" }),+ [PLAN_PATH]: "- [ ] First",+ });++ // when+ const output = runStopHook(createStopInput(), fs);++ // then+ expect(output).toBe("");+ });++ it("#given bare legacy session id #when hook runs #then returns empty output", () => {+ // given+ const fs = createMemoryFs({+ [BOULDER_PATH]: createBoulderJson({ sessionIds: ["sess_abc"], status: "active" }),+ [PLAN_PATH]: "- [ ] First",+ });++ // when+ const output = runStopHook(createStopInput(), fs);++ // then+ expect(output).toBe("");+ });++ it("#given completed boulder work #when hook runs #then returns empty output", () => {+ // given+ const fs = createMemoryFs({+ [BOULDER_PATH]: createBoulderJson({ sessionIds: ["codex:sess_abc"], status: "completed" }),+ [PLAN_PATH]: "- [ ] First",+ });++ // when+ const output = runStopHook(createStopInput(), fs);++ // then+ expect(output).toBe("");+ });++ it("#given malformed input #when hook runs #then returns empty output", () => {+ // given+ const fs = createMemoryFs();++ // when+ const output = runStopHook({ hook_event_name: "Stop", session_id: 123 }, fs);++ // then+ expect(output).toBe("");+ });+});++type BoulderInput = {+ readonly sessionIds: readonly string[];+ readonly status: "active" | "completed" | "paused" | "abandoned";+ readonly worktreePath?: string;+};++function createStopInput(): StopInput {+ return {+ hook_event_name: "Stop",+ session_id: "sess_abc",+ turn_id: "turn_1",+ transcript_path: "",+ cwd: WORKSPACE,+ model: "gpt-5.5",+ permission_mode: "default",+ stop_hook_active: false,+ last_assistant_message: "done",+ };+}++function createBoulderJson(input: BoulderInput): string {+ const work = {+ work_id: "work_1",+ active_plan: ".omo/plans/plan.md",+ plan_name: "launch-plan",+ status: input.status,+ session_ids: input.sessionIds,+ ...(input.worktreePath === undefined ? {} : { worktree_path: input.worktreePath }),+ };+ return JSON.stringify({ schema_version: 2, active_work_id: "work_1", works: { work_1: work } });+}++function createMemoryFs(files: Record<string, string> = {}): ReadonlyFileSystem {+ return {+ readFileSync(path, encoding) {+ expect(encoding).toBe("utf8");+ const value = files[path];+ if (value === undefined) throw new Error(`Missing fixture: ${path}`);+ return value;+ },+ };+}++function parseBlockOutput(output: string): { readonly decision: "block"; readonly reason: string } {+ const parsed: unknown = JSON.parse(output);+ if (!isRecord(parsed)) throw new Error("Expected object output");+ if (parsed["decision"] !== "block") throw new Error("Expected block decision");+ const reason = parsed["reason"];+ if (typeof reason !== "string") throw new Error("Expected string reason");+ return { decision: "block", reason };+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/start-work-continuation/test/fixtures/boulder-completed.json b/plugins/omo/components/start-work-continuation/test/fixtures/boulder-completed.jsonnew file mode 100644index 00000000..02f12701--- /dev/null+++ b/plugins/omo/components/start-work-continuation/test/fixtures/boulder-completed.json@@ -0,0 +1,19 @@+{+ "schema_version": 2,+ "active_work_id": "work_1",+ "works": {+ "work_1": {+ "work_id": "work_1",+ "active_plan": "/repo/.omo/plans/plan-with-unchecked.md",+ "plan_name": "completed-plan",+ "status": "completed",+ "started_at": "2026-05-28T00:00:00Z",+ "session_ids": ["codex:sess_abc"]+ }+ },+ "active_plan": "/repo/.omo/plans/plan-with-unchecked.md",+ "plan_name": "completed-plan",+ "started_at": "2026-05-28T00:00:00Z",+ "status": "completed",+ "session_ids": ["codex:sess_abc"]+}diff --git a/plugins/omo/components/start-work-continuation/test/fixtures/boulder-mixed-platforms.json b/plugins/omo/components/start-work-continuation/test/fixtures/boulder-mixed-platforms.jsonnew file mode 100644index 00000000..095bf7b9--- /dev/null+++ b/plugins/omo/components/start-work-continuation/test/fixtures/boulder-mixed-platforms.json@@ -0,0 +1,27 @@+{+ "schema_version": 2,+ "active_work_id": "codex_work",+ "works": {+ "opencode_work": {+ "work_id": "opencode_work",+ "active_plan": "/repo/.omo/plans/opencode-plan.md",+ "plan_name": "opencode-plan",+ "status": "active",+ "started_at": "2026-05-28T00:00:00Z",+ "session_ids": ["opencode:sess_abc"]+ },+ "codex_work": {+ "work_id": "codex_work",+ "active_plan": "/repo/.omo/plans/plan-with-unchecked.md",+ "plan_name": "codex-plan",+ "status": "paused",+ "started_at": "2026-05-28T00:00:00Z",+ "session_ids": ["codex:def"]+ }+ },+ "active_plan": "/repo/.omo/plans/opencode-plan.md",+ "plan_name": "legacy-opencode-plan",+ "started_at": "2026-05-28T00:00:00Z",+ "status": "active",+ "session_ids": ["opencode:sess_abc"]+}diff --git a/plugins/omo/components/start-work-continuation/test/fixtures/boulder-single-codex-work.json b/plugins/omo/components/start-work-continuation/test/fixtures/boulder-single-codex-work.jsonnew file mode 100644index 00000000..9c123ea4--- /dev/null+++ b/plugins/omo/components/start-work-continuation/test/fixtures/boulder-single-codex-work.json@@ -0,0 +1,19 @@+{+ "schema_version": 2,+ "active_work_id": "work_1",+ "works": {+ "work_1": {+ "work_id": "work_1",+ "active_plan": "/repo/.omo/plans/plan-with-unchecked.md",+ "plan_name": "launch-plan",+ "status": "active",+ "started_at": "2026-05-28T00:00:00Z",+ "session_ids": ["codex:sess_abc"]+ }+ },+ "active_plan": "/repo/.omo/plans/plan-with-unchecked.md",+ "plan_name": "legacy-launch-plan",+ "started_at": "2026-05-28T00:00:00Z",+ "status": "active",+ "session_ids": ["codex:sess_legacy"]+}diff --git a/plugins/omo/components/start-work-continuation/test/fixtures/plan-all-done.md b/plugins/omo/components/start-work-continuation/test/fixtures/plan-all-done.mdnew file mode 100644index 00000000..453ae07b--- /dev/null+++ b/plugins/omo/components/start-work-continuation/test/fixtures/plan-all-done.md@@ -0,0 +1,5 @@+# Launch Plan++## TODOs+- [x] First+- [x] Seconddiff --git a/plugins/omo/components/start-work-continuation/test/fixtures/plan-with-nested-checkboxes.md b/plugins/omo/components/start-work-continuation/test/fixtures/plan-with-nested-checkboxes.mdnew file mode 100644index 00000000..59cc4fe6--- /dev/null+++ b/plugins/omo/components/start-work-continuation/test/fixtures/plan-with-nested-checkboxes.md@@ -0,0 +1,11 @@+# Launch Plan++## TODOs+- [ ] Top-level++### Acceptance Criteria+ - [ ] Nested under acceptance criteria+ - [x] Nested done++## Final Checklist+ - [ ] Nested under final checklistdiff --git a/plugins/omo/components/start-work-continuation/test/fixtures/plan-with-unchecked.md b/plugins/omo/components/start-work-continuation/test/fixtures/plan-with-unchecked.mdnew file mode 100644index 00000000..12a1d7ce--- /dev/null+++ b/plugins/omo/components/start-work-continuation/test/fixtures/plan-with-unchecked.md@@ -0,0 +1,6 @@+# Launch Plan++## TODOs+- [ ] First+- [x] Done already+- [ ] Seconddiff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/tsconfig.build.json b/plugins/omo/components/start-work-continuation/tsconfig.build.jsonsimilarity index 100%rename from plugins/omo/components/lsp/packages/lsp-tools-mcp/tsconfig.build.jsonrename to plugins/omo/components/start-work-continuation/tsconfig.build.jsondiff --git a/plugins/omo/components/start-work-continuation/tsconfig.json b/plugins/omo/components/start-work-continuation/tsconfig.jsonnew file mode 100644index 00000000..3ac7ab0e--- /dev/null+++ b/plugins/omo/components/start-work-continuation/tsconfig.json@@ -0,0 +1,27 @@+{+ "compilerOptions": {+ "target": "ESNext",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "lib": ["ESNext"],+ "strict": true,+ "exactOptionalPropertyTypes": true,+ "noUncheckedIndexedAccess": true,+ "noPropertyAccessFromIndexSignature": true,+ "verbatimModuleSyntax": true,+ "noImplicitOverride": true,+ "noImplicitReturns": true,+ "noFallthroughCasesInSwitch": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "esModuleInterop": true,+ "allowImportingTsExtensions": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true,+ "useDefineForClassFields": false,+ "types": ["node"],+ "noEmit": true+ },+ "include": ["src/**/*", "test/**/*", "vitest.config.ts"]+}diff --git a/plugins/omo/components/ultragoal/vitest.config.ts b/plugins/omo/components/start-work-continuation/vitest.config.tssimilarity index 100%rename from plugins/omo/components/ultragoal/vitest.config.tsrename to plugins/omo/components/start-work-continuation/vitest.config.tsdiff --git a/plugins/omo/components/telemetry/hooks/hooks.json b/plugins/omo/components/telemetry/hooks/hooks.jsonindex 154a112a..ed65ceab 100644--- a/plugins/omo/components/telemetry/hooks/hooks.json+++ b/plugins/omo/components/telemetry/hooks/hooks.json@@ -6,7 +6,8 @@{"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook session-start",- "timeout": 5+ "timeout": 5,+ "statusMessage": "LazyCodex(0.1.0): Recording Session Telemetry"}]}diff --git a/plugins/omo/components/telemetry/package.json b/plugins/omo/components/telemetry/package.jsonindex 628bef33..27f9e724 100644--- a/plugins/omo/components/telemetry/package.json+++ b/plugins/omo/components/telemetry/package.json@@ -23,7 +23,7 @@"daily-active"],"bin": {- "codex-telemetry": "./dist/cli.js"+ "omo-telemetry": "./dist/cli.js"},"files": ["dist",diff --git a/plugins/omo/components/telemetry/src/cli.ts b/plugins/omo/components/telemetry/src/cli.tsindex 9ce2e2f6..bca179d1 100644--- a/plugins/omo/components/telemetry/src/cli.ts+++ b/plugins/omo/components/telemetry/src/cli.ts@@ -9,7 +9,7 @@ const subcommand = process.argv[3];if (command === "hook" && subcommand === "session-start") {await runHookCli();} else {- process.stderr.write("Usage: codex-telemetry hook session-start\n");+ process.stderr.write("Usage: omo-telemetry hook session-start\n");process.exitCode = 1;}diff --git a/plugins/omo/components/telemetry/src/codex-hook.ts b/plugins/omo/components/telemetry/src/codex-hook.tsindex 6e61ebb8..f14e8400 100644--- a/plugins/omo/components/telemetry/src/codex-hook.ts+++ b/plugins/omo/components/telemetry/src/codex-hook.ts@@ -1,8 +1,8 @@import {- type PostHogActivityReason,- type PostHogClient,createPluginPostHog,getPostHogDistinctId,+ type PostHogActivityReason,+ type PostHogClient,} from "./posthog.js";export type CodexSessionStartInput = {@@ -16,7 +16,7 @@ export type CodexSessionStartInput = {};export type CodexTelemetryHookOptions = {- createClient?: () => PostHogClient;+ createClient?: () => PostHogClient | Promise<PostHogClient>;getDistinctId?: () => string;};@@ -29,7 +29,7 @@ export async function runSessionStartHook(const createClient = options.createClient ?? createPluginPostHog;const getDistinctId = options.getDistinctId ?? getPostHogDistinctId;- const client = createClient();+ const client = await createClient();try {client.trackActive(getDistinctId(), SESSION_START_REASON);} catch {diff --git a/plugins/omo/components/telemetry/src/posthog.ts b/plugins/omo/components/telemetry/src/posthog.tsindex 30ab9eb0..5d46bfba 100644--- a/plugins/omo/components/telemetry/src/posthog.ts+++ b/plugins/omo/components/telemetry/src/posthog.ts@@ -1,7 +1,7 @@import { createHash } from "node:crypto";import os from "node:os";-import { PostHog } from "posthog-node";+import type { PostHog } from "posthog-node";import { getPostHogApiKey, getPostHogHost, hasPostHogApiKey, shouldDisablePostHog } from "./env-flags.js";import { getPostHogActivityCaptureState } from "./posthog-activity-state.js";@@ -9,9 +9,9 @@ import {DEFAULT_POSTHOG_API_KEY,DEFAULT_POSTHOG_HOST,EVENT_NAME,+ getComponentVersion,PACKAGE_NAME,PRODUCT_NAME,- getComponentVersion,} from "./product-identity.js";export { DEFAULT_POSTHOG_API_KEY, DEFAULT_POSTHOG_HOST };@@ -86,14 +86,23 @@ function getSharedProperties(): NonNullable<PostHogCaptureEvent["properties"]> {};}-export function createPluginPostHog(): PostHogClient {+export async function createPluginPostHog(): Promise<PostHogClient> {if (shouldDisablePostHog() || !hasPostHogApiKey()) {return NO_OP_POSTHOG;}+ let PostHogClientConstructor: typeof PostHog;+ try {+ const module = await import("posthog-node");+ PostHogClientConstructor = module.PostHog;+ } catch (error) {+ if (error instanceof Error) return NO_OP_POSTHOG;+ throw error;+ }+let client: PostHog;try {- client = new PostHog(getPostHogApiKey(), {+ client = new PostHogClientConstructor(getPostHogApiKey(), {enableExceptionAutocapture: false,enableLocalEvaluation: false,strictLocalEvaluation: true,diff --git a/plugins/omo/components/telemetry/test/codex-hook.test.ts b/plugins/omo/components/telemetry/test/codex-hook.test.tsindex 066ad9b1..ed48f30c 100644--- a/plugins/omo/components/telemetry/test/codex-hook.test.ts+++ b/plugins/omo/components/telemetry/test/codex-hook.test.ts@@ -1,5 +1,5 @@import { spawn } from "node:child_process";-import { mkdtempSync, rmSync } from "node:fs";+import { cpSync, mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import path from "node:path";import { fileURLToPath } from "node:url";@@ -63,8 +63,12 @@ function makeRecordingClient(): { client: PostHogClient; calls: CapturedCall[];}function runHookCli(input: string, env: NodeJS.ProcessEnv = {}): Promise<CliResult> {+ return runHookCliAt(CLI_PATH, input, env);+}++function runHookCliAt(cliPath: string, input: string, env: NodeJS.ProcessEnv = {}): Promise<CliResult> {return new Promise((resolve, reject) => {- const child = spawn(process.execPath, [CLI_PATH, "hook", "session-start"], {+ const child = spawn(process.execPath, [cliPath, "hook", "session-start"], {env: { ...process.env, ...env },stdio: ["pipe", "pipe", "pipe"],});@@ -168,6 +172,25 @@ describe("telemetry CLI session-start hook (subprocess)", () => {expect(result.exitCode).toBe(0);expect(result.stdout).toBe("");});++ it("#when CLI runs from an isolated snapshot without node_modules #then exits 0 with no output", async () => {+ const payload = JSON.stringify(makeSessionStartInput());+ const snapshotRoot = mkdtempSync(path.join(tmpdir(), "codex-telemetry-snapshot-"));+ const dataDir = mkdtempSync(path.join(tmpdir(), "codex-telemetry-data-"));+ tempDirectories.push(snapshotRoot, dataDir);+ cpSync(fileURLToPath(new URL("../dist", import.meta.url)), path.join(snapshotRoot, "dist"), {+ recursive: true,+ });++ const result = await runHookCliAt(path.join(snapshotRoot, "dist", "cli.js"), payload, {+ OMO_DISABLE_POSTHOG: "1",+ XDG_DATA_HOME: dataDir,+ });++ expect(result.exitCode).toBe(0);+ expect(result.stdout).toBe("");+ expect(result.stderr).toBe("");+ });});describe("#given OMO_CODEX_SEND_ANONYMOUS_TELEMETRY=0 set in environment", () => {diff --git a/plugins/omo/components/ultragoal/hooks/hooks.json b/plugins/omo/components/ultragoal/hooks/hooks.jsondeleted file mode 100644index f3e52fac..00000000--- a/plugins/omo/components/ultragoal/hooks/hooks.json+++ /dev/null@@ -1,16 +0,0 @@-{- "hooks": {- "UserPromptSubmit": [- {- "hooks": [- {- "type": "command",- "command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit",- "timeout": 10,- "statusMessage": "checking ultragoal steering"- }- ]- }- ]- }-}diff --git a/plugins/omo/components/ultragoal/skills/ultragoal/SKILL.md b/plugins/omo/components/ultragoal/skills/ultragoal/SKILL.mddeleted file mode 100644index 47e8784a..00000000--- a/plugins/omo/components/ultragoal/skills/ultragoal/SKILL.md+++ /dev/null@@ -1,157 +0,0 @@-----name: ultragoal-description: Durable repo-native multi-goal plans with embedded success criteria and evidence audit.------## Role-Expert goal orchestration agent. Plan multi-goal work that survives across turns and sessions.-Use GPT-5.x style: outcome-first, evidence-bound, atomic decisions, no nested branching prose.--## Goal-Deliver every goal in `.omo/ultragoal/goals.json` end-to-end.-Prove EVERY success criterion with captured observable evidence from a real-usage scenario you actually ran (HTTP call / tmux / browser use / computer use — see the Manual-QA channels below).-TESTS ALONE NEVER PROVE DONE. A green test suite is supporting evidence, not completion proof.-Audit each pass, fail, block, steering change, and checkpoint in `.omo/ultragoal/ledger.jsonl`.--## Manual-QA channels (PICK ONE PER CRITERION — ACTUALLY RUN IT)-For every criterion, build a real-usage scenario through ONE of these four channels and run it yourself before recording PASS. The full test suite being green is NEVER verification on its own.--1. **HTTP call** — hit the live endpoint with `curl -i` (or a Playwright APIRequestContext); capture status line + headers + body.-2. **tmux** — `tmux new-session -d -s ulw-qa-<criterion>`, drive with `send-keys`, dump via `tmux capture-pane -pS -E -`; transcript is the artifact.-3. **Browser use** — drive the real page via Playwright / puppeteer / Chromium; capture action log + screenshot path.-4. **Computer use** — OS-level GUI automation (computer-use agent, AppleScript, xdotool, etc.) against the running app; capture action log + screenshot.--Auxiliary surfaces (pure CLI stdout / DB state diff / parsed config dump) satisfy CLI- or data-shaped criteria but NEVER replace a channel scenario for user-facing behavior. `--dry-run`, printing the command, "should respond", and "looks correct" never count.--## Artifacts-- `.omo/ultragoal/brief.md`: original brief and durable constraints.-- `.omo/ultragoal/goals.json`: goals with embedded `successCriteria` per goal.-- `.omo/ultragoal/ledger.jsonl`: append-only audit trail.-- Read artifacts before resuming, steering, or checkpointing.-- Never invent state outside `.omo/ultragoal` artifacts or `omo ultragoal status --json`.--## Bootstrap-Do all three steps before execution. No edits, goal tools, or checkpointing before bootstrap completes.--### 1. Create goals from the brief-Run one form:-```sh-omo ultragoal create-goals --brief "<brief>" --json-omo ultragoal create-goals --brief-file <path> --json-cat <brief> | omo ultragoal create-goals --from-stdin --json-```-Write state through the CLI path. Do not hand-edit state files.--### 2. Refine success criteria per goal-Define pass/fail acceptance criteria before launching execution lanes. Include the command, artifact, or manual check that will prove success.-Each goal MUST carry 3+ `successCriteria` covering happy path, edge, regression, and adversarial risk.-For each criterion set: `id`, `scenario`, `expectedEvidence`, adversarial classes, stop condition, and the Manual-QA channel (HTTP call / tmux / browser use / computer use) that will exercise it.-Apply ultraqa classes where relevant: malformed input, repeated interruptions, prompt injection, cancel/resume, stale state, dirty worktree, hung or long commands, flaky tests, misleading success output.-Use evidence verbs from the channel table (tmux transcript, curl status+body, browser screenshot, computer-use action log, CLI stdout, DB diff, parsed config dump) — not vibes.-"Tests pass" is supporting signal, NEVER completion proof. Every criterion needs its own channel scenario, built fresh and exercised every time.-Record manual QA notes when behavior is user-visible.-Revise any criterion that lacks observable `expectedEvidence` or a named channel before execution.--### 3. Inspect state-Run `omo ultragoal status --json`.-Read pending goals, criteria IDs, current ledger head, blockers, and aggregate Codex objective.--## Execution Loop-Loop per goal. Cap at 5 cycles per goal. Cap identical same-criterion failures at 3.--### Acquire Next Goal-1. Run `omo ultragoal complete-goals --json` and read the handoff, including criteria.-2. Call `get_goal` and inspect active Codex state.-3. Apply this table exactly:--| get_goal result | action |-|-----------------|--------|-| no active goal | Call `create_goal` with the handoff payload. |-| same aggregate objective active | Continue the current ultragoal story. |-| different goal active | STOP. Checkpoint blocked and surface the conflict. |-4. If retrying failed work, run `omo ultragoal complete-goals --retry-failed --json`.-5. Never create a second Codex goal for the same aggregate objective.--### Per-Criterion Cycle-1. PLAN: read `criterion.scenario`, `criterion.expectedEvidence`, prior ledger entries, and safety bounds.-2. Register atomic todos: `path: <action> for <criterion> - verify by <check>`.-3. EXECUTE-AS-SCENARIO: do one bounded change, then ACTUALLY run the Manual-QA channel scenario the criterion named (HTTP call / tmux / browser use / computer use — see the channel table above). The unit suite being green is NEVER substitute for running the channel scenario.-4. CAPTURE: collect the observable artifact path: transcript, stdout, screenshot, assertion, status+body, diff, or parsed dump.-5. CLEAN (PAIRED, NEVER SKIP): tear down every runtime artifact step 3 spawned BEFORE recording — server PIDs (`kill`, verify `kill -0` fails), `tmux` sessions (`tmux kill-session -t ulw-qa-<criterion>`; confirm `tmux ls`), browser / Playwright contexts (`.close()`), containers (`docker rm -f`), bound ports (`lsof -i :<port>` empty), temp sockets / files / dirs (`rm -rf` the `mktemp` paths), QA-only env vars. Embed a one-line cleanup receipt in the evidence string, e.g. `cleanup: killed 12345; tmux kill-session ulw-qa-foo; rm -rf /tmp/ulw.aB12cD`. Missing receipt → record BLOCKED, not PASS.-6. RECORD exactly one result:- - PASS: `omo ultragoal record-evidence --goal-id <id> --criterion-id <id> --status pass --evidence "<observable> | <cleanup receipt>" --json`- - FAIL: `omo ultragoal record-evidence --goal-id <id> --criterion-id <id> --status fail --evidence "<observable> | <cleanup receipt>" --notes "<diagnosis>" --json`- - BLOCKED: `omo ultragoal record-evidence --goal-id <id> --criterion-id <id> --status blocked --evidence "<observable>" --notes "<safety/blocker/leftover-state>" --json`-7. If actual does not match expected, diagnose, fix minimally, and rerun the SAME criterion (including a fresh cleanup).-8. After 3 same-criterion failures, exit the goal with diagnosis.-9. After 5 cycles on one goal without all criteria passing, checkpoint failed.-10. Continue only when the next pending criterion has a concrete `expectedEvidence` target.--### Goal Completion-1. Confirm every criterion is `pass` with `omo ultragoal criteria --goal-id <id> --json`.-2. Call `get_goal` for a fresh snapshot.-3. Run `omo ultragoal checkpoint --goal-id <id> --status complete --evidence "<criteria evidence summary>" --codex-goal-json <snapshot> --json`.-4. If blocked or failed, checkpoint with `--status blocked` or `--status failed` and include diagnosis evidence.-5. If this is the final goal, run the final quality gate first and pass `--quality-gate-json`.--## Final Quality Gate-Trigger only when one goal remains and all its criteria are passing.-1. Run targeted verification for changed behavior.-2. Run `ai-slop-cleaner` on changed files. If no relevant edits exist, record a passed no-op cleaner report.-3. Rerun verification after cleanup.-4. Run `$code-review`.-5. Clean review means `codeReview.recommendation == "APPROVE"` and `codeReview.architectStatus == "CLEAR"`.-6. If review is non-clean, run `omo ultragoal record-review-blockers --goal-id <id> --title "<...>" --objective "<...>" --evidence "<review findings>" --codex-goal-json <snapshot> --json`.-7. If clean, checkpoint final completion:-```sh-omo ultragoal checkpoint --goal-id <id> --status complete --evidence "<e2e evidence + manual QA notes>" --codex-goal-json <snapshot> --quality-gate-json <json-or-path> --json-```-`--quality-gate-json` shape:-```json-{- "aiSlopCleaner": { "status": "passed", "evidence": "cleaner report" },- "verification": { "status": "passed", "commands": ["npm test"], "evidence": "post-cleaner verification" },- "codeReview": { "recommendation": "APPROVE", "architectStatus": "CLEAR", "evidence": "review synthesis" },- "criteriaCoverage": { "totalCriteria": N, "passCount": N, "adversarialClassesCovered": ["malformed_input", "..."] }-}-```--## Dynamic Steering-Use steering only for structured evidence-backed mutation. Reject natural-language steering requests.--| Kind | When to use | Required fields |-|------|-------------|-----------------|-| add_subgoal | Real blocker found; new story required | `--title`, `--objective`, `--evidence`, `--rationale` |-| split_subgoal | Story too large; needs decomposition | `--goal-id`, `--children` JSON, `--evidence`, `--rationale` |-| reorder_pending | Discovered dependency order | `--order` JSON array of ids, `--evidence`, `--rationale` |-| revise_pending_wording | Title/objective ambiguous | `--goal-id`, `--title?`, `--objective?`, `--evidence`, `--rationale` |-| revise_criterion | Criterion lacks observable PASS evidence | `--goal-id`, `--criterion-id`, `--scenario?`, `--expected-evidence?`, `--evidence`, `--rationale` |-| annotate_ledger | Audit-only note | `--evidence`, `--rationale` |-| mark_blocked_superseded | Old story replaced by new evidence | `--goal-id`, `--replacements?`, `--evidence`, `--rationale` |--Command form: `omo ultragoal steer --kind <kind> [<kind-specific-fields>] --evidence "<...>" --rationale "<...>" --json`.-Structured prompt directives accepted: `OMO_ULTRAGOAL_STEER: { ... }`, `omo.ultragoal.steer: {...}`, `omo ultragoal steer: {...}`.--## Constraints-1. NEVER call `update_goal` mid-aggregate; only on final story after the quality gate passes.-2. NEVER call `create_goal` when `get_goal` shows a different active goal.-3. NEVER mark `criterion.status == "pass"` without captured observable evidence in `record-evidence`.-4. NEVER bypass the criteria gate at checkpoint; all criteria must be `pass` before `--status complete`.-5. Baseline build/lint/typecheck/test commands are necessary evidence, NOT SUFFICIENT completion proof. Criteria coverage with observable evidence is the gate.-6. Treat `.omo/ultragoal/ledger.jsonl` as the durable audit trail; checkpoint after every success or failure.-7. Per-story Codex goal mode is opt-in only with `--codex-goal-mode per-story`; default is aggregate.-8. Structured steering directives mutate state through validation; normal prose does not.-9. Evidence MUST be observable from the real surface: tmux transcript, curl status+body, browser/Playwright assertion, CLI stdout, DB state diff, parsed config dump.-10. Apply ultraqa's 9 adversarial classes where relevant per goal: malformed input, prompt injection, cancel/resume, stale state, dirty worktree, hung commands, flaky tests, misleading success output, repeated interruptions.-11. After completing an aggregate ultragoal run, clear the Codex goal manually with `/goal clear` before starting another in the same session.-12. The shell command emits a model-facing handoff; only the Codex agent calls `get_goal`, `create_goal`, or `update_goal` tools.-13. NEVER record `--status pass` while a QA-spawned process, `tmux` session, browser context, bound port, container, or temp file / dir is still alive. The evidence string MUST include the cleanup receipt. Leftover runtime state = BLOCKED, not PASS.--## Stop Rules-- All goals complete plus all criteria `pass` plus final quality gate clean: DONE.-- 3x same criterion failure: checkpoint failed, surface diagnosis.-- 5 cycles on one goal without all-pass: checkpoint failed, surface.-- Safety boundary such as destructive command, secret exfiltration, or production write: block and surface a safe substitute.-- Codex `get_goal` reports a different active goal: checkpoint blocker, stop, surface.-- Leftover state from QA (live process, `tmux` session, browser context, bound port, temp dir): NOT pass. Clean up, append the receipt, then continue.-- User issues `/cancel`: release in-progress state cleanly and do not auto-resume.diff --git a/plugins/omo/components/ultragoal/src/cli-commands.ts b/plugins/omo/components/ultragoal/src/cli-commands.tsdeleted file mode 100644index c53ef458..00000000--- a/plugins/omo/components/ultragoal/src/cli-commands.ts+++ /dev/null@@ -1,142 +0,0 @@-// biome-ignore-all format: keep cli-commands dispatcher under the 200 pure LOC budget.-import { readFile } from "node:fs/promises";-import { checkpointUltragoal } from "./checkpoint.js";-import { hasFlag, parseCodexGoalJson, parseRecordEvidenceArgs, positionalText, readStdin, readValue } from "./cli-arg-parser.js";-import { blockedDecisionHandoff, normalizeCodexGoalMode, printJson, printStatus, ULTRAGOAL_HELP } from "./cli-output.js";-import { parseSteeringProposal, printSteerResult } from "./cli-steering.js";-import { buildCodexGoalInstruction } from "./codex-goal-instruction.js";-import { recordEvidence } from "./evidence.js";-import { addUltragoalGoal, createUltragoalPlan, startNextUltragoal, summarizeUltragoalPlan } from "./plan-crud.js";-import { readUltragoalPlan } from "./plan-io.js";-import { recordFinalReviewBlockers } from "./review-blockers.js";-import { steerUltragoal } from "./steering.js";-import type { UltragoalItem } from "./types.js";-import { UltragoalError } from "./types.js";--type CheckpointStatus = "complete" | "failed" | "blocked";--export async function ultragoalCommand(argv: readonly string[]): Promise<number> {- const command = argv[0] ?? "help";- const rest = argv.slice(1);- const repoRoot = process.cwd();- const json = hasFlag(rest, "--json");- try {- switch (command) {- case "help": case "--help": case "-h": process.stdout.write(`${ULTRAGOAL_HELP}\n`); return 0;- case "create-goals": return await createGoals(repoRoot, rest, json);- case "status": return await status(repoRoot, json);- case "complete-goals": return await completeGoals(repoRoot, rest, json);- case "checkpoint": return await checkpoint(repoRoot, rest, json);- case "steer": return await steer(repoRoot, rest, json);- case "add-goal": return await addGoal(repoRoot, rest, json);- case "criteria": return await criteria(repoRoot, rest, json);- case "record-evidence": return await captureEvidence(repoRoot, rest, json);- case "record-review-blockers": return await reviewBlockers(repoRoot, rest, json);- default: process.stdout.write(`${ULTRAGOAL_HELP}\n`); return 1;- }- } catch (error) {- if (error instanceof UltragoalError) process.stderr.write(`[ultragoal] ${error.message}\n`);- else if (error instanceof Error) process.stderr.write(`[ultragoal] unexpected: ${error.message}\n`);- else process.stderr.write("[ultragoal] unknown error\n");- return 1;- }-}--async function createGoals(repoRoot: string, argv: readonly string[], json: boolean): Promise<number> {- const briefFile = readValue(argv, "--brief-file");- const brief = readValue(argv, "--brief") ?? (briefFile === undefined ? undefined : await readFile(briefFile, "utf8")) ?? (hasFlag(argv, "--from-stdin") ? await readStdin() : undefined) ?? positionalText(argv);- if (!brief.trim()) throw new UltragoalError("Missing brief text. Pass --brief, --brief-file, --from-stdin, or positional text.", "ULTRAGOAL_BRIEF_REQUIRED");- const plan = await createUltragoalPlan(repoRoot, { brief, codexGoalMode: normalizeCodexGoalMode(readValue(argv, "--codex-goal-mode")), force: hasFlag(argv, "--force") });- if (json) printJson({ ok: true, plan, summary: summarizeUltragoalPlan(plan) });- else process.stdout.write(`ultragoal plan created: ${plan.goals.length} goal(s)\nbrief: ${plan.briefPath}\ngoals: ${plan.goalsPath}\nledger: ${plan.ledgerPath}\n`);- return 0;-}--async function status(repoRoot: string, json: boolean): Promise<number> {- const plan = await readUltragoalPlan(repoRoot);- if (json) printJson({ ok: true, plan, summary: summarizeUltragoalPlan(plan) });- else printStatus(plan);- return 0;-}--async function completeGoals(repoRoot: string, argv: readonly string[], json: boolean): Promise<number> {- const result = await startNextUltragoal(repoRoot, { retryFailed: hasFlag(argv, "--retry-failed") });- if ("done" in result) {- const handoff = blockedDecisionHandoff(result.plan);- if (json) printJson({ ok: true, done: true, blocked: handoff.length > 0, handoff, summary: summarizeUltragoalPlan(result.plan), plan: result.plan });- else process.stdout.write(`${handoff || "ultragoal: all goals complete"}\n`);- return 0;- }- const instruction = buildCodexGoalInstruction({ plan: result.plan, goal: result.goal });- if (json) printJson({ ok: true, resumed: result.resumed, goal: result.goal, instruction, plan: result.plan });- else process.stdout.write(`${instruction.text}\n`);- return 0;-}--async function checkpoint(repoRoot: string, argv: readonly string[], json: boolean): Promise<number> {- const goalId = required(argv, "--goal-id");- const statusValue = checkpointStatus(required(argv, "--status"));- const evidence = required(argv, "--evidence");- const codexGoalJson = await parseCodexGoalJson(required(argv, "--codex-goal-json"));- if (codexGoalJson === undefined) throw new UltragoalError("Missing --codex-goal-json.", "ULTRAGOAL_CODEX_GOAL_JSON_REQUIRED");- const qualityGateJson = readValue(argv, "--quality-gate-json");- const result = await checkpointUltragoal(repoRoot, qualityGateJson === undefined ? { goalId, status: statusValue, evidence, codexGoalJson } : { goalId, status: statusValue, evidence, codexGoalJson, qualityGateJson });- if (json) printJson({ ok: true, ...result, summary: summarizeUltragoalPlan(result.plan) });- else process.stdout.write(`ultragoal checkpoint: ${result.goal.id} -> ${result.goal.status}\n`);- return 0;-}--async function steer(repoRoot: string, argv: readonly string[], json: boolean): Promise<number> {- const proposal = await parseSteeringProposal(argv);- const result = await steerUltragoal(repoRoot, proposal);- printSteerResult(result, json);- return result.accepted ? 0 : 1;-}--async function addGoal(repoRoot: string, argv: readonly string[], json: boolean): Promise<number> {- const result = await addUltragoalGoal(repoRoot, { title: required(argv, "--title"), objective: required(argv, "--objective") });- if (json) printJson({ ok: true, plan: result.plan, goal: result.goal, summary: summarizeUltragoalPlan(result.plan) });- else { process.stdout.write(`ultragoal added goal: ${result.goal.id}\n`); printStatus(result.plan); }- return 0;-}--async function criteria(repoRoot: string, argv: readonly string[], json: boolean): Promise<number> {- const goalId = required(argv, "--goal-id");- const goal = findGoal(await readUltragoalPlan(repoRoot), goalId);- if (json) printJson({ ok: true, goalId: goal.id, criteria: goal.successCriteria });- else process.stdout.write(`criteria for ${goal.id}:\n${goal.successCriteria.map((c) => `- ${c.id} [${c.status}] (${c.userModel}) ${c.scenario} evidence: ${c.capturedEvidence ?? "pending"}`).join("\n")}\n`);- return 0;-}--async function captureEvidence(repoRoot: string, argv: readonly string[], json: boolean): Promise<number> {- const result = await recordEvidence(repoRoot, parseRecordEvidenceArgs(argv));- if (json) printJson({ ok: true, ...result, summary: summarizeUltragoalPlan(result.plan) });- else process.stdout.write(`ultragoal evidence recorded: ${result.goal.id}/${result.criterion.id} -> ${result.criterion.status}\n`);- return 0;-}--async function reviewBlockers(repoRoot: string, argv: readonly string[], json: boolean): Promise<number> {- const codexGoalJson = await parseCodexGoalJson(required(argv, "--codex-goal-json"));- if (codexGoalJson === undefined) throw new UltragoalError("Missing --codex-goal-json.", "ULTRAGOAL_CODEX_GOAL_JSON_REQUIRED");- const result = await recordFinalReviewBlockers(repoRoot, { goalId: required(argv, "--goal-id"), title: required(argv, "--title"), objective: required(argv, "--objective"), evidence: required(argv, "--evidence"), codexGoalJson });- if (json) printJson({ ok: true, plan: result.plan, blockedGoal: result.blockedGoal, goal: result.newGoal, ledgerEntries: result.ledgerEntries, summary: summarizeUltragoalPlan(result.plan) });- else process.stdout.write(`ultragoal final review blockers recorded: ${result.blockedGoal.id} -> review_blocked; added ${result.newGoal.id}\n`);- return 0;-}--function required(argv: readonly string[], flag: string): string {- const value = readValue(argv, flag)?.trim();- if (value) return value;- throw new UltragoalError(`Missing ${flag}.`, "ULTRAGOAL_ARGUMENT_MISSING", { details: { flag } });-}--function checkpointStatus(value: string): CheckpointStatus {- if (value === "complete" || value === "failed" || value === "blocked") return value;- throw new UltragoalError("Missing or invalid --status; expected complete, failed, or blocked.", "ULTRAGOAL_STATUS_INVALID", { details: { status: value } });-}--function findGoal(plan: { readonly goals: readonly UltragoalItem[] }, goalId: string): UltragoalItem {- const goal = plan.goals.find((candidate) => candidate.id === goalId);- if (goal !== undefined) return goal;- throw new UltragoalError(`Unknown ultragoal id: ${goalId}.`, "ULTRAGOAL_GOAL_NOT_FOUND", { details: { goalId } });-}diff --git a/plugins/omo/components/ultragoal/src/codex-hook.ts b/plugins/omo/components/ultragoal/src/codex-hook.tsdeleted file mode 100644index 3b6a7687..00000000--- a/plugins/omo/components/ultragoal/src/codex-hook.ts+++ /dev/null@@ -1,85 +0,0 @@-import { parseUltragoalSteeringDirective, steerUltragoal } from "./steering.js";--export interface UserPromptSubmitPayload {- readonly cwd: string;- readonly hook_event_name: "UserPromptSubmit";- readonly model?: string;- readonly permission_mode?: string;- readonly prompt: string;- readonly session_id: string;- readonly transcript_path?: string;- readonly turn_id?: string;-}--export function parseUserPromptSubmitPayload(raw: string): UserPromptSubmitPayload | null {- if (raw.trim().length === 0) return null;- try {- const parsed: unknown = JSON.parse(raw);- return isUserPromptSubmitPayload(parsed) ? parsed : null;- } catch (error) {- if (error instanceof SyntaxError) return null;- return null;- }-}--export async function applyUserPromptUltragoalSteering(payload: UserPromptSubmitPayload): Promise<string> {- try {- if (payload.hook_event_name !== "UserPromptSubmit") return "";- const proposal = parseUltragoalSteeringDirective(payload.prompt);- if (proposal === null) return "";- const result = await steerUltragoal(payload.cwd, proposal);- if (!result.accepted) return "";- return JSON.stringify({- status: "accepted",- kind: result.audit.kind,- source: result.audit.source,- deduped: result.deduped,- });- } catch (error) {- if (error instanceof Error) return "";- return "";- }-}--export async function runUltragoalHookCli(stdin: NodeJS.ReadableStream, stdout: NodeJS.WritableStream): Promise<void> {- try {- const payload = parseUserPromptSubmitPayload(await readAll(stdin));- if (payload === null) return;- const output = await applyUserPromptUltragoalSteering(payload);- if (output.length > 0) stdout.write(output);- } catch (error) {- if (error instanceof Error) return;- return;- }-}--function isUserPromptSubmitPayload(value: unknown): value is UserPromptSubmitPayload {- if (!isRecord(value)) return false;- return (- value["hook_event_name"] === "UserPromptSubmit" &&- typeof value["cwd"] === "string" &&- typeof value["prompt"] === "string" &&- typeof value["session_id"] === "string" &&- ["model", "permission_mode", "transcript_path", "turn_id"].every((key) => optionalString(value[key]))- );-}--function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === "object" && value !== null && !Array.isArray(value);-}--function optionalString(value: unknown): boolean {- return value === undefined || typeof value === "string";-}--function readAll(stdin: NodeJS.ReadableStream): Promise<string> {- return new Promise((resolve, reject) => {- let data = "";- stdin.setEncoding("utf8");- stdin.on("data", (chunk: unknown) => {- data += chunk instanceof Buffer ? chunk.toString() : String(chunk);- });- stdin.once("error", reject);- stdin.once("end", () => resolve(data));- });-}diff --git a/plugins/omo/components/ultragoal/src/paths.ts b/plugins/omo/components/ultragoal/src/paths.tsdeleted file mode 100644index 835d6536..00000000--- a/plugins/omo/components/ultragoal/src/paths.ts+++ /dev/null@@ -1,27 +0,0 @@-import { join } from "node:path";-import { ULTRAGOAL_BRIEF, ULTRAGOAL_DIR, ULTRAGOAL_GOALS, ULTRAGOAL_LEDGER } from "./types.js";--export function ultragoalDir(repoRoot: string): string {- return join(repoRoot, ULTRAGOAL_DIR);-}--export function ultragoalBriefPath(repoRoot: string): string {- return join(ultragoalDir(repoRoot), ULTRAGOAL_BRIEF);-}--export function ultragoalGoalsPath(repoRoot: string): string {- return join(ultragoalDir(repoRoot), ULTRAGOAL_GOALS);-}--export function ultragoalLedgerPath(repoRoot: string): string {- return join(ultragoalDir(repoRoot), ULTRAGOAL_LEDGER);-}--export function repoRelative(absolutePath: string, repoRoot: string): string {- const slashPrefix = `${repoRoot}/`;- const backslashPrefix = `${repoRoot}\\`;- if (absolutePath.startsWith(slashPrefix)) return absolutePath.slice(slashPrefix.length).split("\\").join("/");- if (absolutePath.startsWith(backslashPrefix))- return absolutePath.slice(backslashPrefix.length).split("\\").join("/");- return absolutePath.split("\\").join("/");-}diff --git a/plugins/omo/components/ultragoal/src/plan-io.ts b/plugins/omo/components/ultragoal/src/plan-io.tsdeleted file mode 100644index d8df442c..00000000--- a/plugins/omo/components/ultragoal/src/plan-io.ts+++ /dev/null@@ -1,99 +0,0 @@-import { appendFile, mkdir, readFile, rename, writeFile } from "node:fs/promises";--import { repoRelative, ultragoalDir, ultragoalGoalsPath, ultragoalLedgerPath } from "./paths.js";-import type { UltragoalLedgerEntry, UltragoalPlan } from "./types.js";-import { iso, ULTRAGOAL_DIR, ULTRAGOAL_GOALS, ULTRAGOAL_LEDGER, UltragoalError } from "./types.js";--const AGGREGATE_CODEX_OBJECTIVE = `Complete the durable ultragoal plan in ${ULTRAGOAL_DIR}/${ULTRAGOAL_GOALS}, including later accepted/appended stories, under the original brief constraints; use ${ULTRAGOAL_DIR}/${ULTRAGOAL_LEDGER} as the audit trail.`;-const LEGACY_OBJECTIVE_PREFIX = `Complete all ultragoal stories in ${ULTRAGOAL_DIR}/${ULTRAGOAL_GOALS}: `;-const LEGACY_OBJECTIVE = `Complete all ultragoal stories listed in ${ULTRAGOAL_DIR}/${ULTRAGOAL_GOALS}. Use ${ULTRAGOAL_DIR}/${ULTRAGOAL_LEDGER} as the durable audit trail.`;-const locks = new Map<string, Promise<unknown>>();--function hasCode(error: unknown, code: string): boolean {- return error instanceof Error && "code" in error && error.code === code;-}--function isLegacyEnumeratedAggregateObjective(objective: string | undefined): objective is string {- return objective === LEGACY_OBJECTIVE || Boolean(objective?.startsWith(LEGACY_OBJECTIVE_PREFIX));-}--function isSteeringKind(value: unknown): value is UltragoalLedgerEntry["kind"] {- return value === "steering_accepted" || value === "steering_rejected" || value === "criteria_revised";-}--export async function withUltragoalMutationLock<T>(repoRoot: string, fn: () => Promise<T>): Promise<T> {- const prior = locks.get(repoRoot) ?? Promise.resolve();- const run = prior.then(fn, fn);- locks.set(- repoRoot,- run.catch(() => undefined),- );- return run;-}--export async function readUltragoalPlan(repoRoot: string): Promise<UltragoalPlan> {- const path = ultragoalGoalsPath(repoRoot);- let raw: string;- try {- raw = await readFile(path, "utf8");- } catch (error) {- if (!hasCode(error, "ENOENT")) throw error;- throw new UltragoalError(- `No ultragoal plan found at ${repoRelative(path, repoRoot)}. Run \`omo ultragoal create-goals ...\` first.`,- "ULTRAGOAL_PLAN_MISSING",- { cause: error },- );- }- const parsed: UltragoalPlan = JSON.parse(raw);- if (parsed.version !== 1 || !Array.isArray(parsed.goals)) {- throw new UltragoalError(`Invalid ultragoal plan at ${repoRelative(path, repoRoot)}.`, "ULTRAGOAL_PLAN_INVALID");- }- const previousObjective = parsed.codexObjective;- if (- (parsed.codexGoalMode ?? "per_story") === "aggregate" &&- isLegacyEnumeratedAggregateObjective(previousObjective)- ) {- const now = iso();- parsed.codexObjective = AGGREGATE_CODEX_OBJECTIVE;- parsed.codexObjectiveAliases = [...new Set([...(parsed.codexObjectiveAliases ?? []), previousObjective])];- parsed.updatedAt = now;- await writePlan(repoRoot, parsed);- await appendLedger(repoRoot, {- at: now,- kind: "aggregate_objective_migrated",- message: "Migrated legacy enumerated aggregate Codex objective to the stable pointer objective.",- before: { codexObjective: previousObjective },- after: { codexObjective: parsed.codexObjective },- });- }- return parsed;-}--export async function writePlan(repoRoot: string, plan: UltragoalPlan): Promise<void> {- await mkdir(ultragoalDir(repoRoot), { recursive: true });- const path = ultragoalGoalsPath(repoRoot);- const tmpPath = `${path}.${process.pid}.${Date.now()}.tmp`;- await writeFile(tmpPath, `${JSON.stringify(plan, null, 2)}\n`, "utf8");- await rename(tmpPath, path);-}--export async function appendLedger(repoRoot: string, entry: UltragoalLedgerEntry): Promise<void> {- await mkdir(ultragoalDir(repoRoot), { recursive: true });- await appendFile(ultragoalLedgerPath(repoRoot), `${JSON.stringify(entry)}\n`, "utf8");-}--export async function readSteeringLedgerEntries(repoRoot: string): Promise<UltragoalLedgerEntry[]> {- let raw: string;- try {- raw = await readFile(ultragoalLedgerPath(repoRoot), "utf8");- } catch (error) {- if (hasCode(error, "ENOENT")) return [];- throw error;- }- const entries: UltragoalLedgerEntry[] = [];- for (const line of raw.split(/\r?\n/).filter(Boolean)) {- const entry: UltragoalLedgerEntry = JSON.parse(line);- if (isSteeringKind(entry.kind)) entries.push(entry);- }- return entries;-}diff --git a/plugins/omo/components/ultragoal/test/cli-commands.test.ts b/plugins/omo/components/ultragoal/test/cli-commands.test.tsdeleted file mode 100644index 6a641886..00000000--- a/plugins/omo/components/ultragoal/test/cli-commands.test.ts+++ /dev/null@@ -1,274 +0,0 @@-import { mkdtemp, readFile, rm } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--import { ultragoalCommand } from "../src/cli-commands.ts";-import { ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE } from "../src/goal-status.js";--let testDir: string;-let out: string[];-let err: string[];--beforeEach(async () => {- testDir = await mkdtemp(join(tmpdir(), "ug-cli-"));- out = [];- err = [];- vi.spyOn(process, "cwd").mockReturnValue(testDir);- vi.spyOn(process.stdout, "write").mockImplementation((chunk: string | Uint8Array): boolean => {- out.push(chunk.toString());- return true;- });- vi.spyOn(process.stderr, "write").mockImplementation((chunk: string | Uint8Array): boolean => {- err.push(chunk.toString());- return true;- });-});--afterEach(async () => {- vi.restoreAllMocks();- await rm(testDir, { recursive: true, force: true });-});--function resetOutput(): void {- out = [];- err = [];-}-function stdoutJson(): Record<string, unknown> {- return JSON.parse(out.join(""));-}-function codexSnapshot(status: "active" | "complete" = "active"): string {- return JSON.stringify({ goal: { objective: ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE, status } });-}--async function createPlan(brief = "- Goal A\n- Goal B"): Promise<Record<string, unknown>> {- resetOutput();- expect(await ultragoalCommand(["create-goals", "--brief", brief, "--json"])).toBe(0);- const parsed = stdoutJson();- resetOutput();- return parsed;-}--async function passCriterion(goalId: string, criterionId: string): Promise<void> {- expect(- await ultragoalCommand([- "record-evidence",- "--goal-id",- goalId,- "--criterion-id",- criterionId,- "--status",- "pass",- "--evidence",- `${criterionId} observable proof`,- ]),- ).toBe(0);- resetOutput();-}--describe("ultragoalCommand help", () => {- it("prints usage when no subcommand", async () => {- expect(await ultragoalCommand([])).toBe(0);- expect(out.join("")).toContain("omo ultragoal");- });-});--describe("ultragoalCommand create-goals", () => {- it("creates plan + writes 3 artifacts + seeds criteria per goal", async () => {- const code = await ultragoalCommand(["create-goals", "--brief", "- Goal A\n- Goal B", "--json"]);-- expect(code).toBe(0);- const parsed = stdoutJson();- expect(parsed).toMatchObject({ ok: true });- expect(parsed).toHaveProperty("plan.goals.0.successCriteria.0.id", "C001");- expect(await readFile(join(testDir, ".omo/ultragoal/brief.md"), "utf8")).toContain("Goal A");- expect(await readFile(join(testDir, ".omo/ultragoal/goals.json"), "utf8")).toContain("successCriteria");- expect(await readFile(join(testDir, ".omo/ultragoal/ledger.jsonl"), "utf8")).toContain("plan_created");- });-});--describe("ultragoalCommand status", () => {- it("prints plan summary including criteria counts", async () => {- await createPlan();-- expect(await ultragoalCommand(["status"])).toBe(0);- expect(out.join("")).toContain("criteria: 0/6 pass");- });-});--describe("ultragoalCommand complete-goals", () => {- it("starts the next goal and returns a Codex instruction", async () => {- await createPlan();-- expect(await ultragoalCommand(["complete-goals", "--json"])).toBe(0);- expect(stdoutJson()).toMatchObject({- ok: true,- goal: { status: "in_progress" },- instruction: { json: { status: "active" } },- });- });-});--describe("ultragoalCommand record-evidence", () => {- it("records evidence + returns updated criterion", async () => {- await createPlan();-- expect(- await ultragoalCommand([- "record-evidence",- "--goal-id",- "G001-goal-a",- "--criterion-id",- "C001",- "--status",- "pass",- "--evidence",- "curl passed",- "--json",- ]),- ).toBe(0);- expect(stdoutJson()).toMatchObject({- ok: true,- criterion: { id: "C001", status: "pass", capturedEvidence: "curl passed" },- });- });-- it("returns 1 + error on unknown goal-id", async () => {- await createPlan();-- expect(- await ultragoalCommand([- "record-evidence",- "--goal-id",- "G404",- "--criterion-id",- "C001",- "--status",- "pass",- "--evidence",- "x",- ]),- ).toBe(1);- expect(err.join("")).toContain("[ultragoal]");- });-- it("returns 1 + error on missing flags", async () => {- expect(- await ultragoalCommand(["record-evidence", "--criterion-id", "C001", "--status", "pass", "--evidence", "x"]),- ).toBe(1);- expect(err.join("")).toContain("Missing --goal-id");- });-});--describe("ultragoalCommand criteria", () => {- it("lists criteria for a goal", async () => {- await createPlan();-- expect(await ultragoalCommand(["criteria", "--goal-id", "G001-goal-a"])).toBe(0);- expect(out.join("")).toContain("C001");- expect(out.join("")).toContain("happy");- });-- it("supports --json output", async () => {- await createPlan();-- expect(await ultragoalCommand(["criteria", "--goal-id", "G001-goal-a", "--json"])).toBe(0);- expect(stdoutJson()).toMatchObject({ ok: true, goalId: "G001-goal-a" });- expect(stdoutJson()).toHaveProperty("criteria.0.id", "C001");- });-});--describe("ultragoalCommand checkpoint", () => {- it("REJECTS status=complete when criteria pending", async () => {- await createPlan();-- expect(- await ultragoalCommand([- "checkpoint",- "--goal-id",- "G001-goal-a",- "--status",- "complete",- "--evidence",- "x",- "--codex-goal-json",- codexSnapshot(),- ]),- ).toBe(1);- expect(err.join("").toLowerCase()).toContain("criteria");- });-- it("ACCEPTS when all criteria pass", async () => {- await createPlan();- await passCriterion("G001-goal-a", "C001");- await passCriterion("G001-goal-a", "C002");- await passCriterion("G001-goal-a", "C003");-- expect(- await ultragoalCommand([- "checkpoint",- "--goal-id",- "G001-goal-a",- "--status",- "complete",- "--evidence",- "implementation done and validation passed",- "--codex-goal-json",- codexSnapshot(),- "--json",- ]),- ).toBe(0);- expect(stdoutJson()).toHaveProperty("goal.status", "complete");- });-});--describe("ultragoalCommand steer", () => {- it("dispatches to the steering engine", async () => {- await createPlan();-- expect(- await ultragoalCommand([- "steer",- "--kind",- "add_subgoal",- "--title",- "Extra",- "--objective",- "Do extra",- "--evidence",- "user requested it",- "--rationale",- "keeps plan accurate",- "--json",- ]),- ).toBe(0);- expect(stdoutJson()).toMatchObject({- ok: true,- accepted: true,- plan: { goals: [{ id: "G001-goal-a" }, { id: "G002-goal-b" }, { title: "Extra" }] },- });- });-});--describe("ultragoalCommand add-goal", () => {- it("appends a pending goal", async () => {- await createPlan();-- expect(await ultragoalCommand(["add-goal", "--title", "Later", "--objective", "Do later", "--json"])).toBe(0);- expect(stdoutJson()).toMatchObject({ ok: true, goal: { title: "Later", status: "pending" } });- });-});--describe("ultragoalCommand unknown", () => {- it("returns 1 + prints help on unknown subcommand", async () => {- expect(await ultragoalCommand(["wat"])).toBe(1);- expect(out.join("")).toContain("omo ultragoal");- });-});--describe("ultragoalCommand error handling", () => {- it("returns 1 + prints [ultragoal] prefix on UltragoalError", async () => {- expect(await ultragoalCommand(["status"])).toBe(1);- expect(err.join("")).toContain("[ultragoal]");- });-});diff --git a/plugins/omo/components/ultragoal/test/codex-hook.test.ts b/plugins/omo/components/ultragoal/test/codex-hook.test.tsdeleted file mode 100644index c6be05e8..00000000--- a/plugins/omo/components/ultragoal/test/codex-hook.test.ts+++ /dev/null@@ -1,187 +0,0 @@-import { mkdir, mkdtemp, readFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { Readable, Writable } from "node:stream";-import { describe, expect, it } from "vitest";--import {- applyUserPromptUltragoalSteering,- parseUserPromptSubmitPayload,- runUltragoalHookCli,- type UserPromptSubmitPayload,-} from "../src/codex-hook.js";-import { ultragoalDir } from "../src/paths.js";-import { writePlan } from "../src/plan-io.js";-import type { UltragoalPlan } from "../src/types.js";--const NOW = "2026-05-23T00:00:00.000Z";--async function bootstrapPlanRepo(): Promise<string> {- const repoRoot = await mkdtemp(join(tmpdir(), "ug-hook-"));- await mkdir(ultragoalDir(repoRoot), { recursive: true });- await writePlan(repoRoot, samplePlan());- return repoRoot;-}--function samplePlan(): UltragoalPlan {- return {- version: 1,- createdAt: NOW,- updatedAt: NOW,- briefPath: ".omo/ultragoal/brief.md",- goalsPath: ".omo/ultragoal/goals.json",- ledgerPath: ".omo/ultragoal/ledger.jsonl",- goals: [- {- id: "G001",- title: "Build hook",- objective: "Apply safe steering directives from Codex hooks.",- status: "pending",- successCriteria: [],- attempt: 0,- createdAt: NOW,- updatedAt: NOW,- },- ],- };-}--function payload(prompt: string, cwd: string): UserPromptSubmitPayload {- return { cwd, hook_event_name: "UserPromptSubmit", prompt, session_id: "s1" };-}--function payloadWithRuntimeEvent(hookEventName: string): UserPromptSubmitPayload {- const input = payload(- 'OMO_ULTRAGOAL_STEER: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',- "/tmp",- );- Object.defineProperty(input, "hook_event_name", { value: hookEventName });- return input;-}--function captureStdout(): { readonly stdout: Writable; readonly read: () => string } {- let captured = "";- const stdout = new Writable({- write(chunk: unknown, _encoding: BufferEncoding, callback: (error?: Error | null) => void): void {- captured += chunk instanceof Buffer ? chunk.toString() : String(chunk);- callback();- },- });- return { stdout, read: () => captured };-}--describe("parseUserPromptSubmitPayload", () => {- it("parses valid JSON payload", async () => {- const raw = await readFile("test/fixtures/user-prompt-submit.json", "utf8");- const parsed = parseUserPromptSubmitPayload(raw);- expect(parsed?.hook_event_name).toBe("UserPromptSubmit");- expect(parsed?.prompt).toContain("OMO_ULTRAGOAL_STEER");- });-- it("returns null for empty input", () => {- expect(parseUserPromptSubmitPayload("")).toBeNull();- });-- it("returns null for invalid JSON", () => {- expect(parseUserPromptSubmitPayload("{bad")).toBeNull();- });-- it("returns null when hook_event_name missing", () => {- expect(parseUserPromptSubmitPayload(JSON.stringify({ cwd: "/repo", prompt: "x", session_id: "s1" }))).toBeNull();- });-});--describe("applyUserPromptUltragoalSteering - OMO directive patterns", () => {- it("processes OMO_ULTRAGOAL_STEER: prompt and returns audit text on success", async () => {- const repoRoot = await bootstrapPlanRepo();- const out = await applyUserPromptUltragoalSteering(- payload(- 'OMO_ULTRAGOAL_STEER: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',- repoRoot,- ),- );- expect(out.length).toBeGreaterThan(0);- expect(out).toContain("annotate_ledger");- });-- it("processes omo.ultragoal.steer: pattern", async () => {- const repoRoot = await bootstrapPlanRepo();- const out = await applyUserPromptUltragoalSteering(- payload(- 'omo.ultragoal.steer: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',- repoRoot,- ),- );- expect(out).toContain("accepted");- });-- it("processes omo ultragoal steer: pattern", async () => {- const repoRoot = await bootstrapPlanRepo();- const out = await applyUserPromptUltragoalSteering(- payload(- 'omo ultragoal steer: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',- repoRoot,- ),- );- expect(out).toContain("annotate_ledger");- });-});--describe("applyUserPromptUltragoalSteering - non-matching prompts", () => {- it("returns empty string when no directive in prompt", async () => {- expect(await applyUserPromptUltragoalSteering(payload("just a normal user message", "/tmp"))).toBe("");- });-- it("returns empty for OMX_ULTRAGOAL_STEER (deprecated marker - must reject)", async () => {- expect(- await applyUserPromptUltragoalSteering(- payload('OMX_ULTRAGOAL_STEER: {"kind":"annotate_ledger","evidence":"x","rationale":"y"}', "/tmp"),- ),- ).toBe("");- });-- it("returns empty when hook_event_name is not UserPromptSubmit", async () => {- expect(await applyUserPromptUltragoalSteering(payloadWithRuntimeEvent("PostToolUse"))).toBe("");- });-});--describe("applyUserPromptUltragoalSteering - error swallowing", () => {- it("returns empty (never throws) when plan does not exist", async () => {- const repoRoot = await mkdtemp(join(tmpdir(), "ug-nohook-"));- const out = await applyUserPromptUltragoalSteering(- payload(- 'OMO_ULTRAGOAL_STEER: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',- repoRoot,- ),- );- expect(out).toBe("");- });-- it("returns empty when steering proposal is malformed JSON after marker", async () => {- const out = await applyUserPromptUltragoalSteering(payload("OMO_ULTRAGOAL_STEER: {bad", "/tmp"));- expect(out).toBe("");- });-});--describe("runUltragoalHookCli (stdin/stdout integration)", () => {- it("reads stdin, applies steering, writes audit to stdout", async () => {- const repoRoot = await bootstrapPlanRepo();- const stdin = Readable.from([- JSON.stringify(- payload(- 'OMO_ULTRAGOAL_STEER: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',- repoRoot,- ),- ),- ]);- const capture = captureStdout();- await runUltragoalHookCli(stdin, capture.stdout);- expect(capture.read().length).toBeGreaterThan(0);- });-- it("writes nothing when stdin is empty", async () => {- const capture = captureStdout();- await runUltragoalHookCli(Readable.from([""]), capture.stdout);- expect(capture.read()).toBe("");- });-});diff --git a/plugins/omo/components/ultragoal/test/fixtures/codex-goal-snapshot.json b/plugins/omo/components/ultragoal/test/fixtures/codex-goal-snapshot.jsondeleted file mode 100644index f88a3c5e..00000000--- a/plugins/omo/components/ultragoal/test/fixtures/codex-goal-snapshot.json+++ /dev/null@@ -1 +0,0 @@-{ "goal": { "objective": "Complete the durable ultragoal plan", "status": "active" } }diff --git a/plugins/omo/components/ultragoal/test/package-smoke.test.ts b/plugins/omo/components/ultragoal/test/package-smoke.test.tsdeleted file mode 100644index a1181e52..00000000--- a/plugins/omo/components/ultragoal/test/package-smoke.test.ts+++ /dev/null@@ -1,106 +0,0 @@-// biome-ignore-all format: smoke test pulls verbatim JSON for structural assertion.-import { readFile, stat } from "node:fs/promises";-import { dirname, join, resolve } from "node:path";-import { fileURLToPath } from "node:url";-import { describe, expect, it } from "vitest";--const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");--async function readText(relative: string): Promise<string> {- return readFile(join(repoRoot, relative), "utf8");-}--async function readJson(relative: string): Promise<unknown> {- return JSON.parse(await readText(relative));-}--describe("package.json", () => {- it("declares ESM + npm + Node >=20", async () => {- const pkg = await readJson("package.json") as Record<string, unknown>;- expect(pkg["type"]).toBe("module");- expect(pkg["packageManager"]).toBe("[email protected]");- expect((pkg["engines"] as Record<string, unknown>)["node"]).toBe(">=20.0.0");- });-- it("exposes the omo binary pointing at dist/cli.js", async () => {- const pkg = await readJson("package.json") as Record<string, unknown>;- const bin = pkg["bin"] as Record<string, string>;- expect(bin["omo"]).toBe("./dist/cli.js");- });-- it("ships the expected files for npm publish", async () => {- const pkg = await readJson("package.json") as Record<string, unknown>;- const files = pkg["files"] as readonly string[];- expect(files).toContain("dist");- expect(files).toContain("hooks");- expect(files).toContain("skills");- expect(files).not.toContain(".codex-plugin");- });-});--describe("component plugin identity", () => {- it("is owned by the aggregate OMO plugin root", async () => {- await expect(readText(".codex-plugin/plugin.json")).rejects.toMatchObject({ code: "ENOENT" });- });-});--describe("hooks/hooks.json", () => {- it("registers UserPromptSubmit with PLUGIN_ROOT interpolation", async () => {- const hooks = await readJson("hooks/hooks.json") as Record<string, unknown>;- const events = (hooks["hooks"] as Record<string, unknown>)["UserPromptSubmit"] as readonly Record<string, unknown>[];- expect(events.length).toBeGreaterThan(0);- const command = ((events[0]?.["hooks"] as readonly Record<string, unknown>[])[0]?.["command"]) as string;- expect(command).toContain(`$${"{PLUGIN_ROOT}"}`);- expect(command).toContain("dist/cli.js");- expect(command).toContain("hook user-prompt-submit");- });-});--describe("src/cli.ts", () => {- it("starts with #!/usr/bin/env node shebang", async () => {- const text = await readText("src/cli.ts");- expect(text.split("\n")[0]).toBe("#!/usr/bin/env node");- });-});--describe("skills/ultragoal/SKILL.md", () => {- it("exists", async () => {- const info = await stat(join(repoRoot, "skills/ultragoal/SKILL.md"));- expect(info.isFile()).toBe(true);- });-- it("contains no omx references", async () => {- const text = await readText("skills/ultragoal/SKILL.md");- expect(text.toLowerCase()).not.toContain("omx");- });-- it("references the success criteria and record-evidence vocabulary", async () => {- const text = await readText("skills/ultragoal/SKILL.md");- expect(text.toLowerCase()).toMatch(/success criteria|successcriteria/);- expect(text.toLowerCase()).toContain("record-evidence");- });-- it("uses the .omo workspace path", async () => {- const text = await readText("skills/ultragoal/SKILL.md");- expect(text).toContain(".omo/ultragoal");- });-});--describe("source LOC budget", () => {- it("every source file stays at or under 250 pure LOC", async () => {- const files = [- "src/types.ts", "src/paths.ts", "src/plan-io.ts", "src/plan-crud.ts", "src/goal-status.ts",- "src/evidence.ts", "src/quality-gate.ts", "src/checkpoint.ts", "src/review-blockers.ts",- "src/steering.ts", "src/codex-goal-instruction.ts", "src/codex-goal-snapshot.ts", "src/codex-hook.ts",- "src/cli.ts", "src/cli-arg-parser.ts", "src/cli-output.ts", "src/cli-steering.ts", "src/cli-commands.ts",- ];- for (const file of files) {- const text = await readText(file);- const pure = text.split("\n").filter((line) => {- const trimmed = line.trim();- return trimmed.length > 0 && !trimmed.startsWith("//");- }).length;- expect(pure, `${file} pure LOC`).toBeLessThanOrEqual(250);- }- });-});diff --git a/plugins/omo/components/ultragoal/test/paths.test.ts b/plugins/omo/components/ultragoal/test/paths.test.tsdeleted file mode 100644index aa35f460..00000000--- a/plugins/omo/components/ultragoal/test/paths.test.ts+++ /dev/null@@ -1,37 +0,0 @@-import { describe, expect, it } from "vitest";--import {- repoRelative,- ultragoalBriefPath,- ultragoalDir,- ultragoalGoalsPath,- ultragoalLedgerPath,-} from "../src/paths.ts";--describe("ultragoalDir(repo)", () => {- it("returns repo + '/.omo/ultragoal'", () => {- // when/then- expect(ultragoalDir("/repo")).toBe("/repo/.omo/ultragoal");- });-});--describe("ultragoal*Path helpers", () => {- it("compose artifact filenames under ultragoalDir", () => {- // when/then- expect(ultragoalBriefPath("/r")).toBe("/r/.omo/ultragoal/brief.md");- expect(ultragoalGoalsPath("/r")).toBe("/r/.omo/ultragoal/goals.json");- expect(ultragoalLedgerPath("/r")).toBe("/r/.omo/ultragoal/ledger.jsonl");- });-});--describe("repoRelative", () => {- it("strips repo prefix when path is inside repo", () => {- // when/then- expect(repoRelative("/repo/.omo/ultragoal/goals.json", "/repo")).toBe(".omo/ultragoal/goals.json");- });-- it("returns absolute when path is outside repo", () => {- // when/then- expect(repoRelative("/elsewhere/file", "/repo")).toBe("/elsewhere/file");- });-});diff --git a/plugins/omo/components/ultrawork/AGENTS.md b/plugins/omo/components/ultrawork/AGENTS.mdindex 9bc71b7f..e2f31484 100644--- a/plugins/omo/components/ultrawork/AGENTS.md+++ b/plugins/omo/components/ultrawork/AGENTS.md@@ -5,14 +5,18 @@ Conventions for human contributors and AI agents working on this repository.## Style- Terse technical prose. No emojis in commits, issues, PR comments, or code.-- Python: PEP 484 type hints. Hook script stays in standard-library only — no pip dependencies.-- Tabs for indentation in JSON and Markdown tables. Spaces (4) for Python.+- TypeScript strict mode. No `any`, no `@ts-ignore`, no `@ts-expect-error`, no enums, no non-null assertions.+- ESM modules with `.js` suffix in runtime import paths.+- Runtime is Node only because Codex launches plugin hooks with Node.+- Tabs for indentation in JSON, TypeScript, and Markdown tables.- Double quotes for JSON strings.## Layout-- `hooks/ultrawork-detector.py` — pure stdlib `UserPromptSubmit` hook. Reads JSON on stdin, writes the directive to stdout when the keyword matches, exits 0 otherwise.-- `agents/*.toml` — bundled Codex agent role files. Installed into `CODEX_HOME/agents/` by `src/cli/install-codex/link-cached-plugin-agents.ts` at install time (symlink on Unix, copy on Windows). No runtime `SessionStart` hook is involved.+- `src/cli.ts` — `UserPromptSubmit` hook CLI. Reads JSON on stdin, writes the directive to stdout when the keyword matches, exits 0 otherwise.+- `src/codex-hook.ts` — pure detector/hook behavior.+- `directive.md` — bundled ultrawork directive text.+- `agents/*.toml` — bundled Codex agent role files. Installed into `CODEX_HOME/agents/` by `src/cli/install-codex/link-cached-plugin-agents.ts` at install time (symlink on Unix, copy on Windows). Public `sisyphuslabs` installs source them from Codex's stable installed-marketplace snapshot, not the versioned plugin cache, so they survive Codex auto-update cache pruning. No runtime `SessionStart` hook is involved.- `hooks/hooks.json` — registers the prompt-detector hook only.- `.codex-plugin/plugin.json` — Codex plugin manifest. Marketplace metadata lives here, not in `package.json`.@@ -20,17 +24,18 @@ Conventions for human contributors and AI agents working on this repository.- Never let the hook block a turn — exit code is always 0.- Never make a network call from the hook.-- Keep the directive in `ULTRAWORK_DIRECTIVE` self-contained inside the Python file. The prompt hook is a single artifact a reviewer can read top-to-bottom.+- Keep the directive in `directive.md`. Do not inline it into TypeScript files.- Keep bundled agent role prompts concise and model-specific; measure prompt length when changing them.-- When editing `ULTRAWORK_DIRECTIVE`, apply the `prompt-engineering` skill's entropy gate: every edit must reduce uncertainty per token. Re-measure character count before committing.+- When editing `directive.md`, apply the `prompt-engineering` skill's entropy gate: every edit must reduce uncertainty per token. Re-measure character count before committing.## Commands```bash# smoke test the hookPAYLOAD='{"cwd":"/tmp","hook_event_name":"UserPromptSubmit","model":"gpt-5.5","permission_mode":"default","session_id":"x","transcript_path":"","turn_id":"y","prompt":"please ultrawork"}'-echo "$PAYLOAD" | python3 hooks/ultrawork-detector.py | head -3+npm run build+echo "$PAYLOAD" | node dist/cli.js hook user-prompt-submit | head -3# pattern boundary check (must be empty)-echo '{"hook_event_name":"UserPromptSubmit","prompt":"refactor ulw_helper.ts"}' | python3 hooks/ultrawork-detector.py | wc -c+echo '{"hook_event_name":"UserPromptSubmit","prompt":"refactor ulw_helper.ts"}' | node dist/cli.js hook user-prompt-submit | wc -c```diff --git a/plugins/omo/components/ultrawork/CHANGELOG.md b/plugins/omo/components/ultrawork/CHANGELOG.mdindex 0153a025..e36ecc27 100644--- a/plugins/omo/components/ultrawork/CHANGELOG.md+++ b/plugins/omo/components/ultrawork/CHANGELOG.md@@ -2,12 +2,13 @@## Unreleased+- Runtime hook migrated from `python3 hooks/ultrawork-detector.py` to the component-standard TypeScript build output `node dist/cli.js hook user-prompt-submit`, removing the Codex runtime dependency on Python.- New top-level **`# Manual-QA channels`** section explicitly enumerates the four real-usage channels the agent MUST verify through: (1) HTTP call, (2) tmux, (3) Browser use, (4) Computer use — each with concrete commands and the artifact to capture. Auxiliary surfaces (CLI stdout / DB diff / parsed config dump) only count for genuinely CLI- or data-shaped criteria.- Goal section now shouts **TESTS ALONE NEVER PROVE DONE**: a green test suite is supporting evidence, never completion proof. Every criterion needs its own real-usage scenario, built fresh and run through one of the four channels, every time.- Bootstrap criterion item 2 and execution step 4 collapse onto the new channel table to remove triple-enumeration of the same surfaces (single source of truth, less drift).- Execution loop step 4 (**SURFACE-AS-SCENARIO**) runs the chosen channel scenario; step 5 (**CLEANUP, PAIRED**) tears down server PIDs, `tmux` sessions, browser / Playwright contexts, containers, bound ports, temp files / dirs, QA-only env vars and records a one-line receipt. Missing receipt → criterion stays in_progress. Leftover state from QA = NOT done (Stop rule).-- Regression tests in `hooks/ultrawork-hooks.test.mjs` now pin: the four channel labels (`HTTP call`, `tmux`, `Browser use`, `Computer use`), `TESTS ALONE NEVER PROVE DONE`, `every criterion needs its own real-usage scenario`, the `# Manual-QA channels` heading, plus SURFACE-AS-SCENARIO + CLEANUP + leftover-state stop rule.-- Directive size: 11,005 chars across 232 lines.+- Regression tests in `test/codex-hook.test.ts` now pin: the four channel labels (`HTTP call`, `tmux`, `Browser use`, `Computer use`), `TESTS ALONE NEVER PROVE DONE`, `every criterion needs its own real-usage scenario`, the `# Manual-QA channels` heading, plus SURFACE-AS-SCENARIO + CLEANUP + leftover-state stop rule.+- Directive size: 10,951 chars across 231 lines.### Pre-cleanup unreleased entries (folded above)@@ -19,6 +20,6 @@Initial release.-- Codex `UserPromptSubmit` hook (`hooks/ultrawork-detector.py`) that detects `ultrawork` / `ulw` (word-bounded, case-insensitive) in the user prompt and injects the ultrawork orchestration directive.-- Directive enforces: goal + binding success criteria with manual-QA scenarios + evidence, durable `/tmp` notepad lifecycle, obsessive atomic todos, scenario-driven execution loop, and a GPT-5.2 xhigh verification gate with no "false positive" escape hatch.+- Codex `UserPromptSubmit` hook that detects `ultrawork` / `ulw` (word-bounded, case-insensitive) in the user prompt and injects the ultrawork orchestration directive.+- Directive enforces: goal + binding success criteria with manual-QA scenarios + evidence, durable `/tmp` notepad lifecycle, obsessive atomic todos, scenario-driven execution loop, and a ChatGPT-compatible xhigh verification gate with no "false positive" escape hatch.- Directive size: 5,775 chars across 143 lines.diff --git a/plugins/omo/components/ultrawork/README.md b/plugins/omo/components/ultrawork/README.mdindex 420ea31e..09b0ecde 100644--- a/plugins/omo/components/ultrawork/README.md+++ b/plugins/omo/components/ultrawork/README.md@@ -2,7 +2,7 @@Codex plugin that injects a compact orchestration directive (the **ultrawork** prompt) when the user prompt contains `ultrawork` or `ulw` (word-bounded, case-insensitive).-Bundled Codex agent role TOMLs in `agents/` are installed into `CODEX_HOME/agents/` by the omo-codex installer (`linkCachedPluginAgents`, in `src/cli/install-codex/link-cached-plugin-agents.ts`). Install-time linking uses symlinks on Linux / macOS and file copies on Windows. There is no Python `SessionStart` hook anymore.+Bundled Codex agent role TOMLs in `agents/` are installed into `CODEX_HOME/agents/` by the omo-codex installer (`linkCachedPluginAgents`, in `src/cli/install-codex/link-cached-plugin-agents.ts`). Install-time linking uses symlinks on Linux / macOS and file copies on Windows. For the public `sisyphuslabs` marketplace, those files point at Codex's stable installed-marketplace snapshot so they keep resolving after Codex prunes old plugin-cache versions. There is no runtime Python hook.## What the injected directive enforces@@ -13,9 +13,9 @@ Bundled Codex agent role TOMLs in `agents/` are installed into `CODEX_HOME/agent| Surface + paired cleanup | Execution loop step 4 (**SURFACE-AS-SCENARIO**) runs the chosen channel scenario end-to-end. Step 5 (**CLEANUP, PAIRED**) tears down every QA-spawned process / tmux session / browser context / container / port / temp dir, with a one-line receipt appended to the notepad. Leftover state → NOT done. || Durable /tmp notepad | `mktemp -t ulw-$(date +%Y%m%d-%H%M%S).XXXXXX.md` with sections `Plan`, `Success criteria + QA scenarios`, `Now`, `Todo`, `Findings`, `Learnings`. **Append**, never rewrite. || Obsessive atomic todos | Every action — even one-line edits, `ls`, single test runs — becomes a todo. Format: `path: <action> for <criterion> — verify by <check>`. One in_progress at a time, mark completed immediately. |-| GPT-5.2 xhigh verification gate | Triggered automatically on user-requested rigor, 3+ files, 20+ turns, 30+ minutes, or refactor/migration/perf/security work. Use the bundled `codex-ultrawork-reviewer` agent role when available. Reviewer verdict is **binding** — no "false positive", no minimising, no arguing. Loop until **unconditional** approval. "Looks good but…" = REJECTION. |+| ChatGPT-compatible xhigh verification gate | Triggered automatically on user-requested rigor, 3+ files, 20+ turns, 30+ minutes, or refactor/migration/perf/security work. Use the bundled `codex-ultrawork-reviewer` agent role when available. Reviewer verdict is **binding**: no "false positive", no minimising, no arguing. Loop until **unconditional** approval. "Looks good but..." = REJECTION. |-The directive is currently 11,005 chars / 232 lines and follows the GPT-5.5 prompting structure (Role / Goal / Manual-QA channels / Bootstrap / Execution loop / Verification gate / Commits / Constraints / Output / Stop rules).+The directive is currently 10,951 chars / 231 lines and follows the GPT-5.5 prompting structure (Role / Goal / Manual-QA channels / Bootstrap / Execution loop / Verification gate / Commits / Constraints / Output / Stop rules).## Install (via this marketplace)@@ -23,32 +23,33 @@ The directive is currently 11,005 chars / 232 lines and follows the GPT-5.5 promnpx lazycodex-ai install```-The installer copies the plugin into `~/.codex/plugins/cache/sisyphuslabs/omo/0.1.0`, registers the `sisyphuslabs` marketplace from the `lazycodex` Git repository, enables `omo@sisyphuslabs` in `~/.codex/config.toml`, registers the `UserPromptSubmit` hook, and installs the bundled agent TOMLs into `~/.codex/agents/` (symlinks on Unix, copies on Windows). A manifest at `<plugin-cache>/.installed-agents.json` records the installed paths for clean uninstall.+The installer copies the plugin into `~/.codex/plugins/cache/sisyphuslabs/omo/0.1.0`, writes the stable Codex marketplace snapshot at `~/.codex/.tmp/marketplaces/sisyphuslabs/`, registers the `sisyphuslabs` marketplace from the `lazycodex` Git repository, enables `omo@sisyphuslabs` in `~/.codex/config.toml`, registers the `UserPromptSubmit` hook, and installs the bundled agent TOMLs into `~/.codex/agents/` (symlinks on Unix, copies on Windows). A `.installed-agents.json` manifest is written next to the bundled TOMLs' source root for clean uninstall tracking.## How it works`hooks/hooks.json` registers a `UserPromptSubmit` hook running:```-python3 ${PLUGIN_ROOT}/hooks/ultrawork-detector.py+node ${PLUGIN_ROOT}/dist/cli.js hook user-prompt-submit```Codex passes the prompt payload on stdin. When the pattern `\b(?:ultrawork|ulw)\b` (case-insensitive) matches, the hook writes the directive to stdout — Codex injects non-JSON stdout as `additional_context` for the next turn. Otherwise the hook writes nothing and exits 0. Malformed input also exits 0 to never block the turn.-Bundled agent role TOMLs in `agents/` ship to `CODEX_HOME/agents/` at install time, not via a runtime hook. The installer creates a symlink on Linux / macOS (so the cache directory is the single source of truth and removal of the cache cleanly breaks the link) and a file copy on Windows (because symlinks require admin privileges or Developer Mode). Both code paths overwrite stale files and write a `.installed-agents.json` manifest under the plugin cache for clean uninstall tracking.+Bundled agent role TOMLs in `agents/` ship to `CODEX_HOME/agents/` at install time, not via a runtime hook. The installer creates a symlink on Linux / macOS and a file copy on Windows (because symlinks require admin privileges or Developer Mode). For the public marketplace, the source is the stable installed-marketplace snapshot, not the versioned plugin cache, so agent role configs remain valid when Codex replaces `~/.codex/plugins/cache/sisyphuslabs/omo/<version>/` during auto-update. Both code paths overwrite stale files and write a `.installed-agents.json` manifest next to the source root for clean uninstall tracking.## Smoke test```bashPAYLOAD='{"cwd":"/tmp","hook_event_name":"UserPromptSubmit","model":"gpt-5.5","permission_mode":"default","session_id":"x","transcript_path":"","turn_id":"y","prompt":"please ultrawork"}'-echo "$PAYLOAD" | python3 hooks/ultrawork-detector.py | head -3+npm run build+echo "$PAYLOAD" | node dist/cli.js hook user-prompt-submit | head -3```Expect `<ultrawork-mode>` ... directive body.## Agent role smoke test-Run `npx --yes --package oh-my-openagent omo install --platform=codex`, then inspect `~/.codex/agents/`. On Linux / macOS you should see symlinks; on Windows you should see file copies. Each TOML should declare a non-empty `name`, `description`, and `developer_instructions`.+Run `npx lazycodex-ai install`, then inspect `~/.codex/agents/`. On Linux / macOS you should see symlinks; on Windows you should see file copies. Each TOML should declare a non-empty `name`, `description`, and `developer_instructions`.## Licensediff --git a/plugins/omo/components/ultrawork/agents/codex-ultrawork-reviewer.toml b/plugins/omo/components/ultrawork/agents/codex-ultrawork-reviewer.tomlindex c7af592a..1f334aa4 100644--- a/plugins/omo/components/ultrawork/agents/codex-ultrawork-reviewer.toml+++ b/plugins/omo/components/ultrawork/agents/codex-ultrawork-reviewer.toml@@ -1,13 +1,16 @@name = "codex-ultrawork-reviewer"description = "Strict ultrawork verification reviewer. Use after full QA evidence to audit the diff, goal, and scenario evidence before declaring done."nickname_candidates = ["Verifier"]-model = "gpt-5.2"+model = "gpt-5.5"model_reasoning_effort = "xhigh"developer_instructions = """You are the ultrawork verification reviewer.Review only. Do not implement.+The default model intentionally uses a ChatGPT account compatible frontier model. If a caller supplies a different supported reviewer model, follow the caller's assignment while preserving this review contract.+Input should include the goal, success criteria, full diff, QA evidence, and notepad path.+If Codex delivers parent review context as inter-agent commentary, treat the latest parent message with goal/diff/evidence as your active review assignment, not passive context.Verdict rules:- Return `UNCONDITIONAL APPROVAL` only when the diff satisfies every success criterion and the evidence proves the real surface works.diff --git a/plugins/omo/components/ultrawork/agents/explorer.toml b/plugins/omo/components/ultrawork/agents/explorer.tomlindex 638b55ed..1c946a3d 100644--- a/plugins/omo/components/ultrawork/agents/explorer.toml+++ b/plugins/omo/components/ultrawork/agents/explorer.toml@@ -63,7 +63,7 @@ Fire 3+ independent calls in the first action. Cross-validate findings across mu- Both `<analysis>` and `<results>` blocks are present.# Constraints-- READ-ONLY. Tools I will NEVER call: `edit`, `write`, `apply_patch`, anything that mutates the filesystem, anything that spawns another agent (`task`, `spawn_agent`, `call_*_agent`).+- READ-ONLY. Tools I will NEVER call: `edit`, `write`, `apply_patch`, anything that mutates the filesystem.- NEVER create files. Report findings as message text only - no scratch files, no notes on disk, no temp dumps.- Do not browse the internet. External research is the librarian's job.- No emojis. Keep output clean and parseable.diff --git a/plugins/omo/components/ultrawork/agents/librarian.toml b/plugins/omo/components/ultrawork/agents/librarian.tomlindex 5327e093..422ef00d 100644--- a/plugins/omo/components/ultrawork/agents/librarian.toml+++ b/plugins/omo/components/ultrawork/agents/librarian.toml@@ -55,7 +55,7 @@ If the user names a version ("React 18", "Next.js 14", "v2.x"):## Step 4 - targeted investigation- `webfetch(<specific-doc-page-from-sitemap>)`.-- If a docs-indexer / library-index tool is available, query it for the specific topic. Otherwise rely on the sitemap-driven webfetch pages.+- 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.@@ -70,7 +70,7 @@ If the user names a version ("React 18", "Next.js 14", "v2.x"):Run Phase 0.5 first, then in parallel:- `web_search` for current-year usage examples + best practices.- `webfetch` for the targeted doc pages identified by the sitemap.-- `gh search code "<usage pattern>" --language <lang>` for real-world code samples.+- `grep_app` for broad GitHub code search; fall back to `gh search code "<usage pattern>" --language <lang>`.## TYPE B - IMPLEMENTATION REFERENCEExecute in sequence:@@ -81,9 +81,9 @@ Execute in sequence:Parallel acceleration (4+ calls in one batch when independent):- Shallow clone.-- `gh search code "<function-name>" --repo <owner>/<repo>`.+- `grep_app` broad code search or `gh search code "<function-name>" --repo <owner>/<repo>`.- `gh api repos/<owner>/<repo>/commits/HEAD --jq '.sha'`.-- Sitemap-targeted `webfetch` of the relevant docs page for the same API surface.+- `context7` or sitemap-targeted `webfetch` of the relevant docs page for the same API surface.## TYPE C - CONTEXT & HISTORYExecute in parallel (4+ calls):@@ -100,7 +100,7 @@ For a specific issue / PR:## TYPE D - COMPREHENSIVERun Phase 0.5 first, then execute 6+ parallel calls:- 2 docs calls: `webfetch` targeted doc pages + (if available) a docs-indexer query.-- 2 code-search calls: `gh search code` with varied queries (different angles).+- 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.@@ -147,8 +147,9 @@ Never link to a branch name (`/blob/main/...`) - always pin to a SHA so the line- Sitemap -> `webfetch(<base>/sitemap.xml)` (fallbacks: `/sitemap-0.xml`, `/sitemap_index.xml`).- Read a specific page -> `webfetch(<page-url>)`.- Latest info -> `web_search("<query> <CURRENT_YEAR>")`.-- Code search (fast, broad) -> `gh search code "<query>" --language <lang>` (org-wide or repo-scoped).-- Code search (deep, repo-scoped) -> after cloning, `rg` / `ast_grep_search` over the clone.+- 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`.@@ -204,7 +205,7 @@ gh search code "useQuery"# CONSTRAINTS-- READ-ONLY. Tools I will NEVER call: `edit`, `write`, `apply_patch`, anything that mutates the working-tree filesystem, anything that spawns another agent (`task`, `spawn_agent`, `call_*_agent`). Cloning into `${TMPDIR:-/tmp}` is allowed; cloning into the working tree is not.+- 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.diff --git a/plugins/omo/components/ultrawork/agents/metis.toml b/plugins/omo/components/ultrawork/agents/metis.tomlnew file mode 100644index 00000000..02628d6c--- /dev/null+++ b/plugins/omo/components/ultrawork/agents/metis.toml@@ -0,0 +1,65 @@+name = "metis"+description = "Pre-planning analyst. Detects contradictions, ambiguity, missing constraints, and execution risks in a draft plan or request before the planner commits. Read-only."+nickname_candidates = ["Analyst"]+model = "gpt-5.5"+model_reasoning_effort = "high"+service_tier = "fast"++developer_instructions = """+Role: pre-planning analyst. You examine a draft plan or vague request and surface contradictions, ambiguity, missing constraints, and execution risks BEFORE the planner finalizes. Read-only — you never write plans or code.++# Goal+Produce a structured gap report the planner uses to patch the plan in one pass. Every finding must be specific enough that the planner can act on it without further clarification.++# Success criteria+- Every contradiction between stated requirements is cited with the two conflicting sentences.+- Every ambiguous term that would force the executor to guess is named, with a concrete clarifying question.+- Every missing constraint that a senior engineer would ask about is listed (error handling, auth, concurrency, rollback, test strategy).+- Every execution risk (missing file references, unreachable acceptance criteria, vague QA scenarios) is flagged with a suggested fix.+- Brownfield context: if the work modifies an existing codebase, flag integration risks with existing patterns, naming, and registration conventions.++# What you check++**Contradictions**: two requirements that cannot both be true. Cite both sentences. Example: scope says "no database changes" but a task adds a migration.++**Ambiguity**: a term the executor would need to guess. Name the term, state why it is ambiguous, suggest a clarifying question. Example: "real-time" — polling interval? WebSocket? SSE?++**Missing constraints**: things a senior engineer would demand before starting. Auth model, error handling strategy, concurrency bounds, rollback plan, test framework, deployment target.++**Execution risks**: file references that may not exist, acceptance criteria that cannot be verified by an agent, QA scenarios that say "verify it works" instead of naming a tool + steps + expected result.++**Topology gaps**: if the request spans multiple independent components, flag any component that lacks goal clarity, constraints, or acceptance criteria.++# Constraints+- Read-only. Never write, edit, or mutate files.+- Inspect the codebase before flagging risks — cite file paths when a referenced pattern exists or is missing.+- No numeric scoring or ambiguity formulas. Qualitative assessment only.+- No design opinions. Flag gaps, not preferences.+- Findings must be actionable — "Task 3 is vague" is not actionable. "Task 3 says 'add auth' without specifying JWT vs session vs OAuth — ask the user" is.++# Output+```+## Contradictions+- [contradiction with both cited sentences, or "None found"]++## Ambiguity+- [term]: [why ambiguous] — suggested question: [question]++## Missing Constraints+- [constraint]: [why it matters]++## Execution Risks+- [risk]: [suggested fix]++## Topology Gaps+- [component]: [what is missing]++## Verdict+[CLEAR — no blocking gaps] or [GAPS FOUND — N issues above must be resolved before plan generation]+```++# Stop rules+- Stop after one pass. Do not loop or re-analyze.+- If the input is already a clean plan with no gaps, say CLEAR and stop.+- Do not invent problems. Report only gaps that would block a competent executor.+"""diff --git a/plugins/omo/components/ultrawork/agents/momus.toml b/plugins/omo/components/ultrawork/agents/momus.tomlnew file mode 100644index 00000000..d9dc627b--- /dev/null+++ b/plugins/omo/components/ultrawork/agents/momus.toml@@ -0,0 +1,69 @@+name = "momus"+description = "Plan reviewer. Verifies a work plan is executable: references exist, tasks are startable, QA scenarios are concrete. Issues OKAY, ITERATE, or REJECT. Read-only."+nickname_candidates = ["Reviewer"]+model = "gpt-5.5"+model_reasoning_effort = "xhigh"+service_tier = "fast"++developer_instructions = """+Role: plan reviewer. You verify that a work plan is executable and references are valid. You are a blocker-finder, not a perfectionist. Read-only — you never write plans or code.++# Goal+Answer one question: "Can a capable developer execute this plan without getting stuck?"++# Success criteria+- Referenced files verified to exist and contain claimed content.+- Every task has enough context to start working.+- No blocking contradictions or impossible requirements.+- Every task has executable QA scenarios with tool + steps + expected result.+- Verdict issued: OKAY, ITERATE, or REJECT with max 3 specific issues.++# What you check (only these four)++**Reference verification**: Do referenced files exist? Do line numbers contain relevant code? If "follow pattern in X" is mentioned, does X demonstrate that pattern? PASS if the reference exists and is reasonably relevant. FAIL only if it does not exist or points to completely wrong content.++**Executability**: Can a developer START working on each task? Is there at least a starting point? PASS if some details need figuring out during implementation. FAIL only if the task is so vague the developer has no idea where to begin.++**Critical blockers**: Missing information that would COMPLETELY STOP work. Contradictions that make the plan impossible to follow. Missing edge case handling, stylistic preferences, and "could be clearer" suggestions are NOT blockers.++**QA scenario executability**: Does each task have QA scenarios with a specific tool, concrete steps, and expected results? Missing or vague QA scenarios ("verify it works", "check the page") ARE blockers because they prevent the Final Verification Wave.++# What you do NOT check+Whether the approach is optimal, whether there is a better way, whether all edge cases are documented, architecture quality, code quality, performance, or security unless explicitly broken.++# Decision framework++**OKAY** (default): Referenced files exist. Tasks have enough context to start. No contradictions. A capable developer could make progress. When in doubt, approve — 80% clear is good enough.++**ITERATE**: The plan is basically valid but has up to 3 fixable gaps. Each gap can be patched by the planner without asking the user. Examples: missing file reference that exists elsewhere, vague QA scenario that can be made concrete, task missing a commit instruction. The planner fixes the cited issues and resubmits. Max 2 auto-fix rounds before escalating to the user.++**REJECT**: Referenced file does not exist (verified by reading). Task is completely impossible to start (zero context). Plan contains internal contradictions. A user decision is needed that the planner cannot make alone. REJECT means stop and surface the issue to the user.++# Constraints+- Read-only. Never write, edit, or mutate files.+- Approval bias: when in doubt, APPROVE.+- Maximum 3 issues per ITERATE or REJECT.+- No design opinions. The author's approach is not your concern.+- Parallelize independent file reads when verifying references.+- Do not narrate routine reads. Move directly to the verdict.++# Output+**[OKAY]** or **[ITERATE]** or **[REJECT]**++**Summary**: 1-2 sentences explaining the verdict.++If ITERATE or REJECT — **Issues** (max 3):+1. [Specific issue + what needs to change]+2. [Specific issue + what needs to change]+3. [Specific issue + what needs to change]++ITERATE issues must be directly patchable by the planner. REJECT issues must explain what user decision or input is missing.++# Stop rules+- Approve by default. Reject only for true blockers.+- Max 3 issues. More is overwhelming and counterproductive.+- Be specific: "Task X needs Y", not "needs more clarity".+- Trust developers. They can figure out minor gaps.+- Your job is to UNBLOCK work, not to BLOCK it with perfectionism.+- Response language: match the language of the plan content.+"""diff --git a/plugins/omo/components/ultrawork/agents/plan.toml b/plugins/omo/components/ultrawork/agents/plan.tomlindex d54b78df..919f3d0a 100644--- a/plugins/omo/components/ultrawork/agents/plan.toml+++ b/plugins/omo/components/ultrawork/agents/plan.toml@@ -1,5 +1,5 @@name = "plan"-description = "Strategic planning consultant. Produces a single executable work plan from a vague or large request. Planner only - never implements. Writes the plan to plans/<slug>.md."+description = "Strategic planning consultant. Produces a single executable work plan from a vague or large request. Planner only - never implements. Writes the plan to .omo/plans/<slug>.md."nickname_candidates = ["Planner"]model = "gpt-5.5"model_reasoning_effort = "xhigh"@@ -29,13 +29,14 @@ Never plan blind. Fire parallel research BEFORE drafting:- Spawn parallel read-only subagents for internal-source aspects (codebase patterns, conventions, existing implementations, test infrastructure, naming/registration patterns). One subagent per aspect.- Spawn parallel read-only subagents for external-source aspects (official docs, OSS reference implementations, API contracts, RFCs). One subagent per aspect.- While they run, use direct read-only tools (`read`, `rg`, `ast_grep_search`, `lsp_*`) for immediate context. Do not idle.-- The role's own system prompt determines each subagent's output shape. Do not re-specify it; pass only the question, context you have, and what decision the answer informs.+- 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. Treat `wait_agent` as a signal, not proof; if a child is silent or ack-only after one targeted followup, mark that lane inconclusive and answer from direct evidence or respawn smaller.Wait for context to converge before drafting. Rushed plans fail.# Phase 2 - Plan output (single markdown file, single plan)-Write the plan to `plans/<slug>.md` in the working tree (create the `plans/` directory if absent). One plan per request - no "Phase 1 plan / Phase 2 plan" splits. 50+ tasks is fine if the work demands it.+Write the plan to `.omo/plans/<slug>.md` in the working tree (create the `.omo/plans/` directory if absent). One plan per request - no "Phase 1 plan / Phase 2 plan" splits. 50+ tasks is fine if the work demands it.Use this template verbatim (fill the placeholders):@@ -59,7 +60,7 @@ Use this template verbatim (fill the placeholders):> Zero human intervention - all verification is agent-executed.- Test decision: <TDD | tests-after | none> + framework- QA policy: every task has agent-executed scenarios-- Evidence: `evidence/task-<N>-<slug>.<ext>`+- Evidence: `.omo/evidence/task-<N>-<slug>.<ext>`## Execution strategy### Parallel execution waves@@ -107,18 +108,19 @@ Critical path: Task 1 -> Task 2 -> Task 6- [ ] <verifiable condition with the exact command or assertion>QA scenarios (MANDATORY - task incomplete without these):+ > Name the exact tool AND its exact invocation - not "verify it works". Browser use: use Chrome to drive the page; if Chrome is not available, download and use agent-browser (https://github.com/vercel-labs/agent-browser). Computer use: OS-level GUI automation for a non-browser desktop app.```Scenario: <happy path>- Tool: <bash | curl | tmux | playwright | ...>- Steps: <exact actions with specific inputs>- Expected: <concrete, binary pass/fail>- Evidence: evidence/task-<N>-<slug>.<ext>+ Tool: <bash | curl | tmux | playwright(real Chrome) | agent-browser | computer-use>+ Steps: <exact command / API call / page action with concrete inputs - URL, payload, keystrokes, selectors>+ Expected: <concrete, binary pass/fail observable>+ Evidence: .omo/evidence/task-<N>-<slug>.<ext>Scenario: <failure / edge case>- Tool: <same>- Steps: <trigger the error>+ Tool: <same, with exact invocation>+ Steps: <trigger the error with specific inputs>Expected: <graceful failure with the exact error message/code>- Evidence: evidence/task-<N>-<slug>-error.<ext>+ Evidence: .omo/evidence/task-<N>-<slug>-error.<ext>```Commit: <YES|NO> | Message: `<type>(<scope>): <imperative summary>` | Files: [<paths>]@@ -134,14 +136,14 @@ Critical path: Task 1 -> Task 2 -> Task 6- One logical change per commit. Conventional Commits (`<type>(<scope>): <subject>` body + footer).- Atomic: every commit builds and passes tests on its own.- No "WIP" / "fix typo squash later" commits on the final branch - clean up before merge.-- Reference the plan file path in the final commit footer: `Plan: plans/<slug>.md`.+- Reference the plan file path in the final commit footer: `Plan: .omo/plans/<slug>.md`.## Success criteria- All Must-Have shipped; all QA scenarios pass with captured evidence; F1-F4 approved; commit history clean.```# Constraints-- READ + plan-file write only. Tools I will NEVER call: `edit`/`write`/`apply_patch` on anything outside `plans/<slug>.md`, anything that mutates non-plan files, anything that spawns another planner.+- READ + plan-file write only. Tools I will NEVER call: `edit`/`write`/`apply_patch` on anything outside `.omo/plans/<slug>.md`, anything that mutates non-plan files.- DO NOT split work into multiple plans. ONE plan per request.- DO NOT skip context gathering. NEVER plan blind.- DO NOT include "user manually tests" as an acceptance criterion. Every check must be agent-executable.diff --git a/plugins/omo/components/ultragoal/biome.json b/plugins/omo/components/ultrawork/biome.jsonsimilarity index 100%rename from plugins/omo/components/ultragoal/biome.jsonrename to plugins/omo/components/ultrawork/biome.jsondiff --git a/plugins/omo/components/ultrawork/hooks/ultrawork-detector.py b/plugins/omo/components/ultrawork/directive.mdold mode 100755new mode 100644similarity index 70%rename from plugins/omo/components/ultrawork/hooks/ultrawork-detector.pyrename to plugins/omo/components/ultrawork/directive.mdindex 45623a9f..a1644ff0--- a/plugins/omo/components/ultrawork/hooks/ultrawork-detector.py+++ b/plugins/omo/components/ultrawork/directive.md@@ -1,28 +1,4 @@-#!/usr/bin/env python3-"""Codex UserPromptSubmit hook: inject ultrawork directive on `ulw`/`ultrawork`.--Contract (required for codex hooks runtime):- stdin: JSON {cwd, hook_event_name="UserPromptSubmit", model,- permission_mode, prompt, session_id, transcript_path, turn_id}- stdout: when the user prompt matches the ultrawork keyword, the directive- text below; otherwise empty. Non-JSON stdout is treated by codex as- `additional_context` and injected into the model's turn context.- exit: 0 always (this hook never blocks the turn).-"""--from __future__ import annotations--import json-import re-import sys-from typing import cast---# `\b(?:ultrawork|ulw)\b` — word-bounded match excludes paths and identifiers.-ULTRAWORK_PATTERN = re.compile(r"\b(?:ultrawork|ulw)\b", re.IGNORECASE)---ULTRAWORK_DIRECTIVE = """<ultrawork-mode>+<ultrawork-mode>**MANDATORY**: First user-visible line this turn MUST be exactly:`ULTRAWORK MODE ENABLED!`@@ -55,11 +31,23 @@ The full test suite being green is NEVER verification on its own.2. tmux — `tmux new-session -d -s ulw-qa-<criterion>`, drive with`send-keys`, dump via `tmux capture-pane -pS -E -`; transcriptis the artifact.- 3. Browser use — drive the real page via Playwright / puppeteer /- Chromium; capture action log + screenshot path.- 4. Computer use — OS-level GUI automation (computer-use agent,+ 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.+ action log + screenshot. USE THIS for any non-browser GUI+ criterion; do not substitute a CLI dump for it.++For EVERY scenario name the exact tool and the exact invocation+upfront: the literal command / API call / page action with its concrete+inputs (URL, payload, keystrokes, selectors) and the single binary+observable that decides PASS vs FAIL. "run the endpoint", "open the+page", "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 configdump) are valid evidence when the criterion is genuinely CLI- or@@ -67,7 +55,22 @@ data-shaped, but they do NOT replace a channel scenario for anyuser-facing behavior. `--dry-run`, printing the command, "shouldrespond", and "looks correct" never count.-# Bootstrap (DO ALL THREE BEFORE ANY OTHER WORK — NO SKIPPING)+# 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.## 1. Create the goal with binding success criteriaCall `create_goal` (or open your reply with a `# Goal` block treated as@@ -159,7 +162,11 @@ Until every success-criteria scenario PASSES with BOTH evidence pieces:the top). Actually invoke it end-to-end — the unit suite beinggreen is NEVER substitute. Paste the artifact path into thenotepad.-5. CLEANUP (PAIRED — NEVER SKIP): every runtime artifact the QA+5. CLEANUP (PAIRED — NEVER SKIP): the moment a QA scenario spawns any+ resource, 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 QAspawned 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`),@@ -179,19 +186,46 @@ Until every success-criteria scenario PASSES with BOTH evidence pieces: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+`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+required; paste only the context the child needs. Full-history forks can+make the child continue old parent context instead of the delegated task.++Do not use `list_agents` as a polling or status tool in long or+high-context runs; it can replay large agent status and latest-message+payloads. Track spawned agent names locally. 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. Use `wait_agent` for completion+signals, but treat `wait_agent` as a mailbox signal, not proof of+completion, content, or errors. A worker/reviewer counts only after you+receive substantive output and verify its diff/evidence.+After two waits with no substantive result, send one targeted followup:+`TASK STILL ACTIVE: return <deliverable> or BLOCKED: <reason>`. If it is+still silent or ack-only, record the result as inconclusive, do not+count it as approval/pass, close it if safe, and respawn a smaller+`fork_turns: "none"` task with the missing deliverable. Use targeted+followups only when needed, and `close_agent` after integrating each+result.+# Verification gate (TRIGGERED, NOT OPTIONAL)Trigger when ANY apply:-- User said "strictly", "rigorously", "properly review", or- explicitly demanded review.+- 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 "deeply".+ anything the user called deep.Procedure (NON-NEGOTIABLE):-1. Spawn agent_type `codex-ultrawork-reviewer` (or any `gpt-5.2`- xhigh reviewer if unavailable). Pass: goal, success-criteria,- scenario evidence, full diff, notepad path.+1. Spawn `agent_type="codex-ultrawork-reviewer"` with+ `fork_turns: "none"`. If unavailable, spawn `agent_type="worker"`+ with a self-contained reviewer assignment and tight scope. `model` ++ `reasoning_effort` alone creates a default agent, not a reviewer.+ Pass: goal, success-criteria, scenario evidence, full diff, notepad+ path.2. Treat the reviewer's verdict as binding. There is NO "falsepositive". Every concern is real. Do not argue. Do not minimise. Donot explain it away.@@ -207,7 +241,7 @@ Atomic, Conventional Commits (`<type>(<scope>): <imperative>` — feat /fix / refactor / test / docs / chore / build / ci / perf). One logicalchange per commit; each commit builds + tests green on its own. No WIPon the final branch. If a plan file exists, final commit footer:-`Plan: plans/<slug>.md`. Do NOT auto-`git commit` unless the user+`Plan: .omo/plans/<slug>.md`. Do NOT auto-`git commit` unless the userrequested or preauthorised this session — default is stage + draftmessage + present for approval.@@ -253,42 +287,4 @@ message + present for approval.- After 2 parallel exploration waves yield no new useful facts, stopexploring and act.-</ultrawork-mode>"""---def _load_payload() -> dict[str, object] | None:- try:- raw = sys.stdin.read()- except (OSError, ValueError):- return None- if not raw.strip():- return None- try:- parsed = cast(object, json.loads(raw))- except json.JSONDecodeError:- return None- if not isinstance(parsed, dict):- return None- values = cast(dict[object, object], parsed)- return {str(k): v for k, v in values.items()}---def _should_inject(payload: dict[str, object]) -> bool:- if payload.get("hook_event_name") != "UserPromptSubmit":- return False- prompt = payload.get("prompt")- if not isinstance(prompt, str) or not prompt:- return False- return ULTRAWORK_PATTERN.search(prompt) is not None---def main() -> None:- payload = _load_payload()- if payload is not None and _should_inject(payload):- _ = sys.stdout.write(ULTRAWORK_DIRECTIVE)- _ = sys.stdout.flush()- sys.exit(0)---if __name__ == "__main__":- main()+</ultrawork-mode>diff --git a/plugins/omo/components/ultrawork/hooks/hooks.json b/plugins/omo/components/ultrawork/hooks/hooks.jsonindex af24adb7..3f1efcd9 100644--- a/plugins/omo/components/ultrawork/hooks/hooks.json+++ b/plugins/omo/components/ultrawork/hooks/hooks.json@@ -5,8 +5,9 @@"hooks": [{"type": "command",- "command": "python3 \"${PLUGIN_ROOT}/hooks/ultrawork-detector.py\"",- "timeout": 5+ "command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit",+ "timeout": 5,+ "statusMessage": "LazyCodex(0.1.0): Checking Ultrawork Trigger"}]}diff --git a/plugins/omo/components/ultrawork/hooks/ultrawork-hooks.test.mjs b/plugins/omo/components/ultrawork/hooks/ultrawork-hooks.test.mjsdeleted file mode 100644index dc332891..00000000--- a/plugins/omo/components/ultrawork/hooks/ultrawork-hooks.test.mjs+++ /dev/null@@ -1,169 +0,0 @@-import assert from "node:assert/strict";-import { spawn } from "node:child_process";-import { readFile } from "node:fs/promises";-import { dirname, join } from "node:path";-import { fileURLToPath } from "node:url";-import test from "node:test";--const hookDir = dirname(fileURLToPath(import.meta.url));-const pluginRoot = dirname(hookDir);-const detectorPath = join(hookDir, "ultrawork-detector.py");--async function runPython(scriptPath, input, env = {}) {- return new Promise((resolve, reject) => {- const child = spawn("python3", [scriptPath], {- env: {- ...process.env,- ...env,- },- });- let stdout = "";- let stderr = "";- child.stdout.setEncoding("utf8");- child.stderr.setEncoding("utf8");- child.stdout.on("data", (chunk) => {- stdout += chunk;- });- child.stderr.on("data", (chunk) => {- stderr += chunk;- });- child.once("error", reject);- child.once("close", (code, signal) => {- resolve({ code, signal, stdout, stderr });- });- child.stdin.end(input);- });-}--test("#given ultrawork prompt #when detector runs #then emits directive", async () => {- const payload = JSON.stringify({- hook_event_name: "UserPromptSubmit",- prompt: "please ulw this change",- });-- const result = await runPython(detectorPath, payload);-- assert.equal(result.code, 0);- assert.equal(result.signal, null);- assert.equal(result.stderr, "");- assert.match(result.stdout, /^<ultrawork-mode>/);- assert.match(result.stdout, /First user-visible line this turn MUST be exactly:/);-});--test("#given ultrawork prompt #when detector runs #then directive keeps goal budget unlimited", async () => {- const payload = JSON.stringify({- hook_event_name: "UserPromptSubmit",- prompt: "please ultrawork this change",- });-- const result = await runPython(detectorPath, payload);-- assert.equal(result.code, 0);- assert.equal(result.signal, null);- assert.equal(result.stderr, "");- assert.match(result.stdout, /Goals are\s+unlimited/);- assert.match(result.stdout, /exactly `objective` and `status` fields/);- assert.doesNotMatch(result.stdout, /token[_-]?budget/i);- assert.doesNotMatch(result.stdout, /200000/i);-});--test("#given ultrawork prompt #when detector runs #then directive mandates manual-QA-as-scenario for http/tmux/computer-use", async () => {- const payload = JSON.stringify({- hook_event_name: "UserPromptSubmit",- prompt: "please ultrawork",- });-- const result = await runPython(detectorPath, payload);-- assert.equal(result.code, 0);- assert.equal(result.stderr, "");- assert.match(result.stdout, /SURFACE-AS-SCENARIO/);- assert.match(result.stdout, /MANUAL QA \u2014 YOU EXECUTE IT, NO STUBS/);- assert.match(result.stdout, /curl -i/);- assert.match(result.stdout, /tmux new-session/);-});--test("#given ultrawork prompt #when detector runs #then directive enumerates 4 manual-QA channels explicitly", async () => {- const payload = JSON.stringify({- hook_event_name: "UserPromptSubmit",- prompt: "please ultrawork",- });-- const result = await runPython(detectorPath, payload);-- assert.equal(result.code, 0);- assert.equal(result.stderr, "");- assert.match(result.stdout, /# Manual-QA channels/);- assert.match(result.stdout, /PICK ONE PER CRITERION \u2014 ACTUALLY RUN IT/);- assert.match(result.stdout, /1\. HTTP call/);- assert.match(result.stdout, /2\. tmux/);- assert.match(result.stdout, /3\. Browser use/);- assert.match(result.stdout, /4\. Computer use/);-});--test("#given ultrawork prompt #when detector runs #then directive forbids tests-alone verification", async () => {- const payload = JSON.stringify({- hook_event_name: "UserPromptSubmit",- prompt: "please ultrawork",- });-- const result = await runPython(detectorPath, payload);-- assert.equal(result.code, 0);- assert.equal(result.stderr, "");- assert.match(result.stdout, /TESTS ALONE NEVER PROVE DONE/);- assert.match(result.stdout, /Every[\s\n]+criterion needs its own real-usage scenario/);- assert.match(result.stdout, /every time/);-});--test("#given ultrawork prompt #when detector runs #then directive mandates paired cleanup with receipt and leftover-state stop rule", async () => {- const payload = JSON.stringify({- hook_event_name: "UserPromptSubmit",- prompt: "please ultrawork",- });-- const result = await runPython(detectorPath, payload);-- assert.equal(result.code, 0);- assert.equal(result.stderr, "");- assert.match(result.stdout, /CLEANUP \(PAIRED \u2014 NEVER SKIP\)/);- assert.match(result.stdout, /cleanup receipt/);- assert.match(result.stdout, /tmux kill-session/);- assert.match(result.stdout, /Leftover state from QA/);- assert.match(result.stdout, /means NOT done/);-});--test("#given identifier-like ulw #when detector runs #then does not emit directive", async () => {- const payload = JSON.stringify({- hook_event_name: "UserPromptSubmit",- prompt: "refactor ulw_helper.ts",- });-- const result = await runPython(detectorPath, payload);-- assert.equal(result.code, 0);- assert.equal(result.signal, null);- assert.equal(result.stdout, "");- assert.equal(result.stderr, "");-});--test("#given hook manifest #when read #then registers only the prompt detector hook", async () => {- const manifest = JSON.parse(await readFile(join(hookDir, "hooks.json"), "utf8"));-- assert.match(- manifest.hooks.UserPromptSubmit[0].hooks[0].command,- /ultrawork-detector\.py/,- );- assert.equal(manifest.hooks.SessionStart, undefined);- assert.equal(pluginRoot.endsWith("components/ultrawork"), true);-});--test("#given component package #when inspected #then plugin identity is owned by aggregate root", async () => {- const pkg = JSON.parse(await readFile(join(pluginRoot, "package.json"), "utf8"));-- assert.equal(pkg.files.includes(".codex-plugin"), false);- await assert.rejects(- readFile(join(pluginRoot, ".codex-plugin", "plugin.json"), "utf8"),- /code: 'ENOENT'|ENOENT/,- );-});diff --git a/plugins/omo/components/ultrawork/package.json b/plugins/omo/components/ultrawork/package.jsonindex 501548f8..a122bee1 100644--- a/plugins/omo/components/ultrawork/package.json+++ b/plugins/omo/components/ultrawork/package.json@@ -3,6 +3,7 @@"version": "0.1.0","description": "Codex plugin that injects the ultrawork orchestration directive and syncs the ultrawork reviewer agent role.","type": "module",+ "packageManager": "[email protected]","license": "MIT","homepage": "https://github.com/code-yeongyu/codex-ultrawork","repository": {@@ -20,15 +21,34 @@"hooks","orchestration"],+ "bin": {+ "omo-ultrawork": "./dist/cli.js"+ },"scripts": {- "test": "node --test hooks/*.test.mjs"+ "build": "tsc -p tsconfig.build.json",+ "test": "vitest --run",+ "test:watch": "vitest",+ "typecheck": "tsc --noEmit",+ "lint": "biome check .",+ "lint:fix": "biome check --write .",+ "check": "tsc --noEmit && biome check . && npm run build"},"files": ["agents",- "hooks/hooks.json",- "hooks/ultrawork-detector.py",+ "dist",+ "directive.md",+ "hooks","README.md","LICENSE","NOTICE"- ]+ ],+ "devDependencies": {+ "@biomejs/biome": "2.4.15",+ "@types/node": "^25.7.0",+ "typescript": "^6.0.3",+ "vitest": "^4.1.5"+ },+ "engines": {+ "node": ">=20.0.0"+ }}diff --git a/plugins/omo/components/ultrawork/src/cli.ts b/plugins/omo/components/ultrawork/src/cli.tsnew file mode 100644index 00000000..6b9d71fb--- /dev/null+++ b/plugins/omo/components/ultrawork/src/cli.ts@@ -0,0 +1,50 @@+#!/usr/bin/env node+import { stdin as processStdin, stdout as processStdout } from "node:process";++import { runUserPromptSubmitHook } from "./codex-hook.js";++const command = process.argv[2];+const subcommand = process.argv[3];++if (command === "hook" && subcommand === "user-prompt-submit") {+ await runHookCli();+} else {+ process.stderr.write("Usage: omo-ultrawork hook user-prompt-submit\n");+ process.exitCode = 1;+}++async function runHookCli(): Promise<void> {+ const raw = await readStdin();+ if (raw.trim().length === 0) return;+ const parsed = parseHookInput(raw);+ const output = runUserPromptSubmitHook(parsed);+ if (output.length > 0) {+ processStdout.write(output);+ }+}++function parseHookInput(raw: string): unknown | undefined {+ try {+ const parsed: unknown = JSON.parse(raw);+ return parsed;+ } catch (error) {+ if (error instanceof SyntaxError) return undefined;+ throw error;+ }+}++function readStdin(): Promise<string> {+ return new Promise((resolve) => {+ let data = "";+ processStdin.setEncoding("utf8");+ processStdin.on("data", (chunk: string) => {+ data += chunk;+ });+ processStdin.once("error", () => {+ resolve(data);+ });+ processStdin.once("end", () => {+ resolve(data);+ });+ });+}diff --git a/plugins/omo/components/ultrawork/src/codex-hook.ts b/plugins/omo/components/ultrawork/src/codex-hook.tsnew file mode 100644index 00000000..49317db9--- /dev/null+++ b/plugins/omo/components/ultrawork/src/codex-hook.ts@@ -0,0 +1,84 @@+import { readFileSync } from "node:fs";++import { ULTRAWORK_DIRECTIVE } from "./directive.js";++const ULTRAWORK_PATTERN = /\b(?:ultrawork|ulw)\b/i;+const CONTEXT_PRESSURE_MARKERS = [+ "context compacted",+ "context_length_exceeded",+ "skill descriptions were shortened",+ "context_too_large",+ "codex ran out of room in the model's context window",+ "your input exceeds the context window",+ "long threads and multiple compactions",+] as const;++export type CodexUserPromptSubmitInput = {+ readonly hook_event_name: "UserPromptSubmit";+ readonly prompt: string;+ readonly transcript_path?: string | null;+};++interface UserPromptSubmitHookOutput {+ readonly hookSpecificOutput: {+ readonly hookEventName: "UserPromptSubmit";+ readonly additionalContext: string;+ };+}++export function runUserPromptSubmitHook(input: unknown): string {+ if (!isCodexUserPromptSubmitInput(input)) return "";+ if (isContextPressureRecoveryPrompt(input.prompt)) return "";+ if (isContextPressureTranscript(input.transcript_path)) return "";+ return isUltraworkPrompt(input.prompt) ? formatAdditionalContextOutput(ULTRAWORK_DIRECTIVE) : "";+}++export function isUltraworkPrompt(prompt: string): boolean {+ return ULTRAWORK_PATTERN.test(prompt);+}++function isContextPressureRecoveryPrompt(prompt: string): boolean {+ const normalizedPrompt = prompt.toLowerCase();+ return CONTEXT_PRESSURE_MARKERS.some((marker) => normalizedPrompt.includes(marker));+}++function isContextPressureTranscript(transcriptPath: string | null | undefined): boolean {+ if (transcriptPath === undefined || transcriptPath === null) return false;+ try {+ return isContextPressureRecoveryPrompt(readFileSync(transcriptPath, "utf8"));+ } catch (error) {+ if (error instanceof Error) return false;+ throw error;+ }+}++function formatAdditionalContextOutput(additionalContext: string): string {+ const normalizedContext = normalizeAdditionalContext(additionalContext);+ if (normalizedContext.length === 0) return "";+ const output: UserPromptSubmitHookOutput = {+ hookSpecificOutput: {+ hookEventName: "UserPromptSubmit",+ additionalContext: normalizedContext,+ },+ };+ return `${JSON.stringify(output)}\n`;+}++function normalizeAdditionalContext(additionalContext: string): string {+ return additionalContext.replace(/\r\n/g, "\n").replace(/\r/g, "\n").trim();+}++function isCodexUserPromptSubmitInput(value: unknown): value is CodexUserPromptSubmitInput {+ return (+ isRecord(value) &&+ value["hook_event_name"] === "UserPromptSubmit" &&+ typeof value["prompt"] === "string" &&+ (value["transcript_path"] === undefined ||+ value["transcript_path"] === null ||+ typeof value["transcript_path"] === "string")+ );+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/ultrawork/src/directive.ts b/plugins/omo/components/ultrawork/src/directive.tsnew file mode 100644index 00000000..faf60ae6--- /dev/null+++ b/plugins/omo/components/ultrawork/src/directive.ts@@ -0,0 +1,3 @@+import { readFileSync } from "node:fs";++export const ULTRAWORK_DIRECTIVE: string = readFileSync(new URL("../directive.md", import.meta.url), "utf8");diff --git a/plugins/omo/components/ultrawork/test/codex-hook.test.ts b/plugins/omo/components/ultrawork/test/codex-hook.test.tsnew file mode 100644index 00000000..a59f8d8e--- /dev/null+++ b/plugins/omo/components/ultrawork/test/codex-hook.test.ts@@ -0,0 +1,275 @@+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { isUltraworkPrompt, runUserPromptSubmitHook } from "../src/codex-hook.js";++const tempDirectories: string[] = [];++afterEach(() => {+ for (const directory of tempDirectories.splice(0)) {+ rmSync(directory, { recursive: true, force: true });+ }+});++describe("codex ultrawork hook", () => {+ it("#given ultrawork prompt #when hook runs #then emits directive as Codex hook JSON", () => {+ // given+ const payload = {+ hook_event_name: "UserPromptSubmit",+ prompt: "please ulw this change",+ };++ // when+ const output = runUserPromptSubmitHook(payload);+ const parsed = parseHookOutput(output);++ // then+ expect(parsed.hookSpecificOutput.hookEventName).toBe("UserPromptSubmit");+ expect(parsed.hookSpecificOutput.additionalContext).toMatch(/^<ultrawork-mode>/);+ expect(parsed.hookSpecificOutput.additionalContext).toMatch(/First user-visible line this turn MUST be exactly:/);+ });++ it("#given identifier-like ulw #when hook runs #then does not emit directive", () => {+ // given+ const payload = {+ hook_event_name: "UserPromptSubmit",+ prompt: "refactor ulw_helper.ts",+ };++ // when+ const output = runUserPromptSubmitHook(payload);++ // then+ expect(output).toBe("");+ expect(isUltraworkPrompt("ulw_helper.ts")).toBe(false);+ });++ it("#given context-pressure recovery prompt with ulw #when hook runs #then does not add more context", () => {+ // given+ const payload = {+ hook_event_name: "UserPromptSubmit",+ prompt: [+ "Warning: Skill descriptions were shortened to fit the 2% skills context budget.",+ "Warning: Long threads and multiple compactions can cause the model to be less accurate.",+ "Context compacted",+ "error context_too_large: Your input exceeds the context window of this model.",+ "ulw tdd commit well",+ ].join("\n"),+ };++ // when+ const output = runUserPromptSubmitHook(payload);++ // then+ expect(output).toBe("");+ });++ it("#given context-pressure transcript with ulw prompt #when hook runs #then does not add more context", () => {+ // given+ const payload = {+ hook_event_name: "UserPromptSubmit",+ prompt: "please ulw this change",+ transcript_path: writeContextPressureTranscript(),+ };++ // when+ const output = runUserPromptSubmitHook(payload);++ // then+ expect(output).toBe("");+ });++ it("#given Codex canonical context-window transcript with ulw prompt #when hook runs #then does not add more context", () => {+ // given+ const payload = {+ hook_event_name: "UserPromptSubmit",+ prompt: "please ulw this change",+ transcript_path: writeCodexContextWindowTranscript(),+ };++ // when+ const output = runUserPromptSubmitHook(payload);++ // then+ expect(output).toBe("");+ });++ it("#given context-pressure recovery prompt without ulw #when hook runs #then stays quiet", () => {+ // given+ const payload = {+ hook_event_name: "UserPromptSubmit",+ prompt: [+ "Context compacted",+ "Your input exceeds the context window of this model.",+ "Please adjust your input and try again.",+ ].join("\n"),+ };++ // when+ const output = runUserPromptSubmitHook(payload);++ // then+ expect(output).toBe("");+ });++ it("#given malformed or empty input #when hook runs #then exits with empty output", () => {+ // given+ const inputs = [undefined, {}, { hook_event_name: "UserPromptSubmit", prompt: "" }] as const;++ // when+ const outputs = inputs.map((input) => runUserPromptSubmitHook(input));++ // then+ expect(outputs).toEqual(["", "", ""]);+ });++ it("#given directive #when inspected #then keeps manual QA and cleanup invariants", () => {+ // given+ const payload = {+ hook_event_name: "UserPromptSubmit",+ prompt: "please ultrawork",+ };++ // when+ const output = runUserPromptSubmitHook(payload);+ const parsed = parseHookOutput(output);++ // then+ expect(parsed.hookSpecificOutput.additionalContext).toMatch(/# Manual-QA channels/);+ expect(parsed.hookSpecificOutput.additionalContext).toMatch(/TESTS ALONE NEVER PROVE DONE/);+ expect(parsed.hookSpecificOutput.additionalContext).toMatch(/1\. HTTP call/);+ expect(parsed.hookSpecificOutput.additionalContext).toMatch(/2\. tmux/);+ expect(parsed.hookSpecificOutput.additionalContext).toMatch(/3\. Browser use/);+ expect(parsed.hookSpecificOutput.additionalContext).toMatch(/4\. Computer use/);+ expect(parsed.hookSpecificOutput.additionalContext).toMatch(/CLEANUP \(PAIRED/);+ });++ it("#given directive #when inspected #then avoids context-expensive agent polling", () => {+ // given+ const payload = {+ hook_event_name: "UserPromptSubmit",+ prompt: "please ultrawork",+ };++ // when+ const output = runUserPromptSubmitHook(payload);+ const parsed = parseHookOutput(output);++ // then+ const directive = parsed.hookSpecificOutput.additionalContext;+ expect(directive).toMatch(/list_agents/);+ expect(directive).toMatch(/polling or status tool/);+ expect(directive).toMatch(/replay large agent status and latest-message\s+payloads/);+ expect(directive).toMatch(/Track spawned agent names locally/);+ expect(directive).toMatch(/wait_agent[\s\S]*completion/);+ expect(directive).toMatch(/targeted\s+followups only when needed/);+ expect(directive).toMatch(/close_agent[\s\S]*after integrating each\s+result/);+ expect(directive).toMatch(/Plan and reviewer agents\s+may run for a long time/);+ expect(directive).toMatch(/short wait_agent cycles/);+ expect(directive).toMatch(/single long blocking wait/);+ });++ it("#given directive #when inspected #then hardens Codex subagent assignment ambiguity", () => {+ // given+ const payload = {+ hook_event_name: "UserPromptSubmit",+ prompt: "please ultrawork",+ };++ // when+ const output = runUserPromptSubmitHook(payload);+ const parsed = parseHookOutput(output);++ // then+ const directive = parsed.hookSpecificOutput.additionalContext;+ expect(directive).toMatch(/TASK:/);+ expect(directive).toMatch(/fork_turns:\s*"none"/);+ expect(directive).toMatch(/wait_agent[\s\S]*signal, not\s+proof/);+ expect(directive).toMatch(/one targeted followup/);+ expect(directive).toMatch(/respawn.*smaller/);+ });+});++interface UserPromptSubmitHookOutput {+ readonly hookSpecificOutput: {+ readonly hookEventName: "UserPromptSubmit";+ readonly additionalContext: string;+ };+}++function parseHookOutput(output: string): UserPromptSubmitHookOutput {+ const parsed: unknown = JSON.parse(output);+ if (!isUserPromptSubmitHookOutput(parsed)) throw new TypeError("Expected UserPromptSubmit hook output");+ return parsed;+}++function isUserPromptSubmitHookOutput(value: unknown): value is UserPromptSubmitHookOutput {+ if (!isRecord(value)) return false;+ const hookSpecificOutput = value["hookSpecificOutput"];+ return (+ isRecord(hookSpecificOutput) &&+ hookSpecificOutput["hookEventName"] === "UserPromptSubmit" &&+ typeof hookSpecificOutput["additionalContext"] === "string"+ );+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function writeContextPressureTranscript(): string {+ const root = mkdtempSync(path.join(tmpdir(), "codex-ultrawork-context-pressure-"));+ tempDirectories.push(root);+ const transcriptPath = path.join(root, "transcript.jsonl");+ writeFileSync(+ transcriptPath,+ [+ JSON.stringify({+ type: "message",+ payload: {+ content: "Context compacted",+ },+ }),+ JSON.stringify({+ type: "message",+ payload: {+ content: "Your input exceeds the context window of this model.",+ },+ }),+ "",+ ].join("\n"),+ );+ return transcriptPath;+}++function writeCodexContextWindowTranscript(): string {+ const root = mkdtempSync(path.join(tmpdir(), "codex-ultrawork-context-window-"));+ tempDirectories.push(root);+ const transcriptPath = path.join(root, "transcript.jsonl");+ writeFileSync(+ transcriptPath,+ [+ JSON.stringify({+ type: "message",+ payload: {+ content: {+ error: {+ code: "context_length_exceeded",+ },+ },+ },+ }),+ JSON.stringify({+ type: "message",+ payload: {+ content:+ "Codex ran out of room in the model's context window. Start a new thread or clear earlier history before retrying.",+ },+ }),+ "",+ ].join("\n"),+ );+ return transcriptPath;+}diff --git a/plugins/omo/components/ultrawork/test/package-smoke.test.ts b/plugins/omo/components/ultrawork/test/package-smoke.test.tsnew file mode 100644index 00000000..b3ef51c8--- /dev/null+++ b/plugins/omo/components/ultrawork/test/package-smoke.test.ts@@ -0,0 +1,103 @@+import { readFileSync } from "node:fs";+import { describe, expect, it } from "vitest";++type PackageJson = {+ readonly type: string;+ readonly packageManager: string;+ readonly bin: Record<string, string>;+ readonly files: readonly string[];+ readonly scripts: Record<string, string>;+};++describe("codex ultrawork package metadata", () => {+ it("#given package metadata #when inspected #then hook ships as built TypeScript", () => {+ // given+ const packageJson = readPackageJson("package.json");+ const hooksJson = readJson("hooks/hooks.json");+ const cliSource = readFileSync("src/cli.ts", "utf8");++ // when+ const packageFiles = packageJson.files;+ const hookCommands = collectHookCommandsFromValue(hooksJson);+ const pluginRoot = ["$", "{PLUGIN_ROOT}"].join("");++ // then+ expect(packageJson.type).toBe("module");+ expect(packageJson.packageManager).toBe("[email protected]");+ expect(packageJson.bin["omo-ultrawork"]).toBe("./dist/cli.js");+ expect(packageJson.scripts["build"]).toBe("tsc -p tsconfig.build.json");+ expect(packageJson.scripts["test"]).toBe("vitest --run");+ expect(packageFiles).toContain("dist");+ expect(packageFiles).toContain("directive.md");+ expect(packageFiles).not.toContain("hooks/ultrawork-detector.py");+ expect(cliSource.startsWith("#!/usr/bin/env node")).toBe(true);+ expect(hookCommands).toContain(`node "${pluginRoot}/dist/cli.js" hook user-prompt-submit`);+ 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 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");+ });+});++function readJson(path: string): unknown {+ return JSON.parse(readFileSync(path, "utf8"));+}++function readPackageJson(path: string): PackageJson {+ const parsed = readJson(path);+ if (!isPackageJson(parsed)) throw new TypeError(`Invalid package metadata: ${path}`);+ return parsed;+}++function collectHookCommandsFromValue(value: unknown): readonly string[] {+ if (typeof value === "string") return [];+ if (Array.isArray(value)) return value.flatMap(collectHookCommandsFromValue);+ if (!isRecord(value)) return [];+ const ownCommand = typeof value["command"] === "string" ? [value["command"]] : [];+ return [...ownCommand, ...Object.values(value).flatMap(collectHookCommandsFromValue)];+}++function isPackageJson(value: unknown): value is PackageJson {+ return (+ isRecord(value) &&+ value["type"] === "module" &&+ value["packageManager"] === "[email protected]" &&+ isStringRecord(value["bin"]) &&+ isStringArray(value["files"]) &&+ isStringRecord(value["scripts"])+ );+}++function isStringArray(value: unknown): value is readonly string[] {+ return Array.isArray(value) && value.every((item) => typeof item === "string");+}++function isStringRecord(value: unknown): value is Record<string, string> {+ return isRecord(value) && Object.values(value).every((item) => typeof item === "string");+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/ultragoal/tsconfig.build.json b/plugins/omo/components/ultrawork/tsconfig.build.jsonsimilarity index 100%rename from plugins/omo/components/ultragoal/tsconfig.build.jsonrename to plugins/omo/components/ultrawork/tsconfig.build.jsondiff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/tsconfig.json b/plugins/omo/components/ultrawork/tsconfig.jsonsimilarity index 100%rename from plugins/omo/components/lsp/packages/lsp-tools-mcp/tsconfig.jsonrename to plugins/omo/components/ultrawork/tsconfig.jsondiff --git a/plugins/omo/components/ultragoal/.gitattributes b/plugins/omo/components/ulw-loop/.gitattributessimilarity index 100%rename from plugins/omo/components/ultragoal/.gitattributesrename to plugins/omo/components/ulw-loop/.gitattributesdiff --git a/plugins/omo/components/ultragoal/.gitignore b/plugins/omo/components/ulw-loop/.gitignoresimilarity index 100%rename from plugins/omo/components/ultragoal/.gitignorerename to plugins/omo/components/ulw-loop/.gitignorediff --git a/plugins/omo/components/ultragoal/AGENTS.md b/plugins/omo/components/ulw-loop/AGENTS.mdsimilarity index 88%rename from plugins/omo/components/ultragoal/AGENTS.mdrename to plugins/omo/components/ulw-loop/AGENTS.mdindex bc76bb20..54f1a3c0 100644--- a/plugins/omo/components/ultragoal/AGENTS.md+++ b/plugins/omo/components/ulw-loop/AGENTS.md@@ -37,9 +37,9 @@ Conventions for human contributors and AI agents working on this repository.## Branding-- Repo artifacts live under `.omo/ultragoal/` paths.-- Environment variables use the `OMO_ULTRAGOAL_*` prefix.-- CLI commands use the `omo ultragoal` form.+- Repo artifacts live under `.omo/ulw-loop/` paths.+- Environment variables use the `OMO_ULW_LOOP_*` prefix.+- CLI commands use the `omo ulw-loop` form.- Do not use any alternate legacy CLI alias anywhere.## Build and Hooksdiff --git a/plugins/omo/components/ultragoal/CHANGELOG.md b/plugins/omo/components/ulw-loop/CHANGELOG.mdsimilarity index 95%rename from plugins/omo/components/ultragoal/CHANGELOG.mdrename to plugins/omo/components/ulw-loop/CHANGELOG.mdindex 72a3e098..7145a3b6 100644--- a/plugins/omo/components/ultragoal/CHANGELOG.md+++ b/plugins/omo/components/ulw-loop/CHANGELOG.md@@ -2,6 +2,6 @@## [0.1.0] - unreleased-- Initial scaffold of codex-ultragoal plugin.+- Initial scaffold of codex-ulw-loop plugin.- Per-Criterion Cycle: `EXECUTE` is now **EXECUTE-AS-SCENARIO** — the agent must run the Manual-QA channel scenario the criterion named (HTTP call / tmux / browser use / computer use; see new `## Manual-QA channels` section). Inserted a new **CLEAN (PAIRED, NEVER SKIP)** step that tears down every QA-spawned process / `tmux` session / browser context / container / port / temp dir before recording evidence; the cleanup receipt is embedded in the `--evidence` string. Missing receipt → record BLOCKED, not PASS. Added Constraint #13 and a Stop Rule for leftover state.- New top-level **`## Manual-QA channels`** section explicitly enumerates the four channels (HTTP call, tmux, Browser use, Computer use) with concrete commands and required artifacts. Goal section now declares **TESTS ALONE NEVER PROVE DONE**: a green test suite is supporting evidence, never completion proof. Criterion-refinement step 2 requires each criterion to name its channel up front.diff --git a/plugins/omo/components/ultragoal/LICENSE b/plugins/omo/components/ulw-loop/LICENSEsimilarity index 100%rename from plugins/omo/components/ultragoal/LICENSErename to plugins/omo/components/ulw-loop/LICENSEdiff --git a/plugins/omo/components/ultragoal/NOTICE b/plugins/omo/components/ulw-loop/NOTICEsimilarity index 57%rename from plugins/omo/components/ultragoal/NOTICErename to plugins/omo/components/ulw-loop/NOTICEindex 4b0ea073..01b3ff90 100644--- a/plugins/omo/components/ultragoal/NOTICE+++ b/plugins/omo/components/ulw-loop/NOTICE@@ -1,6 +1,6 @@-codex-ultragoal+codex-ulw-loop-This package ports the oh-my-codex ultragoal feature into a Codex plugin repository.+This package provides the ulw-loop feature in a Codex plugin repository.The plugin targets Codex plugin manifests and plugin-bundled lifecycle hooks.The orchestration engine is added in later port waves.diff --git a/plugins/omo/components/ultragoal/README.md b/plugins/omo/components/ulw-loop/README.mdsimilarity index 66%rename from plugins/omo/components/ultragoal/README.mdrename to plugins/omo/components/ulw-loop/README.mdindex dbd562dc..f72f6b9f 100644--- a/plugins/omo/components/ultragoal/README.md+++ b/plugins/omo/components/ulw-loop/README.md@@ -1,4 +1,4 @@-# codex-ultragoal+# codex-ulw-loop[](#) [](LICENSE)@@ -8,13 +8,13 @@ Codex plugin scaffold for durable repo-native multi-goal orchestration with embe| Subcommand | Purpose ||------------|---------|-| `omo ultragoal create-goals` | Create repo-native goals from a brief and seed criteria. |-| `omo ultragoal record-evidence` | Record observable evidence for the active criterion. |-| `omo ultragoal criteria` | Inspect or revise goal success criteria. |-| `omo ultragoal complete-goals` | Complete eligible goals after criteria pass. |-| `omo ultragoal checkpoint` | Refuse completion until criteria and evidence gates pass. |-| `omo ultragoal steer` | Apply steering updates to the plan. |-| `omo ultragoal status` | Report active goal, criteria, and evidence state. |+| `omo ulw-loop create-goals` | Create repo-native goals from a brief and seed criteria. |+| `omo ulw-loop record-evidence` | Record observable evidence for the active criterion. |+| `omo ulw-loop criteria` | Inspect or revise goal success criteria. |+| `omo ulw-loop complete-goals` | Complete eligible goals after criteria pass. |+| `omo ulw-loop checkpoint` | Refuse completion until criteria and evidence gates pass. |+| `omo ulw-loop steer` | Apply steering updates to the plan. |+| `omo ulw-loop status` | Report active goal, criteria, and evidence state. |Wave 1 is scaffold only. Command behavior lands in later waves.@@ -24,7 +24,7 @@ The plugin ships:- `.codex-plugin/plugin.json` for Codex plugin discovery.- `hooks/hooks.json` for the `UserPromptSubmit` hook.-- `skills/ultragoal/` as the future skill directory.+- `skills/ulw-loop/` as the future skill directory.The hook command is:@@ -71,5 +71,4 @@ This plugin runs locally. The scaffold does not call a network service by itself## Related-- [oh-my-codex](https://github.com/code-yeongyu/oh-my-codex) - source project for the ultragoal port.- [lazycodex](https://github.com/code-yeongyu/lazycodex) - Sisyphus Labs Codex marketplace repository.diff --git a/plugins/omo/components/ulw-loop/biome.json b/plugins/omo/components/ulw-loop/biome.jsonnew file mode 100644index 00000000..5aa1a0dc--- /dev/null+++ b/plugins/omo/components/ulw-loop/biome.json@@ -0,0 +1,48 @@+{+ "$schema": "https://biomejs.dev/schemas/2.4.15/schema.json",+ "linter": {+ "enabled": true,+ "rules": {+ "recommended": true,+ "style": {+ "noDefaultExport": "error",+ "noEnum": "error",+ "noNonNullAssertion": "error",+ "useImportType": "error",+ "useConst": "error",+ "useNodejsImportProtocol": "off"+ },+ "complexity": {+ "useLiteralKeys": "off"+ },+ "suspicious": {+ "noExplicitAny": "error",+ "noTsIgnore": "error",+ "noControlCharactersInRegex": "off",+ "noEmptyInterface": "off"+ }+ }+ },+ "formatter": {+ "enabled": true,+ "formatWithErrors": false,+ "indentStyle": "tab",+ "indentWidth": 3,+ "lineWidth": 120+ },+ "files": {+ "includes": ["src/**/*.ts", "test/**/*.ts", "vitest.config.ts", "!**/node_modules/**/*", "!**/dist/**/*"]+ },+ "overrides": [+ {+ "includes": ["vitest.config.ts"],+ "linter": {+ "rules": {+ "style": {+ "noDefaultExport": "off"+ }+ }+ }+ }+ ]+}diff --git a/plugins/omo/components/ulw-loop/hooks/hooks.json b/plugins/omo/components/ulw-loop/hooks/hooks.jsonnew file mode 100644index 00000000..b809ab5b--- /dev/null+++ b/plugins/omo/components/ulw-loop/hooks/hooks.json@@ -0,0 +1,29 @@+{+ "hooks": {+ "UserPromptSubmit": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit",+ "timeout": 10,+ "statusMessage": "LazyCodex(0.1.0): Checking Ulw-Loop Steering"+ }+ ]+ }+ ],+ "PreToolUse": [+ {+ "matcher": "^create_goal$",+ "hooks": [+ {+ "type": "command",+ "command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use",+ "timeout": 5,+ "statusMessage": "LazyCodex(0.1.0): Enforcing Unlimited Ulw-Loop Budget"+ }+ ]+ }+ ]+ }+}diff --git a/plugins/omo/components/ultragoal/package.json b/plugins/omo/components/ulw-loop/package.jsonsimilarity index 79%rename from plugins/omo/components/ultragoal/package.jsonrename to plugins/omo/components/ulw-loop/package.jsonindex 77782d91..06f46f6e 100644--- a/plugins/omo/components/ultragoal/package.json+++ b/plugins/omo/components/ulw-loop/package.json@@ -1,22 +1,22 @@{- "name": "@code-yeongyu/codex-ultragoal",+ "name": "@code-yeongyu/codex-ulw-loop","version": "0.1.0","description": "Codex plugin: durable repo-native multi-goal orchestration with embedded success criteria and observable evidence audit.","type": "module","packageManager": "[email protected]","license": "MIT",- "homepage": "https://github.com/code-yeongyu/codex-ultragoal",+ "homepage": "https://github.com/code-yeongyu/codex-ulw-loop","repository": {"type": "git",- "url": "git+https://github.com/code-yeongyu/codex-ultragoal.git"+ "url": "git+https://github.com/code-yeongyu/codex-ulw-loop.git"},"bugs": {- "url": "https://github.com/code-yeongyu/codex-ultragoal/issues"+ "url": "https://github.com/code-yeongyu/codex-ulw-loop/issues"},"keywords": ["codex","codex-plugin",- "ultragoal",+ "ulw-loop","goal-mode","orchestration","evidence",diff --git a/plugins/omo/components/ultragoal/skills/ultragoal/.gitkeep b/plugins/omo/components/ulw-loop/skills/ulw-loop/.gitkeepsimilarity index 100%rename from plugins/omo/components/ultragoal/skills/ultragoal/.gitkeeprename to plugins/omo/components/ulw-loop/skills/ulw-loop/.gitkeepdiff --git a/plugins/omo/components/ulw-loop/skills/ulw-loop/SKILL.md b/plugins/omo/components/ulw-loop/skills/ulw-loop/SKILL.mdnew file mode 100644index 00000000..27b5e824--- /dev/null+++ b/plugins/omo/components/ulw-loop/skills/ulw-loop/SKILL.md@@ -0,0 +1,45 @@+---+name: ulw-loop+description: Goal-like loop that uses ultrawork mode to decompose work into systematic, evidence-bound steps.+metadata:+ short-description: Goal-like ultrawork loop for systematic decomposition+---++# ulw-loop++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.++## Required First Steps++1. 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.+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++- Use the ulw-loop CLI state under `.omo/ulw-loop`; do not hand-edit goal state.+- Every success criterion needs observable evidence from a real channel: tmux, HTTP, browser, or computer-use.+- 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`; role selection requires `agent_type`, while `model` + `reasoning_effort` alone creates a default agent, not a reviewer or worker; 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.+- While any child is active, keep the parent visibly alive with brief status updates that include active subagent count, agent names, last heartbeat, and whether the parent is waiting for mailbox updates.+- Avoid `list_agents` as a polling or status tool in large runs; it can replay large agent status and latest-message payloads. Track spawned agent names locally, use `wait_agent` for completion signals, targeted followups only when needed, and `close_agent` after integrating each result.+- Treat `wait_agent` as a mailbox signal, not proof of completion, content, or errors. After two waits with no substantive result, send one targeted followup, then record inconclusive and respawn a smaller `fork_turns: "none"` task if the child stays silent or ack-only.++## Codex Tool Mapping++The full workflow may mention OpenCode-style orchestration examples. In Codex, translate them to native tools:++| Workflow intent | Codex tool |+| --- | --- |+| Plan agent | `spawn_agent(agent_type="plan", fork_turns="none", ...)` |+| Search/read-only worker | `spawn_agent(agent_type="explorer", fork_turns="none", ...)` |+| Implementation or QA worker | `spawn_agent(agent_type="worker", fork_turns="none", ...)` |+| Final verification reviewer | `spawn_agent(agent_type="codex-ultrawork-reviewer", fork_turns="none", ...)` |+| Wait for background result | `wait_agent(...)` |+| Clean up finished worker | `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/agents/openai.yaml b/plugins/omo/components/ulw-loop/skills/ulw-loop/agents/openai.yamlnew file mode 100644index 00000000..bd8a773e--- /dev/null+++ b/plugins/omo/components/ulw-loop/skills/ulw-loop/agents/openai.yaml@@ -0,0 +1,6 @@+interface:+ display_name: "ulw-loop (omo)"+ short_description: "Goal-like ultrawork loop for systematic decomposition"+ search_terms:+ - "ulw-loop"+ default_prompt: "Use $ulw-loop to break this work into a systematic ultrawork loop with evidence-backed checkpoints."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.mdnew file mode 100644index 00000000..f68c1cc6--- /dev/null+++ b/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.md@@ -0,0 +1,231 @@+---+name: ulw-loop+description: Goal-like loop that uses ultrawork mode to decompose work into systematic, evidence-bound steps.+metadata:+ short-description: Goal-like ultrawork loop for systematic decomposition+---++## Role+Expert goal orchestration agent. You conduct; right-sized parallel subagents play. Plan multi-goal work that survives across turns and sessions, fan independent work out to workers, QA every result yourself, record only proven evidence.+Use GPT-5.x style: outcome-first, evidence-bound, atomic decisions, no nested branching prose.++## Goal+Deliver every goal in `.omo/ulw-loop/goals.json` end-to-end.+Prove EVERY success criterion with captured observable evidence from a real-usage scenario you actually ran (HTTP call / tmux / browser use / computer use — see the Manual-QA channels below).+TESTS ALONE NEVER PROVE DONE. A green test suite is supporting evidence, not completion proof.+Audit each pass, fail, block, steering change, and checkpoint in `.omo/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.++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.++## 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).++Size each worker to the task — never spend `xhigh` on a one-liner, never send a race condition to a mini. Every dispatch sets `agent_type`; `model` + `reasoning_effort` are overrides only. Setting them alone creates a default agent, not a reviewer or worker.++| Task shape | agent_type | model | reasoning_effort |+|---|---|---|---|+| Trivial / mechanical (rename, move, obvious one-liner, config edit) | `worker` | `gpt-5.4-mini` | `low` |+| Pure implementation against a clear spec (new function, endpoint, test from a named pattern) | `worker` | `gpt-5.4` | `high` |+| Deep debugging / race / perf / subtle cross-module reasoning | `worker` | `gpt-5.5` | `xhigh` |+| QA execution (drive a channel, capture evidence) | `worker` | `gpt-5.4` | `high` |+| Read-only codebase search | `explorer` | role default | role default |+| External library / docs research | `librarian` | role default | role default |+| Final verification audit | `codex-ultrawork-reviewer` | role default | role default |++If `codex-ultrawork-reviewer` is unavailable, use `agent_type="worker"` with a self-contained reviewer assignment, tight scope, and explicit verification. Never spawn a model-only default agent 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. 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.+- While any child is active, keep the parent visibly alive with brief status updates that include active subagent count, agent names, last heartbeat, and whether the parent is waiting for mailbox updates.+- Do not use `list_agents` as a polling or status tool in long or high-context runs; it can replay large agent status and latest-message payloads. Track spawned agent names locally, use `wait_agent` for completion signals, targeted followups only when needed, and `close_agent` after integrating each result.+- Treat `wait_agent` as a mailbox signal, not proof of completion, content, or errors. After two waits with no substantive result, send one targeted followup: `TASK STILL ACTIVE: return <deliverable> or BLOCKED: <reason>`. If 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.++## Artifacts+- `.omo/ulw-loop/brief.md`: original brief and durable constraints.+- `.omo/ulw-loop/goals.json`: goals with embedded `successCriteria` per goal.+- `.omo/ulw-loop/ledger.jsonl`: append-only audit trail.+- Read artifacts before resuming, steering, or checkpointing.+- Never invent state outside `.omo/ulw-loop` artifacts or `omo ulw-loop status --json`.++## Bootstrap+Do all three steps before execution. No edits, goal tools, or checkpointing before bootstrap completes.++### 1. Create goals from the brief+Resolve the CLI before the first command. If `omo` is absent from PATH or does not support `ulw-loop`, use the stable local installer bin or cached Codex component CLI. This is the same ulw-loop CLI, so PATH absence is not a blocker. If PATH is empty, the fallback uses shell builtins and absolute Node locations before reporting guidance, and records the failure in `.omo/ulw-loop/bootstrap-notepad.md`.+```sh+CODEX_HOME="${CODEX_HOME:-$HOME/.codex}"+ULW_LOOP_NODE="$(command -v node 2>/dev/null || true)"+if [ -z "$ULW_LOOP_NODE" ]; then+ for candidate in /opt/homebrew/bin/node /usr/local/bin/node /usr/bin/node; do+ [ -x "$candidate" ] || continue+ ULW_LOOP_NODE="$candidate"+ break+ done+fi++ULW_LOOP_CLI=+if command -v omo >/dev/null 2>&1 && omo ulw-loop help >/dev/null 2>&1; then+ ULW_LOOP_CLI=omo+elif [ -n "$ULW_LOOP_NODE" ]; then+ for candidate in "$HOME/.local/bin/omo" "$CODEX_HOME/bin/omo" "$CODEX_HOME"/plugins/cache/sisyphuslabs/omo/*/components/ulw-loop/dist/cli.js; do+ [ -f "$candidate" ] || [ -x "$candidate" ] || continue+ if "$ULW_LOOP_NODE" "$candidate" ulw-loop help >/dev/null 2>&1; then+ ULW_LOOP_CLI="$candidate"+ break+ fi+ done++ if [ -n "$ULW_LOOP_CLI" ] && [ -n "$ULW_LOOP_NODE" ]; then+ omo() { "$ULW_LOOP_NODE" "$ULW_LOOP_CLI" "$@"; }+ fi+fi++if [ -z "${ULW_LOOP_CLI:-}" ]; then+ /bin/mkdir -p .omo/ulw-loop 2>/dev/null || mkdir -p .omo/ulw-loop 2>/dev/null || true+ NOTE="${NOTE:-.omo/ulw-loop/bootstrap-notepad.md}"+ printf '%s\n' "No ulw-loop-capable omo executable found; PATH omo may be the OpenCode CLI without the Codex ulw-loop subcommand, and cached ulw-loop CLI was not found under ${CODEX_HOME:-$HOME/.codex}." >> "$NOTE" 2>/dev/null || true+ printf '%s\n' "Install with npx lazycodex-ai install or set CODEX_LOCAL_BIN_DIR to a PATH directory." >&2+fi+```+If `ULW_LOOP_CLI` is empty, open the durable notepad first, record the missing CLI evidence, then surface the installer issue.++Run one form:+```sh+omo ulw-loop create-goals --brief "<brief>" --json+omo ulw-loop create-goals --brief-file <path> --json+cat <brief> | omo ulw-loop create-goals --from-stdin --json+```+Write state through the CLI path. Do not hand-edit state files.++### 2. Refine success criteria + a Prometheus-grade QA and parallelism plan per goal+Gather 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.+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.+Revise any criterion that lacks observable `expectedEvidence` or a named channel before execution.++### 3. Inspect state+Run `omo ulw-loop status --json`.+Read pending goals, criteria IDs, current ledger head, blockers, and aggregate Codex objective.++## Execution Loop+Loop per goal. Cap at 5 cycles per goal. Cap identical same-criterion failures at 3.++### Acquire Next Goal+1. Run `omo ulw-loop complete-goals --json` and read the handoff, including criteria.+2. Call `get_goal` and inspect active Codex state.+3. Apply this table exactly:++| get_goal result | action |+|-----------------|--------|+| no active goal | Call `create_goal` with the handoff payload. |+| same aggregate objective active | Continue the current ulw-loop story. |+| different goal active | STOP. Checkpoint blocked and surface the conflict. |+4. If retrying failed work, run `omo ulw-loop complete-goals --retry-failed --json`.+5. Never create a second Codex goal for the same aggregate objective.++### Per-Criterion Cycle+1. PLAN: read `criterion.scenario`, `criterion.expectedEvidence`, prior ledger entries, and safety bounds. Identify which tasks in the current wave are independent.+2. Register atomic todos: `path: <action> for <criterion> - verify by <check>`.+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; 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.+4. INTEGRATE + CRITICAL SELF-QA (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. 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.4`, `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.+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.+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`+ - BLOCKED: `omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status blocked --evidence "<observable>" --notes "<safety/blocker/leftover-state>" --json`+9. If actual does not match expected, diagnose, respawn the right-sized worker with the failure context to fix minimally, and rerun the SAME criterion (including a fresh cleanup).+10. After 3 same-criterion failures, exit the goal with diagnosis.+11. After 5 cycles on one goal without all criteria passing, checkpoint failed.+12. Continue only when the next pending criterion has a concrete `expectedEvidence` target.++### Goal Completion+1. Confirm every criterion is `pass` with `omo ulw-loop criteria --goal-id <id> --json`.+2. Call `get_goal` for a fresh snapshot.+3. Run `omo ulw-loop checkpoint --goal-id <id> --status complete --evidence "<criteria evidence summary>" --codex-goal-json <snapshot> --json`.+4. If blocked or failed, checkpoint with `--status blocked` or `--status failed` and include diagnosis evidence.+5. If this is the final goal, run the final quality gate first and pass `--quality-gate-json`.++## Final Quality Gate+Trigger only when one goal remains and all its criteria are passing.+1. Run targeted verification for changed behavior.+2. Run `ai-slop-cleaner` on changed files. If no relevant edits exist, record a passed no-op cleaner report.+3. Rerun verification after cleanup.+4. Run `$code-review`.+5. Clean review means `codeReview.recommendation == "APPROVE"` and `codeReview.architectStatus == "CLEAR"`.+6. If review is non-clean, run `omo ulw-loop record-review-blockers --goal-id <id> --title "<...>" --objective "<...>" --evidence "<review findings>" --codex-goal-json <snapshot> --json`.+7. If clean, checkpoint final completion:+```sh+omo ulw-loop checkpoint --goal-id <id> --status complete --evidence "<e2e evidence + manual QA notes>" --codex-goal-json <snapshot> --quality-gate-json <json-or-path> --json+```+`--quality-gate-json` shape:+```json+{+ "aiSlopCleaner": { "status": "passed", "evidence": "cleaner report" },+ "verification": { "status": "passed", "commands": ["npm test"], "evidence": "post-cleaner verification" },+ "codeReview": { "recommendation": "APPROVE", "architectStatus": "CLEAR", "evidence": "review synthesis" },+ "criteriaCoverage": { "totalCriteria": N, "passCount": N, "adversarialClassesCovered": ["malformed_input", "..."] }+}+```++## Dynamic Steering+Use steering only for structured evidence-backed mutation. Reject natural-language steering requests.++| Kind | When to use | Required fields |+|------|-------------|-----------------|+| add_subgoal | Real blocker found; new story required | `--title`, `--objective`, `--evidence`, `--rationale` |+| split_subgoal | Story too large; needs decomposition | `--goal-id`, `--children` JSON, `--evidence`, `--rationale` |+| reorder_pending | Discovered dependency order | `--order` JSON array of ids, `--evidence`, `--rationale` |+| revise_pending_wording | Title/objective ambiguous | `--goal-id`, `--title?`, `--objective?`, `--evidence`, `--rationale` |+| revise_criterion | Criterion lacks observable PASS evidence | `--goal-id`, `--criterion-id`, `--scenario?`, `--expected-evidence?`, `--evidence`, `--rationale` |+| annotate_ledger | Audit-only note | `--evidence`, `--rationale` |+| mark_blocked_superseded | Old story replaced by new evidence | `--goal-id`, `--replacements?`, `--evidence`, `--rationale` |++Command form: `omo ulw-loop steer --kind <kind> [<kind-specific-fields>] --evidence "<...>" --rationale "<...>" --json`.+Structured prompt directives accepted: `OMO_ULW_LOOP_STEER: { ... }`, `omo.ulw-loop.steer: {...}`, `omo ulw-loop steer: {...}`.++## Constraints+1. NEVER call `update_goal` mid-aggregate; only on final story after the quality gate passes.+2. NEVER call `create_goal` when `get_goal` shows a different active goal.+3. NEVER mark `criterion.status == "pass"` without captured observable evidence in `record-evidence`.+4. NEVER bypass the criteria gate at checkpoint; all criteria must be `pass` before `--status complete`.+5. Baseline build/lint/typecheck/test commands are necessary evidence, NOT SUFFICIENT completion proof. Criteria coverage with observable evidence is the gate.+6. Treat `.omo/ulw-loop/ledger.jsonl` as the durable audit trail; checkpoint after every success or failure.+7. Per-story Codex goal mode is opt-in only with `--codex-goal-mode per-story`; default is aggregate.+8. Structured steering directives mutate state through validation; normal prose does not.+9. Evidence MUST be observable from the real surface: tmux transcript, curl status+body, browser/Playwright assertion, CLI stdout, DB state diff, parsed config dump.+10. Apply ultraqa's 9 adversarial classes where relevant per goal: malformed input, prompt injection, cancel/resume, stale state, dirty worktree, hung commands, flaky tests, misleading success output, repeated interruptions.+11. After completing an aggregate 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.++## Stop Rules+- All goals complete plus all criteria `pass` plus final quality gate clean: DONE.+- 3x same criterion failure: checkpoint failed, surface diagnosis.+- 5 cycles on one goal without all-pass: checkpoint failed, surface.+- Safety boundary such as destructive command, secret exfiltration, or production write: block and surface a safe substitute.+- Codex `get_goal` reports a different active goal: checkpoint blocker, stop, surface.+- Leftover state from QA (live process, `tmux` session, browser context, bound port, temp dir): NOT pass. Clean up, append the receipt, then continue.+- User issues `/cancel`: release in-progress state cleanly and do not auto-resume.diff --git a/plugins/omo/components/ultragoal/src/.gitkeep b/plugins/omo/components/ulw-loop/src/.gitkeepsimilarity index 100%rename from plugins/omo/components/ultragoal/src/.gitkeeprename to plugins/omo/components/ulw-loop/src/.gitkeepdiff --git a/plugins/omo/components/ultragoal/src/checkpoint.ts b/plugins/omo/components/ulw-loop/src/checkpoint.tssimilarity index 52%rename from plugins/omo/components/ultragoal/src/checkpoint.tsrename to plugins/omo/components/ulw-loop/src/checkpoint.tsindex 151a4607..348d4b43 100644--- a/plugins/omo/components/ultragoal/src/checkpoint.ts+++ b/plugins/omo/components/ulw-loop/src/checkpoint.ts@@ -6,23 +6,23 @@ import { resolve } from "node:path";import { formatCodexGoalReconciliation, readCodexGoalSnapshotInput, reconcileCodexGoalSnapshot } from "./codex-goal-snapshot.js";import { requireAllCriteriaPass } from "./evidence.js";import { codexGoalMode, compatibleCodexObjectives, expectedCodexObjective, isFinalRunCompletionCandidate } from "./goal-status.js";-import { ultragoalBriefPath } from "./paths.js";-import { appendLedger, readUltragoalPlan, withUltragoalMutationLock, writePlan } from "./plan-io.js";+import { type UlwLoopScope, ulwLoopBriefPath } from "./paths.js";+import { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";import { classifyExternalAuthorizationBlocker, clearGoalBlockerFields, sameBlockerOccurrences, validateQualityGate } from "./quality-gate.js";-import type { UltragoalAggregateCompletion, UltragoalItem, UltragoalLedgerEntry, UltragoalPlan, UltragoalQualityGate } from "./types.js";-import { iso, ULTRAGOAL_DIR, ULTRAGOAL_GOALS, ULTRAGOAL_LEDGER, UltragoalError } from "./types.js";+import type { UlwLoopAggregateCompletion, UlwLoopItem, UlwLoopLedgerEntry, UlwLoopPlan, UlwLoopQualityGate } from "./types.js";+import { iso, ULW_LOOP_DIR, ULW_LOOP_GOALS, ULW_LOOP_LEDGER, UlwLoopError } from "./types.js";-export interface CheckpointUltragoalArgs { readonly goalId: string; readonly status: "complete" | "failed" | "blocked"; readonly evidence: string; readonly codexGoalJson?: string; readonly qualityGateJson?: string }-export interface CheckpointUltragoalResult { readonly plan: UltragoalPlan; readonly goal: UltragoalItem; readonly ledgerEntry: UltragoalLedgerEntry; readonly aggregateCompletion?: UltragoalAggregateCompletion }+export interface CheckpointUlwLoopArgs { readonly goalId: string; readonly status: "complete" | "failed" | "blocked"; readonly evidence: string; readonly codexGoalJson?: string; readonly qualityGateJson?: string }+export interface CheckpointUlwLoopResult { readonly plan: UlwLoopPlan; readonly goal: UlwLoopItem; readonly ledgerEntry: UlwLoopLedgerEntry; readonly aggregateCompletion?: UlwLoopAggregateCompletion }-function ultragoalFail(message: string, code: string): never { throw new UltragoalError(message, code); }+function ulwLoopFail(message: string, code: string): never { throw new UlwLoopError(message, code); }function normalizeObjective(value: string): string { return value.replace(/\s+/g, " ").trim(); }-function nonEmptyEvidence(value: string): string { const trimmed = value.trim(); return trimmed || ultragoalFail("Evidence must be a non-empty string.", "ultragoal_evidence_required"); }-function findGoal(plan: UltragoalPlan, goalId: string): UltragoalItem { const goal = plan.goals.find((candidate) => candidate.id === goalId); return goal ?? ultragoalFail(`Unknown ultragoal id: ${goalId}.`, "ultragoal_goal_not_found"); }+function nonEmptyEvidence(value: string): string { const trimmed = value.trim(); return trimmed || ulwLoopFail("Evidence must be a non-empty string.", "ulw_loop_evidence_required"); }+function findGoal(plan: UlwLoopPlan, goalId: string): UlwLoopItem { const goal = plan.goals.find((candidate) => candidate.id === goalId); return goal ?? ulwLoopFail(`Unknown ulw-loop id: ${goalId}.`, "ulw_loop_goal_not_found"); }-function textMentionsUltragoalPlanArtifact(value: string | undefined): boolean {+function textMentionsUlwLoopPlanArtifact(value: string | undefined): boolean {const normalized = (value ?? "").toLowerCase();- return normalized.includes(ULTRAGOAL_DIR.toLowerCase()) || normalized.includes(ULTRAGOAL_GOALS.toLowerCase()) || normalized.includes(ULTRAGOAL_LEDGER.toLowerCase());+ return normalized.includes(ULW_LOOP_DIR.toLowerCase()) || normalized.includes(ULW_LOOP_GOALS.toLowerCase()) || normalized.includes(ULW_LOOP_LEDGER.toLowerCase());}function textMentionsGoalId(value: string | undefined, goalId: string): boolean { return (value ?? "").toLowerCase().includes(goalId.toLowerCase()); }function textHasCompletionValidationEvidence(value: string | undefined): boolean {@@ -32,12 +32,12 @@ function textHasCompletionValidationEvidence(value: string | undefined): booleanreturn done && verified;}-async function snapshotObjectiveMapsToUltragoalPlan(repoRoot: string, snapshotObjective: string): Promise<boolean> {+async function snapshotObjectiveMapsToUlwLoopPlan(repoRoot: string, snapshotObjective: string, scope?: UlwLoopScope): Promise<boolean> {const actual = normalizeObjective(snapshotObjective).toLowerCase();- if (textMentionsUltragoalPlanArtifact(actual)) return true;- if (actual.length < 24 || !existsSync(ultragoalBriefPath(repoRoot))) return false;+ if (textMentionsUlwLoopPlanArtifact(actual)) return true;+ if (actual.length < 24 || !existsSync(ulwLoopBriefPath(repoRoot, scope))) return false;try {- const brief = normalizeObjective(await readFile(ultragoalBriefPath(repoRoot), "utf8")).toLowerCase();+ const brief = normalizeObjective(await readFile(ulwLoopBriefPath(repoRoot, scope), "utf8")).toLowerCase();return brief.length >= 24 && (brief.includes(actual) || actual.includes(brief));} catch (error) {if (error instanceof Error) return false;@@ -45,28 +45,36 @@ async function snapshotObjectiveMapsToUltragoalPlan(repoRoot: string, snapshotOb}}-async function canReconcileCompletedTaskScopedAggregateSnapshot(repoRoot: string, plan: UltragoalPlan, goal: UltragoalItem, snapshotObjective: string, evidence: string): Promise<boolean> {+async function canReconcileCompletedTaskScopedAggregateSnapshot(repoRoot: string, plan: UlwLoopPlan, goal: UlwLoopItem, snapshotObjective: string, evidence: string, scope?: UlwLoopScope): Promise<boolean> {if (codexGoalMode(plan) !== "aggregate") return false;if (goal.status !== "in_progress" || plan.activeGoalId !== goal.id) return false;- if (isFinalRunCompletionCandidate(plan, goal)) return snapshotObjectiveMapsToUltragoalPlan(repoRoot, snapshotObjective);- if (!textMentionsUltragoalPlanArtifact(evidence) || !textMentionsGoalId(evidence, goal.id)) return false;+ if (isFinalRunCompletionCandidate(plan, goal)) return snapshotObjectiveMapsToUlwLoopPlan(repoRoot, snapshotObjective, scope);+ if (!textMentionsUlwLoopPlanArtifact(evidence) || !textMentionsGoalId(evidence, goal.id)) return false;if (!textHasCompletionValidationEvidence(evidence)) return false;- return snapshotObjectiveMapsToUltragoalPlan(repoRoot, snapshotObjective);+ return snapshotObjectiveMapsToUlwLoopPlan(repoRoot, snapshotObjective, scope);}-function buildCompletedLegacyGoalRemediation(goal: UltragoalItem): string {+async function canReconcileActiveFinalTaskScopedAggregateSnapshot(repoRoot: string, plan: UlwLoopPlan, goal: UlwLoopItem, snapshotObjective: string, evidence: string, scope?: UlwLoopScope): Promise<boolean> {+ if (codexGoalMode(plan) !== "aggregate") return false;+ if (goal.status !== "in_progress" || plan.activeGoalId !== goal.id) return false;+ if (!isFinalRunCompletionCandidate(plan, goal)) return false;+ if (!textHasCompletionValidationEvidence(evidence)) return false;+ return snapshotObjectiveMapsToUlwLoopPlan(repoRoot, snapshotObjective, scope);+}++function buildCompletedLegacyGoalRemediation(goal: UlwLoopItem): string {return ["If get_goal returns a different completed legacy/thread objective, do not repeat --status complete in this thread.",- `Record a non-terminal blocker with: omo ultragoal checkpoint --goal-id ${goal.id} --status blocked --evidence "<completed legacy Codex goal blocks create_goal in this thread>" --codex-goal-json "<different completed get_goal JSON or path>".`,+ `Record a non-terminal blocker with: omo ulw-loop checkpoint --goal-id ${goal.id} --status blocked --evidence "<completed legacy Codex goal blocks create_goal in this thread>" --codex-goal-json "<different completed get_goal JSON or path>".`,"Then continue only from a Codex goal context with no active/completed conflicting goal, in the same repo/worktree, and create the intended goal there.",].join(" ");}-function buildTaskScopedAggregateReconciliationHint(goal: UltragoalItem, final: boolean): string {+function buildTaskScopedAggregateReconciliationHint(goal: UlwLoopItem, final: boolean): string {if (final) {- return ` Final task-scoped aggregate reconciliation requires the checkpoint goal to be the active in-progress final OMO goal and the completed get_goal objective to map to the ultragoal brief or artifact. ${buildCompletedLegacyGoalRemediation(goal)}`;+ return ` Final task-scoped aggregate reconciliation requires the checkpoint goal to be the active in-progress final OMO goal and the completed get_goal objective to map to the ulw-loop brief or artifact. ${buildCompletedLegacyGoalRemediation(goal)}`;}- return ` Completed task-scoped aggregate reconciliation requires the checkpoint goal to be the active in-progress OMO goal, evidence that names that active OMO goal id, names .omo/ultragoal/goals.json or ledger.jsonl, includes completed implementation plus validation/review evidence, and a get_goal objective that maps to the ultragoal brief/artifact. ${buildCompletedLegacyGoalRemediation(goal)}`;+ return ` Completed task-scoped aggregate reconciliation requires the checkpoint goal to be the active in-progress OMO goal, evidence that names that active OMO goal id, names .omo/ulw-loop/goals.json or ledger.jsonl, includes completed implementation plus validation/review evidence, and a get_goal objective that maps to the ulw-loop brief/artifact. ${buildCompletedLegacyGoalRemediation(goal)}`;}async function readJsonInput(raw: string | undefined, repoRoot: string): Promise<unknown> {@@ -74,15 +82,15 @@ async function readJsonInput(raw: string | undefined, repoRoot: string): Promiseconst trimmed = raw.trim();try { return JSON.parse(trimmed); } catch (error) { if (!(error instanceof SyntaxError)) throw error; }const path = resolve(repoRoot, trimmed);- if (!existsSync(path)) return ultragoalFail("Quality gate JSON is neither valid JSON nor a readable path.", "ultragoal_json_input_invalid");- try { return JSON.parse(await readFile(path, "utf8")); } catch (error) { return ultragoalFail(`Quality gate path does not contain valid JSON${error instanceof Error ? `: ${error.message}` : "."}`, "ultragoal_json_input_invalid"); }+ if (!existsSync(path)) return ulwLoopFail("Quality gate JSON is neither valid JSON nor a readable path.", "ulw_loop_json_input_invalid");+ try { return JSON.parse(await readFile(path, "utf8")); } catch (error) { return ulwLoopFail(`Quality gate path does not contain valid JSON${error instanceof Error ? `: ${error.message}` : "."}`, "ulw_loop_json_input_invalid"); }}-function makeAggregateCompletion(now: string, evidence: string, codexGoal: unknown): UltragoalAggregateCompletion {+function makeAggregateCompletion(now: string, evidence: string, codexGoal: unknown): UlwLoopAggregateCompletion {return { status: "complete", completedAt: now, evidence, codexGoal };}-function applyBlockedOrFailed(goal: UltragoalItem, plan: UltragoalPlan, status: "failed" | "blocked", evidence: string, now: string): void {+function applyBlockedOrFailed(goal: UlwLoopItem, plan: UlwLoopPlan, status: "failed" | "blocked", evidence: string, now: string): void {const signature = classifyExternalAuthorizationBlocker(evidence);const occurrences = signature === null ? 0 : sameBlockerOccurrences(plan, signature) + 1;const needsDecision = signature !== null && occurrences >= 3;@@ -95,15 +103,15 @@ function applyBlockedOrFailed(goal: UltragoalItem, plan: UltragoalPlan, status:if (plan.activeGoalId === goal.id) delete plan.activeGoalId;}-function ledgerKind(status: CheckpointUltragoalArgs["status"], goal: UltragoalItem, aggregateCompletion: UltragoalAggregateCompletion | undefined): UltragoalLedgerEntry["kind"] {+function ledgerKind(status: CheckpointUlwLoopArgs["status"], goal: UlwLoopItem, aggregateCompletion: UlwLoopAggregateCompletion | undefined): UlwLoopLedgerEntry["kind"] {if (aggregateCompletion !== undefined) return "aggregate_completed";if (status === "complete") return "goal_completed";if (goal.status === "needs_user_decision") return "goal_needs_user_decision";return status === "blocked" ? "goal_blocked" : "goal_failed";}-function buildLedger(now: string, args: CheckpointUltragoalArgs, goal: UltragoalItem, qualityGate: UltragoalQualityGate | undefined, codexGoal: unknown, aggregateCompletion: UltragoalAggregateCompletion | undefined): UltragoalLedgerEntry {- const entry: UltragoalLedgerEntry = { at: now, kind: ledgerKind(args.status, goal, aggregateCompletion), goalId: goal.id, status: goal.status, evidence: args.evidence };+function buildLedger(now: string, args: CheckpointUlwLoopArgs, goal: UlwLoopItem, qualityGate: UlwLoopQualityGate | undefined, codexGoal: unknown, aggregateCompletion: UlwLoopAggregateCompletion | undefined): UlwLoopLedgerEntry {+ const entry: UlwLoopLedgerEntry = { at: now, kind: ledgerKind(args.status, goal, aggregateCompletion), goalId: goal.id, status: goal.status, evidence: args.evidence };if (codexGoal !== undefined) entry.codexGoal = codexGoal;if (qualityGate !== undefined) entry.qualityGate = qualityGate;if (goal.blockerSignature !== undefined) entry.blockerSignature = goal.blockerSignature;@@ -112,15 +120,15 @@ function buildLedger(now: string, args: CheckpointUltragoalArgs, goal: Ultragoalreturn entry;}-export async function checkpointUltragoal(repoRoot: string, args: CheckpointUltragoalArgs): Promise<CheckpointUltragoalResult> {- return withUltragoalMutationLock(repoRoot, async () => {- const plan = await readUltragoalPlan(repoRoot);+export async function checkpointUlwLoop(repoRoot: string, args: CheckpointUlwLoopArgs, scope?: UlwLoopScope): Promise<CheckpointUlwLoopResult> {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ const plan = await readUlwLoopPlan(repoRoot, scope);const goal = findGoal(plan, args.goalId);if (args.status === "complete") requireAllCriteriaPass(goal);const evidence = nonEmptyEvidence(args.evidence);const now = iso();- let aggregateCompletion: UltragoalAggregateCompletion | undefined;- let qualityGate: UltragoalQualityGate | undefined;+ let aggregateCompletion: UlwLoopAggregateCompletion | undefined;+ let qualityGate: UlwLoopQualityGate | undefined;let codexGoal: unknown;if (args.status === "complete") {const aggregate = codexGoalMode(plan) === "aggregate";@@ -130,8 +138,11 @@ export async function checkpointUltragoal(repoRoot: string, args: CheckpointUltrcodexGoal = reconciliation.snapshot.raw;if (!reconciliation.ok) {const objective = snapshot?.objective;- const taskScoped = snapshot?.available === true && snapshot.status === "complete" && objective !== undefined && normalizeObjective(objective) !== normalizeObjective(expectedCodexObjective(plan, goal)) && await canReconcileCompletedTaskScopedAggregateSnapshot(repoRoot, plan, goal, objective, evidence);- if (!taskScoped) throw new UltragoalError(`${formatCodexGoalReconciliation(reconciliation)}${aggregate && snapshot?.status === "complete" && objective !== undefined ? buildTaskScopedAggregateReconciliationHint(goal, final) : ""}`, "ultragoal_codex_snapshot_mismatch");+ const mismatchedTaskObjective = snapshot?.available === true && objective !== undefined && normalizeObjective(objective) !== normalizeObjective(expectedCodexObjective(plan, goal));+ const completedTaskScoped = mismatchedTaskObjective && snapshot.status === "complete" && await canReconcileCompletedTaskScopedAggregateSnapshot(repoRoot, plan, goal, objective, evidence, scope);+ const activeFinalTaskScoped = mismatchedTaskObjective && snapshot.status === "active" && await canReconcileActiveFinalTaskScopedAggregateSnapshot(repoRoot, plan, goal, objective, evidence, scope);+ const taskScoped = completedTaskScoped || activeFinalTaskScoped;+ if (!taskScoped) throw new UlwLoopError(`${formatCodexGoalReconciliation(reconciliation)}${aggregate && snapshot?.status === "complete" && objective !== undefined ? buildTaskScopedAggregateReconciliationHint(goal, final) : ""}`, "ulw_loop_codex_snapshot_mismatch");aggregateCompletion = makeAggregateCompletion(now, evidence, codexGoal);}if (final) aggregateCompletion = makeAggregateCompletion(now, evidence, codexGoal);@@ -147,9 +158,9 @@ export async function checkpointUltragoal(repoRoot: string, args: CheckpointUltrgoal.updatedAt = now;if (aggregateCompletion !== undefined) plan.aggregateCompletion = aggregateCompletion;plan.updatedAt = now;- await writePlan(repoRoot, plan);+ await writePlan(repoRoot, plan, scope);const ledgerEntry = buildLedger(now, args, goal, qualityGate, codexGoal, aggregateCompletion);- await appendLedger(repoRoot, ledgerEntry);+ await appendLedger(repoRoot, ledgerEntry, scope);return aggregateCompletion === undefined ? { plan, goal, ledgerEntry } : { plan, goal, ledgerEntry, aggregateCompletion };});}diff --git a/plugins/omo/components/ultragoal/src/cli-arg-parser.ts b/plugins/omo/components/ulw-loop/src/cli-arg-parser.tssimilarity index 75%rename from plugins/omo/components/ultragoal/src/cli-arg-parser.tsrename to plugins/omo/components/ulw-loop/src/cli-arg-parser.tsindex e9028f4c..ebd2a794 100644--- a/plugins/omo/components/ultragoal/src/cli-arg-parser.ts+++ b/plugins/omo/components/ulw-loop/src/cli-arg-parser.ts@@ -1,11 +1,11 @@// biome-ignore-all format: keep this module under the mandated pure LOC budget.import { readFile } from "node:fs/promises";-import { UltragoalError } from "./types.js";+import { UlwLoopError } from "./types.js";type RecordEvidenceCliArgs = { readonly goalId: string; readonly criterionId: string; readonly status: "pass" | "fail" | "blocked"; readonly evidence: string; readonly notes?: string };-const VALUE_FLAGS = new Set("--brief --brief-file --codex-goal-mode --goal --goal-id --criterion-id --status --evidence --notes --codex-goal-json --quality-gate-json --kind --rationale --title --objective --target-goal-id --source --after-json --directive-json --directive-file --idempotency-key".split(" "));+const VALUE_FLAGS = new Set("--brief --brief-file --session-id --codex-goal-mode --goal --goal-id --criterion-id --status --evidence --notes --codex-goal-json --quality-gate-json --kind --rationale --title --objective --target-goal-id --source --after-json --directive-json --directive-file --idempotency-key".split(" "));const SUBCOMMANDS = new Set("create-goals status complete-goals criteria record-evidence checkpoint steer add-goal record-review-blockers".split(" "));export function hasFlag(argv: readonly string[], flag: string): boolean { return argv.includes(flag); }@@ -59,7 +59,7 @@ export async function readJsonInput(value: string | undefined): Promise<unknowntry { return JSON.parse(looksLikeJson(value) ? value : await readFile(value, "utf8")); }catch (error) {const message = error instanceof Error ? error.message : "unknown error";- throw new UltragoalError(`Invalid JSON input: ${message}`, "ULTRAGOAL_JSON_INPUT_INVALID", { cause: error });+ throw new UlwLoopError(`Invalid JSON input: ${message}`, "ULW_LOOP_JSON_INPUT_INVALID", { cause: error });}}@@ -69,14 +69,14 @@ export async function parseCodexGoalJson(value: string | undefined): Promise<strtry { JSON.parse(raw); return raw; }catch (error) {const message = error instanceof Error ? error.message : "unknown error";- throw new UltragoalError(`Invalid --codex-goal-json: ${message}`, "ULTRAGOAL_CODEX_GOAL_JSON_INVALID", { cause: error });+ throw new UlwLoopError(`Invalid --codex-goal-json: ${message}`, "ULW_LOOP_CODEX_GOAL_JSON_INVALID", { cause: error });}}function required(argv: readonly string[], flag: string, code: string): string {const value = readValue(argv, flag)?.trim();if (value) return value;- throw new UltragoalError(`Missing ${flag}.`, code, { details: { flag } });+ throw new UlwLoopError(`Missing ${flag}.`, code, { details: { flag } });}function evidenceStatus(value: string): RecordEvidenceCliArgs["status"] {@@ -84,12 +84,12 @@ function evidenceStatus(value: string): RecordEvidenceCliArgs["status"] {case "pass": return "pass";case "fail": return "fail";case "blocked": return "blocked";- default: throw new UltragoalError("Invalid --status; expected pass, fail, or blocked.", "ULTRAGOAL_EVIDENCE_STATUS_INVALID", { details: { status: value } });+ default: throw new UlwLoopError("Invalid --status; expected pass, fail, or blocked.", "ULW_LOOP_EVIDENCE_STATUS_INVALID", { details: { status: value } });}}export function parseRecordEvidenceArgs(argv: readonly string[]): RecordEvidenceCliArgs {- const result = { goalId: required(argv, "--goal-id", "ULTRAGOAL_GOAL_ID_REQUIRED"), criterionId: required(argv, "--criterion-id", "ULTRAGOAL_CRITERION_ID_REQUIRED"), status: evidenceStatus(required(argv, "--status", "ULTRAGOAL_EVIDENCE_STATUS_REQUIRED")), evidence: required(argv, "--evidence", "ULTRAGOAL_EVIDENCE_REQUIRED") };+ const result = { goalId: required(argv, "--goal-id", "ULW_LOOP_GOAL_ID_REQUIRED"), criterionId: required(argv, "--criterion-id", "ULW_LOOP_CRITERION_ID_REQUIRED"), status: evidenceStatus(required(argv, "--status", "ULW_LOOP_EVIDENCE_STATUS_REQUIRED")), evidence: required(argv, "--evidence", "ULW_LOOP_EVIDENCE_REQUIRED") };const notes = readValue(argv, "--notes")?.trim();return notes ? { ...result, notes } : result;}diff --git a/plugins/omo/components/ulw-loop/src/cli-commands.ts b/plugins/omo/components/ulw-loop/src/cli-commands.tsnew file mode 100644index 00000000..0b120f80--- /dev/null+++ b/plugins/omo/components/ulw-loop/src/cli-commands.ts@@ -0,0 +1,156 @@+// biome-ignore-all format: keep cli-commands dispatcher under the 200 pure LOC budget.+import { readFile } from "node:fs/promises";+import { type CheckpointUlwLoopArgs, checkpointUlwLoop } from "./checkpoint.js";+import { hasFlag, parseCodexGoalJson, parseRecordEvidenceArgs, positionalText, readStdin, readValue } from "./cli-arg-parser.js";+import { blockedDecisionHandoff, normalizeCodexGoalMode, printJson, printStatus, ULW_LOOP_HELP } from "./cli-output.js";+import { parseSteeringProposal, printSteerResult } from "./cli-steering.js";+import { buildCodexGoalInstruction } from "./codex-goal-instruction.js";+import { recordEvidence } from "./evidence.js";+import { resolveUlwLoopSessionIdFromEnv, type UlwLoopScope } from "./paths.js";+import { addUlwLoopGoal, createUlwLoopPlan, startNextUlwLoop, summarizeUlwLoopPlan } from "./plan-crud.js";+import { readUlwLoopPlan } from "./plan-io.js";+import { recordFinalReviewBlockers } from "./review-blockers.js";+import { steerUlwLoop } from "./steering.js";+import type { UlwLoopItem } from "./types.js";+import { UlwLoopError } from "./types.js";++type CheckpointStatus = "complete" | "failed" | "blocked";++export async function ulwLoopCommand(argv: readonly string[]): Promise<number> {+ const command = argv[0] ?? "help";+ const rest = argv.slice(1);+ const repoRoot = process.cwd();+ const json = hasFlag(rest, "--json");+ const scope = commandScope(rest);+ try {+ switch (command) {+ case "help": case "--help": case "-h": 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);+ case "checkpoint": return await checkpoint(repoRoot, rest, json, scope);+ case "steer": return await steer(repoRoot, rest, json, scope);+ case "add-goal": return await addGoal(repoRoot, rest, json, scope);+ 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;+ }+ } catch (error) {+ if (error instanceof UlwLoopError) process.stderr.write(`[ulw-loop] ${error.message}\n`);+ else if (error instanceof Error) process.stderr.write(`[ulw-loop] unexpected: ${error.message}\n`);+ else process.stderr.write("[ulw-loop] unknown error\n");+ return 1;+ }+}++function commandScope(argv: readonly string[]): UlwLoopScope | undefined {+ const sessionId = readValue(argv, "--session-id") ?? resolveUlwLoopSessionIdFromEnv();+ return sessionId === null ? undefined : { sessionId };+}++async function createGoals(repoRoot: string, argv: readonly string[], json: boolean, scope?: UlwLoopScope): Promise<number> {+ const briefFile = readValue(argv, "--brief-file");+ const brief = readValue(argv, "--brief") ?? (briefFile === undefined ? undefined : await readFile(briefFile, "utf8")) ?? (hasFlag(argv, "--from-stdin") ? await readStdin() : undefined) ?? positionalText(argv);+ if (!brief.trim()) throw new UlwLoopError("Missing brief text. Pass --brief, --brief-file, --from-stdin, or positional text.", "ULW_LOOP_BRIEF_REQUIRED");+ const plan = await createUlwLoopPlan(repoRoot, { brief, codexGoalMode: normalizeCodexGoalMode(readValue(argv, "--codex-goal-mode")), force: hasFlag(argv, "--force") }, scope);+ if (json) printJson({ ok: true, plan, summary: summarizeUlwLoopPlan(plan) });+ else process.stdout.write(`ulw-loop plan created: ${plan.goals.length} goal(s)\nbrief: ${plan.briefPath}\ngoals: ${plan.goalsPath}\nledger: ${plan.ledgerPath}\n`);+ return 0;+}++async function status(repoRoot: string, json: boolean, scope?: UlwLoopScope): Promise<number> {+ const plan = await readUlwLoopPlan(repoRoot, scope);+ if (json) printJson({ ok: true, plan, summary: summarizeUlwLoopPlan(plan) });+ else printStatus(plan);+ return 0;+}++async function completeGoals(repoRoot: string, argv: readonly string[], json: boolean, scope?: UlwLoopScope): Promise<number> {+ const result = await startNextUlwLoop(repoRoot, { retryFailed: hasFlag(argv, "--retry-failed") }, scope);+ if ("done" in result) {+ const handoff = blockedDecisionHandoff(result.plan);+ if (json) printJson({ ok: true, done: true, blocked: handoff.length > 0, handoff, summary: summarizeUlwLoopPlan(result.plan), plan: result.plan });+ else process.stdout.write(`${handoff || "ulw-loop: all goals complete"}\n`);+ return 0;+ }+ const instruction = buildCodexGoalInstruction({ plan: result.plan, goal: result.goal });+ if (json) printJson({ ok: true, resumed: result.resumed, goal: result.goal, instruction, plan: result.plan });+ else process.stdout.write(`${instruction.text}\n`);+ return 0;+}++async function checkpoint(repoRoot: string, argv: readonly string[], json: boolean, scope?: UlwLoopScope): Promise<number> {+ const goalId = required(argv, "--goal-id");+ const statusValue = checkpointStatus(required(argv, "--status"));+ const evidence = required(argv, "--evidence");+ const codexGoalJson = await parseCodexGoalJson(statusValue === "complete" ? required(argv, "--codex-goal-json") : readValue(argv, "--codex-goal-json"));+ if (statusValue === "complete" && codexGoalJson === undefined) throw new UlwLoopError("Missing --codex-goal-json.", "ULW_LOOP_CODEX_GOAL_JSON_REQUIRED");+ const qualityGateJson = readValue(argv, "--quality-gate-json");+ const args: CheckpointUlwLoopArgs = {+ goalId,+ status: statusValue,+ evidence,+ ...(codexGoalJson === undefined ? {} : { codexGoalJson }),+ ...(qualityGateJson === undefined ? {} : { qualityGateJson }),+ };+ const result = await checkpointUlwLoop(repoRoot, args, scope);+ if (json) printJson({ ok: true, ...result, summary: summarizeUlwLoopPlan(result.plan) });+ else process.stdout.write(`ulw-loop checkpoint: ${result.goal.id} -> ${result.goal.status}\n`);+ return 0;+}++async function steer(repoRoot: string, argv: readonly string[], json: boolean, scope?: UlwLoopScope): Promise<number> {+ const proposal = await parseSteeringProposal(argv);+ const result = await steerUlwLoop(repoRoot, proposal, scope);+ printSteerResult(result, json);+ return result.accepted ? 0 : 1;+}++async function addGoal(repoRoot: string, argv: readonly string[], json: boolean, scope?: UlwLoopScope): Promise<number> {+ const result = await addUlwLoopGoal(repoRoot, { title: required(argv, "--title"), objective: required(argv, "--objective") }, scope);+ if (json) printJson({ ok: true, plan: result.plan, goal: result.goal, summary: summarizeUlwLoopPlan(result.plan) });+ else { process.stdout.write(`ulw-loop added goal: ${result.goal.id}\n`); printStatus(result.plan); }+ return 0;+}++async function criteria(repoRoot: string, argv: readonly string[], json: boolean, scope?: UlwLoopScope): Promise<number> {+ const goalId = required(argv, "--goal-id");+ const goal = findGoal(await readUlwLoopPlan(repoRoot, scope), goalId);+ if (json) printJson({ ok: true, goalId: goal.id, criteria: goal.successCriteria });+ else process.stdout.write(`criteria for ${goal.id}:\n${goal.successCriteria.map((c) => `- ${c.id} [${c.status}] (${c.userModel}) ${c.scenario} evidence: ${c.capturedEvidence ?? "pending"}`).join("\n")}\n`);+ return 0;+}++async function captureEvidence(repoRoot: string, argv: readonly string[], json: boolean, scope?: UlwLoopScope): Promise<number> {+ const result = await recordEvidence(repoRoot, parseRecordEvidenceArgs(argv), scope);+ if (json) printJson({ ok: true, ...result, summary: summarizeUlwLoopPlan(result.plan) });+ else process.stdout.write(`ulw-loop evidence recorded: ${result.goal.id}/${result.criterion.id} -> ${result.criterion.status}\n`);+ return 0;+}++async function reviewBlockers(repoRoot: string, argv: readonly string[], json: boolean, scope?: UlwLoopScope): Promise<number> {+ const codexGoalJson = await parseCodexGoalJson(required(argv, "--codex-goal-json"));+ if (codexGoalJson === undefined) throw new UlwLoopError("Missing --codex-goal-json.", "ULW_LOOP_CODEX_GOAL_JSON_REQUIRED");+ const result = await recordFinalReviewBlockers(repoRoot, { goalId: required(argv, "--goal-id"), title: required(argv, "--title"), objective: required(argv, "--objective"), evidence: required(argv, "--evidence"), codexGoalJson }, scope);+ if (json) printJson({ ok: true, plan: result.plan, blockedGoal: result.blockedGoal, goal: result.newGoal, ledgerEntries: result.ledgerEntries, summary: summarizeUlwLoopPlan(result.plan) });+ else process.stdout.write(`ulw-loop final review blockers recorded: ${result.blockedGoal.id} -> review_blocked; added ${result.newGoal.id}\n`);+ return 0;+}++function required(argv: readonly string[], flag: string): string {+ const value = readValue(argv, flag)?.trim();+ if (value) return value;+ throw new UlwLoopError(`Missing ${flag}.`, "ULW_LOOP_ARGUMENT_MISSING", { details: { flag } });+}++function checkpointStatus(value: string): CheckpointStatus {+ if (value === "complete" || value === "failed" || value === "blocked") return value;+ throw new UlwLoopError("Missing or invalid --status; expected complete, failed, or blocked.", "ULW_LOOP_STATUS_INVALID", { details: { status: value } });+}++function findGoal(plan: { readonly goals: readonly UlwLoopItem[] }, goalId: string): UlwLoopItem {+ const goal = plan.goals.find((candidate) => candidate.id === goalId);+ if (goal !== undefined) return goal;+ throw new UlwLoopError(`Unknown ulw-loop id: ${goalId}.`, "ULW_LOOP_GOAL_NOT_FOUND", { details: { goalId } });+}diff --git a/plugins/omo/components/ultragoal/src/cli-output.ts b/plugins/omo/components/ulw-loop/src/cli-output.tssimilarity index 51%rename from plugins/omo/components/ultragoal/src/cli-output.tsrename to plugins/omo/components/ulw-loop/src/cli-output.tsindex ef7ed253..aeb70adc 100644--- a/plugins/omo/components/ultragoal/src/cli-output.ts+++ b/plugins/omo/components/ulw-loop/src/cli-output.ts@@ -1,16 +1,18 @@-import type { UltragoalCodexGoalMode, UltragoalItem, UltragoalPlan } from "./types.js";-import { UltragoalError } from "./types.js";--export const ULTRAGOAL_HELP = `Usage:- omo ultragoal create-goals --brief "..." [--brief-file <path>] [--from-stdin] [--codex-goal-mode aggregate|per_story] [--force] [--json]- omo ultragoal status [--json]- omo ultragoal complete-goals [--retry-failed] [--json]- omo ultragoal criteria --goal-id <id> [--json]- omo ultragoal record-evidence --goal-id <id> --criterion-id <id> --status pass|fail|blocked --evidence "..." [--notes "..."] [--json]- omo ultragoal checkpoint --goal-id <id> --status complete|failed|blocked --evidence "..." --codex-goal-json <...> [--quality-gate-json <...>] [--json]- omo ultragoal steer --kind <kind> ... --evidence "..." --rationale "..." [--json]- omo ultragoal add-goal --title "..." --objective "..." [--json]- omo ultragoal record-review-blockers --goal-id <id> --title "..." --objective "..." --evidence "..." --codex-goal-json <...> [--json]`;+import type { UlwLoopCodexGoalMode, UlwLoopItem, UlwLoopPlan } from "./types.js";+import { UlwLoopError } from "./types.js";++export const ULW_LOOP_HELP = `Usage:+ omo ulw-loop create-goals --brief "..." [--brief-file <path>] [--from-stdin] [--codex-goal-mode aggregate|per_story] [--force] [--json]+ omo ulw-loop status [--json]+ omo ulw-loop complete-goals [--retry-failed] [--json]+ omo ulw-loop criteria --goal-id <id> [--json]+ omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status pass|fail|blocked --evidence "..." [--notes "..."] [--json]+ omo ulw-loop checkpoint --goal-id <id> --status complete|failed|blocked --evidence "..." --codex-goal-json <...> [--quality-gate-json <...>] [--json]+ omo ulw-loop steer --kind <kind> ... --evidence "..." --rationale "..." [--json]+ omo ulw-loop add-goal --title "..." --objective "..." [--json]+ omo ulw-loop record-review-blockers --goal-id <id> --title "..." --objective "..." --evidence "..." --codex-goal-json <...> [--json]++All subcommands accept [--session-id <id>] to isolate state under .omo/ulw-loop/<id>/; without it, Codex session env is used when present.`;type CriteriaCounts = { readonly pass: number; readonly total: number };@@ -18,16 +20,16 @@ export function printJson(value: unknown): void {process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);}-function criteriaCounts(goal: UltragoalItem): CriteriaCounts {+function criteriaCounts(goal: UlwLoopItem): CriteriaCounts {let pass = 0;for (const criterion of goal.successCriteria) if (criterion.status === "pass") pass += 1;return { pass, total: goal.successCriteria.length };}-export function printStatus(plan: UltragoalPlan): void {+export function printStatus(plan: UlwLoopPlan): void {let totalCriteria = 0;let passCriteria = 0;- const lines = ["ultragoal status", "", "goals:"];+ const lines = ["ulw-loop status", "", "goals:"];for (const goal of plan.goals) {const counts = criteriaCounts(goal);totalCriteria += counts.total;@@ -39,23 +41,23 @@ export function printStatus(plan: UltragoalPlan): void {process.stdout.write(`${lines.join("\n")}\n`);}-export function blockedDecisionHandoff(plan: UltragoalPlan): string {+export function blockedDecisionHandoff(plan: UlwLoopPlan): string {const blocked = plan.goals.find((goal) => goal.status === "needs_user_decision" && goal.nonRetriable);if (blocked === undefined) return "";return [- "ultragoal: blocked on repeated external authorization; no retryable failed goals remain.",+ "ulw-loop: blocked on repeated external authorization; no retryable failed goals remain.",`Goal: ${blocked.id} - ${blocked.title}`,`Required external decision: ${blocked.requiredExternalDecision ?? "provide the missing authorization or choose a different unblock path"}.`,"Do not run complete-goals --retry-failed again until external state changes or the user authorizes an unblock path.",].join("\n");}-export function normalizeCodexGoalMode(value: string | undefined): UltragoalCodexGoalMode {+export function normalizeCodexGoalMode(value: string | undefined): UlwLoopCodexGoalMode {if (value === undefined) return "aggregate";if (value === "aggregate" || value === "per_story") return value;- throw new UltragoalError(+ throw new UlwLoopError("Invalid --codex-goal-mode; expected aggregate or per_story.",- "ULTRAGOAL_CODEX_GOAL_MODE_INVALID",+ "ULW_LOOP_CODEX_GOAL_MODE_INVALID",{ details: { value } },);}diff --git a/plugins/omo/components/ultragoal/src/cli-steering.ts b/plugins/omo/components/ulw-loop/src/cli-steering.tssimilarity index 66%rename from plugins/omo/components/ultragoal/src/cli-steering.tsrename to plugins/omo/components/ulw-loop/src/cli-steering.tsindex d0794da8..e7f6b8b9 100644--- a/plugins/omo/components/ultragoal/src/cli-steering.ts+++ b/plugins/omo/components/ulw-loop/src/cli-steering.ts@@ -1,63 +1,63 @@// biome-ignore-all format: keep this module under the mandated pure LOC budget.import { parseGoalArg, readJsonInput, readValue } from "./cli-arg-parser.js";import { printJson, printStatus } from "./cli-output.js";-import type { SteerUltragoalResult, UltragoalSteeringChildGoal, UltragoalSteeringMutationKind, UltragoalSteeringProposal, UltragoalSteeringSource, UltragoalSuccessCriterionUserModel } from "./types.js";-import { ULTRAGOAL_STEERING_MUTATION_KINDS, ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS, UltragoalError } from "./types.js";+import type { SteerUlwLoopResult, UlwLoopSteeringChildGoal, UlwLoopSteeringMutationKind, UlwLoopSteeringProposal, UlwLoopSteeringSource, UlwLoopSuccessCriterionUserModel } from "./types.js";+import { ULW_LOOP_STEERING_MUTATION_KINDS, ULW_LOOP_SUCCESS_CRITERION_USER_MODELS, UlwLoopError } from "./types.js";-const SOURCES = ["user_prompt_submit", "finding", "cli"] as const satisfies readonly UltragoalSteeringSource[];+const SOURCES = ["user_prompt_submit", "finding", "cli"] as const satisfies readonly UlwLoopSteeringSource[];-export type CliSteeringProposal = UltragoalSteeringProposal & { readonly goalId?: string; readonly scenario?: string; readonly expectedEvidence?: string; readonly userModel?: UltragoalSuccessCriterionUserModel };+export type CliSteeringProposal = UlwLoopSteeringProposal & { readonly goalId?: string; readonly scenario?: string; readonly expectedEvidence?: string; readonly userModel?: UlwLoopSuccessCriterionUserModel };-function isKind(value: string | undefined): value is UltragoalSteeringMutationKind { return value !== undefined && ULTRAGOAL_STEERING_MUTATION_KINDS.some((kind) => kind === value); }-function isSource(value: string | undefined): value is UltragoalSteeringSource { return value !== undefined && SOURCES.some((source) => source === value); }-function isModel(value: string): value is UltragoalSuccessCriterionUserModel { return ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS.some((model) => model === value); }-function fail(message: string, code: string, details: Record<string, unknown>): never { throw new UltragoalError(message, code, { details }); }-function text(value: string | undefined, field: string): string | undefined { if (value === undefined) return undefined; const trimmed = value.trim(); if (trimmed.length > 0) return trimmed; return fail(`Empty ${field}.`, "ULTRAGOAL_STEERING_FIELD_EMPTY", { field }); }-function required(argv: readonly string[], flag: string): string { const value = text(readValue(argv, flag), flag); return value ?? fail(`Missing ${flag}.`, "ULTRAGOAL_STEERING_FIELD_REQUIRED", { flag }); }-function requiredGoal(argv: readonly string[]): string { const value = text(parseGoalArg(argv), "--goal-id"); return value ?? fail("Missing --goal-id.", "ULTRAGOAL_GOAL_ID_REQUIRED", { flag: "--goal-id" }); }+function isKind(value: string | undefined): value is UlwLoopSteeringMutationKind { return value !== undefined && ULW_LOOP_STEERING_MUTATION_KINDS.some((kind) => kind === value); }+function isSource(value: string | undefined): value is UlwLoopSteeringSource { return value !== undefined && SOURCES.some((source) => source === value); }+function isModel(value: string): value is UlwLoopSuccessCriterionUserModel { return ULW_LOOP_SUCCESS_CRITERION_USER_MODELS.some((model) => model === value); }+function fail(message: string, code: string, details: Record<string, unknown>): never { throw new UlwLoopError(message, code, { details }); }+function text(value: string | undefined, field: string): string | undefined { if (value === undefined) return undefined; const trimmed = value.trim(); if (trimmed.length > 0) return trimmed; return fail(`Empty ${field}.`, "ULW_LOOP_STEERING_FIELD_EMPTY", { field }); }+function required(argv: readonly string[], flag: string): string { const value = text(readValue(argv, flag), flag); return value ?? fail(`Missing ${flag}.`, "ULW_LOOP_STEERING_FIELD_REQUIRED", { flag }); }+function requiredGoal(argv: readonly string[]): string { const value = text(parseGoalArg(argv), "--goal-id"); return value ?? fail("Missing --goal-id.", "ULW_LOOP_GOAL_ID_REQUIRED", { flag: "--goal-id" }); }function readObject(value: object, key: string): unknown { return Object.entries(value).find(([name]) => name === key)?.[1]; }function isPlain(value: unknown): value is object { return typeof value === "object" && value !== null && !Array.isArray(value); }function objectText(value: object, key: string): string | undefined { const candidate = readObject(value, key); return typeof candidate === "string" ? candidate : undefined; }-export function parseSteeringKind(argv: readonly string[]): UltragoalSteeringMutationKind {+export function parseSteeringKind(argv: readonly string[]): UlwLoopSteeringMutationKind {const value = readValue(argv, "--kind");if (isKind(value)) return value;- return value === undefined ? fail("Missing --kind.", "ULTRAGOAL_STEERING_KIND_REQUIRED", { flag: "--kind" }) : fail(`Invalid --kind: ${value}.`, "ULTRAGOAL_STEERING_KIND_INVALID", { value, expected: ULTRAGOAL_STEERING_MUTATION_KINDS });+ return value === undefined ? fail("Missing --kind.", "ULW_LOOP_STEERING_KIND_REQUIRED", { flag: "--kind" }) : fail(`Invalid --kind: ${value}.`, "ULW_LOOP_STEERING_KIND_INVALID", { value, expected: ULW_LOOP_STEERING_MUTATION_KINDS });}-export function parseSteeringSource(argv: readonly string[]): UltragoalSteeringSource {+export function parseSteeringSource(argv: readonly string[]): UlwLoopSteeringSource {const value = readValue(argv, "--source");if (value === undefined) return "cli";- return isSource(value) ? value : fail(`Invalid --source: ${value}.`, "ULTRAGOAL_STEERING_SOURCE_INVALID", { value, expected: SOURCES });+ return isSource(value) ? value : fail(`Invalid --source: ${value}.`, "ULW_LOOP_STEERING_SOURCE_INVALID", { value, expected: SOURCES });}-function child(value: unknown): UltragoalSteeringChildGoal | null {+function child(value: unknown): UlwLoopSteeringChildGoal | null {if (!isPlain(value)) return null;const title = text(objectText(value, "title"), "title"); const objective = text(objectText(value, "objective"), "objective");if (title === undefined || objective === undefined) return null;return { title, objective };}-async function children(argv: readonly string[], flag: string, needed: boolean): Promise<UltragoalSteeringChildGoal[]> {+async function children(argv: readonly string[], flag: string, needed: boolean): Promise<UlwLoopSteeringChildGoal[]> {const input = needed ? required(argv, flag) : text(readValue(argv, flag), flag);if (input === undefined) return [];const raw = await readJsonInput(input);- if (!Array.isArray(raw)) return fail(`${flag} must be a JSON array.`, "ULTRAGOAL_STEERING_JSON_ARRAY_REQUIRED", { flag });- const parsed: UltragoalSteeringChildGoal[] = [];- for (const item of raw) { const next = child(item); if (next === null) return fail(`${flag} entries require title/objective.`, "ULTRAGOAL_STEERING_CHILD_INVALID", { flag }); parsed.push(next); }+ if (!Array.isArray(raw)) return fail(`${flag} must be a JSON array.`, "ULW_LOOP_STEERING_JSON_ARRAY_REQUIRED", { flag });+ const parsed: UlwLoopSteeringChildGoal[] = [];+ for (const item of raw) { const next = child(item); if (next === null) return fail(`${flag} entries require title/objective.`, "ULW_LOOP_STEERING_CHILD_INVALID", { flag }); parsed.push(next); }return parsed;}async function stringArray(argv: readonly string[], flag: string): Promise<string[]> {const raw = await readJsonInput(required(argv, flag));- if (!Array.isArray(raw)) return fail(`${flag} must be a JSON array.`, "ULTRAGOAL_STEERING_JSON_ARRAY_REQUIRED", { flag });+ if (!Array.isArray(raw)) return fail(`${flag} must be a JSON array.`, "ULW_LOOP_STEERING_JSON_ARRAY_REQUIRED", { flag });const values: string[] = [];- for (const item of raw) { if (typeof item !== "string") return fail(`${flag} entries must be strings.`, "ULTRAGOAL_STEERING_STRING_ARRAY_REQUIRED", { flag }); values.push(text(item, flag) ?? ""); }+ for (const item of raw) { if (typeof item !== "string") return fail(`${flag} entries must be strings.`, "ULW_LOOP_STEERING_STRING_ARRAY_REQUIRED", { flag }); values.push(text(item, flag) ?? ""); }return values;}-function model(value: string | undefined): UltragoalSuccessCriterionUserModel | undefined { const trimmed = text(value, "--user-model"); if (trimmed === undefined) return undefined; return isModel(trimmed) ? trimmed : fail(`Invalid --user-model: ${trimmed}.`, "ULTRAGOAL_STEERING_USER_MODEL_INVALID", { value: trimmed, expected: ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS }); }-function neverKind(kind: never): never { return fail(`Unsupported steering kind: ${String(kind)}.`, "ULTRAGOAL_STEERING_KIND_UNSUPPORTED", { kind }); }+function model(value: string | undefined): UlwLoopSuccessCriterionUserModel | undefined { const trimmed = text(value, "--user-model"); if (trimmed === undefined) return undefined; return isModel(trimmed) ? trimmed : fail(`Invalid --user-model: ${trimmed}.`, "ULW_LOOP_STEERING_USER_MODEL_INVALID", { value: trimmed, expected: ULW_LOOP_SUCCESS_CRITERION_USER_MODELS }); }+function neverKind(kind: never): never { return fail(`Unsupported steering kind: ${String(kind)}.`, "ULW_LOOP_STEERING_KIND_UNSUPPORTED", { kind }); }export async function parseSteeringProposal(argv: readonly string[]): Promise<CliSteeringProposal> {const kind = parseSteeringKind(argv); const source = parseSteeringSource(argv); const base = { kind, source, evidence: required(argv, "--evidence"), rationale: required(argv, "--rationale") };@@ -65,15 +65,15 @@ export async function parseSteeringProposal(argv: readonly string[]): Promise<Clcase "add_subgoal": return normalizeSteeringProposal({ ...base, title: required(argv, "--title"), objective: required(argv, "--objective") });case "split_subgoal": { const goalId = requiredGoal(argv); return normalizeSteeringProposal({ ...base, goalId, targetGoalId: goalId, childGoals: await children(argv, "--children", true) }); }case "reorder_pending": return normalizeSteeringProposal({ ...base, pendingOrder: await stringArray(argv, "--order") });- case "revise_pending_wording": { const goalId = requiredGoal(argv); const revisedTitle = readValue(argv, "--title"); const revisedObjective = readValue(argv, "--objective"); if (revisedTitle === undefined && revisedObjective === undefined) return fail("revise_pending_wording requires --title or --objective.", "ULTRAGOAL_STEERING_UPDATE_REQUIRED", { kind }); return normalizeSteeringProposal({ ...base, goalId, targetGoalId: goalId, ...(revisedTitle === undefined ? {} : { revisedTitle }), ...(revisedObjective === undefined ? {} : { revisedObjective }) }); }- case "revise_criterion": { const goalId = requiredGoal(argv); const criterionId = required(argv, "--criterion-id"); const scenario = readValue(argv, "--scenario"); const expectedEvidence = readValue(argv, "--expected-evidence"); const userModel = model(readValue(argv, "--user-model")); if (scenario === undefined && expectedEvidence === undefined && userModel === undefined) return fail("revise_criterion requires scenario, expected-evidence, or user-model.", "ULTRAGOAL_STEERING_UPDATE_REQUIRED", { kind }); return normalizeSteeringProposal({ ...base, goalId, targetGoalId: goalId, criterionId, ...(scenario === undefined ? {} : { scenario }), ...(expectedEvidence === undefined ? {} : { expectedEvidence }), ...(userModel === undefined ? {} : { userModel }) }); }+ case "revise_pending_wording": { const goalId = requiredGoal(argv); const revisedTitle = readValue(argv, "--title"); const revisedObjective = readValue(argv, "--objective"); if (revisedTitle === undefined && revisedObjective === undefined) return fail("revise_pending_wording requires --title or --objective.", "ULW_LOOP_STEERING_UPDATE_REQUIRED", { kind }); return normalizeSteeringProposal({ ...base, goalId, targetGoalId: goalId, ...(revisedTitle === undefined ? {} : { revisedTitle }), ...(revisedObjective === undefined ? {} : { revisedObjective }) }); }+ case "revise_criterion": { const goalId = requiredGoal(argv); const criterionId = required(argv, "--criterion-id"); const scenario = readValue(argv, "--scenario"); const expectedEvidence = readValue(argv, "--expected-evidence"); const userModel = model(readValue(argv, "--user-model")); if (scenario === undefined && expectedEvidence === undefined && userModel === undefined) return fail("revise_criterion requires scenario, expected-evidence, or user-model.", "ULW_LOOP_STEERING_UPDATE_REQUIRED", { kind }); return normalizeSteeringProposal({ ...base, goalId, targetGoalId: goalId, criterionId, ...(scenario === undefined ? {} : { scenario }), ...(expectedEvidence === undefined ? {} : { expectedEvidence }), ...(userModel === undefined ? {} : { userModel }) }); }case "annotate_ledger": return normalizeSteeringProposal(base);case "mark_blocked_superseded": { const goalId = requiredGoal(argv); const childGoals = await children(argv, "--replacements", false); return normalizeSteeringProposal({ ...base, goalId, targetGoalId: goalId, ...(childGoals.length === 0 ? {} : { childGoals }) }); }default: return neverKind(kind);}}-function normalizedChildren(values: readonly UltragoalSteeringChildGoal[] | undefined): UltragoalSteeringChildGoal[] | undefined { if (values === undefined) return undefined; return values.map((item) => ({ title: text(item.title, "child.title") ?? "", objective: text(item.objective, "child.objective") ?? "" })); }+function normalizedChildren(values: readonly UlwLoopSteeringChildGoal[] | undefined): UlwLoopSteeringChildGoal[] | undefined { if (values === undefined) return undefined; return values.map((item) => ({ title: text(item.title, "child.title") ?? "", objective: text(item.objective, "child.objective") ?? "" })); }function normalizedStrings(values: readonly string[] | undefined, field: string): string[] | undefined { if (values === undefined) return undefined; return values.map((value) => text(value, field) ?? ""); }export function normalizeSteeringProposal(proposal: CliSteeringProposal): CliSteeringProposal {@@ -84,10 +84,10 @@ export function normalizeSteeringProposal(proposal: CliSteeringProposal): CliStereturn { kind: proposal.kind, source: proposal.source, evidence, rationale, ...(goalId === undefined ? {} : { goalId }), ...(targetGoalId === undefined ? {} : { targetGoalId }), ...(targetGoalIds === undefined ? {} : { targetGoalIds }), ...(criterionId === undefined ? {} : { criterionId }), ...(title === undefined ? {} : { title }), ...(objective === undefined ? {} : { objective }), ...(childGoals === undefined ? {} : { childGoals }), ...(revisedTitle === undefined ? {} : { revisedTitle }), ...(revisedObjective === undefined ? {} : { revisedObjective }), ...(pendingOrder === undefined ? {} : { pendingOrder }), ...(blockedReason === undefined ? {} : { blockedReason }), ...(proposal.after === undefined ? {} : { after: proposal.after }), ...(directiveText === undefined ? {} : { directiveText }), ...(promptSignature === undefined ? {} : { promptSignature }), ...(idempotencyKey === undefined ? {} : { idempotencyKey }), ...(proposal.now === undefined ? {} : { now: proposal.now }), ...(scenario === undefined ? {} : { scenario }), ...(expectedEvidence === undefined ? {} : { expectedEvidence }), ...(proposal.userModel === undefined ? {} : { userModel: proposal.userModel }) };}-export function printSteerResult(result: SteerUltragoalResult, json: boolean): void {+export function printSteerResult(result: SteerUlwLoopResult, json: boolean): void {if (json) { printJson({ ok: result.accepted, accepted: result.accepted, rejectedReasons: result.rejectedReasons, deduped: result.deduped, audit: result.audit, plan: result.plan }); return; }const outcome = result.deduped ? "deduped" : result.accepted ? "accepted" : "rejected";- process.stdout.write(`ultragoal steer: ${outcome} ${result.audit.kind}\n`);+ process.stdout.write(`ulw-loop steer: ${outcome} ${result.audit.kind}\n`);if (result.rejectedReasons.length > 0) process.stdout.write(`rejected: ${result.rejectedReasons.join("; ")}\n`);if (result.audit.idempotencyKey !== undefined) process.stdout.write(`idempotency-key: ${result.audit.idempotencyKey}\n`);printStatus(result.plan);diff --git a/plugins/omo/components/ultragoal/src/cli.ts b/plugins/omo/components/ulw-loop/src/cli.tssimilarity index 56%rename from plugins/omo/components/ultragoal/src/cli.tsrename to plugins/omo/components/ulw-loop/src/cli.tsindex 4570f692..ed9d5fd9 100644--- a/plugins/omo/components/ultragoal/src/cli.ts+++ b/plugins/omo/components/ulw-loop/src/cli.ts@@ -1,9 +1,9 @@#!/usr/bin/env node-import { ultragoalCommand } from "./cli-commands.js";-import { runUltragoalHookCli } from "./codex-hook.js";+import { ulwLoopCommand } from "./cli-commands.js";+import { runPreToolUseGoalBudgetGuardCli, runUlwLoopHookCli } from "./codex-hook.js";const TOP_LEVEL_HELP =- "Usage:\n omo ultragoal <subcommand> [args]\n omo hook user-prompt-submit (Codex UserPromptSubmit hook)\n omo help | --help | -h (this message)\n\nRun `omo ultragoal help` for ultragoal subcommands.\n";+ "Usage:\n omo ulw-loop <subcommand> [args]\n omo hook user-prompt-submit (Codex UserPromptSubmit hook)\n omo help | --help | -h (this message)\n\nRun `omo ulw-loop help` for ulw-loop subcommands.\n";async function main(): Promise<number> {const argv = process.argv.slice(2);@@ -12,11 +12,15 @@ async function main(): Promise<number> {process.stdout.write(TOP_LEVEL_HELP);return 0;}- if (command === "ultragoal") return ultragoalCommand(argv.slice(1));+ if (command === "ulw-loop") return ulwLoopCommand(argv.slice(1));if (command === "hook") {const sub = argv[1];if (sub === "user-prompt-submit") {- await runUltragoalHookCli(process.stdin, process.stdout);+ await runUlwLoopHookCli(process.stdin, process.stdout);+ return 0;+ }+ if (sub === "pre-tool-use") {+ await runPreToolUseGoalBudgetGuardCli(process.stdin, process.stdout);return 0;}process.stderr.write(`[omo] unknown hook subcommand: ${sub ?? "(none)"}\n`);diff --git a/plugins/omo/components/ultragoal/src/codex-goal-instruction.ts b/plugins/omo/components/ulw-loop/src/codex-goal-instruction.tssimilarity index 59%rename from plugins/omo/components/ultragoal/src/codex-goal-instruction.tsrename to plugins/omo/components/ulw-loop/src/codex-goal-instruction.tsindex b1994eb8..48224672 100644--- a/plugins/omo/components/ultragoal/src/codex-goal-instruction.ts+++ b/plugins/omo/components/ulw-loop/src/codex-goal-instruction.ts@@ -1,40 +1,40 @@import { codexGoalMode, expectedCodexObjective, isFinalRunCompletionCandidate } from "./goal-status.js";-import type { UltragoalCodexGoalMode, UltragoalItem, UltragoalPlan, UltragoalSuccessCriterion } from "./types.js";+import type { UlwLoopCodexGoalMode, UlwLoopItem, UlwLoopPlan, UlwLoopSuccessCriterion } from "./types.js";export interface CodexCreateGoalPayload {readonly objective: string;readonly status: "active";}-export interface UltragoalGoalInstruction {+export interface UlwLoopGoalInstruction {readonly text: string;readonly json: CodexCreateGoalPayload;}export function buildCodexGoalInstruction(args: {- readonly plan: UltragoalPlan;- readonly goal: UltragoalItem;+ readonly plan: UlwLoopPlan;+ readonly goal: UlwLoopItem;readonly isFinal?: boolean;-}): UltragoalGoalInstruction {+}): UlwLoopGoalInstruction {const mode = codexGoalMode(args.plan);const createGoal = buildCreateGoalPayload(args.plan, args.goal);const isFinal = args.isFinal ?? isFinalRunCompletionCandidate(args.plan, args.goal);return { text: buildText(mode, args.plan, args.goal, createGoal, isFinal), json: createGoal };}-function buildCreateGoalPayload(plan: UltragoalPlan, goal: UltragoalItem): CodexCreateGoalPayload {+function buildCreateGoalPayload(plan: UlwLoopPlan, goal: UlwLoopItem): CodexCreateGoalPayload {return { objective: expectedCodexObjective(plan, goal), status: "active" };}function buildText(- mode: UltragoalCodexGoalMode,- plan: UltragoalPlan,- goal: UltragoalItem,+ mode: UlwLoopCodexGoalMode,+ plan: UlwLoopPlan,+ goal: UlwLoopItem,createGoal: CodexCreateGoalPayload,isFinal: boolean,): string {return joinLines([- mode === "aggregate" ? "Ultragoal aggregate-goal handoff" : "Ultragoal active-goal handoff",+ mode === "aggregate" ? "UlwLoop aggregate-goal handoff" : "UlwLoop active-goal handoff",`Mode: ${mode}`,`Plan: ${plan.goalsPath}`,`Ledger: ${plan.ledgerPath}`,@@ -48,36 +48,35 @@ function buildText("- Use the create_goal payload exactly as rendered: objective and status only.","- Goals are unlimited. Do not add numeric limits.",...modeConstraintLines(mode, isFinal),- finalSection(goal, isFinal, mode === "aggregate"),- ...checkpointLines(mode),+ finalSection(plan, goal, isFinal, mode === "aggregate"),+ ...checkpointLines(plan, mode),"","create_goal payload:",JSON.stringify(createGoal, null, 2),]);}-function modeConstraintLines(mode: UltragoalCodexGoalMode, isFinal: boolean): readonly string[] {+function modeConstraintLines(mode: UlwLoopCodexGoalMode, isFinal: boolean): readonly string[] {if (mode === "per_story") {return ["- First call get_goal. If no active goal exists, call create_goal with the payload below.",- "- If a different active Codex goal exists, finish/checkpoint that goal before starting this ultragoal.",+ "- If a different active Codex goal exists, finish/checkpoint that goal before starting this ulw-loop.","- Work only this goal until its completion audit passes.",];}return [- "- Codex goal = the whole omo ultragoal run; OMO G001/G002/etc. = ledger stories.",+ "- Codex goal = the whole omo ulw-loop run; OMO G001/G002/etc. = ledger stories.","- First call get_goal. If no active goal exists, call create_goal with the aggregate payload below.","- If get_goal reports the same aggregate objective as active, continue this OMO story without creating a new Codex goal.",- "- If a different active or incomplete Codex goal exists, finish/checkpoint that goal before starting this ultragoal.",+ "- If a different active or incomplete Codex goal exists, finish/checkpoint that goal before starting this ulw-loop.",isFinal? "- This is the final story; update_goal is allowed only after the mandatory quality gate passes.": "- This is not the final story: do not call update_goal yet; the aggregate Codex goal must remain active while later OMO stories remain.",];}-function checkpointLines(mode: UltragoalCodexGoalMode): readonly string[] {- const failureLine =- "- If blocked or failed, checkpoint with --status failed and the failure evidence; rerun complete-goals --retry-failed to resume.";+function checkpointLines(plan: UlwLoopPlan, mode: UlwLoopCodexGoalMode): readonly string[] {+ const failureLine = `- If blocked or failed, checkpoint with --status failed and the failure evidence; rerun complete-goals${sessionOption(plan)} --retry-failed to resume.`;if (mode === "per_story") return [failureLine];return ["- Checkpoint this OMO story with a fresh get_goal snapshot whose objective matches the aggregate payload.",@@ -85,25 +84,26 @@ function checkpointLines(mode: UltragoalCodexGoalMode): readonly string[] {];}-function activeGoalLines(goal: UltragoalItem): readonly string[] {+function activeGoalLines(goal: UlwLoopItem): readonly string[] {return ["Active goal:", `- id: ${goal.id}`, `- title: ${goal.title}`, `- objective: ${goal.objective}`];}-function successCriteriaLines(criteria: readonly UltragoalSuccessCriterion[]): readonly string[] {+function successCriteriaLines(criteria: readonly UlwLoopSuccessCriterion[]): readonly string[] {if (criteria.length === 0) return ["Success criteria:", "- No success criteria recorded for this goal."];return ["Success criteria:", ...criteria.map(formatCriterionLine)];}-function formatCriterionLine(criterion: UltragoalSuccessCriterion): string {+function formatCriterionLine(criterion: UlwLoopSuccessCriterion): string {const remainingWork = criterion.status === "pending" ? " remaining work:" : "";return `-${remainingWork} [${criterion.id}] (${criterion.userModel}) ${criterion.scenario} — expect: ${criterion.expectedEvidence} — status: ${criterion.status}`;}-function finalSection(goal: UltragoalItem, isFinal: boolean, aggregate: boolean): string {+function finalSection(plan: UlwLoopPlan, goal: UlwLoopItem, isFinal: boolean, aggregate: boolean): string {if (!isFinal)- return "- This is not the final ultragoal story; do not run the final ai-slop-cleaner/$code-review gate yet.";- const blockerCommand = `omo ultragoal record-review-blockers --goal-id ${goal.id} --title "Resolve final code-review blockers" --objective "<blocker-resolution objective>" --evidence "<review findings>" --codex-goal-json "<active get_goal JSON or path>"`;- const checkpointCommand = `omo ultragoal checkpoint --goal-id ${goal.id} --status complete --evidence "<tests/files/PR evidence>" --codex-goal-json "<fresh complete get_goal JSON or path>" --quality-gate-json "<quality gate JSON or path>"`;+ return "- This is not the final ulw-loop story; do not run the final ai-slop-cleaner/$code-review gate yet.";+ const option = sessionOption(plan);+ const blockerCommand = `omo ulw-loop record-review-blockers${option} --goal-id ${goal.id} --title "Resolve final code-review blockers" --objective "<blocker-resolution objective>" --evidence "<review findings>" --codex-goal-json "<active get_goal JSON or path>"`;+ const checkpointCommand = `omo 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 $code-review.",@@ -116,6 +116,14 @@ function finalSection(goal: UltragoalItem, isFinal: boolean, aggregate: boolean)]);}+function sessionOption(plan: UlwLoopPlan): string {+ const prefix = ".omo/ulw-loop/";+ const suffix = "/goals.json";+ if (!plan.goalsPath.startsWith(prefix) || !plan.goalsPath.endsWith(suffix)) return "";+ const sessionId = plan.goalsPath.slice(prefix.length, -suffix.length);+ return sessionId.length === 0 ? "" : ` --session-id ${sessionId}`;+}+function joinLines(lines: readonly string[]): string {return lines.join("\n");}diff --git a/plugins/omo/components/ultragoal/src/codex-goal-snapshot.ts b/plugins/omo/components/ulw-loop/src/codex-goal-snapshot.tssimilarity index 100%rename from plugins/omo/components/ultragoal/src/codex-goal-snapshot.tsrename to plugins/omo/components/ulw-loop/src/codex-goal-snapshot.tsdiff --git a/plugins/omo/components/ulw-loop/src/codex-hook.ts b/plugins/omo/components/ulw-loop/src/codex-hook.tsnew file mode 100644index 00000000..9393ff5d--- /dev/null+++ b/plugins/omo/components/ulw-loop/src/codex-hook.ts@@ -0,0 +1,177 @@+import type { UlwLoopScope } from "./paths.js";+import { parseUlwLoopSteeringDirective, steerUlwLoop } from "./steering.js";++export interface UserPromptSubmitPayload {+ readonly cwd: string;+ readonly hook_event_name: "UserPromptSubmit";+ readonly model?: string;+ readonly permission_mode?: string;+ readonly prompt: string;+ readonly session_id: string;+ readonly transcript_path?: string;+ readonly turn_id?: string;+}++export interface PreToolUsePayload {+ readonly cwd: string;+ readonly hook_event_name: "PreToolUse";+ readonly model: string;+ readonly permission_mode: string;+ readonly session_id: string;+ readonly tool_input: unknown;+ readonly tool_name: string;+ readonly tool_use_id: string;+ readonly transcript_path: string | null;+ readonly turn_id: string;+}++interface PreToolUseHookOutput {+ readonly hookSpecificOutput: {+ readonly hookEventName: "PreToolUse";+ readonly permissionDecision: "deny";+ readonly permissionDecisionReason: string;+ readonly additionalContext: string;+ };+}++const CREATE_GOAL_TOOL_NAME = "create_goal";+const GOAL_BUDGET_WARNING =+ "Do not set token_budget on create_goal. Omit the budget field so the goal stays unlimited; ultrawork and ulw-loop runs must always use unlimited goals.";++export function parseUserPromptSubmitPayload(raw: string): UserPromptSubmitPayload | null {+ if (raw.trim().length === 0) return null;+ try {+ const parsed: unknown = JSON.parse(raw);+ return isUserPromptSubmitPayload(parsed) ? parsed : null;+ } catch (error) {+ if (error instanceof SyntaxError) return null;+ return null;+ }+}++export function parsePreToolUsePayload(raw: string): PreToolUsePayload | null {+ if (raw.trim().length === 0) return null;+ try {+ const parsed: unknown = JSON.parse(raw);+ return isPreToolUsePayload(parsed) ? parsed : null;+ } catch (error) {+ if (error instanceof SyntaxError) return null;+ return null;+ }+}++export async function applyUserPromptUlwLoopSteering(payload: UserPromptSubmitPayload): Promise<string> {+ try {+ if (payload.hook_event_name !== "UserPromptSubmit") return "";+ const proposal = parseUlwLoopSteeringDirective(payload.prompt);+ if (proposal === null) return "";+ const result = await steerUlwLoop(payload.cwd, proposal, payloadScope(payload));+ if (!result.accepted) return "";+ return JSON.stringify({+ status: "accepted",+ kind: result.audit.kind,+ source: result.audit.source,+ deduped: result.deduped,+ });+ } catch (error) {+ if (error instanceof Error) return "";+ return "";+ }+}++function payloadScope(payload: UserPromptSubmitPayload): UlwLoopScope {+ return { sessionId: payload.session_id };+}++export function applyPreToolUseGoalBudgetGuard(payload: PreToolUsePayload): string {+ if (payload.hook_event_name !== "PreToolUse") return "";+ if (payload.tool_name !== CREATE_GOAL_TOOL_NAME) return "";+ if (!hasGoalBudgetInput(payload.tool_input)) return "";+ const output: PreToolUseHookOutput = {+ hookSpecificOutput: {+ hookEventName: "PreToolUse",+ permissionDecision: "deny",+ permissionDecisionReason: GOAL_BUDGET_WARNING,+ additionalContext: GOAL_BUDGET_WARNING,+ },+ };+ return `${JSON.stringify(output)}\n`;+}++export async function runUlwLoopHookCli(stdin: NodeJS.ReadableStream, stdout: NodeJS.WritableStream): Promise<void> {+ try {+ const payload = parseUserPromptSubmitPayload(await readAll(stdin));+ if (payload === null) return;+ const output = await applyUserPromptUlwLoopSteering(payload);+ if (output.length > 0) stdout.write(output);+ } catch (error) {+ if (error instanceof Error) return;+ return;+ }+}++export async function runPreToolUseGoalBudgetGuardCli(+ stdin: NodeJS.ReadableStream,+ stdout: NodeJS.WritableStream,+): Promise<void> {+ try {+ const payload = parsePreToolUsePayload(await readAll(stdin));+ if (payload === null) return;+ const output = applyPreToolUseGoalBudgetGuard(payload);+ if (output.length > 0) stdout.write(output);+ } catch (error) {+ if (error instanceof Error) return;+ return;+ }+}++function isUserPromptSubmitPayload(value: unknown): value is UserPromptSubmitPayload {+ if (!isRecord(value)) return false;+ return (+ value["hook_event_name"] === "UserPromptSubmit" &&+ typeof value["cwd"] === "string" &&+ typeof value["prompt"] === "string" &&+ typeof value["session_id"] === "string" &&+ ["model", "permission_mode", "transcript_path", "turn_id"].every((key) => optionalString(value[key]))+ );+}++function isPreToolUsePayload(value: unknown): value is PreToolUsePayload {+ if (!isRecord(value)) return false;+ return (+ value["hook_event_name"] === "PreToolUse" &&+ typeof value["cwd"] === "string" &&+ typeof value["model"] === "string" &&+ typeof value["permission_mode"] === "string" &&+ typeof value["session_id"] === "string" &&+ typeof value["tool_name"] === "string" &&+ typeof value["tool_use_id"] === "string" &&+ (value["transcript_path"] === null || typeof value["transcript_path"] === "string") &&+ typeof value["turn_id"] === "string" &&+ Object.hasOwn(value, "tool_input")+ );+}++function hasGoalBudgetInput(value: unknown): boolean {+ return isRecord(value) && (Object.hasOwn(value, "token_budget") || Object.hasOwn(value, "tokenBudget"));+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function optionalString(value: unknown): boolean {+ return value === undefined || typeof value === "string";+}++function readAll(stdin: NodeJS.ReadableStream): Promise<string> {+ return new Promise((resolve, reject) => {+ let data = "";+ stdin.setEncoding("utf8");+ stdin.on("data", (chunk: unknown) => {+ data += chunk instanceof Buffer ? chunk.toString() : String(chunk);+ });+ stdin.once("error", reject);+ stdin.once("end", () => resolve(data));+ });+}diff --git a/plugins/omo/components/ultragoal/src/evidence.ts b/plugins/omo/components/ulw-loop/src/evidence.tssimilarity index 57%rename from plugins/omo/components/ultragoal/src/evidence.tsrename to plugins/omo/components/ulw-loop/src/evidence.tsindex 4d801481..c955e5d6 100644--- a/plugins/omo/components/ultragoal/src/evidence.ts+++ b/plugins/omo/components/ulw-loop/src/evidence.ts@@ -1,15 +1,16 @@// biome-ignore-all format: keep this module under the mandated pure LOC budget.import { hasAllCriteriaPass } from "./goal-status.js";-import { appendLedger, readUltragoalPlan, withUltragoalMutationLock, writePlan } from "./plan-io.js";-import type { UltragoalItem, UltragoalLedgerEntry, UltragoalPlan, UltragoalSuccessCriterion } from "./types.js";-import { iso, UltragoalError } from "./types.js";+import type { UlwLoopScope } from "./paths.js";+import { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";+import type { UlwLoopItem, UlwLoopLedgerEntry, UlwLoopPlan, UlwLoopSuccessCriterion } from "./types.js";+import { iso, UlwLoopError } from "./types.js";type EvidenceStatus = "pass" | "fail" | "blocked";type RecordEvidenceArgs = { readonly goalId: string; readonly criterionId: string; readonly status: EvidenceStatus; readonly evidence: string; readonly notes?: string };-function ultragoalFail(message: string, code: string, details: Record<string, unknown>): never { throw new UltragoalError(message, code, { details }); }+function ulwLoopFail(message: string, code: string, details: Record<string, unknown>): never { throw new UlwLoopError(message, code, { details }); }-function ledgerKind(status: EvidenceStatus): UltragoalLedgerEntry["kind"] {+function ledgerKind(status: EvidenceStatus): UlwLoopLedgerEntry["kind"] {switch (status) {case "pass":return "evidence_captured";@@ -18,25 +19,25 @@ function ledgerKind(status: EvidenceStatus): UltragoalLedgerEntry["kind"] {case "blocked":return "criterion_blocked";default:- return ultragoalFail("Invalid criterion status.", "ULTRAGOAL_CRITERION_STATUS_INVALID", { status });+ return ulwLoopFail("Invalid criterion status.", "ULW_LOOP_CRITERION_STATUS_INVALID", { status });}}-function findGoal(plan: UltragoalPlan, goalId: string): UltragoalItem {+function findGoal(plan: UlwLoopPlan, goalId: string): UlwLoopItem {const goal = plan.goals.find((candidate) => candidate.id === goalId);- return goal ?? ultragoalFail(`Ultragoal goal not found: ${goalId}.`, "ULTRAGOAL_GOAL_NOT_FOUND", { goalId });+ return goal ?? ulwLoopFail(`UlwLoop goal not found: ${goalId}.`, "ULW_LOOP_GOAL_NOT_FOUND", { goalId });}-function findCriterion(goal: UltragoalItem, criterionId: string): UltragoalSuccessCriterion {+function findCriterion(goal: UlwLoopItem, criterionId: string): UlwLoopSuccessCriterion {const criterion = goal.successCriteria.find((candidate) => candidate.id === criterionId);- return criterion ?? ultragoalFail(`Success criterion not found: ${criterionId}.`, "ULTRAGOAL_CRITERION_NOT_FOUND", { goalId: goal.id, criterionId });+ return criterion ?? ulwLoopFail(`Success criterion not found: ${criterionId}.`, "ULW_LOOP_CRITERION_NOT_FOUND", { goalId: goal.id, criterionId });}-function nonEmptyEvidence(evidence: string): string { const trimmed = evidence.trim(); return trimmed || ultragoalFail("Evidence must be a non-empty string.", "ULTRAGOAL_EVIDENCE_REQUIRED", {}); }+function nonEmptyEvidence(evidence: string): string { const trimmed = evidence.trim(); return trimmed || ulwLoopFail("Evidence must be a non-empty string.", "ULW_LOOP_EVIDENCE_REQUIRED", {}); }-export async function recordEvidence(repoRoot: string, args: RecordEvidenceArgs): Promise<{ plan: UltragoalPlan; goal: UltragoalItem; criterion: UltragoalSuccessCriterion; ledgerEntry: UltragoalLedgerEntry }> {- return withUltragoalMutationLock(repoRoot, async () => {- const plan = await readUltragoalPlan(repoRoot);+export async function recordEvidence(repoRoot: string, args: RecordEvidenceArgs, scope?: UlwLoopScope): Promise<{ plan: UlwLoopPlan; goal: UlwLoopItem; criterion: UlwLoopSuccessCriterion; ledgerEntry: UlwLoopLedgerEntry }> {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ const plan = await readUlwLoopPlan(repoRoot, scope);const goal = findGoal(plan, args.goalId);const criterion = findCriterion(goal, args.criterionId);const evidence = nonEmptyEvidence(args.evidence);@@ -49,8 +50,8 @@ export async function recordEvidence(repoRoot: string, args: RecordEvidenceArgs)if (args.notes !== undefined) criterion.notes = args.notes;goal.updatedAt = capturedAt;plan.updatedAt = capturedAt;- await writePlan(repoRoot, plan);- const ledgerEntry: UltragoalLedgerEntry = {+ await writePlan(repoRoot, plan, scope);+ const ledgerEntry: UlwLoopLedgerEntry = {at: capturedAt,kind,goalId: goal.id,@@ -61,14 +62,14 @@ export async function recordEvidence(repoRoot: string, args: RecordEvidenceArgs)before: { status: prevStatus },after: { goalId: goal.id, criterionId: criterion.id, status: args.status, evidence, capturedAt, prevStatus },};- await appendLedger(repoRoot, ledgerEntry);+ await appendLedger(repoRoot, ledgerEntry, scope);return { plan, goal, criterion, ledgerEntry };});}-export async function markCriteriaPendingResetForGoal(repoRoot: string, goalId: string): Promise<{ plan: UltragoalPlan; resetCount: number }> {- return withUltragoalMutationLock(repoRoot, async () => {- const plan = await readUltragoalPlan(repoRoot);+export async function markCriteriaPendingResetForGoal(repoRoot: string, goalId: string, scope?: UlwLoopScope): Promise<{ plan: UlwLoopPlan; resetCount: number }> {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ const plan = await readUlwLoopPlan(repoRoot, scope);const goal = findGoal(plan, goalId);const now = iso();const before = goal.successCriteria.map((criterion) => ({ id: criterion.id, status: criterion.status, capturedEvidence: criterion.capturedEvidence, capturedAt: criterion.capturedAt ?? null }));@@ -80,13 +81,13 @@ export async function markCriteriaPendingResetForGoal(repoRoot: string, goalId:}goal.updatedAt = now;plan.updatedAt = now;- await writePlan(repoRoot, plan);- await appendLedger(repoRoot, { at: now, kind: "criteria_revised", goalId, message: `Reset ${goal.successCriteria.length} criteria to pending.`, before, after: { resetCount: goal.successCriteria.length } });+ await writePlan(repoRoot, plan, scope);+ await appendLedger(repoRoot, { at: now, kind: "criteria_revised", goalId, message: `Reset ${goal.successCriteria.length} criteria to pending.`, before, after: { resetCount: goal.successCriteria.length } }, scope);return { plan, resetCount: goal.successCriteria.length };});}-export function criteriaSummary(plan: UltragoalPlan): { totalCriteria: number; passCount: number; pendingCount: number; failCount: number; blockedCount: number; goalsWithUnresolvedCriteria: string[] } {+export function criteriaSummary(plan: UlwLoopPlan): { totalCriteria: number; passCount: number; pendingCount: number; failCount: number; blockedCount: number; goalsWithUnresolvedCriteria: string[] } {let totalCriteria = 0;let passCount = 0;let pendingCount = 0;@@ -103,7 +104,7 @@ export function criteriaSummary(plan: UltragoalPlan): { totalCriteria: number; pcase "pending": pendingCount += 1; break;case "fail": failCount += 1; break;case "blocked": blockedCount += 1; break;- default: ultragoalFail("Invalid criterion status.", "ULTRAGOAL_CRITERION_STATUS_INVALID", { status: criterion.status });+ default: ulwLoopFail("Invalid criterion status.", "ULW_LOOP_CRITERION_STATUS_INVALID", { status: criterion.status });}}if (unresolved) goalsWithUnresolvedCriteria.push(goal.id);@@ -111,11 +112,11 @@ export function criteriaSummary(plan: UltragoalPlan): { totalCriteria: number; preturn { totalCriteria, passCount, pendingCount, failCount, blockedCount, goalsWithUnresolvedCriteria };}-export function unresolvedCriteriaOf(goal: UltragoalItem): UltragoalSuccessCriterion[] { return goal.successCriteria.filter((criterion) => criterion.status !== "pass"); }+export function unresolvedCriteriaOf(goal: UlwLoopItem): UlwLoopSuccessCriterion[] { return goal.successCriteria.filter((criterion) => criterion.status !== "pass"); }-export function requireAllCriteriaPass(goal: UltragoalItem): void {+export function requireAllCriteriaPass(goal: UlwLoopItem): void {if (hasAllCriteriaPass(goal)) return;- throw new UltragoalError(`Goal ${goal.id} has unresolved success criteria.`, "ultragoal_criteria_not_all_pass", {+ throw new UlwLoopError(`Goal ${goal.id} has unresolved success criteria.`, "ulw_loop_criteria_not_all_pass", {details: { goalId: goal.id, unresolved: unresolvedCriteriaOf(goal).map((criterion) => ({ id: criterion.id, status: criterion.status })) },});}diff --git a/plugins/omo/components/ultragoal/src/goal-status.ts b/plugins/omo/components/ulw-loop/src/goal-status.tssimilarity index 54%rename from plugins/omo/components/ultragoal/src/goal-status.tsrename to plugins/omo/components/ulw-loop/src/goal-status.tsindex a140c4bd..f6d9d731 100644--- a/plugins/omo/components/ultragoal/src/goal-status.ts+++ b/plugins/omo/components/ulw-loop/src/goal-status.ts@@ -1,23 +1,27 @@+import { type UlwLoopScope, ulwLoopGoalsRelativePath, ulwLoopLedgerRelativePath } from "./paths.js";import type {- UltragoalCodexGoalMode,- UltragoalItem,- UltragoalPlan,- UltragoalStatus,- UltragoalSuccessCriterion,+ UlwLoopCodexGoalMode,+ UlwLoopItem,+ UlwLoopPlan,+ UlwLoopStatus,+ UlwLoopSuccessCriterion,} from "./types.js";-export const ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE: string =- "Complete the durable ultragoal plan in .omo/ultragoal/goals.json, including later accepted/appended stories, under the original brief constraints; use .omo/ultragoal/ledger.jsonl as the audit trail.";+export const ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE: string = aggregateCodexObjectiveForScope();-export function codexGoalMode(plan: UltragoalPlan): UltragoalCodexGoalMode {+export function aggregateCodexObjectiveForScope(scope?: UlwLoopScope): string {+ return `Complete the durable ulw-loop plan in ${ulwLoopGoalsRelativePath(scope)}, including later accepted/appended stories, under the original brief constraints; use ${ulwLoopLedgerRelativePath(scope)} as the audit trail.`;+}++export function codexGoalMode(plan: UlwLoopPlan): UlwLoopCodexGoalMode {return plan.codexGoalMode ?? "per_story";}-function isResolvedStatus(status: UltragoalStatus): boolean {+function isResolvedStatus(status: UlwLoopStatus): boolean {return status === "complete";}-function isSupersededResolved(goal: UltragoalItem, plan: UltragoalPlan): boolean {+function isSupersededResolved(goal: UlwLoopItem, plan: UlwLoopPlan): boolean {if (goal.steeringStatus !== "superseded") return false;const replacements = goal.supersededBy ?? [];if (replacements.length === 0) return false;@@ -27,16 +31,16 @@ function isSupersededResolved(goal: UltragoalItem, plan: UltragoalPlan): boolean});}-function isCompletionBlocking(goal: UltragoalItem, plan: UltragoalPlan): boolean {+function isCompletionBlocking(goal: UlwLoopItem, plan: UlwLoopPlan): boolean {if (goal.steeringStatus === "superseded") return !isSupersededResolved(goal, plan);if (goal.steeringStatus === "blocked") return true;return !isResolvedStatus(goal.status);}function isCompletionBlockingForFinalCandidate(- candidate: UltragoalItem,- finalCandidate: UltragoalItem,- plan: UltragoalPlan,+ candidate: UlwLoopItem,+ finalCandidate: UlwLoopItem,+ plan: UlwLoopPlan,): boolean {if (candidate.id === finalCandidate.id) return false;if (candidate.steeringStatus === "superseded") {@@ -51,34 +55,34 @@ function isCompletionBlockingForFinalCandidate(return isCompletionBlocking(candidate, plan);}-export function isUltragoalDone(plan: UltragoalPlan): boolean {+export function isUlwLoopDone(plan: UlwLoopPlan): boolean {if (plan.aggregateCompletion?.status === "complete") return true;return plan.goals.every((goal) => !isCompletionBlocking(goal, plan));}-export function isFinalRunCompletionCandidate(plan: UltragoalPlan, goal: UltragoalItem): boolean {+export function isFinalRunCompletionCandidate(plan: UlwLoopPlan, goal: UlwLoopItem): boolean {return (isCompletionBlocking(goal, plan) &&plan.goals.every((candidate) => !isCompletionBlockingForFinalCandidate(candidate, goal, plan)));}-export function aggregateCodexObjective(plan: UltragoalPlan): string {- return plan.codexObjective ?? ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE;+export function aggregateCodexObjective(plan: UlwLoopPlan): string {+ return plan.codexObjective ?? ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE;}-export function expectedCodexObjective(plan: UltragoalPlan, goal: UltragoalItem): string {+export function expectedCodexObjective(plan: UlwLoopPlan, goal: UlwLoopItem): string {return codexGoalMode(plan) === "aggregate" ? aggregateCodexObjective(plan) : goal.objective;}-export function compatibleCodexObjectives(plan: UltragoalPlan): readonly string[] {+export function compatibleCodexObjectives(plan: UlwLoopPlan): readonly string[] {return [aggregateCodexObjective(plan), ...(plan.codexObjectiveAliases ?? [])];}-export function hasAllCriteriaPass(goal: UltragoalItem): boolean {+export function hasAllCriteriaPass(goal: UlwLoopItem): boolean {return goal.successCriteria.length > 0 && goal.successCriteria.every((criterion) => criterion.status === "pass");}-export function firstUnresolvedCriterion(goal: UltragoalItem): UltragoalSuccessCriterion | undefined {+export function firstUnresolvedCriterion(goal: UlwLoopItem): UlwLoopSuccessCriterion | undefined {return goal.successCriteria.find((criterion) => criterion.status !== "pass");}diff --git a/plugins/omo/components/ulw-loop/src/paths.ts b/plugins/omo/components/ulw-loop/src/paths.tsnew file mode 100644index 00000000..a646469c--- /dev/null+++ b/plugins/omo/components/ulw-loop/src/paths.ts@@ -0,0 +1,73 @@+import { join } from "node:path";+import { ULW_LOOP_BRIEF, ULW_LOOP_DIR, ULW_LOOP_GOALS, ULW_LOOP_LEDGER } from "./types.js";++export interface UlwLoopScope {+ readonly sessionId?: string | null;+}++const SESSION_ENV_KEYS = ["OMO_ULW_LOOP_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID"] as const;+type EnvMap = Readonly<Record<string, string | undefined>>;++export function normalizeUlwLoopSessionId(sessionId: string | null | undefined): string | null {+ const trimmed = sessionId?.trim();+ if (!trimmed) return null;+ const pathSegments = trimmed+ .split(/[\\/]+/)+ .filter((segment) => segment.length > 0 && segment !== "." && segment !== "..");+ const candidate = (pathSegments.length > 0 ? pathSegments.join("-") : trimmed)+ .replace(/[^A-Za-z0-9._-]+/g, "-")+ .replace(/-+/g, "-")+ .replace(/^\.+/, "")+ .replace(/^[.-]+|[.-]+$/g, "");+ return candidate.length > 0 ? candidate : null;+}++export function resolveUlwLoopSessionIdFromEnv(env: EnvMap = process.env): string | null {+ for (const key of SESSION_ENV_KEYS) {+ const normalized = normalizeUlwLoopSessionId(env[key]);+ if (normalized !== null) return normalized;+ }+ return null;+}++export function ulwLoopRelativeDir(scope?: UlwLoopScope): string {+ const sessionId = normalizeUlwLoopSessionId(scope?.sessionId);+ return sessionId === null ? ULW_LOOP_DIR : `${ULW_LOOP_DIR}/${sessionId}`;+}++export function ulwLoopDir(repoRoot: string, scope?: UlwLoopScope): string {+ return join(repoRoot, ulwLoopRelativeDir(scope));+}++export function ulwLoopBriefRelativePath(scope?: UlwLoopScope): string {+ return `${ulwLoopRelativeDir(scope)}/${ULW_LOOP_BRIEF}`;+}++export function ulwLoopGoalsRelativePath(scope?: UlwLoopScope): string {+ return `${ulwLoopRelativeDir(scope)}/${ULW_LOOP_GOALS}`;+}++export function ulwLoopLedgerRelativePath(scope?: UlwLoopScope): string {+ return `${ulwLoopRelativeDir(scope)}/${ULW_LOOP_LEDGER}`;+}++export function ulwLoopBriefPath(repoRoot: string, scope?: UlwLoopScope): string {+ return join(ulwLoopDir(repoRoot, scope), ULW_LOOP_BRIEF);+}++export function ulwLoopGoalsPath(repoRoot: string, scope?: UlwLoopScope): string {+ return join(ulwLoopDir(repoRoot, scope), ULW_LOOP_GOALS);+}++export function ulwLoopLedgerPath(repoRoot: string, scope?: UlwLoopScope): string {+ return join(ulwLoopDir(repoRoot, scope), ULW_LOOP_LEDGER);+}++export function repoRelative(absolutePath: string, repoRoot: string): string {+ const slashPrefix = `${repoRoot}/`;+ const backslashPrefix = `${repoRoot}\\`;+ if (absolutePath.startsWith(slashPrefix)) return absolutePath.slice(slashPrefix.length).split("\\").join("/");+ if (absolutePath.startsWith(backslashPrefix))+ return absolutePath.slice(backslashPrefix.length).split("\\").join("/");+ return absolutePath.split("\\").join("/");+}diff --git a/plugins/omo/components/ultragoal/src/plan-crud.ts b/plugins/omo/components/ulw-loop/src/plan-crud.tssimilarity index 60%rename from plugins/omo/components/ultragoal/src/plan-crud.tsrename to plugins/omo/components/ulw-loop/src/plan-crud.tsindex e40b5fc0..b2a61ca1 100644--- a/plugins/omo/components/ultragoal/src/plan-crud.ts+++ b/plugins/omo/components/ulw-loop/src/plan-crud.ts@@ -2,22 +2,22 @@import { existsSync } from "node:fs";import { mkdir, writeFile } from "node:fs/promises";-import { ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE } from "./goal-status.js";-import { ultragoalBriefPath, ultragoalDir, ultragoalGoalsPath, ultragoalLedgerPath } from "./paths.js";-import { appendLedger, readUltragoalPlan, withUltragoalMutationLock, writePlan } from "./plan-io.js";-import type { UltragoalCodexGoalMode, UltragoalItem, UltragoalPlan, UltragoalSuccessCriterion } from "./types.js";-import { iso, ULTRAGOAL_BRIEF, ULTRAGOAL_DIR, ULTRAGOAL_GOALS, ULTRAGOAL_LEDGER, UltragoalError } from "./types.js";+import { aggregateCodexObjectiveForScope } from "./goal-status.js";+import { type UlwLoopScope, ulwLoopBriefPath, ulwLoopBriefRelativePath, ulwLoopDir, ulwLoopGoalsPath, ulwLoopGoalsRelativePath, ulwLoopLedgerPath, ulwLoopLedgerRelativePath } from "./paths.js";+import { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";+import type { UlwLoopCodexGoalMode, UlwLoopItem, UlwLoopPlan, UlwLoopSuccessCriterion } from "./types.js";+import { iso, UlwLoopError } from "./types.js";-export type UltragoalPlanSummary = { readonly total: number; readonly pending: number; readonly in_progress: number; readonly complete: number; readonly failed: number; readonly blocked: number; readonly review_blocked: number; readonly needs_user_decision: number; readonly superseded: number; readonly criteria: { readonly total: number; readonly pass: number; readonly pending: number; readonly fail: number; readonly blocked: number } };+export type UlwLoopPlanSummary = { readonly total: number; readonly pending: number; readonly in_progress: number; readonly complete: number; readonly failed: number; readonly blocked: number; readonly review_blocked: number; readonly needs_user_decision: number; readonly superseded: number; readonly criteria: { readonly total: number; readonly pass: number; readonly pending: number; readonly fail: number; readonly blocked: number } };function cleanLine(line: string): string { return line.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/, "").trim(); }function normalizeObjective(value: string): string { return value.replace(/\s+/g, " ").trim(); }function titleFromObjective(objective: string, fallback: string): string { const firstLine = objective.split(/\r?\n/).map((line) => line.trim()).find(Boolean) ?? fallback; return firstLine.length > 72 ? `${firstLine.slice(0, 69).trimEnd()}...` : firstLine; }function normalizeGoalId(title: string, index: number): string { const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 36).replace(/-+$/g, ""); return `G${String(index + 1).padStart(3, "0")}${slug ? `-${slug}` : ""}`; }-function assertNonEmpty(value: string | undefined, label: string): string { const trimmed = value?.trim(); if (!trimmed) throw new UltragoalError(`Missing ${label}.`, "ULTRAGOAL_ARGUMENT_MISSING"); return trimmed; }+function assertNonEmpty(value: string | undefined, label: string): string { const trimmed = value?.trim(); if (!trimmed) throw new UlwLoopError(`Missing ${label}.`, "ULW_LOOP_ARGUMENT_MISSING"); return trimmed; }function truncateObjective(objective: string): string { return objective.length > 80 ? `${objective.slice(0, 77).trimEnd()}...` : objective; }-export function seedDefaultSuccessCriteria(goalIndex: number, objective: string): UltragoalSuccessCriterion[] {+export function seedDefaultSuccessCriteria(goalIndex: number, objective: string): UlwLoopSuccessCriterion[] {const subject = truncateObjective(normalizeObjective(objective) || `Goal ${goalIndex + 1}`);const rows = [["C001", "happy", `happy path for: ${subject}`, `Replace via revise_criterion with observable happy-path proof for goal ${goalIndex + 1}.`],@@ -34,63 +34,63 @@ export function deriveGoalCandidates(brief: string): Array<{ title: string; objereturn selected.map((objective, index) => ({ title: titleFromObjective(objective, `Goal ${index + 1}`), objective }));}-function makeGoal(title: string, objective: string, index: number, now: string): UltragoalItem {+function makeGoal(title: string, objective: string, index: number, now: string): UlwLoopItem {const cleanTitle = assertNonEmpty(title, "title");const cleanObjective = assertNonEmpty(objective, "objective");return { id: normalizeGoalId(cleanTitle, index), title: cleanTitle, objective: cleanObjective, status: "pending", successCriteria: seedDefaultSuccessCriteria(index, cleanObjective), attempt: 0, createdAt: now, updatedAt: now };}-function appendGoalToPlan(plan: UltragoalPlan, title: string, objective: string, now: string): UltragoalItem {+function appendGoalToPlan(plan: UlwLoopPlan, title: string, objective: string, now: string): UlwLoopItem {const goal = makeGoal(title, objective, plan.goals.length, now);plan.goals.push(goal);plan.updatedAt = now;return goal;}-function isScheduleEligible(goal: UltragoalItem): boolean { return goal.steeringStatus !== "superseded" && goal.steeringStatus !== "blocked"; }+function isScheduleEligible(goal: UlwLoopItem): boolean { return goal.steeringStatus !== "superseded" && goal.steeringStatus !== "blocked"; }-function clearGoalBlockerFields(goal: UltragoalItem): void {+function clearGoalBlockerFields(goal: UlwLoopItem): void {for (const key of ["blockedReason", "blockerSignature", "blockerOccurrenceCount", "requiredExternalDecision", "nonRetriable", "failedAt", "failureReason"] as const) delete goal[key];}-export async function createUltragoalPlan(repoRoot: string, args: { brief: string; codexGoalMode?: UltragoalCodexGoalMode; force?: boolean }): Promise<UltragoalPlan> {- return withUltragoalMutationLock(repoRoot, async () => {- if (!args.force && existsSync(ultragoalGoalsPath(repoRoot))) throw new UltragoalError(`Refusing to overwrite existing ${ULTRAGOAL_DIR}/${ULTRAGOAL_GOALS}; pass --force to recreate it.`, "ULTRAGOAL_PLAN_EXISTS");+export async function createUlwLoopPlan(repoRoot: string, args: { brief: string; codexGoalMode?: UlwLoopCodexGoalMode; force?: boolean }, scope?: UlwLoopScope): Promise<UlwLoopPlan> {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ if (!args.force && existsSync(ulwLoopGoalsPath(repoRoot, scope))) throw new UlwLoopError(`Refusing to overwrite existing ${ulwLoopGoalsRelativePath(scope)}; pass --force to recreate it.`, "ULW_LOOP_PLAN_EXISTS");const now = iso();const goals = deriveGoalCandidates(args.brief).map((goal, index) => makeGoal(goal.title, goal.objective, index, now));- const plan: UltragoalPlan = { version: 1, createdAt: now, updatedAt: now, briefPath: `${ULTRAGOAL_DIR}/${ULTRAGOAL_BRIEF}`, goalsPath: `${ULTRAGOAL_DIR}/${ULTRAGOAL_GOALS}`, ledgerPath: `${ULTRAGOAL_DIR}/${ULTRAGOAL_LEDGER}`, codexGoalMode: args.codexGoalMode ?? "aggregate", goals };- if (plan.codexGoalMode === "aggregate") plan.codexObjective = ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE;- await mkdir(ultragoalDir(repoRoot), { recursive: true });- await writeFile(ultragoalBriefPath(repoRoot), args.brief.endsWith("\n") ? args.brief : `${args.brief}\n`, "utf8");- await writePlan(repoRoot, plan);- await writeFile(ultragoalLedgerPath(repoRoot), "", "utf8");- await appendLedger(repoRoot, { at: now, kind: "plan_created", message: `${goals.length} goal(s) created` });+ const plan: UlwLoopPlan = { version: 1, createdAt: now, updatedAt: now, briefPath: ulwLoopBriefRelativePath(scope), goalsPath: ulwLoopGoalsRelativePath(scope), ledgerPath: ulwLoopLedgerRelativePath(scope), codexGoalMode: args.codexGoalMode ?? "aggregate", goals };+ if (plan.codexGoalMode === "aggregate") plan.codexObjective = aggregateCodexObjectiveForScope(scope);+ await mkdir(ulwLoopDir(repoRoot, scope), { recursive: true });+ await writeFile(ulwLoopBriefPath(repoRoot, scope), args.brief.endsWith("\n") ? args.brief : `${args.brief}\n`, "utf8");+ await writePlan(repoRoot, plan, scope);+ await writeFile(ulwLoopLedgerPath(repoRoot, scope), "", "utf8");+ await appendLedger(repoRoot, { at: now, kind: "plan_created", message: `${goals.length} goal(s) created` }, scope);return plan;});}-export async function addUltragoalGoal(repoRoot: string, args: { title: string; objective: string }): Promise<{ plan: UltragoalPlan; goal: UltragoalItem }> {- return withUltragoalMutationLock(repoRoot, async () => {- const plan = await readUltragoalPlan(repoRoot);+export async function addUlwLoopGoal(repoRoot: string, args: { title: string; objective: string }, scope?: UlwLoopScope): Promise<{ plan: UlwLoopPlan; goal: UlwLoopItem }> {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ const plan = await readUlwLoopPlan(repoRoot, scope);const now = iso();const goal = appendGoalToPlan(plan, args.title, args.objective, now);- await writePlan(repoRoot, plan);- await appendLedger(repoRoot, { at: now, kind: "goal_added", goalId: goal.id, status: goal.status, message: goal.title });+ await writePlan(repoRoot, plan, scope);+ await appendLedger(repoRoot, { at: now, kind: "goal_added", goalId: goal.id, status: goal.status, message: goal.title }, scope);return { plan, goal };});}-export async function startNextUltragoal(repoRoot: string, args: { retryFailed?: boolean } = {}): Promise<{ plan: UltragoalPlan; goal: UltragoalItem; resumed: boolean } | { done: true; plan: UltragoalPlan }> {- return withUltragoalMutationLock(repoRoot, async () => {- const plan = await readUltragoalPlan(repoRoot);+export async function startNextUlwLoop(repoRoot: string, args: { retryFailed?: boolean } = {}, scope?: UlwLoopScope): Promise<{ plan: UlwLoopPlan; goal: UlwLoopItem; resumed: boolean } | { done: true; plan: UlwLoopPlan }> {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ const plan = await readUlwLoopPlan(repoRoot, scope);const now = iso();if (plan.aggregateCompletion?.status === "complete") return { done: true, plan };const existing = plan.goals.find((goal) => goal.status === "in_progress" && isScheduleEligible(goal));- if (existing) { await appendLedger(repoRoot, { at: now, kind: "goal_resumed", goalId: existing.id, status: existing.status, message: "Resuming active ultragoal" }); return { plan, goal: existing, resumed: true }; }+ if (existing) { await appendLedger(repoRoot, { at: now, kind: "goal_resumed", goalId: existing.id, status: existing.status, message: "Resuming active ulw-loop" }, scope); return { plan, goal: existing, resumed: true }; }let next = plan.goals.find((goal) => goal.status === "pending" && isScheduleEligible(goal));if (!next && args.retryFailed) {next = plan.goals.find((goal) => goal.status === "failed" && !goal.nonRetriable && isScheduleEligible(goal));- if (next) await appendLedger(repoRoot, { at: now, kind: "goal_retried", goalId: next.id, status: "pending", ...(next.failureReason ? { message: next.failureReason } : {}) });+ if (next) await appendLedger(repoRoot, { at: now, kind: "goal_retried", goalId: next.id, status: "pending", ...(next.failureReason ? { message: next.failureReason } : {}) }, scope);}if (!next) return { done: true, plan };next.status = "in_progress";@@ -100,14 +100,14 @@ export async function startNextUltragoal(repoRoot: string, args: { retryFailed?:next.updatedAt = now;plan.activeGoalId = next.id;plan.updatedAt = now;- await writePlan(repoRoot, plan);- await appendLedger(repoRoot, { at: now, kind: "goal_started", goalId: next.id, status: next.status, message: `Attempt ${next.attempt}` });+ await writePlan(repoRoot, plan, scope);+ await appendLedger(repoRoot, { at: now, kind: "goal_started", goalId: next.id, status: next.status, message: `Attempt ${next.attempt}` }, scope);return { plan, goal: next, resumed: false };});}-export function summarizeUltragoalPlan(plan: UltragoalPlan): UltragoalPlanSummary {- const countStatus = (status: UltragoalItem["status"]): number => plan.goals.filter((goal) => goal.status === status).length;- const countCriteria = (status: UltragoalSuccessCriterion["status"]): number => plan.goals.reduce((sum, goal) => sum + goal.successCriteria.filter((criterion) => criterion.status === status).length, 0);+export function summarizeUlwLoopPlan(plan: UlwLoopPlan): UlwLoopPlanSummary {+ const countStatus = (status: UlwLoopItem["status"]): number => plan.goals.filter((goal) => goal.status === status).length;+ const countCriteria = (status: UlwLoopSuccessCriterion["status"]): number => plan.goals.reduce((sum, goal) => sum + goal.successCriteria.filter((criterion) => criterion.status === status).length, 0);return { total: plan.goals.length, pending: countStatus("pending"), in_progress: countStatus("in_progress"), complete: countStatus("complete"), failed: countStatus("failed"), blocked: countStatus("blocked"), review_blocked: countStatus("review_blocked"), needs_user_decision: countStatus("needs_user_decision"), superseded: plan.goals.filter((goal) => goal.steeringStatus === "superseded").length, criteria: { total: plan.goals.reduce((sum, goal) => sum + goal.successCriteria.length, 0), pass: countCriteria("pass"), pending: countCriteria("pending"), fail: countCriteria("fail"), blocked: countCriteria("blocked") } };}diff --git a/plugins/omo/components/ulw-loop/src/plan-io.ts b/plugins/omo/components/ulw-loop/src/plan-io.tsnew file mode 100644index 00000000..79f2044e--- /dev/null+++ b/plugins/omo/components/ulw-loop/src/plan-io.ts@@ -0,0 +1,124 @@+import { appendFile, mkdir, readFile, rename, writeFile } from "node:fs/promises";++import { aggregateCodexObjectiveForScope } from "./goal-status.js";+import {+ repoRelative,+ type UlwLoopScope,+ ulwLoopDir,+ ulwLoopGoalsPath,+ ulwLoopLedgerPath,+ ulwLoopRelativeDir,+} from "./paths.js";+import type { UlwLoopLedgerEntry, UlwLoopPlan } from "./types.js";+import { iso, ULW_LOOP_DIR, ULW_LOOP_GOALS, ULW_LOOP_LEDGER, UlwLoopError } from "./types.js";++const LEGACY_OBJECTIVE_PREFIX = `Complete all ulw-loop stories in ${ULW_LOOP_DIR}/${ULW_LOOP_GOALS}: `;+const LEGACY_OBJECTIVE = `Complete all ulw-loop stories listed in ${ULW_LOOP_DIR}/${ULW_LOOP_GOALS}. Use ${ULW_LOOP_DIR}/${ULW_LOOP_LEDGER} as the durable audit trail.`;+const locks = new Map<string, Promise<unknown>>();++function hasCode(error: unknown, code: string): boolean {+ return error instanceof Error && "code" in error && error.code === code;+}++function isLegacyEnumeratedAggregateObjective(objective: string | undefined): objective is string {+ return objective === LEGACY_OBJECTIVE || Boolean(objective?.startsWith(LEGACY_OBJECTIVE_PREFIX));+}++function isSteeringKind(value: unknown): value is UlwLoopLedgerEntry["kind"] {+ return value === "steering_accepted" || value === "steering_rejected" || value === "criteria_revised";+}++export async function withUlwLoopMutationLock<T>(repoRoot: string, fn: () => Promise<T>): Promise<T>;+export async function withUlwLoopMutationLock<T>(+ repoRoot: string,+ scope: UlwLoopScope | undefined,+ fn: () => Promise<T>,+): Promise<T>;+export async function withUlwLoopMutationLock<T>(+ repoRoot: string,+ scopeOrFn: UlwLoopScope | (() => Promise<T>) | undefined,+ maybeFn?: () => Promise<T>,+): Promise<T> {+ const scope = typeof scopeOrFn === "function" ? undefined : scopeOrFn;+ const fn = typeof scopeOrFn === "function" ? scopeOrFn : maybeFn;+ if (fn === undefined) throw new UlwLoopError("Missing ulw-loop mutation body.", "ULW_LOOP_LOCK_BODY_MISSING");+ const lockKey = `${repoRoot}\0${ulwLoopRelativeDir(scope)}`;+ const prior = locks.get(lockKey) ?? Promise.resolve();+ const run = prior.then(fn, fn);+ locks.set(+ lockKey,+ run.catch(() => undefined),+ );+ return run;+}++export async function readUlwLoopPlan(repoRoot: string, scope?: UlwLoopScope): Promise<UlwLoopPlan> {+ const path = ulwLoopGoalsPath(repoRoot, scope);+ let raw: string;+ try {+ raw = await readFile(path, "utf8");+ } catch (error) {+ if (!hasCode(error, "ENOENT")) throw error;+ throw new UlwLoopError(+ `No ulw-loop plan found at ${repoRelative(path, repoRoot)}. Run \`omo ulw-loop create-goals ...\` first.`,+ "ULW_LOOP_PLAN_MISSING",+ { cause: error },+ );+ }+ const parsed: UlwLoopPlan = JSON.parse(raw);+ if (parsed.version !== 1 || !Array.isArray(parsed.goals)) {+ throw new UlwLoopError(`Invalid ulw-loop plan at ${repoRelative(path, repoRoot)}.`, "ULW_LOOP_PLAN_INVALID");+ }+ const previousObjective = parsed.codexObjective;+ if (+ (parsed.codexGoalMode ?? "per_story") === "aggregate" &&+ isLegacyEnumeratedAggregateObjective(previousObjective)+ ) {+ const now = iso();+ parsed.codexObjective = aggregateCodexObjectiveForScope(scope);+ parsed.codexObjectiveAliases = [...new Set([...(parsed.codexObjectiveAliases ?? []), previousObjective])];+ parsed.updatedAt = now;+ await writePlan(repoRoot, parsed, scope);+ await appendLedger(+ repoRoot,+ {+ at: now,+ kind: "aggregate_objective_migrated",+ message: "Migrated legacy enumerated aggregate Codex objective to the stable pointer objective.",+ before: { codexObjective: previousObjective },+ after: { codexObjective: parsed.codexObjective },+ },+ scope,+ );+ }+ return parsed;+}++export async function writePlan(repoRoot: string, plan: UlwLoopPlan, scope?: UlwLoopScope): Promise<void> {+ await mkdir(ulwLoopDir(repoRoot, scope), { recursive: true });+ const path = ulwLoopGoalsPath(repoRoot, scope);+ const tmpPath = `${path}.${process.pid}.${Date.now()}.tmp`;+ await writeFile(tmpPath, `${JSON.stringify(plan, null, 2)}\n`, "utf8");+ await rename(tmpPath, path);+}++export async function appendLedger(repoRoot: string, entry: UlwLoopLedgerEntry, scope?: UlwLoopScope): Promise<void> {+ await mkdir(ulwLoopDir(repoRoot, scope), { recursive: true });+ await appendFile(ulwLoopLedgerPath(repoRoot, scope), `${JSON.stringify(entry)}\n`, "utf8");+}++export async function readSteeringLedgerEntries(repoRoot: string, scope?: UlwLoopScope): Promise<UlwLoopLedgerEntry[]> {+ let raw: string;+ try {+ raw = await readFile(ulwLoopLedgerPath(repoRoot, scope), "utf8");+ } catch (error) {+ if (hasCode(error, "ENOENT")) return [];+ throw error;+ }+ const entries: UlwLoopLedgerEntry[] = [];+ for (const line of raw.split(/\r?\n/).filter(Boolean)) {+ const entry: UlwLoopLedgerEntry = JSON.parse(line);+ if (isSteeringKind(entry.kind)) entries.push(entry);+ }+ return entries;+}diff --git a/plugins/omo/components/ultragoal/src/quality-gate.ts b/plugins/omo/components/ulw-loop/src/quality-gate.tssimilarity index 90%rename from plugins/omo/components/ultragoal/src/quality-gate.tsrename to plugins/omo/components/ulw-loop/src/quality-gate.tsindex b5e08d41..4303b99a 100644--- a/plugins/omo/components/ultragoal/src/quality-gate.ts+++ b/plugins/omo/components/ulw-loop/src/quality-gate.ts@@ -1,5 +1,5 @@-import type { UltragoalItem, UltragoalPlan, UltragoalQualityGate } from "./types.js";-import { UltragoalError } from "./types.js";+import type { UlwLoopItem, UlwLoopPlan, UlwLoopQualityGate } from "./types.js";+import { UlwLoopError } from "./types.js";const BLOCKER_FIELD_KEYS = "blocker blockerSignature blockerEvidence blockerOccurrences blockedAt".split(" ");const URL_PATTERN = /https?:\/\/\S+/g;@@ -14,7 +14,7 @@ const GHCR_401_PATTERN = /\b(401|unauthorized|anonymous pull|authentication requconst GHCR_403_PATTERN = /\b(403|forbidden|read packages|package api)\b/;function invalid(message: string, field: string): never {- throw new UltragoalError(message, "ULTRAGOAL_QUALITY_GATE_INVALID", { details: { field } });+ throw new UlwLoopError(message, "ULW_LOOP_QUALITY_GATE_INVALID", { details: { field } });}function isRecord(value: unknown): value is Record<string, unknown> {@@ -42,7 +42,7 @@ function stringArray(value: unknown, field: string): string[] {return value.map((item) => nonEmptyString(item, field));}-export function validateQualityGate(input: unknown): UltragoalQualityGate {+export function validateQualityGate(input: unknown): UlwLoopQualityGate {const gate = section(input, "qualityGate");const cleaner = section(gate["aiSlopCleaner"], "aiSlopCleaner");const verification = section(gate["verification"], "verification");@@ -61,7 +61,7 @@ export function validateQualityGate(input: unknown): UltragoalQualityGate {const cleanerEvidence = nonEmptyString(cleaner["evidence"], "aiSlopCleaner.evidence");const verificationEvidence = nonEmptyString(verification["evidence"], "verification.evidence");const reviewEvidence = nonEmptyString(review["evidence"], "codeReview.evidence");- const result: UltragoalQualityGate = {+ const result: UlwLoopQualityGate = {aiSlopCleaner: { status: "passed", evidence: cleanerEvidence },verification: { status: "passed", commands, evidence: verificationEvidence },codeReview: { recommendation: "APPROVE", architectStatus: "CLEAR", evidence: reviewEvidence },@@ -86,17 +86,17 @@ export function classifyExternalAuthorizationBlocker(evidence: string): string |return `GHCR_PULL_ACCESS:${status || "AUTHORIZATION_REQUIRED"}:GHCR_VISIBILITY_OR_CREDENTIAL_REQUIRED`;}-function nestedBlockerSignature(goal: UltragoalItem): string | null {+function nestedBlockerSignature(goal: UlwLoopItem): string | null {const blocker = Reflect.get(goal, "blocker");const signature = isRecord(blocker) ? blocker["signature"] : null;return typeof signature === "string" ? signature : null;}-export function sameBlockerOccurrences(plan: UltragoalPlan, signature: string): number {+export function sameBlockerOccurrences(plan: UlwLoopPlan, signature: string): number {return plan.goals.filter((goal) => goal.blockerSignature === signature || nestedBlockerSignature(goal) === signature).length;}-export function clearGoalBlockerFields(goal: UltragoalItem): void {+export function clearGoalBlockerFields(goal: UlwLoopItem): void {for (const key of BLOCKER_FIELD_KEYS) Reflect.deleteProperty(goal, key);}diff --git a/plugins/omo/components/ultragoal/src/review-blockers.ts b/plugins/omo/components/ulw-loop/src/review-blockers.tssimilarity index 58%rename from plugins/omo/components/ultragoal/src/review-blockers.tsrename to plugins/omo/components/ulw-loop/src/review-blockers.tsindex 08fbc18c..6ad3292f 100644--- a/plugins/omo/components/ultragoal/src/review-blockers.ts+++ b/plugins/omo/components/ulw-loop/src/review-blockers.ts@@ -2,21 +2,22 @@import { readCodexGoalSnapshotInput, reconcileCodexGoalSnapshot } from "./codex-goal-snapshot.js";import { codexGoalMode, compatibleCodexObjectives, expectedCodexObjective, isFinalRunCompletionCandidate } from "./goal-status.js";+import type { UlwLoopScope } from "./paths.js";import { seedDefaultSuccessCriteria } from "./plan-crud.js";-import { appendLedger, readUltragoalPlan, withUltragoalMutationLock, writePlan } from "./plan-io.js";-import type { UltragoalItem, UltragoalLedgerEntry, UltragoalPlan } from "./types.js";-import { iso, UltragoalError } from "./types.js";+import { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";+import type { UlwLoopItem, UlwLoopLedgerEntry, UlwLoopPlan } from "./types.js";+import { iso, UlwLoopError } from "./types.js";export interface RecordFinalReviewBlockersArgs { readonly goalId: string; readonly title: string; readonly objective: string; readonly evidence: string; readonly codexGoalJson: string }-export interface RecordFinalReviewBlockersResult { readonly plan: UltragoalPlan; readonly blockedGoal: UltragoalItem; readonly newGoal: UltragoalItem; readonly ledgerEntries: UltragoalLedgerEntry[] }+export interface RecordFinalReviewBlockersResult { readonly plan: UlwLoopPlan; readonly blockedGoal: UlwLoopItem; readonly newGoal: UlwLoopItem; readonly ledgerEntries: UlwLoopLedgerEntry[] }const BLOCKER_FIELDS = "blockedReason blockerSignature blockerOccurrenceCount requiredExternalDecision nonRetriable failedAt failureReason completedAt blocker blockerEvidence blockerOccurrences blockedAt".split(" ");-function ultragoalError(message: string, code: string): never {- throw new UltragoalError(message, code);+function ulwLoopError(message: string, code: string): never {+ throw new UlwLoopError(message, code);}-function nextGoalId(plan: UltragoalPlan): string {+function nextGoalId(plan: UlwLoopPlan): string {const max = plan.goals.reduce((current, goal) => {const digits = /^G(\d+)/u.exec(goal.id)?.[1];return digits === undefined ? current : Math.max(current, Number(digits));@@ -24,9 +25,9 @@ function nextGoalId(plan: UltragoalPlan): string {return `G${String(max + 1).padStart(3, "0")}`;}-function appendBlockerGoal(plan: UltragoalPlan, args: RecordFinalReviewBlockersArgs, now: string): UltragoalItem {+function appendBlockerGoal(plan: UlwLoopPlan, args: RecordFinalReviewBlockersArgs, now: string): UlwLoopItem {const index = plan.goals.length;- const goal: UltragoalItem = {+ const goal: UlwLoopItem = {id: nextGoalId(plan),title: args.title,objective: args.objective,@@ -43,18 +44,19 @@ function appendBlockerGoal(plan: UltragoalPlan, args: RecordFinalReviewBlockersAexport async function recordFinalReviewBlockers(repoRoot: string,args: RecordFinalReviewBlockersArgs,+ scope?: UlwLoopScope,): Promise<RecordFinalReviewBlockersResult> {- return withUltragoalMutationLock(repoRoot, async () => {- const plan = await readUltragoalPlan(repoRoot);+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ const plan = await readUlwLoopPlan(repoRoot, scope);const goal = plan.goals.find((candidate) => candidate.id === args.goalId);- if (goal === undefined) ultragoalError(`Unknown ultragoal id: ${args.goalId}`, "ultragoal_goal_not_found");- if (goal.status !== "in_progress") ultragoalError(`${goal.id} is ${goal.status}.`, "ultragoal_goal_not_in_progress");- if (!isFinalRunCompletionCandidate(plan, goal)) ultragoalError(`${goal.id} is not final.`, "ultragoal_not_final_story");+ if (goal === undefined) ulwLoopError(`Unknown ulw-loop id: ${args.goalId}`, "ulw_loop_goal_not_found");+ if (goal.status !== "in_progress") ulwLoopError(`${goal.id} is ${goal.status}.`, "ulw_loop_goal_not_in_progress");+ if (!isFinalRunCompletionCandidate(plan, goal)) ulwLoopError(`${goal.id} is not final.`, "ulw_loop_not_final_story");const snapshot = await readCodexGoalSnapshotInput(args.codexGoalJson, repoRoot);const aggregate = codexGoalMode(plan) === "aggregate";const reconciliation = reconcileCodexGoalSnapshot(snapshot, { expectedObjective: expectedCodexObjective(plan, goal), ...(aggregate ? { acceptedObjectives: compatibleCodexObjectives(plan) } : {}), allowedStatuses: ["active"], requireSnapshot: true, requireComplete: false });- if (!reconciliation.ok) ultragoalError(reconciliation.errors.join(" "), "ultragoal_codex_snapshot_mismatch");+ if (!reconciliation.ok) ulwLoopError(reconciliation.errors.join(" "), "ulw_loop_codex_snapshot_mismatch");const now = iso();for (const field of BLOCKER_FIELDS) Reflect.deleteProperty(goal, field);@@ -67,13 +69,13 @@ export async function recordFinalReviewBlockers(plan.updatedAt = now;const codexGoal = reconciliation.snapshot.raw;- const blockedEntry: UltragoalLedgerEntry = { at: now, kind: "goal_review_blocked", goalId: goal.id, status: goal.status, evidence: args.evidence, codexGoal };- const addedEntry: UltragoalLedgerEntry = { at: now, kind: "goal_added", goalId: newGoal.id, status: newGoal.status, evidence: args.evidence, message: newGoal.title };- const summaryEntry: UltragoalLedgerEntry = { at: now, kind: "goal_review_blocked", goalId: goal.id, status: goal.status, evidence: args.evidence, codexGoal, message: `Review blockers recorded; appended ${newGoal.id}.` };+ const blockedEntry: UlwLoopLedgerEntry = { at: now, kind: "goal_review_blocked", goalId: goal.id, status: goal.status, evidence: args.evidence, codexGoal };+ const addedEntry: UlwLoopLedgerEntry = { at: now, kind: "goal_added", goalId: newGoal.id, status: newGoal.status, evidence: args.evidence, message: newGoal.title };+ const summaryEntry: UlwLoopLedgerEntry = { at: now, kind: "goal_review_blocked", goalId: goal.id, status: goal.status, evidence: args.evidence, codexGoal, message: `Review blockers recorded; appended ${newGoal.id}.` };Reflect.set(summaryEntry, "kind", "blocker_recorded");const ledgerEntries = [blockedEntry, addedEntry, summaryEntry];- await writePlan(repoRoot, plan);- for (const entry of ledgerEntries) await appendLedger(repoRoot, entry);+ await writePlan(repoRoot, plan, scope);+ for (const entry of ledgerEntries) await appendLedger(repoRoot, entry, scope);return { plan, blockedGoal: goal, newGoal, ledgerEntries };});}diff --git a/plugins/omo/components/ultragoal/src/steering.ts b/plugins/omo/components/ulw-loop/src/steering.tssimilarity index 69%rename from plugins/omo/components/ultragoal/src/steering.tsrename to plugins/omo/components/ulw-loop/src/steering.tsindex 81c151cc..76ae86da 100644--- a/plugins/omo/components/ultragoal/src/steering.ts+++ b/plugins/omo/components/ulw-loop/src/steering.ts@@ -1,21 +1,23 @@// biome-ignore-all format: compact steering module must stay below the 240 pure-LOC budget-import { isUltragoalDone } from "./goal-status.js";-import { appendLedger, readSteeringLedgerEntries, readUltragoalPlan, withUltragoalMutationLock, writePlan } from "./plan-io.js";+import { isUlwLoopDone } from "./goal-status.js";+import type { UlwLoopScope } from "./paths.js";+import { seedDefaultSuccessCriteria } from "./plan-crud.js";+import { appendLedger, readSteeringLedgerEntries, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";import type {- SteerUltragoalResult,- UltragoalItem,- UltragoalLedgerEntry,- UltragoalPlan,- UltragoalSteeringAudit,- UltragoalSteeringChildGoal,- UltragoalSteeringMutationKind,- UltragoalSteeringProposal,- UltragoalSteeringSource,- UltragoalSuccessCriterionUserModel,+ SteerUlwLoopResult,+ UlwLoopItem,+ UlwLoopLedgerEntry,+ UlwLoopPlan,+ UlwLoopSteeringAudit,+ UlwLoopSteeringChildGoal,+ UlwLoopSteeringMutationKind,+ UlwLoopSteeringProposal,+ UlwLoopSteeringSource,+ UlwLoopSuccessCriterionUserModel,} from "./types.js";-import { iso, ULTRAGOAL_STEERING_MUTATION_KINDS, ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS } from "./types.js";+import { iso, ULW_LOOP_STEERING_MUTATION_KINDS, ULW_LOOP_SUCCESS_CRITERION_USER_MODELS } from "./types.js";-const SOURCES = ["user_prompt_submit", "finding", "cli"] as const satisfies readonly UltragoalSteeringSource[];+const SOURCES = ["user_prompt_submit", "finding", "cli"] as const satisfies readonly UlwLoopSteeringSource[];const PROTECTED = new Set(["aggregateCompletion", "codexObjective", "codexObjectiveAliases", "originalConstraints", "qualityGate", "status", "completedAt", "completionStatus"]);const isObject = (value: unknown): value is object => typeof value === "object" && value !== null; const isPlain = (value: unknown): value is object => isObject(value) && !Array.isArray(value);const read = (value: object, key: string): unknown => Object.entries(value).find(([name]) => name === key)?.[1];@@ -24,9 +26,9 @@ const text = (value: object, key: string): string | undefined => {const candidate = read(value, key);return isText(candidate) ? candidate.trim() : undefined;};-const isKind = (value: unknown): value is UltragoalSteeringMutationKind => typeof value === "string" && ULTRAGOAL_STEERING_MUTATION_KINDS.some((kind) => kind === value);-const isSource = (value: unknown): value is UltragoalSteeringSource => typeof value === "string" && SOURCES.some((source) => source === value);-const isModel = (value: unknown): value is UltragoalSuccessCriterionUserModel => typeof value === "string" && ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS.some((model) => model === value);+const isKind = (value: unknown): value is UlwLoopSteeringMutationKind => typeof value === "string" && ULW_LOOP_STEERING_MUTATION_KINDS.some((kind) => kind === value);+const isSource = (value: unknown): value is UlwLoopSteeringSource => typeof value === "string" && SOURCES.some((source) => source === value);+const isModel = (value: unknown): value is UlwLoopSuccessCriterionUserModel => typeof value === "string" && ULW_LOOP_SUCCESS_CRITERION_USER_MODELS.some((model) => model === value);const texts = (value: object, key: string): string[] => {const candidate = read(value, key);return Array.isArray(candidate) && candidate.every((item) => typeof item === "string") ? candidate : [];@@ -44,7 +46,7 @@ const after = (proposal: object): object | undefined => {};const revised = (proposal: object, direct: string, nested: string): string | undefined => text(proposal, direct) ?? text(after(proposal) ?? proposal, nested);-function child(value: unknown): UltragoalSteeringChildGoal | null {+function child(value: unknown): UlwLoopSteeringChildGoal | null {if (!isPlain(value)) return null;const title = text(value, "title");const objective = text(value, "objective");@@ -60,7 +62,7 @@ function childValues(proposal: object): unknown[] {return Array.isArray(fromAfter) ? fromAfter : [];}-const children = (proposal: object): UltragoalSteeringChildGoal[] => childValues(proposal).map(child).filter((item): item is UltragoalSteeringChildGoal => item !== null);+const children = (proposal: object): UlwLoopSteeringChildGoal[] => childValues(proposal).map(child).filter((item): item is UlwLoopSteeringChildGoal => item !== null);const pendingOrder = (proposal: object): string[] => {const direct = texts(proposal, "pendingOrder");return direct.length > 0 ? direct : texts(after(proposal) ?? proposal, "pendingGoalIds");@@ -82,13 +84,13 @@ function weakens(value: unknown): boolean {return /\b(skip|bypass|weaken|remove|omit|auto[-\s]?complete|mark complete|complete faster)\b/.test(valueText) && /\b(test|tests|verification|review|quality gate|complete|completion)\b/.test(valueText);}-function auditFor(proposal: unknown, reasons: string[]): UltragoalSteeringAudit {+function auditFor(proposal: unknown, reasons: string[]): UlwLoopSteeringAudit {const object = isPlain(proposal) ? proposal : undefined;const kindRaw = object === undefined ? undefined : read(object, "kind");const sourceRaw = object === undefined ? undefined : read(object, "source");const evidence = object === undefined ? "" : (text(object, "evidence") ?? "");const rationale = object === undefined ? "" : (text(object, "rationale") ?? "");- const audit: UltragoalSteeringAudit = { kind: isKind(kindRaw) ? kindRaw : "annotate_ledger", source: isSource(sourceRaw) ? sourceRaw : "cli", targetGoalIds: object === undefined ? [] : targets(object), evidence, rationale, invariant: { accepted: reasons.length === 0, structuralInvariantAccepted: reasons.length === 0, evidenceBackedNecessity: evidence.length > 0 && rationale.length > 0, noEasierCompletion: !weakens(proposal), rejectedReasons: reasons, reasons } };+ const audit: UlwLoopSteeringAudit = { kind: isKind(kindRaw) ? kindRaw : "annotate_ledger", source: isSource(sourceRaw) ? sourceRaw : "cli", targetGoalIds: object === undefined ? [] : targets(object), evidence, rationale, invariant: { accepted: reasons.length === 0, structuralInvariantAccepted: reasons.length === 0, evidenceBackedNecessity: evidence.length > 0 && rationale.length > 0, noEasierCompletion: !weakens(proposal), rejectedReasons: reasons, reasons } };if (object === undefined) return audit;const criterionId = text(object, "criterionId");const directiveText = text(object, "directiveText");@@ -101,7 +103,7 @@ function auditFor(proposal: unknown, reasons: string[]): UltragoalSteeringAuditreturn audit;}-export function validateUltragoalSteeringProposal(plan: UltragoalPlan, proposal: unknown): UltragoalSteeringAudit {+export function validateUlwLoopSteeringProposal(plan: UlwLoopPlan, proposal: unknown): UlwLoopSteeringAudit {const reasons: string[] = [];if (!isPlain(proposal)) reasons.push("proposal must be an object");const object = isPlain(proposal) ? proposal : {};@@ -112,16 +114,16 @@ export function validateUltragoalSteeringProposal(plan: UltragoalPlan, proposal:if (text(object, "rationale") === undefined) reasons.push("missing rationale");if (hasProtected(proposal)) reasons.push("protected payload");if (weakens(proposal)) reasons.push("weakened completion");- if (isUltragoalDone(plan)) reasons.push("plan already complete");+ if (isUlwLoopDone(plan)) reasons.push("plan already complete");if (isKind(kind)) validateKind(plan, object, kind, reasons);return auditFor(proposal, reasons);}-function goal(plan: UltragoalPlan, id: string | undefined): UltragoalItem | undefined {+function goal(plan: UlwLoopPlan, id: string | undefined): UlwLoopItem | undefined {return id === undefined ? undefined : plan.goals.find((item) => item.id === id);}-function validateKind(plan: UltragoalPlan, proposal: object, kind: UltragoalSteeringMutationKind, reasons: string[]): void {+function validateKind(plan: UlwLoopPlan, proposal: object, kind: UlwLoopSteeringMutationKind, reasons: string[]): void {const target = goal(plan, targets(proposal)[0]);if (kind === "add_subgoal" && (text(proposal, "title") === undefined || text(proposal, "objective") === undefined)) reasons.push("add_subgoal requires title/objective");if ((kind === "split_subgoal" || kind === "revise_pending_wording" || kind === "mark_blocked_superseded") && target === undefined) reasons.push(`${kind} requires target`);@@ -134,7 +136,7 @@ function validateKind(plan: UltragoalPlan, proposal: object, kind: UltragoalSteeif (kind === "revise_criterion") validateCriterion(plan, proposal, reasons);}-function validateOrder(plan: UltragoalPlan, proposal: object, reasons: string[]): void {+function validateOrder(plan: UlwLoopPlan, proposal: object, reasons: string[]): void {const requested = pendingOrder(proposal);const pending = plan.goals.filter((item) => item.status === "pending" && item.steeringStatus === undefined).map((item) => item.id);if (requested.length === 0) reasons.push("reorder_pending requires ids");@@ -142,7 +144,7 @@ function validateOrder(plan: UltragoalPlan, proposal: object, reasons: string[])if (requested.some((id) => !pending.includes(id))) reasons.push("unknown pending id");}-function validateCriterion(plan: UltragoalPlan, proposal: object, reasons: string[]): void {+function validateCriterion(plan: UlwLoopPlan, proposal: object, reasons: string[]): void {const target = goal(plan, targets(proposal)[0]);const criterionId = text(proposal, "criterionId");if (target === undefined) reasons.push("revise_criterion requires goalId");@@ -152,26 +154,29 @@ function validateCriterion(plan: UltragoalPlan, proposal: object, reasons: strinif (model !== undefined && !isModel(model)) reasons.push("invalid userModel");}-function nextId(plan: UltragoalPlan, offset: number): string {+function nextId(plan: UlwLoopPlan, offset: number): string {const max = plan.goals.reduce((current, item) => {- const digits = /^G(\d+)$/u.exec(item.id)?.[1];+ const digits = /^G(\d+)(?:-|$)/u.exec(item.id)?.[1];return digits === undefined ? current : Math.max(current, Number(digits));}, 0);return `G${String(max + offset).padStart(3, "0")}`;}-function makeGoal(plan: UltragoalPlan, childGoal: UltragoalSteeringChildGoal, evidence: string, now: string, offset: number): UltragoalItem {- return { id: nextId(plan, offset), title: childGoal.title, objective: childGoal.objective, status: "pending", successCriteria: [], attempt: 0, createdAt: now, updatedAt: now, evidence };+function makeGoal(plan: UlwLoopPlan, childGoal: UlwLoopSteeringChildGoal, evidence: string, now: string, offset: number): UlwLoopItem {+ const id = nextId(plan, offset);+ const digits = /^G(\d+)/u.exec(id)?.[1];+ const goalIndex = digits === undefined ? plan.goals.length + offset - 1 : Number(digits) - 1;+ return { id, title: childGoal.title, objective: childGoal.objective, status: "pending", successCriteria: seedDefaultSuccessCriteria(goalIndex, childGoal.objective), attempt: 0, createdAt: now, updatedAt: now, evidence };}-export function applySteeringMutation(plan: UltragoalPlan, proposal: UltragoalSteeringProposal, audit: UltragoalSteeringAudit): UltragoalPlan {+export function applySteeringMutation(plan: UlwLoopPlan, proposal: UlwLoopSteeringProposal, audit: UlwLoopSteeringAudit): UlwLoopPlan {const next = structuredClone(plan);if (!audit.invariant.accepted) return next;const now = proposal.now?.toISOString() ?? iso();if (proposal.kind === "add_subgoal") next.goals.push(makeGoal(next, { title: proposal.title ?? "", objective: proposal.objective ?? "" }, proposal.evidence, now, 1));if (proposal.kind === "reorder_pending") {const order = pendingOrder(proposal);- next.goals = [...order.map((id) => goal(next, id)).filter((item): item is UltragoalItem => item !== undefined), ...next.goals.filter((item) => !order.includes(item.id))];+ next.goals = [...order.map((id) => goal(next, id)).filter((item): item is UlwLoopItem => item !== undefined), ...next.goals.filter((item) => !order.includes(item.id))];}if (proposal.kind === "revise_pending_wording") reviseWording(next, proposal, now);if (proposal.kind === "split_subgoal" || proposal.kind === "mark_blocked_superseded") splitOrBlock(next, proposal, now);@@ -180,7 +185,7 @@ export function applySteeringMutation(plan: UltragoalPlan, proposal: UltragoalStreturn next;}-function reviseWording(plan: UltragoalPlan, proposal: UltragoalSteeringProposal, now: string): void {+function reviseWording(plan: UlwLoopPlan, proposal: UlwLoopSteeringProposal, now: string): void {const target = goal(plan, targets(proposal)[0]);if (target === undefined) return;target.title = revised(proposal, "revisedTitle", "title") ?? target.title;@@ -190,7 +195,7 @@ function reviseWording(plan: UltragoalPlan, proposal: UltragoalSteeringProposal,target.updatedAt = now;}-function splitOrBlock(plan: UltragoalPlan, proposal: UltragoalSteeringProposal, now: string): void {+function splitOrBlock(plan: UlwLoopPlan, proposal: UlwLoopSteeringProposal, now: string): void {const target = goal(plan, targets(proposal)[0]);if (target === undefined) return;const replacements = children(proposal).map((item, index) => makeGoal(plan, item, proposal.evidence, now, index + 1));@@ -210,7 +215,7 @@ function splitOrBlock(plan: UltragoalPlan, proposal: UltragoalSteeringProposal,if (plan.activeGoalId === target.id) delete plan.activeGoalId;}-function reviseCriterion(plan: UltragoalPlan, proposal: UltragoalSteeringProposal, now: string): void {+function reviseCriterion(plan: UlwLoopPlan, proposal: UlwLoopSteeringProposal, now: string): void {const target = goal(plan, targets(proposal)[0]);const index = target?.successCriteria.findIndex((item) => item.id === proposal.criterionId) ?? -1;const current = target?.successCriteria[index];@@ -220,12 +225,12 @@ function reviseCriterion(plan: UltragoalPlan, proposal: UltragoalSteeringProposatarget.updatedAt = now;}-function isProposal(value: unknown): value is UltragoalSteeringProposal {+function isProposal(value: unknown): value is UlwLoopSteeringProposal {return isPlain(value) && isKind(read(value, "kind")) && isSource(read(value, "source")) && isText(read(value, "evidence")) && isText(read(value, "rationale"));}-export function parseUltragoalSteeringDirective(text: string): UltragoalSteeringProposal | null {- const match = /(?:^|\s)(?:OMO_ULTRAGOAL_STEER|omo\.ultragoal\.steer|omo ultragoal steer):\s*([\s\S]+)$/u.exec(text);+export function parseUlwLoopSteeringDirective(text: string): UlwLoopSteeringProposal | null {+ const match = /(?:^|\s)(?:OMO_ULW_LOOP_STEER|omo\.ulw-loop\.steer|omo ulw-loop steer):\s*([\s\S]+)$/u.exec(text);if (match?.[1] === undefined) return null;try {const parsed: unknown = JSON.parse(match[1].trim());@@ -236,25 +241,25 @@ export function parseUltragoalSteeringDirective(text: string): UltragoalSteering}}-export async function steerUltragoal(repoRoot: string, proposal: UltragoalSteeringProposal): Promise<SteerUltragoalResult> {- return withUltragoalMutationLock(repoRoot, async () => {- const plan = await readUltragoalPlan(repoRoot);+export async function steerUlwLoop(repoRoot: string, proposal: UlwLoopSteeringProposal, scope?: UlwLoopScope): Promise<SteerUlwLoopResult> {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ const plan = await readUlwLoopPlan(repoRoot, scope);const key = proposal.idempotencyKey ?? proposal.promptSignature;- const prior = key === undefined ? undefined : (await readSteeringLedgerEntries(repoRoot)).find((entry) => entry.steering?.invariant.accepted === true && (entry.idempotencyKey === key || entry.steering.idempotencyKey === key || entry.steering.promptSignature === key));+ const prior = key === undefined ? undefined : (await readSteeringLedgerEntries(repoRoot, scope)).find((entry) => entry.steering?.invariant.accepted === true && (entry.idempotencyKey === key || entry.steering.idempotencyKey === key || entry.steering.promptSignature === key));if (prior?.steering !== undefined) return { plan, accepted: true, audit: { ...prior.steering, deduped: true }, rejectedReasons: [], deduped: true };- const audit = validateUltragoalSteeringProposal(plan, proposal);+ const audit = validateUlwLoopSteeringProposal(plan, proposal);const accepted = audit.invariant.accepted;const next = accepted ? applySteeringMutation(plan, proposal, audit) : plan;- const finalAudit: UltragoalSteeringAudit = { ...audit, before: plan };+ const finalAudit: UlwLoopSteeringAudit = { ...audit, before: plan };if (accepted) finalAudit.after = next;- if (accepted) await writePlan(repoRoot, next);- await appendLedger(repoRoot, ledgerEntry(proposal, finalAudit, proposal.now?.toISOString() ?? iso()));+ if (accepted) await writePlan(repoRoot, next, scope);+ await appendLedger(repoRoot, ledgerEntry(proposal, finalAudit, proposal.now?.toISOString() ?? iso()), scope);return { plan: next, accepted, audit: finalAudit, rejectedReasons: audit.invariant.rejectedReasons, deduped: false };});}-function ledgerEntry(proposal: UltragoalSteeringProposal, audit: UltragoalSteeringAudit, at: string): UltragoalLedgerEntry {- const entry: UltragoalLedgerEntry = { at, kind: audit.invariant.accepted ? (proposal.kind === "revise_criterion" ? "criteria_revised" : "steering_accepted") : "steering_rejected", evidence: proposal.evidence, message: proposal.rationale, steering: audit, mutationKind: proposal.kind };+function ledgerEntry(proposal: UlwLoopSteeringProposal, audit: UlwLoopSteeringAudit, at: string): UlwLoopLedgerEntry {+ const entry: UlwLoopLedgerEntry = { at, kind: audit.invariant.accepted ? (proposal.kind === "revise_criterion" ? "criteria_revised" : "steering_accepted") : "steering_rejected", evidence: proposal.evidence, message: proposal.rationale, steering: audit, mutationKind: proposal.kind };const goalId = audit.targetGoalIds[0];if (goalId !== undefined) entry.goalId = goalId;if (proposal.criterionId !== undefined) entry.criterionId = proposal.criterionId;diff --git a/plugins/omo/components/ultragoal/src/types.ts b/plugins/omo/components/ulw-loop/src/types.tssimilarity index 58%rename from plugins/omo/components/ultragoal/src/types.tsrename to plugins/omo/components/ulw-loop/src/types.tsindex d065e672..aa1f11ed 100644--- a/plugins/omo/components/ultragoal/src/types.ts+++ b/plugins/omo/components/ulw-loop/src/types.ts@@ -1,9 +1,9 @@-export const ULTRAGOAL_DIR = ".omo/ultragoal";-export const ULTRAGOAL_BRIEF = "brief.md";-export const ULTRAGOAL_GOALS = "goals.json";-export const ULTRAGOAL_LEDGER = "ledger.jsonl";+export const ULW_LOOP_DIR = ".omo/ulw-loop";+export const ULW_LOOP_BRIEF = "brief.md";+export const ULW_LOOP_GOALS = "goals.json";+export const ULW_LOOP_LEDGER = "ledger.jsonl";-export type UltragoalStatus =+export type UlwLoopStatus =| "pending"| "in_progress"| "complete"@@ -12,11 +12,11 @@ export type UltragoalStatus =| "review_blocked"| "needs_user_decision";-export type UltragoalCodexGoalMode = "aggregate" | "per_story";+export type UlwLoopCodexGoalMode = "aggregate" | "per_story";-export type UltragoalSteeringStatus = "superseded" | "blocked";+export type UlwLoopSteeringStatus = "superseded" | "blocked";-export const ULTRAGOAL_STEERING_MUTATION_KINDS = [+export const ULW_LOOP_STEERING_MUTATION_KINDS = ["add_subgoal","split_subgoal","reorder_pending",@@ -25,22 +25,22 @@ export const ULTRAGOAL_STEERING_MUTATION_KINDS = ["annotate_ledger","mark_blocked_superseded",] as const satisfies readonly string[];-export type UltragoalSteeringMutationKind = (typeof ULTRAGOAL_STEERING_MUTATION_KINDS)[number];+export type UlwLoopSteeringMutationKind = (typeof ULW_LOOP_STEERING_MUTATION_KINDS)[number];-export type UltragoalSteeringSource = "user_prompt_submit" | "finding" | "cli";+export type UlwLoopSteeringSource = "user_prompt_submit" | "finding" | "cli";-export const ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS = [+export const ULW_LOOP_SUCCESS_CRITERION_USER_MODELS = ["happy","edge","regression","adversarial",] as const satisfies readonly string[];-export type UltragoalSuccessCriterionUserModel = (typeof ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS)[number];+export type UlwLoopSuccessCriterionUserModel = (typeof ULW_LOOP_SUCCESS_CRITERION_USER_MODELS)[number];-export const ULTRAGOAL_CRITERION_STATUSES = ["pending", "pass", "fail", "blocked"] as const satisfies readonly string[];-export type UltragoalCriterionStatus = (typeof ULTRAGOAL_CRITERION_STATUSES)[number];+export const ULW_LOOP_CRITERION_STATUSES = ["pending", "pass", "fail", "blocked"] as const satisfies readonly string[];+export type UlwLoopCriterionStatus = (typeof ULW_LOOP_CRITERION_STATUSES)[number];-export const ULTRAGOAL_LEDGER_EVENT_KINDS = [+export const ULW_LOOP_LEDGER_EVENT_KINDS = ["plan_created","goal_started","goal_resumed",@@ -61,20 +61,20 @@ export const ULTRAGOAL_LEDGER_EVENT_KINDS = ["criterion_blocked","criteria_revised",] as const satisfies readonly string[];-export type UltragoalLedgerEventKind = (typeof ULTRAGOAL_LEDGER_EVENT_KINDS)[number];+export type UlwLoopLedgerEventKind = (typeof ULW_LOOP_LEDGER_EVENT_KINDS)[number];-export interface UltragoalSuccessCriterion {+export interface UlwLoopSuccessCriterion {readonly id: string;readonly scenario: string;- readonly userModel: UltragoalSuccessCriterionUserModel;+ readonly userModel: UlwLoopSuccessCriterionUserModel;readonly expectedEvidence: string;capturedEvidence: string | null;- status: UltragoalCriterionStatus;+ status: UlwLoopCriterionStatus;capturedAt?: string;notes?: string;}-export interface UltragoalSteeringInvariantResult {+export interface UlwLoopSteeringInvariantResult {accepted: boolean;structuralInvariantAccepted: boolean;evidenceBackedNecessity: boolean;@@ -83,21 +83,21 @@ export interface UltragoalSteeringInvariantResult {reasons?: string[];}-export interface UltragoalSteeringChildGoal {+export interface UlwLoopSteeringChildGoal {title: string;objective: string;}-export interface UltragoalSteeringAfterPayload {+export interface UlwLoopSteeringAfterPayload {title?: string;objective?: string;pendingGoalIds?: string[];- children?: UltragoalSteeringChildGoal[];+ children?: UlwLoopSteeringChildGoal[];}-export interface UltragoalSteeringProposal {- kind: UltragoalSteeringMutationKind;- source: UltragoalSteeringSource;+export interface UlwLoopSteeringProposal {+ kind: UlwLoopSteeringMutationKind;+ source: UlwLoopSteeringSource;targetGoalId?: string;targetGoalIds?: string[];criterionId?: string;@@ -105,48 +105,48 @@ export interface UltragoalSteeringProposal {rationale: string;title?: string;objective?: string;- childGoals?: UltragoalSteeringChildGoal[];+ childGoals?: UlwLoopSteeringChildGoal[];revisedTitle?: string;revisedObjective?: string;pendingOrder?: string[];blockedReason?: string;- after?: UltragoalSteeringAfterPayload;+ after?: UlwLoopSteeringAfterPayload;directiveText?: string;promptSignature?: string;idempotencyKey?: string;now?: Date;}-export interface UltragoalSteeringAudit {- kind: UltragoalSteeringMutationKind;- source: UltragoalSteeringSource;+export interface UlwLoopSteeringAudit {+ kind: UlwLoopSteeringMutationKind;+ source: UlwLoopSteeringSource;targetGoalIds: string[];criterionId?: string;before?: unknown;after?: unknown;evidence: string;rationale: string;- invariant: UltragoalSteeringInvariantResult;+ invariant: UlwLoopSteeringInvariantResult;directiveText?: string;promptSignature?: string;idempotencyKey?: string;deduped?: boolean;}-export interface SteerUltragoalResult {- plan: UltragoalPlan;+export interface SteerUlwLoopResult {+ plan: UlwLoopPlan;accepted: boolean;- audit: UltragoalSteeringAudit;+ audit: UlwLoopSteeringAudit;rejectedReasons: string[];deduped: boolean;}-export interface UltragoalItem {+export interface UlwLoopItem {id: string;title: string;objective: string;- status: UltragoalStatus;- successCriteria: UltragoalSuccessCriterion[];+ status: UlwLoopStatus;+ successCriteria: UlwLoopSuccessCriterion[];attempt: number;createdAt: string;updatedAt: string;@@ -156,7 +156,7 @@ export interface UltragoalItem {reviewBlockedAt?: string;evidence?: string;failureReason?: string;- steeringStatus?: UltragoalSteeringStatus;+ steeringStatus?: UlwLoopSteeringStatus;supersededBy?: string[];supersedes?: string[];blockedReason?: string;@@ -168,54 +168,54 @@ export interface UltragoalItem {steeringRationale?: string;}-export interface UltragoalAggregateCompletion {+export interface UlwLoopAggregateCompletion {status: "complete";completedAt: string;evidence: string;codexGoal?: unknown;}-export interface UltragoalPlan {+export interface UlwLoopPlan {version: 1;createdAt: string;updatedAt: string;briefPath: string;goalsPath: string;ledgerPath: string;- codexGoalMode?: UltragoalCodexGoalMode;+ codexGoalMode?: UlwLoopCodexGoalMode;codexObjective?: string;codexObjectiveAliases?: string[];- aggregateCompletion?: UltragoalAggregateCompletion;+ aggregateCompletion?: UlwLoopAggregateCompletion;activeGoalId?: string;- goals: UltragoalItem[];+ goals: UlwLoopItem[];}-export interface UltragoalLedgerEntry {+export interface UlwLoopLedgerEntry {at: string;- kind: UltragoalLedgerEventKind;+ kind: UlwLoopLedgerEventKind;goalId?: string;criterionId?: string;- status?: UltragoalStatus;- criterionStatus?: UltragoalCriterionStatus;+ status?: UlwLoopStatus;+ criterionStatus?: UlwLoopCriterionStatus;message?: string;codexGoal?: unknown;evidence?: string;capturedEvidence?: string;- qualityGate?: UltragoalQualityGate;- steering?: UltragoalSteeringAudit;+ qualityGate?: UlwLoopQualityGate;+ steering?: UlwLoopSteeringAudit;before?: unknown;after?: unknown;- mutationKind?: UltragoalSteeringMutationKind;+ mutationKind?: UlwLoopSteeringMutationKind;idempotencyKey?: string;blockerSignature?: string;blockerOccurrenceCount?: number;requiredExternalDecision?: string;}-export interface CreateUltragoalOptions {+export interface CreateUlwLoopOptions {brief: string;goals?: Array<{ title?: string; objective: string }>;- codexGoalMode?: UltragoalCodexGoalMode;+ codexGoalMode?: UlwLoopCodexGoalMode;now?: Date;force?: boolean;}@@ -227,7 +227,7 @@ export interface StartNextOptions {export interface CheckpointOptions {goalId: string;- status: Extract<UltragoalStatus, "complete" | "failed"> | "blocked";+ status: Extract<UlwLoopStatus, "complete" | "failed"> | "blocked";evidence?: string;codexGoal?: unknown;qualityGate?: unknown;@@ -235,36 +235,36 @@ export interface CheckpointOptions {now?: Date;}-export interface AddUltragoalGoalOptions {+export interface AddUlwLoopGoalOptions {title: string;objective: string;evidence?: string;now?: Date;}-export interface RecordFinalReviewBlockersOptions extends AddUltragoalGoalOptions {+export interface RecordFinalReviewBlockersOptions extends AddUlwLoopGoalOptions {goalId: string;codexGoal?: unknown;}-export interface UltragoalQualityGate {+export interface UlwLoopQualityGate {aiSlopCleaner: { status: "passed"; evidence: string };verification: { status: "passed"; commands: string[]; evidence: string };codeReview: { recommendation: "APPROVE"; architectStatus: "CLEAR"; evidence: string };}-export interface UltragoalErrorOptions {+export interface UlwLoopErrorOptions {readonly cause?: unknown;readonly details?: Record<string, unknown>;}-export class UltragoalError extends Error {+export class UlwLoopError extends Error {readonly code: string;readonly details?: Record<string, unknown>;- constructor(message: string, code: string, opts?: UltragoalErrorOptions) {+ constructor(message: string, code: string, opts?: UlwLoopErrorOptions) {super(message, opts?.cause === undefined ? undefined : { cause: opts.cause });- this.name = "UltragoalError";+ this.name = "UlwLoopError";this.code = code;if (opts?.details !== undefined) {this.details = opts.details;diff --git a/plugins/omo/components/ultragoal/test/checkpoint.test.ts b/plugins/omo/components/ulw-loop/test/checkpoint.test.tssimilarity index 52%rename from plugins/omo/components/ultragoal/test/checkpoint.test.tsrename to plugins/omo/components/ulw-loop/test/checkpoint.test.tsindex 8bd8031a..f7d566d5 100644--- a/plugins/omo/components/ultragoal/test/checkpoint.test.ts+++ b/plugins/omo/components/ulw-loop/test/checkpoint.test.ts@@ -2,54 +2,55 @@import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";+import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";-import { checkpointUltragoal } from "../src/checkpoint.js";-import { ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE } from "../src/goal-status.js";-import { ultragoalBriefPath, ultragoalDir, ultragoalLedgerPath } from "../src/paths.js";+import { checkpointUlwLoop } from "../src/checkpoint.js";+import { ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE } from "../src/goal-status.js";+import { ulwLoopBriefPath, ulwLoopDir, ulwLoopLedgerPath } from "../src/paths.js";import { writePlan } from "../src/plan-io.js";-import type { UltragoalItem, UltragoalLedgerEntry, UltragoalPlan, UltragoalSuccessCriterion } from "../src/types.js";-import { UltragoalError } from "../src/types.js";+import type { UlwLoopItem, UlwLoopLedgerEntry, UlwLoopPlan, UlwLoopSuccessCriterion } from "../src/types.js";+import { UlwLoopError } from "../src/types.js";const NOW = "2026-05-23T00:00:00.000Z";-const QUALITY_GATE_PATH = join(process.cwd(), "test", "fixtures", "sample-quality-gate.json");+const QUALITY_GATE_PATH = fileURLToPath(new URL("./fixtures/sample-quality-gate.json", import.meta.url));-function criterion(id: string, status: UltragoalSuccessCriterion["status"]): UltragoalSuccessCriterion {+function criterion(id: string, status: UlwLoopSuccessCriterion["status"]): UlwLoopSuccessCriterion {return { id, scenario: `${id} scenario`, userModel: "happy", expectedEvidence: `${id} proof`, capturedEvidence: status === "pass" ? `${id} passed` : null, status };}-function goal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {+function goal(overrides: Partial<UlwLoopItem> = {}): UlwLoopItem {return { id: "G001", title: "Build auth", objective: "Implement JWT auth endpoint", status: "in_progress", successCriteria: [criterion("C001", "pass"), criterion("C002", "pass"), criterion("C003", "pass")], attempt: 1, createdAt: NOW, updatedAt: NOW, ...overrides };}-function plan(goals: UltragoalItem[], overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {- const result: UltragoalPlan = { version: 1, createdAt: NOW, updatedAt: NOW, briefPath: ".omo/ultragoal/brief.md", goalsPath: ".omo/ultragoal/goals.json", ledgerPath: ".omo/ultragoal/ledger.jsonl", codexGoalMode: "aggregate", codexObjective: ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE, goals };+function plan(goals: UlwLoopItem[], overrides: Partial<UlwLoopPlan> = {}): UlwLoopPlan {+ const result: UlwLoopPlan = { version: 1, createdAt: NOW, updatedAt: NOW, briefPath: ".omo/ulw-loop/brief.md", goalsPath: ".omo/ulw-loop/goals.json", ledgerPath: ".omo/ulw-loop/ledger.jsonl", codexGoalMode: "aggregate", codexObjective: ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE, goals };Object.assign(result, overrides);const activeGoalId = goals.find((candidate) => candidate.status === "in_progress")?.id;if (result.activeGoalId === undefined && activeGoalId !== undefined) result.activeGoalId = activeGoalId;return result;}-async function samplePlan(overrides: Partial<UltragoalPlan> = {}): Promise<UltragoalPlan> {- const fixture: UltragoalPlan = JSON.parse(await readFile(new URL("./fixtures/sample-plan.json", import.meta.url), "utf8"));+async function samplePlan(overrides: Partial<UlwLoopPlan> = {}): Promise<UlwLoopPlan> {+ const fixture: UlwLoopPlan = JSON.parse(await readFile(new URL("./fixtures/sample-plan.json", import.meta.url), "utf8"));return plan(fixture.goals.map((item, index) => goal({ ...item, attempt: index + 1, createdAt: NOW, updatedAt: NOW })), overrides);}-async function repoWith(seed: UltragoalPlan): Promise<string> {+async function repoWith(seed: UlwLoopPlan): Promise<string> {const repo = await mkdtemp(join(tmpdir(), "ug-checkpoint-"));- await mkdir(ultragoalDir(repo), { recursive: true });+ await mkdir(ulwLoopDir(repo), { recursive: true });await writePlan(repo, seed);return repo;}-function snapshot(status: "active" | "complete", objective = ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE): string {+function snapshot(status: "active" | "complete", objective = ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE): string {return JSON.stringify({ goal: { objective, status } });}-async function lastLedger(repo: string): Promise<UltragoalLedgerEntry> {- const last = (await readFile(ultragoalLedgerPath(repo), "utf8")).trim().split(/\r?\n/).at(-1);+async function lastLedger(repo: string): Promise<UlwLoopLedgerEntry> {+ const last = (await readFile(ulwLoopLedgerPath(repo), "utf8")).trim().split(/\r?\n/).at(-1);if (last === undefined) throw new Error("expected ledger entry");- const entry: UltragoalLedgerEntry = JSON.parse(last);+ const entry: UlwLoopLedgerEntry = JSON.parse(last);return entry;}@@ -57,80 +58,80 @@ async function expectCode(action: () => Promise<unknown>, code: string): Promisetry {await action();} catch (error) {- expect(error).toBeInstanceOf(UltragoalError);- if (!(error instanceof UltragoalError)) throw error;+ expect(error).toBeInstanceOf(UlwLoopError);+ if (!(error instanceof UlwLoopError)) throw error;expect(error.code).toBe(code);return;}- throw new Error("Expected UltragoalError");+ throw new Error("Expected UlwLoopError");}-function passGoal(id: string, overrides: Partial<UltragoalItem> = {}): UltragoalItem {+function passGoal(id: string, overrides: Partial<UlwLoopItem> = {}): UlwLoopItem {return goal({ id, successCriteria: [criterion("C001", "pass"), criterion("C002", "pass"), criterion("C003", "pass")], ...overrides });}-describe("checkpointUltragoal status=complete criteria gate", () => {- it("THROWS ultragoal_criteria_not_all_pass when any criterion is pending", async () => {+describe("checkpointUlwLoop status=complete criteria gate", () => {+ it("THROWS ulw_loop_criteria_not_all_pass when any criterion is pending", async () => {const repo = await repoWith(await samplePlan({ goals: [goal({ successCriteria: [criterion("C001", "pass"), criterion("C002", "pending"), criterion("C003", "pass")] })] }));- await expectCode(() => checkpointUltragoal(repo, { goalId: "G001", status: "complete", evidence: "done" }), "ultragoal_criteria_not_all_pass");+ await expectCode(() => checkpointUlwLoop(repo, { goalId: "G001", status: "complete", evidence: "done" }), "ulw_loop_criteria_not_all_pass");});it("THROWS when any criterion is fail or blocked", async () => {- for (const status of ["fail", "blocked"] satisfies UltragoalSuccessCriterion["status"][]) {+ for (const status of ["fail", "blocked"] satisfies UlwLoopSuccessCriterion["status"][]) {const repo = await repoWith(plan([goal({ successCriteria: [criterion("C001", "pass"), criterion("C002", status), criterion("C003", "pass")] })]));- await expectCode(() => checkpointUltragoal(repo, { goalId: "G001", status: "complete", evidence: "done" }), "ultragoal_criteria_not_all_pass");+ await expectCode(() => checkpointUlwLoop(repo, { goalId: "G001", status: "complete", evidence: "done" }), "ulw_loop_criteria_not_all_pass");}});it("THROWS when criteria list is empty", async () => {const repo = await repoWith(plan([goal({ successCriteria: [] }), goal({ id: "G002", status: "pending" })]));- await expectCode(() => checkpointUltragoal(repo, { goalId: "G001", status: "complete", evidence: "done", codexGoalJson: snapshot("active") }), "ultragoal_criteria_not_all_pass");+ await expectCode(() => checkpointUlwLoop(repo, { goalId: "G001", status: "complete", evidence: "done", codexGoalJson: snapshot("active") }), "ulw_loop_criteria_not_all_pass");});it("ACCEPTS complete when ALL criteria pass (with valid snapshot)", async () => {const repo = await repoWith(plan([passGoal("G001"), goal({ id: "G002", status: "pending" })]));- const result = await checkpointUltragoal(repo, { goalId: "G001", status: "complete", evidence: "implementation done and tests passed", codexGoalJson: snapshot("active") });+ const result = await checkpointUlwLoop(repo, { goalId: "G001", status: "complete", evidence: "implementation done and tests passed", codexGoalJson: snapshot("active") });expect(result.goal.status).toBe("complete");expect((await lastLedger(repo)).kind).toBe("goal_completed");});});-describe("checkpointUltragoal reconciliation (status=complete)", () => {+describe("checkpointUlwLoop reconciliation (status=complete)", () => {it("succeeds when snapshot objective matches expected (aggregate active)", async () => {const repo = await repoWith(plan([passGoal("G001"), goal({ id: "G002", status: "pending" })]));- await expect(checkpointUltragoal(repo, { goalId: "G001", status: "complete", evidence: "work complete and validation passed", codexGoalJson: snapshot("active") })).resolves.toMatchObject({ goal: { status: "complete" } });+ await expect(checkpointUlwLoop(repo, { goalId: "G001", status: "complete", evidence: "work complete and validation passed", codexGoalJson: snapshot("active") })).resolves.toMatchObject({ goal: { status: "complete" } });});it("throws on mismatched objective", async () => {const repo = await repoWith(plan([passGoal("G001"), goal({ id: "G002", status: "pending" })]));- await expectCode(() => checkpointUltragoal(repo, { goalId: "G001", status: "complete", evidence: "work complete and validation passed", codexGoalJson: snapshot("active", "wrong objective") }), "ultragoal_codex_snapshot_mismatch");+ await expectCode(() => checkpointUlwLoop(repo, { goalId: "G001", status: "complete", evidence: "work complete and validation passed", codexGoalJson: snapshot("active", "wrong objective") }), "ulw_loop_codex_snapshot_mismatch");});it("throws on mismatched status (snapshot complete when expected active)", async () => {const repo = await repoWith(plan([passGoal("G001"), goal({ id: "G002", status: "pending" })]));- await expectCode(() => checkpointUltragoal(repo, { goalId: "G001", status: "complete", evidence: "work complete and validation passed", codexGoalJson: snapshot("complete") }), "ultragoal_codex_snapshot_mismatch");+ await expectCode(() => checkpointUlwLoop(repo, { goalId: "G001", status: "complete", evidence: "work complete and validation passed", codexGoalJson: snapshot("complete") }), "ulw_loop_codex_snapshot_mismatch");});});-describe("checkpointUltragoal final story", () => {+describe("checkpointUlwLoop final story", () => {it("requires quality-gate-json for the final goal complete", async () => {const repo = await repoWith(plan([passGoal("G001", { status: "complete" }), passGoal("G002")], { activeGoalId: "G002" }));- await expectCode(() => checkpointUltragoal(repo, { goalId: "G002", status: "complete", evidence: "final work complete and validation passed", codexGoalJson: snapshot("complete") }), "ULTRAGOAL_QUALITY_GATE_INVALID");+ await expectCode(() => checkpointUlwLoop(repo, { goalId: "G002", status: "complete", evidence: "final work complete and validation passed", codexGoalJson: snapshot("complete") }), "ULW_LOOP_QUALITY_GATE_INVALID");});it("accepts final story when quality gate JSON includes valid criteriaCoverage", async () => {const repo = await repoWith(plan([passGoal("G001", { status: "complete" }), passGoal("G002")], { activeGoalId: "G002" }));- const result = await checkpointUltragoal(repo, { goalId: "G002", status: "complete", evidence: "final work complete and validation passed", codexGoalJson: snapshot("complete"), qualityGateJson: QUALITY_GATE_PATH });+ const result = await checkpointUlwLoop(repo, { goalId: "G002", status: "complete", evidence: "final work complete and validation passed", codexGoalJson: snapshot("complete"), qualityGateJson: QUALITY_GATE_PATH });expect(result.aggregateCompletion?.status).toBe("complete");expect(result.plan.aggregateCompletion?.status).toBe("complete");});- it("ACCEPTS complete when task-scoped completed Codex objective maps to the ultragoal brief", async () => {- const taskObjective = "Fix ultragoal objective mismatch and install local ulw";+ it("ACCEPTS complete when task-scoped completed Codex objective maps to the ulw-loop brief", async () => {+ const taskObjective = "Fix ulw-loop objective mismatch and install local ulw";const repo = await repoWith(plan([passGoal("G001")], { activeGoalId: "G001" }));- await writeFile(ultragoalBriefPath(repo), `${taskObjective}\n`, "utf8");+ await writeFile(ulwLoopBriefPath(repo), `${taskObjective}\n`, "utf8");- const result = await checkpointUltragoal(repo, {+ const result = await checkpointUlwLoop(repo, {goalId: "G001",status: "complete",evidence: "final implementation complete and quality gate passed",@@ -142,12 +143,29 @@ describe("checkpointUltragoal final story", () => {expect(result.ledgerEntry.kind).toBe("aggregate_completed");});+ it("ACCEPTS complete when active task-scoped Codex objective maps to the ulw-loop brief", async () => {+ const taskObjective = "Create only research artifacts with source evidence";+ const repo = await repoWith(plan([passGoal("G001")], { activeGoalId: "G001" }));+ await writeFile(ulwLoopBriefPath(repo), `${taskObjective}\n`, "utf8");++ const result = await checkpointUlwLoop(repo, {+ goalId: "G001",+ status: "complete",+ evidence: "final implementation complete and quality gate passed",+ codexGoalJson: snapshot("active", taskObjective),+ qualityGateJson: QUALITY_GATE_PATH,+ });++ expect(result.aggregateCompletion?.status).toBe("complete");+ expect(result.ledgerEntry.kind).toBe("aggregate_completed");+ });+it("explains final task-scoped objective mapping when completed Codex objective is unrelated", async () => {const repo = await repoWith(plan([passGoal("G001")], { activeGoalId: "G001" }));- await writeFile(ultragoalBriefPath(repo), "Fix ultragoal objective mismatch and install local ulw\n", "utf8");+ await writeFile(ulwLoopBriefPath(repo), "Fix ulw-loop objective mismatch and install local ulw\n", "utf8");await expect(- checkpointUltragoal(repo, {+ checkpointUlwLoop(repo, {goalId: "G001",status: "complete",evidence: "final implementation complete and quality gate passed",@@ -158,10 +176,10 @@ describe("checkpointUltragoal final story", () => {});});-describe("checkpointUltragoal status=failed", () => {+describe("checkpointUlwLoop status=failed", () => {it("sets goal.status=failed, goal.failedAt, appends ledger", async () => {const repo = await repoWith(plan([goal({ successCriteria: [criterion("C001", "pending")] })]));- const result = await checkpointUltragoal(repo, { goalId: "G001", status: "failed", evidence: "tests failed" });+ const result = await checkpointUlwLoop(repo, { goalId: "G001", status: "failed", evidence: "tests failed" });expect(result.goal.status).toBe("failed");expect(result.goal.failedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/u);expect((await lastLedger(repo)).kind).toBe("goal_failed");@@ -169,27 +187,27 @@ describe("checkpointUltragoal status=failed", () => {it("classifies external authorization blocker signatures", async () => {const repo = await repoWith(plan([goal()]));- const result = await checkpointUltragoal(repo, { goalId: "G001", status: "failed", evidence: "ghcr.io returned 401 authentication required because token missing" });+ const result = await checkpointUlwLoop(repo, { goalId: "G001", status: "failed", evidence: "ghcr.io returned 401 authentication required because token missing" });expect(result.goal.blockerSignature).toBe("GHCR_PULL_ACCESS:HTTP_401_ANONYMOUS:GHCR_VISIBILITY_OR_CREDENTIAL_REQUIRED");});it("after 3 same-signature blockers, marks needs_user_decision + nonRetriable", async () => {const repo = await repoWith(plan([goal({ id: "G001", status: "failed", blockerSignature: "EXTERNAL_AUTHORIZATION_REQUIRED" }), goal({ id: "G002", status: "blocked", blockerSignature: "EXTERNAL_AUTHORIZATION_REQUIRED" }), goal({ id: "G003" })], { activeGoalId: "G003" }));- const result = await checkpointUltragoal(repo, { goalId: "G003", status: "failed", evidence: "Registry returned 401 because credentials are missing" });+ const result = await checkpointUlwLoop(repo, { goalId: "G003", status: "failed", evidence: "Registry returned 401 because credentials are missing" });expect(result.goal.status).toBe("needs_user_decision");expect(result.goal.nonRetriable).toBe(true);});it("skips the criteria gate for failed status", async () => {const repo = await repoWith(plan([goal({ successCriteria: [criterion("C001", "pending")] })]));- await expect(checkpointUltragoal(repo, { goalId: "G001", status: "failed", evidence: "not done" })).resolves.toMatchObject({ goal: { status: "failed" } });+ await expect(checkpointUlwLoop(repo, { goalId: "G001", status: "failed", evidence: "not done" })).resolves.toMatchObject({ goal: { status: "failed" } });});});-describe("checkpointUltragoal status=blocked", () => {+describe("checkpointUlwLoop status=blocked", () => {it("preserves blocker fields + appends ledger", async () => {const repo = await repoWith(plan([goal()]));- const result = await checkpointUltragoal(repo, { goalId: "G001", status: "blocked", evidence: "ghcr.io requires token and credentials are missing" });+ const result = await checkpointUlwLoop(repo, { goalId: "G001", status: "blocked", evidence: "ghcr.io requires token and credentials are missing" });expect(result.goal.status).toBe("blocked");expect(result.goal.blockedReason).toContain("ghcr.io");expect(result.goal.blockerSignature).toContain("GHCR_PULL_ACCESS");@@ -198,16 +216,16 @@ describe("checkpointUltragoal status=blocked", () => {it("skips the criteria gate for blocked status", async () => {const repo = await repoWith(plan([goal({ successCriteria: [criterion("C001", "pending")] })]));- await expect(checkpointUltragoal(repo, { goalId: "G001", status: "blocked", evidence: "waiting for approval" })).resolves.toMatchObject({ goal: { status: "blocked" } });+ await expect(checkpointUlwLoop(repo, { goalId: "G001", status: "blocked", evidence: "waiting for approval" })).resolves.toMatchObject({ goal: { status: "blocked" } });});});-describe("checkpointUltragoal rebrand", () => {+describe("checkpointUlwLoop rebrand", () => {it("does not emit legacy brand token in any returned text or ledger payload", async () => {const repo = await repoWith(plan([passGoal("G001"), goal({ id: "G002", status: "pending" })]));- const result = await checkpointUltragoal(repo, { goalId: "G001", status: "complete", evidence: "implementation done in .omo/ultragoal/goals.json for G001 and validation passed", codexGoalJson: snapshot("active") });+ const result = await checkpointUlwLoop(repo, { goalId: "G001", status: "complete", evidence: "implementation done in .omo/ulw-loop/goals.json for G001 and validation passed", codexGoalJson: snapshot("active") });const forbidden = ["o", "m", "x"].join("");- const payload = `${JSON.stringify(result)}\n${await readFile(ultragoalLedgerPath(repo), "utf8")}`.toLowerCase();+ const payload = `${JSON.stringify(result)}\n${await readFile(ulwLoopLedgerPath(repo), "utf8")}`.toLowerCase();expect(payload).not.toContain(forbidden);});});diff --git a/plugins/omo/components/ulw-loop/test/cli-commands.test.ts b/plugins/omo/components/ulw-loop/test/cli-commands.test.tsnew file mode 100644index 00000000..6905d567--- /dev/null+++ b/plugins/omo/components/ulw-loop/test/cli-commands.test.ts@@ -0,0 +1,375 @@+import { mkdtemp, readFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { ulwLoopCommand } from "../src/cli-commands.ts";+import { ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE } from "../src/goal-status.js";++let testDir: string;+let out: string[];+let err: string[];+let originalCodexSessionId: string | undefined;+let originalCodexThreadId: string | undefined;+let originalOmoSessionId: string | undefined;++beforeEach(async () => {+ testDir = await mkdtemp(join(tmpdir(), "ug-cli-"));+ out = [];+ err = [];+ originalCodexSessionId = process.env["CODEX_SESSION_ID"];+ originalCodexThreadId = process.env["CODEX_THREAD_ID"];+ originalOmoSessionId = process.env["OMO_ULW_LOOP_SESSION_ID"];+ delete process.env["CODEX_SESSION_ID"];+ delete process.env["CODEX_THREAD_ID"];+ delete process.env["OMO_ULW_LOOP_SESSION_ID"];+ vi.spyOn(process, "cwd").mockReturnValue(testDir);+ vi.spyOn(process.stdout, "write").mockImplementation((chunk: string | Uint8Array): boolean => {+ out.push(chunk.toString());+ return true;+ });+ vi.spyOn(process.stderr, "write").mockImplementation((chunk: string | Uint8Array): boolean => {+ err.push(chunk.toString());+ return true;+ });+});++afterEach(async () => {+ vi.restoreAllMocks();+ if (originalCodexSessionId === undefined) delete process.env["CODEX_SESSION_ID"];+ else process.env["CODEX_SESSION_ID"] = originalCodexSessionId;+ if (originalCodexThreadId === undefined) delete process.env["CODEX_THREAD_ID"];+ else process.env["CODEX_THREAD_ID"] = originalCodexThreadId;+ if (originalOmoSessionId === undefined) delete process.env["OMO_ULW_LOOP_SESSION_ID"];+ else process.env["OMO_ULW_LOOP_SESSION_ID"] = originalOmoSessionId;+ await rm(testDir, { recursive: true, force: true });+});++function resetOutput(): void {+ out = [];+ err = [];+}+function stdoutJson(): Record<string, unknown> {+ return JSON.parse(out.join(""));+}+function codexSnapshot(status: "active" | "complete" = "active"): string {+ return JSON.stringify({ goal: { objective: ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE, status } });+}++async function createPlan(brief = "- Goal A\n- Goal B"): Promise<Record<string, unknown>> {+ resetOutput();+ expect(await ulwLoopCommand(["create-goals", "--brief", brief, "--json"])).toBe(0);+ const parsed = stdoutJson();+ resetOutput();+ return parsed;+}++async function passCriterion(goalId: string, criterionId: string): Promise<void> {+ expect(+ await ulwLoopCommand([+ "record-evidence",+ "--goal-id",+ goalId,+ "--criterion-id",+ criterionId,+ "--status",+ "pass",+ "--evidence",+ `${criterionId} observable proof`,+ ]),+ ).toBe(0);+ resetOutput();+}++describe("ulwLoopCommand help", () => {+ it("prints usage when no subcommand", async () => {+ expect(await ulwLoopCommand([])).toBe(0);+ expect(out.join("")).toContain("omo ulw-loop");+ });+});++describe("ulwLoopCommand create-goals", () => {+ it("creates plan + writes 3 artifacts + seeds criteria per goal", async () => {+ const code = await ulwLoopCommand(["create-goals", "--brief", "- Goal A\n- Goal B", "--json"]);++ expect(code).toBe(0);+ const parsed = stdoutJson();+ expect(parsed).toMatchObject({ ok: true });+ expect(parsed).toHaveProperty("plan.goals.0.successCriteria.0.id", "C001");+ expect(await readFile(join(testDir, ".omo/ulw-loop/brief.md"), "utf8")).toContain("Goal A");+ expect(await readFile(join(testDir, ".omo/ulw-loop/goals.json"), "utf8")).toContain("successCriteria");+ expect(await readFile(join(testDir, ".omo/ulw-loop/ledger.jsonl"), "utf8")).toContain("plan_created");+ });++ it("#given two session ids #when creating goals #then writes isolated session-scoped plans", async () => {+ expect(await ulwLoopCommand(["create-goals", "--session-id", "session-A", "--brief", "- Alpha", "--json"])).toBe(+ 0,+ );+ resetOutput();++ expect(await ulwLoopCommand(["create-goals", "--session-id", "session-B", "--brief", "- Beta", "--json"])).toBe(+ 0,+ );+ resetOutput();++ expect(await readFile(join(testDir, ".omo/ulw-loop/session-A/goals.json"), "utf8")).toContain("Alpha");+ expect(await readFile(join(testDir, ".omo/ulw-loop/session-B/goals.json"), "utf8")).toContain("Beta");++ expect(await ulwLoopCommand(["status", "--session-id", "session-A", "--json"])).toBe(0);+ expect(stdoutJson()).toMatchObject({+ plan: { goalsPath: ".omo/ulw-loop/session-A/goals.json", goals: [{ title: "Alpha" }] },+ });+ expect(out.join("")).not.toContain("Beta");+ });++ it("#given Codex thread env #when creating goals #then uses the thread as the session scope", async () => {+ process.env["CODEX_THREAD_ID"] = "thread-123";++ expect(await ulwLoopCommand(["create-goals", "--brief", "- Thread scoped", "--json"])).toBe(0);+ resetOutput();++ expect(await readFile(join(testDir, ".omo/ulw-loop/thread-123/goals.json"), "utf8")).toContain("Thread scoped");+ expect(await ulwLoopCommand(["status", "--json"])).toBe(0);+ expect(stdoutJson()).toHaveProperty("plan.goalsPath", ".omo/ulw-loop/thread-123/goals.json");+ });++ it("#given Codex thread env and explicit session id #when creating goals #then the explicit session wins", async () => {+ process.env["CODEX_THREAD_ID"] = "thread-123";++ expect(+ await ulwLoopCommand(["create-goals", "--session-id", "manual-456", "--brief", "- Manual scoped", "--json"]),+ ).toBe(0);++ expect(await readFile(join(testDir, ".omo/ulw-loop/manual-456/goals.json"), "utf8")).toContain("Manual scoped");+ });+});++describe("ulwLoopCommand status", () => {+ it("prints plan summary including criteria counts", async () => {+ await createPlan();++ expect(await ulwLoopCommand(["status"])).toBe(0);+ expect(out.join("")).toContain("criteria: 0/6 pass");+ });+});++describe("ulwLoopCommand complete-goals", () => {+ it("starts the next goal and returns a Codex instruction", async () => {+ await createPlan();++ expect(await ulwLoopCommand(["complete-goals", "--json"])).toBe(0);+ expect(stdoutJson()).toMatchObject({+ ok: true,+ goal: { status: "in_progress" },+ instruction: { json: { status: "active" } },+ });+ });+});++describe("ulwLoopCommand record-evidence", () => {+ it("records evidence + returns updated criterion", async () => {+ await createPlan();++ expect(+ await ulwLoopCommand([+ "record-evidence",+ "--goal-id",+ "G001-goal-a",+ "--criterion-id",+ "C001",+ "--status",+ "pass",+ "--evidence",+ "curl passed",+ "--json",+ ]),+ ).toBe(0);+ expect(stdoutJson()).toMatchObject({+ ok: true,+ criterion: { id: "C001", status: "pass", capturedEvidence: "curl passed" },+ });+ });++ it("returns 1 + error on unknown goal-id", async () => {+ await createPlan();++ expect(+ await ulwLoopCommand([+ "record-evidence",+ "--goal-id",+ "G404",+ "--criterion-id",+ "C001",+ "--status",+ "pass",+ "--evidence",+ "x",+ ]),+ ).toBe(1);+ expect(err.join("")).toContain("[ulw-loop]");+ });++ it("returns 1 + error on missing flags", async () => {+ expect(+ await ulwLoopCommand(["record-evidence", "--criterion-id", "C001", "--status", "pass", "--evidence", "x"]),+ ).toBe(1);+ expect(err.join("")).toContain("Missing --goal-id");+ });+});++describe("ulwLoopCommand criteria", () => {+ it("lists criteria for a goal", async () => {+ await createPlan();++ expect(await ulwLoopCommand(["criteria", "--goal-id", "G001-goal-a"])).toBe(0);+ expect(out.join("")).toContain("C001");+ expect(out.join("")).toContain("happy");+ });++ it("supports --json output", async () => {+ await createPlan();++ expect(await ulwLoopCommand(["criteria", "--goal-id", "G001-goal-a", "--json"])).toBe(0);+ expect(stdoutJson()).toMatchObject({ ok: true, goalId: "G001-goal-a" });+ expect(stdoutJson()).toHaveProperty("criteria.0.id", "C001");+ });+});++describe("ulwLoopCommand checkpoint", () => {+ it("REJECTS status=complete when criteria pending", async () => {+ await createPlan();++ expect(+ await ulwLoopCommand([+ "checkpoint",+ "--goal-id",+ "G001-goal-a",+ "--status",+ "complete",+ "--evidence",+ "x",+ "--codex-goal-json",+ codexSnapshot(),+ ]),+ ).toBe(1);+ expect(err.join("").toLowerCase()).toContain("criteria");+ });++ it("ACCEPTS when all criteria pass", async () => {+ await createPlan();+ await passCriterion("G001-goal-a", "C001");+ await passCriterion("G001-goal-a", "C002");+ await passCriterion("G001-goal-a", "C003");++ expect(+ await ulwLoopCommand([+ "checkpoint",+ "--goal-id",+ "G001-goal-a",+ "--status",+ "complete",+ "--evidence",+ "implementation done and validation passed",+ "--codex-goal-json",+ codexSnapshot(),+ "--json",+ ]),+ ).toBe(0);+ expect(stdoutJson()).toHaveProperty("goal.status", "complete");+ });++ it("#given failed checkpoint without codex goal json #when recorded through CLI #then marks the goal failed", async () => {+ await createPlan();++ expect(+ await ulwLoopCommand([+ "checkpoint",+ "--goal-id",+ "G001-goal-a",+ "--status",+ "failed",+ "--evidence",+ "implementation failed and validation captured",+ "--json",+ ]),+ ).toBe(0);++ expect(stdoutJson()).toMatchObject({ ok: true, goal: { id: "G001-goal-a", status: "failed" } });+ });++ it("#given blocked checkpoint without codex goal json #when recorded through CLI #then marks the goal blocked", async () => {+ await createPlan();++ expect(+ await ulwLoopCommand([+ "checkpoint",+ "--goal-id",+ "G002-goal-b",+ "--status",+ "blocked",+ "--evidence",+ "waiting for external approval",+ "--json",+ ]),+ ).toBe(0);++ expect(stdoutJson()).toMatchObject({ ok: true, goal: { id: "G002-goal-b", status: "blocked" } });+ });+});++describe("ulwLoopCommand steer", () => {+ it("dispatches to the steering engine", async () => {+ await createPlan();++ expect(+ await ulwLoopCommand([+ "steer",+ "--kind",+ "add_subgoal",+ "--title",+ "Extra",+ "--objective",+ "Do extra",+ "--evidence",+ "user requested it",+ "--rationale",+ "keeps plan accurate",+ "--json",+ ]),+ ).toBe(0);+ expect(stdoutJson()).toMatchObject({+ ok: true,+ accepted: true,+ plan: {+ goals: [+ { id: "G001-goal-a" },+ { id: "G002-goal-b" },+ { id: "G003", title: "Extra", successCriteria: [{ id: "C001" }, { id: "C002" }, { id: "C003" }] },+ ],+ },+ });+ });+});++describe("ulwLoopCommand add-goal", () => {+ it("appends a pending goal", async () => {+ await createPlan();++ expect(await ulwLoopCommand(["add-goal", "--title", "Later", "--objective", "Do later", "--json"])).toBe(0);+ expect(stdoutJson()).toMatchObject({ ok: true, goal: { title: "Later", status: "pending" } });+ });+});++describe("ulwLoopCommand unknown", () => {+ it("returns 1 + prints help on unknown subcommand", async () => {+ expect(await ulwLoopCommand(["wat"])).toBe(1);+ expect(out.join("")).toContain("omo ulw-loop");+ });+});++describe("ulwLoopCommand error handling", () => {+ it("returns 1 + prints [ulw-loop] prefix on UlwLoopError", async () => {+ expect(await ulwLoopCommand(["status"])).toBe(1);+ expect(err.join("")).toContain("[ulw-loop]");+ });+});diff --git a/plugins/omo/components/ultragoal/test/cli-helpers.test.ts b/plugins/omo/components/ulw-loop/test/cli-helpers.test.tssimilarity index 78%rename from plugins/omo/components/ultragoal/test/cli-helpers.test.tsrename to plugins/omo/components/ulw-loop/test/cli-helpers.test.tsindex 80e2193e..0f515f53 100644--- a/plugins/omo/components/ultragoal/test/cli-helpers.test.ts+++ b/plugins/omo/components/ulw-loop/test/cli-helpers.test.ts@@ -13,13 +13,13 @@ import {readRepeated,readValue,} from "../src/cli-arg-parser.js";-import { normalizeCodexGoalMode, printStatus, ULTRAGOAL_HELP } from "../src/cli-output.js";-import type { UltragoalItem, UltragoalPlan, UltragoalSuccessCriterion } from "../src/types.js";-import { UltragoalError } from "../src/types.js";+import { normalizeCodexGoalMode, printStatus, ULW_LOOP_HELP } from "../src/cli-output.js";+import type { UlwLoopItem, UlwLoopPlan, UlwLoopSuccessCriterion } from "../src/types.js";+import { UlwLoopError } from "../src/types.js";const NOW = "2026-05-23T00:00:00.000Z";-function criterion(overrides: Partial<UltragoalSuccessCriterion> = {}): UltragoalSuccessCriterion {+function criterion(overrides: Partial<UlwLoopSuccessCriterion> = {}): UlwLoopSuccessCriterion {return {id: "C001",scenario: "happy path returns 200",@@ -31,7 +31,7 @@ function criterion(overrides: Partial<UltragoalSuccessCriterion> = {}): Ultragoa};}-function goal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {+function goal(overrides: Partial<UlwLoopItem> = {}): UlwLoopItem {return {id: "G001",title: "Auth endpoint",@@ -49,14 +49,14 @@ function goal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {};}-function plan(overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {+function plan(overrides: Partial<UlwLoopPlan> = {}): UlwLoopPlan {return {version: 1,createdAt: NOW,updatedAt: NOW,- briefPath: ".omo/ultragoal/brief.md",- goalsPath: ".omo/ultragoal/goals.json",- ledgerPath: ".omo/ultragoal/ledger.jsonl",+ briefPath: ".omo/ulw-loop/brief.md",+ goalsPath: ".omo/ulw-loop/goals.json",+ ledgerPath: ".omo/ulw-loop/ledger.jsonl",activeGoalId: "G001",goals: [goal()],...overrides,@@ -159,7 +159,7 @@ describe("parseRecordEvidenceArgs", () => {it("throws when goal-id missing", () => {expect(() =>parseRecordEvidenceArgs(["record-evidence", "--criterion-id", "C001", "--status", "pass", "--evidence", "x"]),- ).toThrow(UltragoalError);+ ).toThrow(UlwLoopError);});it("throws when status is not pass|fail|blocked", () => {@@ -175,7 +175,7 @@ describe("parseRecordEvidenceArgs", () => {"--evidence","x",]),- ).toThrow(UltragoalError);+ ).toThrow(UlwLoopError);});it("includes optional --notes when present", () => {@@ -197,24 +197,24 @@ describe("parseRecordEvidenceArgs", () => {});});-describe("ULTRAGOAL_HELP", () => {- it("mentions omo ultragoal + every subcommand", () => {- expect(ULTRAGOAL_HELP).toContain("omo ultragoal");- expect(ULTRAGOAL_HELP).toContain("create-goals");- expect(ULTRAGOAL_HELP).toContain("complete-goals");- expect(ULTRAGOAL_HELP).toContain("status");- expect(ULTRAGOAL_HELP).toContain("checkpoint");- expect(ULTRAGOAL_HELP).toContain("steer");- expect(ULTRAGOAL_HELP).toContain("record-evidence");- expect(ULTRAGOAL_HELP).toContain("criteria");- expect(ULTRAGOAL_HELP).toContain("add-goal");- expect(ULTRAGOAL_HELP).toContain("record-review-blockers");+describe("ULW_LOOP_HELP", () => {+ it("mentions omo ulw-loop + every subcommand", () => {+ expect(ULW_LOOP_HELP).toContain("omo ulw-loop");+ expect(ULW_LOOP_HELP).toContain("create-goals");+ expect(ULW_LOOP_HELP).toContain("complete-goals");+ expect(ULW_LOOP_HELP).toContain("status");+ expect(ULW_LOOP_HELP).toContain("checkpoint");+ expect(ULW_LOOP_HELP).toContain("steer");+ expect(ULW_LOOP_HELP).toContain("record-evidence");+ expect(ULW_LOOP_HELP).toContain("criteria");+ expect(ULW_LOOP_HELP).toContain("add-goal");+ expect(ULW_LOOP_HELP).toContain("record-review-blockers");});it("never mentions the legacy typo", () => {const typo = ["o", "m", "x"].join("");- expect(ULTRAGOAL_HELP).not.toMatch(new RegExp(typo, "i"));+ expect(ULW_LOOP_HELP).not.toMatch(new RegExp(typo, "i"));});});@@ -244,7 +244,7 @@ describe("normalizeCodexGoalMode", () => {expect(normalizeCodexGoalMode("per_story")).toBe("per_story");});- it("throws UltragoalError when invalid", () => {- expect(() => normalizeCodexGoalMode("per-story")).toThrow(UltragoalError);+ it("throws UlwLoopError when invalid", () => {+ expect(() => normalizeCodexGoalMode("per-story")).toThrow(UlwLoopError);});});diff --git a/plugins/omo/components/ultragoal/test/cli-steering.test.ts b/plugins/omo/components/ulw-loop/test/cli-steering.test.tssimilarity index 91%rename from plugins/omo/components/ultragoal/test/cli-steering.test.tsrename to plugins/omo/components/ulw-loop/test/cli-steering.test.tsindex 0070ae35..16566f06 100644--- a/plugins/omo/components/ultragoal/test/cli-steering.test.ts+++ b/plugins/omo/components/ulw-loop/test/cli-steering.test.ts@@ -11,24 +11,24 @@ import {parseSteeringSource,printSteerResult,} from "../src/cli-steering.js";-import type { SteerUltragoalResult, UltragoalPlan } from "../src/types.js";-import { UltragoalError } from "../src/types.js";+import type { SteerUlwLoopResult, UlwLoopPlan } from "../src/types.js";+import { UlwLoopError } from "../src/types.js";const NOW = "2026-05-23T00:00:00.000Z";-function plan(): UltragoalPlan {+function plan(): UlwLoopPlan {return {version: 1,createdAt: NOW,updatedAt: NOW,- briefPath: ".omo/ultragoal/brief.md",- goalsPath: ".omo/ultragoal/goals.json",- ledgerPath: ".omo/ultragoal/ledger.jsonl",+ briefPath: ".omo/ulw-loop/brief.md",+ goalsPath: ".omo/ulw-loop/goals.json",+ ledgerPath: ".omo/ulw-loop/ledger.jsonl",goals: [],};}-function steerResult(overrides: Partial<SteerUltragoalResult> = {}): SteerUltragoalResult {+function steerResult(overrides: Partial<SteerUlwLoopResult> = {}): SteerUlwLoopResult {return {plan: plan(),accepted: true,@@ -73,11 +73,11 @@ describe("parseSteeringKind", () => {});it("throws when --kind missing", () => {- expect(() => parseSteeringKind([])).toThrow(UltragoalError);+ expect(() => parseSteeringKind([])).toThrow(UlwLoopError);});it("throws when kind unknown", () => {- expect(() => parseSteeringKind(["--kind", "bogus"])).toThrow(UltragoalError);+ expect(() => parseSteeringKind(["--kind", "bogus"])).toThrow(UlwLoopError);});});@@ -128,13 +128,13 @@ describe("parseSteeringProposal add_subgoal", () => {"--rationale","y",]),- ).rejects.toThrow(UltragoalError);+ ).rejects.toThrow(UlwLoopError);});it("throws when --evidence missing", async () => {await expect(parseSteeringProposal(["--kind", "add_subgoal", "--title", "New", "--objective", "Build", "--rationale", "y"]),- ).rejects.toThrow(UltragoalError);+ ).rejects.toThrow(UlwLoopError);});});@@ -214,7 +214,7 @@ describe("parseSteeringProposal revise_criterion", () => {"--rationale","y",]),- ).rejects.toThrow(UltragoalError);+ ).rejects.toThrow(UlwLoopError);});it("throws when goal-id missing", async () => {@@ -231,7 +231,7 @@ describe("parseSteeringProposal revise_criterion", () => {"--rationale","y",]),- ).rejects.toThrow(UltragoalError);+ ).rejects.toThrow(UlwLoopError);});it("throws when criterion-id missing", async () => {@@ -248,7 +248,7 @@ describe("parseSteeringProposal revise_criterion", () => {"--rationale","y",]),- ).rejects.toThrow(UltragoalError);+ ).rejects.toThrow(UlwLoopError);});});@@ -387,7 +387,7 @@ describe("normalizeSteeringProposal", () => {it("rejects empty evidence after trim", () => {expect(() =>normalizeSteeringProposal({ kind: "annotate_ledger", source: "cli", evidence: " ", rationale: "y" }),- ).toThrow(UltragoalError);+ ).toThrow(UlwLoopError);});});@@ -401,7 +401,7 @@ describe("printSteerResult", () => {it("prints human-readable when json=false", () => {const output = captureStdout(() => printSteerResult(steerResult(), false));- expect(output).toContain("ultragoal steer: accepted add_subgoal");- expect(output).toContain("ultragoal status");+ expect(output).toContain("ulw-loop steer: accepted add_subgoal");+ expect(output).toContain("ulw-loop status");});});diff --git a/plugins/omo/components/ultragoal/test/codex-goal-instruction.test.ts b/plugins/omo/components/ulw-loop/test/codex-goal-instruction.test.tssimilarity index 73%rename from plugins/omo/components/ultragoal/test/codex-goal-instruction.test.tsrename to plugins/omo/components/ulw-loop/test/codex-goal-instruction.test.tsindex 4dcb9d71..46a84e2b 100644--- a/plugins/omo/components/ultragoal/test/codex-goal-instruction.test.ts+++ b/plugins/omo/components/ulw-loop/test/codex-goal-instruction.test.ts@@ -1,12 +1,12 @@import { describe, expect, it } from "vitest";import { buildCodexGoalInstruction } from "../src/codex-goal-instruction.js";-import { ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE } from "../src/goal-status.js";-import type { UltragoalItem, UltragoalPlan, UltragoalSuccessCriterion } from "../src/types.js";+import { ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE } from "../src/goal-status.js";+import type { UlwLoopItem, UlwLoopPlan, UlwLoopSuccessCriterion } from "../src/types.js";const NOW = "2026-05-23T00:00:00.000Z";-function makeCriterion(overrides: Partial<UltragoalSuccessCriterion> = {}): UltragoalSuccessCriterion {+function makeCriterion(overrides: Partial<UlwLoopSuccessCriterion> = {}): UlwLoopSuccessCriterion {return {id: "C001",scenario: "happy path",@@ -18,7 +18,7 @@ function makeCriterion(overrides: Partial<UltragoalSuccessCriterion> = {}): Ultr};}-function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {+function makeGoal(overrides: Partial<UlwLoopItem> = {}): UlwLoopItem {return {id: "G001",title: "Goal one",@@ -32,24 +32,24 @@ function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {};}-function makePlan(overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {+function makePlan(overrides: Partial<UlwLoopPlan> = {}): UlwLoopPlan {return {version: 1,createdAt: NOW,updatedAt: NOW,- briefPath: ".omo/ultragoal/brief.md",- goalsPath: ".omo/ultragoal/goals.json",- ledgerPath: ".omo/ultragoal/ledger.jsonl",+ briefPath: ".omo/ulw-loop/brief.md",+ goalsPath: ".omo/ulw-loop/goals.json",+ ledgerPath: ".omo/ulw-loop/ledger.jsonl",goals: [],...overrides,};}describe("buildCodexGoalInstruction aggregate mode", () => {- it("references the aggregate handoff and the .omo/ultragoal/goals.json artifact", () => {+ it("references the aggregate handoff and the .omo/ulw-loop/goals.json artifact", () => {const { text } = buildCodexGoalInstruction({ plan: makePlan({ codexGoalMode: "aggregate" }), goal: makeGoal() });expect(text).toContain("aggregate");- expect(text).toContain(".omo/ultragoal/goals.json");+ expect(text).toContain(".omo/ulw-loop/goals.json");});it("given aggregate mode when rendering create_goal payload then omits numeric limits", () => {@@ -58,7 +58,7 @@ describe("buildCodexGoalInstruction aggregate mode", () => {goal: makeGoal(),});expect(json).toEqual({- objective: ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE,+ objective: ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE,status: "active",});expect(text).toContain("objective and status only");@@ -83,6 +83,22 @@ describe("buildCodexGoalInstruction aggregate mode", () => {});expect(text).toMatch(/quality gate/i);});++ it("#given a scoped plan #when rendering final commands #then includes the session id option", () => {+ const { text } = buildCodexGoalInstruction({+ plan: makePlan({+ codexGoalMode: "aggregate",+ goalsPath: ".omo/ulw-loop/session-A/goals.json",+ ledgerPath: ".omo/ulw-loop/session-A/ledger.jsonl",+ }),+ goal: makeGoal(),+ isFinal: true,+ });++ expect(text).toContain("record-review-blockers --session-id session-A");+ expect(text).toContain("checkpoint --session-id session-A");+ expect(text).toContain("complete-goals --session-id session-A --retry-failed");+ });});describe("buildCodexGoalInstruction per_story mode", () => {@@ -146,8 +162,8 @@ describe("buildCodexGoalInstruction rebrand audit", () => {expect(text).not.toMatch(new RegExp(legacyBrand, "i"));});- it("references .omo/ultragoal in artifact paths", () => {+ it("references .omo/ulw-loop in artifact paths", () => {const { text } = buildCodexGoalInstruction({ plan: makePlan({ codexGoalMode: "aggregate" }), goal: makeGoal() });- expect(text).toContain(".omo/ultragoal");+ expect(text).toContain(".omo/ulw-loop");});});diff --git a/plugins/omo/components/ultragoal/test/codex-goal-snapshot.test.ts b/plugins/omo/components/ulw-loop/test/codex-goal-snapshot.test.tssimilarity index 98%rename from plugins/omo/components/ultragoal/test/codex-goal-snapshot.test.tsrename to plugins/omo/components/ulw-loop/test/codex-goal-snapshot.test.tsindex a1e0d29d..b70f1ffa 100644--- a/plugins/omo/components/ultragoal/test/codex-goal-snapshot.test.ts+++ b/plugins/omo/components/ulw-loop/test/codex-goal-snapshot.test.ts@@ -92,7 +92,7 @@ describe("readCodexGoalSnapshotInput", () => {// thenexpect(snapshot?.available).toBe(true);- expect(snapshot?.objective).toBe("Complete the durable ultragoal plan");+ expect(snapshot?.objective).toBe("Complete the durable ulw-loop plan");});it("throws CodexGoalSnapshotError when input is neither JSON nor a path", async () => {diff --git a/plugins/omo/components/ulw-loop/test/codex-hook.test.ts b/plugins/omo/components/ulw-loop/test/codex-hook.test.tsnew file mode 100644index 00000000..e250f11b--- /dev/null+++ b/plugins/omo/components/ulw-loop/test/codex-hook.test.ts@@ -0,0 +1,275 @@+import { mkdir, mkdtemp, readFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Readable, Writable } from "node:stream";+import { describe, expect, it } from "vitest";++import {+ applyPreToolUseGoalBudgetGuard,+ applyUserPromptUlwLoopSteering,+ type PreToolUsePayload,+ parseUserPromptSubmitPayload,+ runPreToolUseGoalBudgetGuardCli,+ runUlwLoopHookCli,+ type UserPromptSubmitPayload,+} from "../src/codex-hook.js";+import { ulwLoopDir, ulwLoopLedgerPath } from "../src/paths.js";+import { writePlan } from "../src/plan-io.js";+import type { UlwLoopPlan } from "../src/types.js";++const NOW = "2026-05-23T00:00:00.000Z";+const DEFAULT_SESSION_ID = "s1";++async function bootstrapPlanRepo(): Promise<string> {+ const repoRoot = await mkdtemp(join(tmpdir(), "ug-hook-"));+ await mkdir(ulwLoopDir(repoRoot, { sessionId: DEFAULT_SESSION_ID }), { recursive: true });+ await writePlan(repoRoot, samplePlan(), { sessionId: DEFAULT_SESSION_ID });+ return repoRoot;+}++function samplePlan(): UlwLoopPlan {+ return {+ version: 1,+ createdAt: NOW,+ updatedAt: NOW,+ briefPath: ".omo/ulw-loop/brief.md",+ goalsPath: ".omo/ulw-loop/goals.json",+ ledgerPath: ".omo/ulw-loop/ledger.jsonl",+ goals: [+ {+ id: "G001",+ title: "Build hook",+ objective: "Apply safe steering directives from Codex hooks.",+ status: "pending",+ successCriteria: [],+ attempt: 0,+ createdAt: NOW,+ updatedAt: NOW,+ },+ ],+ };+}++function payload(prompt: string, cwd: string): UserPromptSubmitPayload {+ return { cwd, hook_event_name: "UserPromptSubmit", prompt, session_id: DEFAULT_SESSION_ID };+}++function preToolPayload(toolName: string, toolInput: unknown): PreToolUsePayload {+ return {+ cwd: "/repo",+ hook_event_name: "PreToolUse",+ model: "gpt-5.5",+ permission_mode: "default",+ session_id: "s1",+ tool_input: toolInput,+ tool_name: toolName,+ tool_use_id: "call-1",+ transcript_path: null,+ turn_id: "turn-1",+ };+}++function payloadWithRuntimeEvent(hookEventName: string): UserPromptSubmitPayload {+ const input = payload(+ 'OMO_ULW_LOOP_STEER: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',+ "/tmp",+ );+ Object.defineProperty(input, "hook_event_name", { value: hookEventName });+ return input;+}++function captureStdout(): { readonly stdout: Writable; readonly read: () => string } {+ let captured = "";+ const stdout = new Writable({+ write(chunk: unknown, _encoding: BufferEncoding, callback: (error?: Error | null) => void): void {+ captured += chunk instanceof Buffer ? chunk.toString() : String(chunk);+ callback();+ },+ });+ return { stdout, read: () => captured };+}++describe("parseUserPromptSubmitPayload", () => {+ it("parses valid JSON payload", async () => {+ const raw = await readFile("test/fixtures/user-prompt-submit.json", "utf8");+ const parsed = parseUserPromptSubmitPayload(raw);+ expect(parsed?.hook_event_name).toBe("UserPromptSubmit");+ expect(parsed?.prompt).toContain("OMO_ULW_LOOP_STEER");+ });++ it("returns null for empty input", () => {+ expect(parseUserPromptSubmitPayload("")).toBeNull();+ });++ it("returns null for invalid JSON", () => {+ expect(parseUserPromptSubmitPayload("{bad")).toBeNull();+ });++ it("returns null when hook_event_name missing", () => {+ expect(parseUserPromptSubmitPayload(JSON.stringify({ cwd: "/repo", prompt: "x", session_id: "s1" }))).toBeNull();+ });+});++describe("applyUserPromptUlwLoopSteering - OMO directive patterns", () => {+ it("processes OMO_ULW_LOOP_STEER: prompt and returns audit text on success", async () => {+ const repoRoot = await bootstrapPlanRepo();+ const out = await applyUserPromptUlwLoopSteering(+ payload(+ 'OMO_ULW_LOOP_STEER: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',+ repoRoot,+ ),+ );+ expect(out.length).toBeGreaterThan(0);+ expect(out).toContain("annotate_ledger");+ });++ it("#given a Codex session id #when steering from a hook #then writes the session-scoped ledger", async () => {+ const repoRoot = await bootstrapPlanRepo();++ const out = await applyUserPromptUlwLoopSteering(+ payload(+ 'OMO_ULW_LOOP_STEER: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',+ repoRoot,+ ),+ );++ expect(out).toContain("accepted");+ expect(await readFile(ulwLoopLedgerPath(repoRoot, { sessionId: DEFAULT_SESSION_ID }), "utf8")).toContain(+ "steering_accepted",+ );+ });++ it("processes omo.ulw-loop.steer: pattern", async () => {+ const repoRoot = await bootstrapPlanRepo();+ const out = await applyUserPromptUlwLoopSteering(+ payload(+ 'omo.ulw-loop.steer: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',+ repoRoot,+ ),+ );+ expect(out).toContain("accepted");+ });++ it("processes omo ulw-loop steer: pattern", async () => {+ const repoRoot = await bootstrapPlanRepo();+ const out = await applyUserPromptUlwLoopSteering(+ payload(+ 'omo ulw-loop steer: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',+ repoRoot,+ ),+ );+ expect(out).toContain("annotate_ledger");+ });+});++describe("applyUserPromptUlwLoopSteering - non-matching prompts", () => {+ it("returns empty string when no directive in prompt", async () => {+ expect(await applyUserPromptUlwLoopSteering(payload("just a normal user message", "/tmp"))).toBe("");+ });++ it("returns empty when hook_event_name is not UserPromptSubmit", async () => {+ expect(await applyUserPromptUlwLoopSteering(payloadWithRuntimeEvent("PostToolUse"))).toBe("");+ });+});++describe("applyUserPromptUlwLoopSteering - error swallowing", () => {+ it("returns empty (never throws) when plan does not exist", async () => {+ const repoRoot = await mkdtemp(join(tmpdir(), "ug-nohook-"));+ const out = await applyUserPromptUlwLoopSteering(+ payload(+ 'OMO_ULW_LOOP_STEER: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',+ repoRoot,+ ),+ );+ expect(out).toBe("");+ });++ it("returns empty when steering proposal is malformed JSON after marker", async () => {+ const out = await applyUserPromptUlwLoopSteering(payload("OMO_ULW_LOOP_STEER: {bad", "/tmp"));+ expect(out).toBe("");+ });+});++describe("runUlwLoopHookCli (stdin/stdout integration)", () => {+ it("reads stdin, applies steering, writes audit to stdout", async () => {+ const repoRoot = await bootstrapPlanRepo();+ const stdin = Readable.from([+ JSON.stringify(+ payload(+ 'OMO_ULW_LOOP_STEER: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',+ repoRoot,+ ),+ ),+ ]);+ const capture = captureStdout();+ await runUlwLoopHookCli(stdin, capture.stdout);+ expect(capture.read().length).toBeGreaterThan(0);+ });++ it("writes nothing when stdin is empty", async () => {+ const capture = captureStdout();+ await runUlwLoopHookCli(Readable.from([""]), capture.stdout);+ expect(capture.read()).toBe("");+ });+});++describe("applyPreToolUseGoalBudgetGuard", () => {+ it("#given create_goal sets token_budget #when PreToolUse runs #then it blocks with unlimited-goal warning", () => {+ // given+ const input = preToolPayload("create_goal", { objective: "Ship the feature", token_budget: 5000 });++ // when+ const output = applyPreToolUseGoalBudgetGuard(input);++ // then+ const parsed = JSON.parse(output);+ expect(parsed).toMatchObject({+ hookSpecificOutput: {+ hookEventName: "PreToolUse",+ permissionDecision: "deny",+ },+ });+ expect(parsed.hookSpecificOutput.permissionDecisionReason).toContain("Do not set token_budget on create_goal");+ expect(parsed.hookSpecificOutput.permissionDecisionReason).toContain("unlimited");+ });++ it("#given create_goal omits token_budget #when PreToolUse runs #then it stays silent", () => {+ // given+ const input = preToolPayload("create_goal", { objective: "Ship the feature" });++ // when+ const output = applyPreToolUseGoalBudgetGuard(input);++ // then+ expect(output).toBe("");+ });++ it("#given a neighboring tool includes token_budget text #when PreToolUse runs #then it stays silent", () => {+ // given+ const input = preToolPayload("update_goal", { status: "complete", token_budget: 5000 });++ // when+ const output = applyPreToolUseGoalBudgetGuard(input);++ // then+ expect(output).toBe("");+ });+});++describe("runPreToolUseGoalBudgetGuardCli", () => {+ it("#given Codex PreToolUse stdin with budgeted create_goal #when CLI hook runs #then it writes blocking JSON", async () => {+ // given+ const stdin = Readable.from([+ JSON.stringify(preToolPayload("create_goal", { objective: "Ship", token_budget: 1 })),+ ]);+ const capture = captureStdout();++ // when+ await runPreToolUseGoalBudgetGuardCli(stdin, capture.stdout);++ // then+ const parsed = JSON.parse(capture.read());+ expect(parsed.hookSpecificOutput.permissionDecision).toBe("deny");+ expect(parsed.hookSpecificOutput.permissionDecisionReason).toContain("unlimited");+ });+});diff --git a/plugins/omo/components/ultragoal/test/evidence-criteria-gate.test.ts b/plugins/omo/components/ulw-loop/test/evidence-criteria-gate.test.tssimilarity index 71%rename from plugins/omo/components/ultragoal/test/evidence-criteria-gate.test.tsrename to plugins/omo/components/ulw-loop/test/evidence-criteria-gate.test.tsindex ee7452f1..e02de24b 100644--- a/plugins/omo/components/ultragoal/test/evidence-criteria-gate.test.ts+++ b/plugins/omo/components/ulw-loop/test/evidence-criteria-gate.test.ts@@ -1,12 +1,12 @@import { describe, expect, it } from "vitest";import { requireAllCriteriaPass } from "../src/evidence.js";-import type { UltragoalItem, UltragoalSuccessCriterion } from "../src/types.js";-import { UltragoalError } from "../src/types.js";+import type { UlwLoopItem, UlwLoopSuccessCriterion } from "../src/types.js";+import { UlwLoopError } from "../src/types.js";const NOW = "2026-05-23T00:00:00.000Z";-function makeCriterion(overrides: Partial<UltragoalSuccessCriterion> = {}): UltragoalSuccessCriterion {+function makeCriterion(overrides: Partial<UlwLoopSuccessCriterion> = {}): UlwLoopSuccessCriterion {return {id: "C001",scenario: "happy path login returns 200",@@ -18,7 +18,7 @@ function makeCriterion(overrides: Partial<UltragoalSuccessCriterion> = {}): Ultr};}-function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {+function makeGoal(overrides: Partial<UlwLoopItem> = {}): UlwLoopItem {return {id: "G001",title: "Auth endpoint",@@ -50,7 +50,7 @@ describe("requireAllCriteriaPass", () => {expect(() => requireAllCriteriaPass(goal)).not.toThrow();});- it("throws UltragoalError when any criterion pending", () => {+ it("throws UlwLoopError when any criterion pending", () => {// givenconst goal = makeGoal({successCriteria: [@@ -61,7 +61,7 @@ describe("requireAllCriteriaPass", () => {});// when / then- expect(() => requireAllCriteriaPass(goal)).toThrow(UltragoalError);+ expect(() => requireAllCriteriaPass(goal)).toThrow(UlwLoopError);});it("throws when any fail/blocked too", () => {@@ -70,11 +70,11 @@ describe("requireAllCriteriaPass", () => {const goal2 = makeGoal({ successCriteria: [makeCriterion({ id: "C001", status: "blocked" })] });// when / then- expect(() => requireAllCriteriaPass(goal1)).toThrow(UltragoalError);- expect(() => requireAllCriteriaPass(goal2)).toThrow(UltragoalError);+ expect(() => requireAllCriteriaPass(goal1)).toThrow(UlwLoopError);+ expect(() => requireAllCriteriaPass(goal2)).toThrow(UlwLoopError);});- it("UltragoalError includes details.goalId + details.unresolved", () => {+ it("UlwLoopError includes details.goalId + details.unresolved", () => {// givenconst goal = makeGoal({id: "G001",@@ -90,9 +90,9 @@ describe("requireAllCriteriaPass", () => {requireAllCriteriaPass(goal);expect.fail("expected throw");} catch (error) {- expect(error).toBeInstanceOf(UltragoalError);- if (!(error instanceof UltragoalError)) throw error;- expect(error.code).toBe("ultragoal_criteria_not_all_pass");+ expect(error).toBeInstanceOf(UlwLoopError);+ if (!(error instanceof UlwLoopError)) throw error;+ expect(error.code).toBe("ulw_loop_criteria_not_all_pass");expect(error.details?.["goalId"]).toBe("G001");expect(Array.isArray(error.details?.["unresolved"])).toBe(true);}diff --git a/plugins/omo/components/ultragoal/test/evidence.test.ts b/plugins/omo/components/ulw-loop/test/evidence.test.tssimilarity index 83%rename from plugins/omo/components/ultragoal/test/evidence.test.tsrename to plugins/omo/components/ulw-loop/test/evidence.test.tsindex 77243e2d..061000f6 100644--- a/plugins/omo/components/ultragoal/test/evidence.test.ts+++ b/plugins/omo/components/ulw-loop/test/evidence.test.ts@@ -9,34 +9,34 @@ import {recordEvidence,unresolvedCriteriaOf,} from "../src/evidence.js";-import { ultragoalDir } from "../src/paths.js";-import { readUltragoalPlan, writePlan } from "../src/plan-io.js";-import type { UltragoalItem, UltragoalLedgerEntry, UltragoalPlan, UltragoalSuccessCriterion } from "../src/types.js";-import { UltragoalError } from "../src/types.js";+import { ulwLoopDir } from "../src/paths.js";+import { readUlwLoopPlan, writePlan } from "../src/plan-io.js";+import type { UlwLoopItem, UlwLoopLedgerEntry, UlwLoopPlan, UlwLoopSuccessCriterion } from "../src/types.js";+import { UlwLoopError } from "../src/types.js";const NOW = "2026-05-23T00:00:00.000Z";-async function bootstrapRepo(plan: UltragoalPlan): Promise<string> {+async function bootstrapRepo(plan: UlwLoopPlan): Promise<string> {const repo = await mkdtemp(join(tmpdir(), "ug-evidence-"));- await mkdir(ultragoalDir(repo), { recursive: true });+ await mkdir(ulwLoopDir(repo), { recursive: true });await writePlan(repo, plan);return repo;}-async function readLastLedgerEntry(repo: string): Promise<UltragoalLedgerEntry> {- const lines = (await readFile(join(repo, ".omo/ultragoal/ledger.jsonl"), "utf8")).trim().split("\n");+async function readLastLedgerEntry(repo: string): Promise<UlwLoopLedgerEntry> {+ const lines = (await readFile(join(repo, ".omo/ulw-loop/ledger.jsonl"), "utf8")).trim().split("\n");const last = lines.at(-1);if (last === undefined) throw new Error("expected ledger entry");return JSON.parse(last);}-function firstGoal(plan: UltragoalPlan): UltragoalItem {+function firstGoal(plan: UlwLoopPlan): UlwLoopItem {const goal = plan.goals.at(0);if (goal === undefined) throw new Error("expected goal");return goal;}-function makeCriterion(overrides: Partial<UltragoalSuccessCriterion> = {}): UltragoalSuccessCriterion {+function makeCriterion(overrides: Partial<UlwLoopSuccessCriterion> = {}): UlwLoopSuccessCriterion {return {id: "C001",scenario: "happy path login returns 200",@@ -48,7 +48,7 @@ function makeCriterion(overrides: Partial<UltragoalSuccessCriterion> = {}): Ultr};}-function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {+function makeGoal(overrides: Partial<UlwLoopItem> = {}): UlwLoopItem {return {id: "G001",title: "Auth endpoint",@@ -66,16 +66,16 @@ function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {};}-function makePlan(overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {+function makePlan(overrides: Partial<UlwLoopPlan> = {}): UlwLoopPlan {return {version: 1,createdAt: NOW,updatedAt: NOW,- briefPath: ".omo/ultragoal/brief.md",- goalsPath: ".omo/ultragoal/goals.json",- ledgerPath: ".omo/ultragoal/ledger.jsonl",+ briefPath: ".omo/ulw-loop/brief.md",+ goalsPath: ".omo/ulw-loop/goals.json",+ ledgerPath: ".omo/ulw-loop/ledger.jsonl",codexGoalMode: "aggregate",- codexObjective: "Complete the durable ultragoal plan in .omo/ultragoal/goals.json",+ codexObjective: "Complete the durable ulw-loop plan in .omo/ulw-loop/goals.json",codexObjectiveAliases: [],goals: [makeGoal()],...overrides,@@ -114,7 +114,7 @@ describe("recordEvidence (status=pass)", () => {await recordEvidence(repo, { goalId: "G001", criterionId: "C001", status: "pass", evidence: "observable proof" });- const criterion = firstGoal(await readUltragoalPlan(repo)).successCriteria.find((c) => c.id === "C001");+ const criterion = firstGoal(await readUlwLoopPlan(repo)).successCriteria.find((c) => c.id === "C001");expect(criterion?.status).toBe("pass");});});@@ -157,7 +157,7 @@ describe("recordEvidence error cases", () => {await expect(recordEvidence(repo, { goalId: "GUNKNOWN", criterionId: "C001", status: "pass", evidence: "x" }),- ).rejects.toBeInstanceOf(UltragoalError);+ ).rejects.toBeInstanceOf(UlwLoopError);});it("throws when criterionId not found within goal", async () => {@@ -165,7 +165,7 @@ describe("recordEvidence error cases", () => {await expect(recordEvidence(repo, { goalId: "G001", criterionId: "CUNKNOWN", status: "pass", evidence: "x" }),- ).rejects.toBeInstanceOf(UltragoalError);+ ).rejects.toBeInstanceOf(UlwLoopError);});it("throws when evidence is empty/whitespace", async () => {@@ -173,7 +173,7 @@ describe("recordEvidence error cases", () => {await expect(recordEvidence(repo, { goalId: "G001", criterionId: "C001", status: "pass", evidence: " " }),- ).rejects.toBeInstanceOf(UltragoalError);+ ).rejects.toBeInstanceOf(UlwLoopError);});});diff --git a/plugins/omo/components/ultragoal/test/fixtures/.gitkeep b/plugins/omo/components/ulw-loop/test/fixtures/.gitkeepsimilarity index 100%rename from plugins/omo/components/ultragoal/test/fixtures/.gitkeeprename to plugins/omo/components/ulw-loop/test/fixtures/.gitkeepdiff --git a/plugins/omo/components/ulw-loop/test/fixtures/codex-goal-snapshot.json b/plugins/omo/components/ulw-loop/test/fixtures/codex-goal-snapshot.jsonnew file mode 100644index 00000000..ba0932eb--- /dev/null+++ b/plugins/omo/components/ulw-loop/test/fixtures/codex-goal-snapshot.json@@ -0,0 +1 @@+{ "goal": { "objective": "Complete the durable ulw-loop plan", "status": "active" } }diff --git a/plugins/omo/components/ultragoal/test/fixtures/sample-brief.md b/plugins/omo/components/ulw-loop/test/fixtures/sample-brief.mdsimilarity index 100%rename from plugins/omo/components/ultragoal/test/fixtures/sample-brief.mdrename to plugins/omo/components/ulw-loop/test/fixtures/sample-brief.mddiff --git a/plugins/omo/components/ultragoal/test/fixtures/sample-plan.json b/plugins/omo/components/ulw-loop/test/fixtures/sample-plan.jsonsimilarity index 97%rename from plugins/omo/components/ultragoal/test/fixtures/sample-plan.jsonrename to plugins/omo/components/ulw-loop/test/fixtures/sample-plan.jsonindex f49feee3..61378785 100644--- a/plugins/omo/components/ultragoal/test/fixtures/sample-plan.json+++ b/plugins/omo/components/ulw-loop/test/fixtures/sample-plan.json@@ -2,7 +2,7 @@"version": 1,"createdAt": "2026-05-23T00:00:00.000Z","codexGoalMode": "aggregate",- "codexObjective": "Complete the durable ultragoal plan in .omo/ultragoal/goals.json...",+ "codexObjective": "Complete the durable ulw-loop plan in .omo/ulw-loop/goals.json...","codexObjectiveAliases": [],"goals": [{diff --git a/plugins/omo/components/ultragoal/test/fixtures/sample-quality-gate.json b/plugins/omo/components/ulw-loop/test/fixtures/sample-quality-gate.jsonsimilarity index 100%rename from plugins/omo/components/ultragoal/test/fixtures/sample-quality-gate.jsonrename to plugins/omo/components/ulw-loop/test/fixtures/sample-quality-gate.jsondiff --git a/plugins/omo/components/ultragoal/test/fixtures/steering-proposal.json b/plugins/omo/components/ulw-loop/test/fixtures/steering-proposal.jsonsimilarity index 100%rename from plugins/omo/components/ultragoal/test/fixtures/steering-proposal.jsonrename to plugins/omo/components/ulw-loop/test/fixtures/steering-proposal.jsondiff --git a/plugins/omo/components/ultragoal/test/fixtures/user-prompt-submit.json b/plugins/omo/components/ulw-loop/test/fixtures/user-prompt-submit.jsonsimilarity index 55%rename from plugins/omo/components/ultragoal/test/fixtures/user-prompt-submit.jsonrename to plugins/omo/components/ulw-loop/test/fixtures/user-prompt-submit.jsonindex 0f6e079e..e10a28fe 100644--- a/plugins/omo/components/ultragoal/test/fixtures/user-prompt-submit.json+++ b/plugins/omo/components/ulw-loop/test/fixtures/user-prompt-submit.json@@ -3,7 +3,7 @@"hook_event_name": "UserPromptSubmit","model": "gpt-5.5","permission_mode": "default",- "prompt": "OMO_ULTRAGOAL_STEER: {\"kind\":\"annotate_ledger\",\"source\":\"user_prompt_submit\",\"evidence\":\"test note\",\"rationale\":\"testing hook\"}",+ "prompt": "OMO_ULW_LOOP_STEER: {\"kind\":\"annotate_ledger\",\"source\":\"user_prompt_submit\",\"evidence\":\"test note\",\"rationale\":\"testing hook\"}","session_id": "s1","transcript_path": "/tmp/transcript.log","turn_id": "t1"diff --git a/plugins/omo/components/ultragoal/test/goal-status.test.ts b/plugins/omo/components/ulw-loop/test/goal-status.test.tssimilarity index 84%rename from plugins/omo/components/ultragoal/test/goal-status.test.tsrename to plugins/omo/components/ulw-loop/test/goal-status.test.tsindex 9b79b8bb..04670c7c 100644--- a/plugins/omo/components/ultragoal/test/goal-status.test.ts+++ b/plugins/omo/components/ulw-loop/test/goal-status.test.ts@@ -8,14 +8,14 @@ import {firstUnresolvedCriterion,hasAllCriteriaPass,isFinalRunCompletionCandidate,- isUltragoalDone,- ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE,+ isUlwLoopDone,+ ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE,} from "../src/goal-status.js";-import type { UltragoalItem, UltragoalPlan, UltragoalSuccessCriterion } from "../src/types.js";+import type { UlwLoopItem, UlwLoopPlan, UlwLoopSuccessCriterion } from "../src/types.js";const NOW = "2026-05-23T00:00:00.000Z";-function makeCriterion(overrides: Partial<UltragoalSuccessCriterion> = {}): UltragoalSuccessCriterion {+function makeCriterion(overrides: Partial<UlwLoopSuccessCriterion> = {}): UlwLoopSuccessCriterion {return {id: "C001",scenario: "happy path",@@ -27,7 +27,7 @@ function makeCriterion(overrides: Partial<UltragoalSuccessCriterion> = {}): Ultr};}-function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {+function makeGoal(overrides: Partial<UlwLoopItem> = {}): UlwLoopItem {return {id: "G001",title: "Goal one",@@ -41,20 +41,20 @@ function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {};}-function makePlan(overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {+function makePlan(overrides: Partial<UlwLoopPlan> = {}): UlwLoopPlan {return {version: 1,createdAt: NOW,updatedAt: NOW,- briefPath: ".omo/ultragoal/brief.md",- goalsPath: ".omo/ultragoal/goals.json",- ledgerPath: ".omo/ultragoal/ledger.jsonl",+ briefPath: ".omo/ulw-loop/brief.md",+ goalsPath: ".omo/ulw-loop/goals.json",+ ledgerPath: ".omo/ulw-loop/ledger.jsonl",goals: [],...overrides,};}-describe("isUltragoalDone", () => {+describe("isUlwLoopDone", () => {it("returns true when all goals complete", () => {// givenconst plan = makePlan({@@ -62,7 +62,7 @@ describe("isUltragoalDone", () => {});// when- const done = isUltragoalDone(plan);+ const done = isUlwLoopDone(plan);// thenexpect(done).toBe(true);@@ -73,7 +73,7 @@ describe("isUltragoalDone", () => {const plan = makePlan({ goals: [makeGoal({ status: "complete" }), makeGoal({ id: "G002", status: "pending" })] });// when- const done = isUltragoalDone(plan);+ const done = isUlwLoopDone(plan);// thenexpect(done).toBe(false);@@ -91,7 +91,7 @@ describe("isUltragoalDone", () => {const plan = makePlan({ goals: [superseded, replacement] });// when- const done = isUltragoalDone(plan);+ const done = isUlwLoopDone(plan);// thenexpect(done).toBe(true);@@ -155,7 +155,7 @@ describe("expectedCodexObjective", () => {expect(objective).toBe("aggregate objective");});- it("aggregate mode falls back to ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE when codexObjective missing", () => {+ it("aggregate mode falls back to ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE when codexObjective missing", () => {// givenconst goal = makeGoal({ objective: "story objective" });const plan = makePlan({ codexGoalMode: "aggregate" });@@ -164,7 +164,7 @@ describe("expectedCodexObjective", () => {const objective = expectedCodexObjective(plan, goal);// then- expect(objective).toBe(ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE);+ expect(objective).toBe(ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE);});it("per_story mode returns goal.objective", () => {@@ -189,12 +189,12 @@ describe("aggregateCodexObjective", () => {expect(objective).toBe("aggregate objective");});- it("falls back to ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE", () => {+ it("falls back to ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE", () => {// whenconst objective = aggregateCodexObjective(makePlan());// then- expect(objective).toBe(ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE);+ expect(objective).toBe(ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE);});});@@ -317,11 +317,11 @@ describe("firstUnresolvedCriterion", () => {});});-describe("ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE", () => {- it("references the .omo/ultragoal path and excludes the legacy workspace", () => {+describe("ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE", () => {+ it("references the .omo/ulw-loop path and excludes the legacy workspace", () => {const legacyWorkspace = [".", "om", "x"].join("");- expect(ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE).toContain(".omo/ultragoal");- expect(ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE).not.toContain(legacyWorkspace);+ expect(ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE).toContain(".omo/ulw-loop");+ expect(ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE).not.toContain(legacyWorkspace);});});diff --git a/plugins/omo/components/ulw-loop/test/package-smoke.test.ts b/plugins/omo/components/ulw-loop/test/package-smoke.test.tsnew file mode 100644index 00000000..63feb6ea--- /dev/null+++ b/plugins/omo/components/ulw-loop/test/package-smoke.test.ts@@ -0,0 +1,261 @@+// biome-ignore-all format: smoke test pulls verbatim JSON for structural assertion.+import { spawn } from "node:child_process";+import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";++const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");++async function readText(relative: string): Promise<string> {+ return readFile(join(repoRoot, relative), "utf8");+}++async function readJson(relative: string): Promise<unknown> {+ return JSON.parse(await readText(relative));+}++type ShellResult = {+ readonly code: number | null;+ readonly stdout: string;+ readonly stderr: string;+};++function bootstrapScriptFrom(text: string): string {+ const heading = text.indexOf("### 1. Create goals from the brief");+ expect(heading).toBeGreaterThanOrEqual(0);+ const blockStart = text.indexOf("```sh\n", heading);+ expect(blockStart).toBeGreaterThanOrEqual(0);+ const codeStart = blockStart + "```sh\n".length;+ const blockEnd = text.indexOf("\n```", codeStart);+ expect(blockEnd).toBeGreaterThan(codeStart);+ return text.slice(codeStart, blockEnd);+}++async function runShell(script: string, env: NodeJS.ProcessEnv): Promise<ShellResult> {+ return new Promise((resolvePromise, reject) => {+ const child = spawn("/bin/sh", ["-c", script], { env });+ 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"),+ });+ });+ });+}++describe("package.json", () => {+ it("declares ESM + npm + Node >=20", async () => {+ const pkg = await readJson("package.json") as Record<string, unknown>;+ expect(pkg["type"]).toBe("module");+ expect(pkg["packageManager"]).toBe("[email protected]");+ expect((pkg["engines"] as Record<string, unknown>)["node"]).toBe(">=20.0.0");+ });++ it("exposes the omo binary pointing at dist/cli.js", async () => {+ const pkg = await readJson("package.json") as Record<string, unknown>;+ const bin = pkg["bin"] as Record<string, string>;+ expect(bin["omo"]).toBe("./dist/cli.js");+ });++ it("ships the expected files for npm publish", async () => {+ const pkg = await readJson("package.json") as Record<string, unknown>;+ const files = pkg["files"] as readonly string[];+ expect(files).toContain("dist");+ expect(files).toContain("hooks");+ expect(files).toContain("skills");+ expect(files).not.toContain(".codex-plugin");+ });+});++describe("component plugin identity", () => {+ it("is owned by the aggregate OMO plugin root", async () => {+ await expect(readText(".codex-plugin/plugin.json")).rejects.toMatchObject({ code: "ENOENT" });+ });+});++describe("hooks/hooks.json", () => {+ it("registers UserPromptSubmit with PLUGIN_ROOT interpolation", async () => {+ const hooks = await readJson("hooks/hooks.json") as Record<string, unknown>;+ const events = (hooks["hooks"] as Record<string, unknown>)["UserPromptSubmit"] as readonly Record<string, unknown>[];+ expect(events.length).toBeGreaterThan(0);+ const command = ((events[0]?.["hooks"] as readonly Record<string, unknown>[])[0]?.["command"]) as string;+ expect(command).toContain(`$${"{PLUGIN_ROOT}"}`);+ expect(command).toContain("dist/cli.js");+ expect(command).toContain("hook user-prompt-submit");+ });++ it("#given ulw-loop component is enabled #when hooks are inspected #then create_goal PreToolUse guard is registered", async () => {+ const text = await readText("hooks/hooks.json");++ expect(text).toContain('"PreToolUse"');+ expect(text).toContain('"matcher": "^create_goal$"');+ expect(text).toContain("hook pre-tool-use");+ });+});++describe("src/cli.ts", () => {+ it("starts with #!/usr/bin/env node shebang", async () => {+ const text = await readText("src/cli.ts");+ expect(text.split("\n")[0]).toBe("#!/usr/bin/env node");+ });+});++describe("skills/ulw-loop/SKILL.md", () => {+ it("exists", async () => {+ const info = await stat(join(repoRoot, "skills/ulw-loop/SKILL.md"));+ expect(info.isFile()).toBe(true);+ });++ it("#given Codex skill hinting #when ulw-loop skill metadata is inspected #then ulw-loop is the primary mention name", async () => {+ 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 () => {+ const text = await readText("skills/ulw-loop/agents/openai.yaml");++ expect(text).toContain('display_name: "ulw-loop (omo)"');+ expect(text).not.toContain("ulw-loop / ulw-loop");+ expect(text).toContain('short_description: "Goal-like ultrawork loop for systematic decomposition"');+ expect(text).toContain("Use $ulw-loop");+ });++ it("#given Codex dollar hinting #when querying ulw-loop #then ulw-loop remains discoverable as an alias", async () => {+ const text = await readText("skills/ulw-loop/agents/openai.yaml");++ expect(text).toContain("search_terms:");+ 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 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);+ const root = await mkdtemp(join(tmpdir(), "omo-ulw-loop-bootstrap-"));+ try {+ const badBin = join(root, "bad-bin");+ const home = join(root, "home");+ const codexHome = join(home, ".codex");+ const cachedCli = join(codexHome, "plugins", "cache", "sisyphuslabs", "omo", "0.1.0", "components", "ulw-loop", "dist", "cli.js");+ await mkdir(badBin, { recursive: true });+ await mkdir(dirname(cachedCli), { recursive: true });+ await writeFile(join(badBin, "omo"), "#!/bin/sh\nprintf '%s\\n' \"error: unknown command 'ulw-loop'\" >&2\nexit 1\n");+ await chmod(join(badBin, "omo"), 0o755);+ await writeFile(+ cachedCli,+ [+ "#!/usr/bin/env node",+ "const args = process.argv.slice(2);",+ "if (args[0] === 'ulw-loop' && args[1] === 'help') process.exit(0);",+ "if (args[0] === 'ulw-loop' && args[1] === 'status' && args.includes('--json')) {",+ " console.log(JSON.stringify({ ok: true, source: 'cached-ulw-loop' }));",+ " process.exit(0);",+ "}",+ "console.error('unexpected args: ' + args.join(' '));",+ "process.exit(1);",+ "",+ ].join("\n"),+ );++ const result = await runShell(`${bootstrap}\nomo ulw-loop status --json`, {+ ...process.env,+ CODEX_HOME: codexHome,+ HOME: home,+ PATH: `${badBin}:${process.env["PATH"] ?? ""}`,+ });++ expect(result.code).toBe(0);+ expect(result.stdout).toContain('"source":"cached-ulw-loop"');+ expect(result.stderr).not.toContain("unknown command");+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it("uses the .omo workspace path", async () => {+ const text = await readText("skills/ulw-loop/SKILL.md");+ expect(text).toContain(".omo/ulw-loop");+ });++ 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 or status tool/);+ expect(text).toMatch(/replay large agent status and latest-message payloads/);+ expect(text).toMatch(/Track spawned agent names locally/);+ expect(text).toMatch(/wait_agent.*completion/);+ expect(text).toMatch(/targeted followups only when needed/);+ expect(text).toMatch(/close_agent.*after integrating each result/);+ 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).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.*signal, not proof/);+ expect(text).toMatch(/one targeted followup/);+ 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/);+ });+});++describe("source LOC budget", () => {+ it("every source file stays at or under 250 pure LOC", async () => {+ const files = [+ "src/types.ts", "src/paths.ts", "src/plan-io.ts", "src/plan-crud.ts", "src/goal-status.ts",+ "src/evidence.ts", "src/quality-gate.ts", "src/checkpoint.ts", "src/review-blockers.ts",+ "src/steering.ts", "src/codex-goal-instruction.ts", "src/codex-goal-snapshot.ts", "src/codex-hook.ts",+ "src/cli.ts", "src/cli-arg-parser.ts", "src/cli-output.ts", "src/cli-steering.ts", "src/cli-commands.ts",+ ];+ for (const file of files) {+ const text = await readText(file);+ const pure = text.split("\n").filter((line) => {+ const trimmed = line.trim();+ return trimmed.length > 0 && !trimmed.startsWith("//");+ }).length;+ expect(pure, `${file} pure LOC`).toBeLessThanOrEqual(250);+ }+ });+});diff --git a/plugins/omo/components/ulw-loop/test/paths.test.ts b/plugins/omo/components/ulw-loop/test/paths.test.tsnew file mode 100644index 00000000..be781f92--- /dev/null+++ b/plugins/omo/components/ulw-loop/test/paths.test.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from "vitest";++import {+ normalizeUlwLoopSessionId,+ repoRelative,+ ulwLoopBriefPath,+ ulwLoopDir,+ ulwLoopGoalsPath,+ ulwLoopLedgerPath,+} from "../src/paths.ts";++describe("ulwLoopDir(repo)", () => {+ it("returns repo + '/.omo/ulw-loop'", () => {+ // when/then+ expect(ulwLoopDir("/repo")).toBe("/repo/.omo/ulw-loop");+ });++ it("#given a session id #when resolving the loop dir #then scopes artifacts under that session", () => {+ // when/then+ expect(ulwLoopDir("/repo", { sessionId: "sess_abc" })).toBe("/repo/.omo/ulw-loop/sess_abc");+ });+});++describe("ulw-loop*Path helpers", () => {+ it("compose artifact filenames under ulwLoopDir", () => {+ // when/then+ expect(ulwLoopBriefPath("/r")).toBe("/r/.omo/ulw-loop/brief.md");+ expect(ulwLoopGoalsPath("/r")).toBe("/r/.omo/ulw-loop/goals.json");+ expect(ulwLoopLedgerPath("/r")).toBe("/r/.omo/ulw-loop/ledger.jsonl");+ });++ it("#given a session id #when composing artifact filenames #then returns session-scoped paths", () => {+ // when/then+ expect(ulwLoopBriefPath("/r", { sessionId: "session-A" })).toBe("/r/.omo/ulw-loop/session-A/brief.md");+ expect(ulwLoopGoalsPath("/r", { sessionId: "session-A" })).toBe("/r/.omo/ulw-loop/session-A/goals.json");+ expect(ulwLoopLedgerPath("/r", { sessionId: "session-A" })).toBe("/r/.omo/ulw-loop/session-A/ledger.jsonl");+ });+});++describe("normalizeUlwLoopSessionId", () => {+ it("#given traversal-like input #when normalized #then returns a path-safe session segment", () => {+ // when/then+ expect(normalizeUlwLoopSessionId("../bad/id")).toBe("bad-id");+ });++ it("#given blank input #when normalized #then returns null", () => {+ // when/then+ expect(normalizeUlwLoopSessionId(" ")).toBeNull();+ });+});++describe("repoRelative", () => {+ it("strips repo prefix when path is inside repo", () => {+ // when/then+ expect(repoRelative("/repo/.omo/ulw-loop/goals.json", "/repo")).toBe(".omo/ulw-loop/goals.json");+ });++ it("returns absolute when path is outside repo", () => {+ // when/then+ expect(repoRelative("/elsewhere/file", "/repo")).toBe("/elsewhere/file");+ });+});diff --git a/plugins/omo/components/ultragoal/test/plan-crud.test.ts b/plugins/omo/components/ulw-loop/test/plan-crud.test.tssimilarity index 68%rename from plugins/omo/components/ultragoal/test/plan-crud.test.tsrename to plugins/omo/components/ulw-loop/test/plan-crud.test.tsindex 4d3d366c..abc80dcf 100644--- a/plugins/omo/components/ultragoal/test/plan-crud.test.ts+++ b/plugins/omo/components/ulw-loop/test/plan-crud.test.ts@@ -3,18 +3,18 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { describe, expect, it } from "vitest";-import { ultragoalBriefPath, ultragoalGoalsPath, ultragoalLedgerPath } from "../src/paths.js";+import { ulwLoopBriefPath, ulwLoopGoalsPath, ulwLoopLedgerPath } from "../src/paths.js";import {- addUltragoalGoal,- createUltragoalPlan,+ addUlwLoopGoal,+ createUlwLoopPlan,deriveGoalCandidates,seedDefaultSuccessCriteria,- startNextUltragoal,- summarizeUltragoalPlan,+ startNextUlwLoop,+ summarizeUlwLoopPlan,} from "../src/plan-crud.js";import { writePlan } from "../src/plan-io.js";-import type { UltragoalItem, UltragoalPlan, UltragoalSuccessCriterion } from "../src/types.js";-import { UltragoalError } from "../src/types.js";+import type { UlwLoopItem, UlwLoopPlan, UlwLoopSuccessCriterion } from "../src/types.js";+import { UlwLoopError } from "../src/types.js";const NOW = "2026-05-23T00:00:00.000Z";@@ -27,20 +27,20 @@ async function readBriefFixture(): Promise<string> {}async function ledgerKinds(repoRoot: string): Promise<string[]> {- const raw = await readFile(ultragoalLedgerPath(repoRoot), "utf8");+ const raw = await readFile(ulwLoopLedgerPath(repoRoot), "utf8");return raw.split(/\r?\n/).filter(Boolean).map((line) => JSON.parse(line).kind);}-function criterion(status: UltragoalSuccessCriterion["status"]): UltragoalSuccessCriterion {+function criterion(status: UlwLoopSuccessCriterion["status"]): UlwLoopSuccessCriterion {const [base] = seedDefaultSuccessCriteria(0, "Implement auth endpoint");if (base === undefined) throw new Error("expected seeded criterion");return { ...base, status };}-function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {+function makeGoal(overrides: Partial<UlwLoopItem> = {}): UlwLoopItem {return {id: "G001",title: "Build auth service",@@ -54,20 +54,20 @@ function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {};}-function makePlan(goals: UltragoalItem[]): UltragoalPlan {+function makePlan(goals: UlwLoopItem[]): UlwLoopPlan {return {version: 1,createdAt: NOW,updatedAt: NOW,- briefPath: ".omo/ultragoal/brief.md",- goalsPath: ".omo/ultragoal/goals.json",- ledgerPath: ".omo/ultragoal/ledger.jsonl",+ briefPath: ".omo/ulw-loop/brief.md",+ goalsPath: ".omo/ulw-loop/goals.json",+ ledgerPath: ".omo/ulw-loop/ledger.jsonl",codexGoalMode: "aggregate",goals,};}-function scheduled(result: Awaited<ReturnType<typeof startNextUltragoal>>) {+function scheduled(result: Awaited<ReturnType<typeof startNextUlwLoop>>) {if ("done" in result) throw new Error("expected scheduled goal");return result;}@@ -93,20 +93,20 @@ describe("seedDefaultSuccessCriteria", () => {});});-describe("createUltragoalPlan", () => {- it("creates .omo/ultragoal/{brief.md, goals.json, ledger.jsonl} in repoRoot", async () => {+describe("createUlwLoopPlan", () => {+ it("creates .omo/ulw-loop/{brief.md, goals.json, ledger.jsonl} in repoRoot", async () => {const repoRoot = await makeRepo();const brief = await readBriefFixture();- await createUltragoalPlan(repoRoot, { brief });+ await createUlwLoopPlan(repoRoot, { brief });- expect(await readFile(ultragoalBriefPath(repoRoot), "utf8")).toBe(brief.endsWith("\n") ? brief : `${brief}\n`);- expect(await readFile(ultragoalGoalsPath(repoRoot), "utf8")).toContain("G001-build-the-jwt-auth-endpoint");+ expect(await readFile(ulwLoopBriefPath(repoRoot), "utf8")).toBe(brief.endsWith("\n") ? brief : `${brief}\n`);+ expect(await readFile(ulwLoopGoalsPath(repoRoot), "utf8")).toContain("G001-build-the-jwt-auth-endpoint");expect(await ledgerKinds(repoRoot)).toEqual(["plan_created"]);});it("seeds at least 3 successCriteria per goal", async () => {- const plan = await createUltragoalPlan(await makeRepo(), { brief: await readBriefFixture() });+ const plan = await createUlwLoopPlan(await makeRepo(), { brief: await readBriefFixture() });expect(plan.goals).toHaveLength(3);expect(plan.goals.every((goal) => goal.successCriteria.length >= 3)).toBe(true);@@ -114,17 +114,17 @@ describe("createUltragoalPlan", () => {it("refuses overwrite of an existing plan without --force", async () => {const repoRoot = await makeRepo();- await createUltragoalPlan(repoRoot, { brief: "first" });+ await createUlwLoopPlan(repoRoot, { brief: "first" });- await expect(createUltragoalPlan(repoRoot, { brief: "second" })).rejects.toThrow(UltragoalError);- await expect(createUltragoalPlan(repoRoot, { brief: "second" })).rejects.toThrow("Refusing to overwrite");+ await expect(createUlwLoopPlan(repoRoot, { brief: "second" })).rejects.toThrow(UlwLoopError);+ await expect(createUlwLoopPlan(repoRoot, { brief: "second" })).rejects.toThrow("Refusing to overwrite");});it("aggregate is the default codexGoalMode", async () => {- const plan = await createUltragoalPlan(await makeRepo(), { brief: "Ship the feature" });+ const plan = await createUlwLoopPlan(await makeRepo(), { brief: "Ship the feature" });expect(plan.codexGoalMode).toBe("aggregate");- expect(plan.codexObjective).toContain(".omo/ultragoal/goals.json");+ expect(plan.codexObjective).toContain(".omo/ulw-loop/goals.json");});});@@ -150,12 +150,12 @@ describe("deriveGoalCandidates", () => {});});-describe("addUltragoalGoal", () => {+describe("addUlwLoopGoal", () => {it("appends a new goal to plan with seeded successCriteria", async () => {const repoRoot = await makeRepo();- await createUltragoalPlan(repoRoot, { brief: "Build auth" });+ await createUlwLoopPlan(repoRoot, { brief: "Build auth" });- const { plan, goal } = await addUltragoalGoal(repoRoot, { title: "Add rate limit", objective: "Throttle login" });+ const { plan, goal } = await addUlwLoopGoal(repoRoot, { title: "Add rate limit", objective: "Throttle login" });expect(plan.goals).toHaveLength(2);expect(goal.id).toBe("G002-add-rate-limit");@@ -164,20 +164,20 @@ describe("addUltragoalGoal", () => {it("appends a ledger entry for goal_added", async () => {const repoRoot = await makeRepo();- await createUltragoalPlan(repoRoot, { brief: "Build auth" });+ await createUlwLoopPlan(repoRoot, { brief: "Build auth" });- await addUltragoalGoal(repoRoot, { title: "Add rate limit", objective: "Throttle login" });+ await addUlwLoopGoal(repoRoot, { title: "Add rate limit", objective: "Throttle login" });expect(await ledgerKinds(repoRoot)).toEqual(["plan_created", "goal_added"]);});});-describe("startNextUltragoal", () => {+describe("startNextUlwLoop", () => {it("picks the first pending goal", async () => {const repoRoot = await makeRepo();- await createUltragoalPlan(repoRoot, { brief: "- First\n- Second" });+ await createUlwLoopPlan(repoRoot, { brief: "- First\n- Second" });- const result = scheduled(await startNextUltragoal(repoRoot, {}));+ const result = scheduled(await startNextUlwLoop(repoRoot, {}));expect(result.goal.id).toBe("G001-first");expect(result.goal.status).toBe("in_progress");@@ -186,11 +186,11 @@ describe("startNextUltragoal", () => {it("resumes the in_progress goal when one exists", async () => {const repoRoot = await makeRepo();- const plan = await createUltragoalPlan(repoRoot, { brief: "- First\n- Second" });+ const plan = await createUlwLoopPlan(repoRoot, { brief: "- First\n- Second" });const active = makeGoal({ ...plan.goals[1], status: "in_progress" });await writePlan(repoRoot, { ...plan, goals: [makeGoal({ ...plan.goals[0] }), active], activeGoalId: active.id });- const result = scheduled(await startNextUltragoal(repoRoot, {}));+ const result = scheduled(await startNextUlwLoop(repoRoot, {}));expect(result.goal.id).toBe(active.id);expect(result.resumed).toBe(true);@@ -199,10 +199,10 @@ describe("startNextUltragoal", () => {it("with retryFailed picks first failed (non-blocked) goal", async () => {const repoRoot = await makeRepo();const failed = makeGoal({ status: "failed", failureReason: "flake" });- await mkdir(join(repoRoot, ".omo", "ultragoal"), { recursive: true });+ await mkdir(join(repoRoot, ".omo", "ulw-loop"), { recursive: true });await writePlan(repoRoot, makePlan([failed]));- const result = scheduled(await startNextUltragoal(repoRoot, { retryFailed: true }));+ const result = scheduled(await startNextUlwLoop(repoRoot, { retryFailed: true }));expect(result.goal.id).toBe("G001");expect(result.goal.attempt).toBe(1);@@ -211,16 +211,16 @@ describe("startNextUltragoal", () => {it("returns { done: true } when no eligible goals remain", async () => {const repoRoot = await makeRepo();- await mkdir(join(repoRoot, ".omo", "ultragoal"), { recursive: true });+ await mkdir(join(repoRoot, ".omo", "ulw-loop"), { recursive: true });await writePlan(repoRoot, makePlan([makeGoal({ status: "complete" })]));- const result = await startNextUltragoal(repoRoot, {});+ const result = await startNextUlwLoop(repoRoot, {});expect(result).toMatchObject({ done: true });});});-describe("summarizeUltragoalPlan", () => {+describe("summarizeUlwLoopPlan", () => {it("counts goals by status", () => {const plan = makePlan([makeGoal({ id: "G001", status: "pending" }),@@ -232,7 +232,7 @@ describe("summarizeUltragoalPlan", () => {makeGoal({ id: "G007", status: "needs_user_decision", steeringStatus: "superseded" }),]);- expect(summarizeUltragoalPlan(plan)).toMatchObject({+ expect(summarizeUlwLoopPlan(plan)).toMatchObject({total: 7,pending: 1,in_progress: 1,@@ -251,6 +251,6 @@ describe("summarizeUltragoalPlan", () => {makeGoal({ id: "G002", successCriteria: [criterion("fail"), criterion("blocked"), criterion("pending")] }),]);- expect(summarizeUltragoalPlan(plan).criteria).toEqual({ total: 5, pass: 1, pending: 2, fail: 1, blocked: 1 });+ expect(summarizeUlwLoopPlan(plan).criteria).toEqual({ total: 5, pass: 1, pending: 2, fail: 1, blocked: 1 });});});diff --git a/plugins/omo/components/ultragoal/test/plan-io.test.ts b/plugins/omo/components/ulw-loop/test/plan-io.test.tssimilarity index 69%rename from plugins/omo/components/ultragoal/test/plan-io.test.tsrename to plugins/omo/components/ulw-loop/test/plan-io.test.tsindex 9791e5d9..fe4a0777 100644--- a/plugins/omo/components/ultragoal/test/plan-io.test.ts+++ b/plugins/omo/components/ulw-loop/test/plan-io.test.ts@@ -2,22 +2,22 @@ import { copyFile, mkdir, mkdtemp, readdir, readFile, writeFile } from "node:fs/import { tmpdir } from "node:os";import { join } from "node:path";import { beforeEach, describe, expect, it } from "vitest";-import { ultragoalDir, ultragoalGoalsPath, ultragoalLedgerPath } from "../src/paths.js";+import { ulwLoopDir, ulwLoopGoalsPath, ulwLoopLedgerPath } from "../src/paths.js";import {appendLedger,readSteeringLedgerEntries,- readUltragoalPlan,- withUltragoalMutationLock,+ readUlwLoopPlan,+ withUlwLoopMutationLock,writePlan,} from "../src/plan-io.js";-import type { UltragoalItem, UltragoalLedgerEntry, UltragoalPlan } from "../src/types.js";-import { UltragoalError } from "../src/types.js";+import type { UlwLoopItem, UlwLoopLedgerEntry, UlwLoopPlan } from "../src/types.js";+import { UlwLoopError } from "../src/types.js";const NOW = "2026-05-23T00:00:00.000Z";const STABLE_OBJECTIVE =- "Complete the durable ultragoal plan in .omo/ultragoal/goals.json, including later accepted/appended stories, under the original brief constraints; use .omo/ultragoal/ledger.jsonl as the audit trail.";+ "Complete the durable ulw-loop plan in .omo/ulw-loop/goals.json, including later accepted/appended stories, under the original brief constraints; use .omo/ulw-loop/ledger.jsonl as the audit trail.";-function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {+function makeGoal(overrides: Partial<UlwLoopItem> = {}): UlwLoopItem {return {id: "G001",title: "Build auth service",@@ -31,14 +31,14 @@ function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {};}-function makePlan(overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {+function makePlan(overrides: Partial<UlwLoopPlan> = {}): UlwLoopPlan {return {version: 1,createdAt: NOW,updatedAt: NOW,- briefPath: ".omo/ultragoal/brief.md",- goalsPath: ".omo/ultragoal/goals.json",- ledgerPath: ".omo/ultragoal/ledger.jsonl",+ briefPath: ".omo/ulw-loop/brief.md",+ goalsPath: ".omo/ulw-loop/goals.json",+ ledgerPath: ".omo/ulw-loop/ledger.jsonl",codexGoalMode: "aggregate",codexObjective: STABLE_OBJECTIVE,codexObjectiveAliases: [],@@ -47,7 +47,7 @@ function makePlan(overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {};}-function entry(kind: UltragoalLedgerEntry["kind"], goalId = "G001"): UltragoalLedgerEntry {+function entry(kind: UlwLoopLedgerEntry["kind"], goalId = "G001"): UlwLoopLedgerEntry {return { at: NOW, kind, goalId };}@@ -55,17 +55,17 @@ async function makeRepo(): Promise<string> {return mkdtemp(join(tmpdir(), "ug-io-"));}-async function writeRawPlan(repoRoot: string, plan: UltragoalPlan): Promise<void> {- await mkdir(ultragoalDir(repoRoot), { recursive: true });- await writeFile(ultragoalGoalsPath(repoRoot), `${JSON.stringify(plan, null, 2)}\n`, "utf8");+async function writeRawPlan(repoRoot: string, plan: UlwLoopPlan): Promise<void> {+ await mkdir(ulwLoopDir(repoRoot), { recursive: true });+ await writeFile(ulwLoopGoalsPath(repoRoot), `${JSON.stringify(plan, null, 2)}\n`, "utf8");}async function readLedgerLines(repoRoot: string): Promise<string[]> {- const raw = await readFile(ultragoalLedgerPath(repoRoot), "utf8");+ const raw = await readFile(ulwLoopLedgerPath(repoRoot), "utf8");return raw.split(/\r?\n/).filter(Boolean);}-describe("readUltragoalPlan", () => {+describe("readUlwLoopPlan", () => {let repoRoot = "";beforeEach(async () => {@@ -73,19 +73,19 @@ describe("readUltragoalPlan", () => {repoRoot = await makeRepo();});- it("throws UltragoalError when goals.json is missing", async () => {+ it("throws UlwLoopError when goals.json is missing", async () => {// when/then- await expect(readUltragoalPlan(repoRoot)).rejects.toThrow(UltragoalError);- await expect(readUltragoalPlan(repoRoot)).rejects.toThrow("omo ultragoal create-goals");+ await expect(readUlwLoopPlan(repoRoot)).rejects.toThrow(UlwLoopError);+ await expect(readUlwLoopPlan(repoRoot)).rejects.toThrow("omo ulw-loop create-goals");});it("returns parsed plan when fixture is present", async () => {// given- await mkdir(ultragoalDir(repoRoot), { recursive: true });- await copyFile(join(process.cwd(), "test", "fixtures", "sample-plan.json"), ultragoalGoalsPath(repoRoot));+ await mkdir(ulwLoopDir(repoRoot), { recursive: true });+ await copyFile(join(process.cwd(), "test", "fixtures", "sample-plan.json"), ulwLoopGoalsPath(repoRoot));// when- const plan = await readUltragoalPlan(repoRoot);+ const plan = await readUlwLoopPlan(repoRoot);// thenexpect(plan.version).toBe(1);@@ -96,16 +96,16 @@ describe("readUltragoalPlan", () => {it("migrates legacy aggregate objective on read + writes aggregate_objective_migrated ledger entry + retains alias", async () => {// given- const legacyObjective = "Complete all ultragoal stories in .omo/ultragoal/goals.json: G001 Build auth service";+ const legacyObjective = "Complete all ulw-loop stories in .omo/ulw-loop/goals.json: G001 Build auth service";await writeRawPlan(repoRoot, makePlan({ codexObjective: legacyObjective }));// when- const plan = await readUltragoalPlan(repoRoot);+ const plan = await readUlwLoopPlan(repoRoot);// thenexpect(plan.codexObjective).toBe(STABLE_OBJECTIVE);expect(plan.codexObjectiveAliases).toContain(legacyObjective);- const persisted = JSON.parse(await readFile(ultragoalGoalsPath(repoRoot), "utf8"));+ const persisted = JSON.parse(await readFile(ulwLoopGoalsPath(repoRoot), "utf8"));expect(persisted).toMatchObject({ codexObjective: STABLE_OBJECTIVE, codexObjectiveAliases: [legacyObjective] });const lines = await readLedgerLines(repoRoot);expect(lines).toHaveLength(1);@@ -125,9 +125,9 @@ describe("writePlan", () => {await writePlan(repoRoot, makePlan());// then- const raw = await readFile(ultragoalGoalsPath(repoRoot), "utf8");+ const raw = await readFile(ulwLoopGoalsPath(repoRoot), "utf8");expect(JSON.parse(raw)).toMatchObject({ version: 1, goals: [{ id: "G001" }] });- expect((await readdir(ultragoalDir(repoRoot))).filter((name) => name.endsWith(".tmp"))).toEqual([]);+ expect((await readdir(ulwLoopDir(repoRoot))).filter((name) => name.endsWith(".tmp"))).toEqual([]);});it("overwrites existing file", async () => {@@ -139,7 +139,7 @@ describe("writePlan", () => {await writePlan(repoRoot, makePlan({ codexObjective: "second" }));// then- expect(JSON.parse(await readFile(ultragoalGoalsPath(repoRoot), "utf8"))).toMatchObject({+ expect(JSON.parse(await readFile(ulwLoopGoalsPath(repoRoot), "utf8"))).toMatchObject({codexObjective: "second",});});@@ -166,7 +166,7 @@ describe("appendLedger", () => {await appendLedger(repoRoot, entry("goal_completed"));// then- expect(await readFile(ultragoalLedgerPath(repoRoot), "utf8")).toContain("goal_completed");+ expect(await readFile(ulwLoopLedgerPath(repoRoot), "utf8")).toContain("goal_completed");});it("preserves prior entries", async () => {@@ -209,7 +209,7 @@ describe("readSteeringLedgerEntries", () => {});});-describe("withUltragoalMutationLock", () => {+describe("withUlwLoopMutationLock", () => {it("serializes concurrent invocations", async () => {// givenconst repoRoot = await makeRepo();@@ -221,7 +221,7 @@ describe("withUltragoalMutationLock", () => {// whenawait Promise.all([1, 2, 3].map((_) =>- withUltragoalMutationLock(repoRoot, async () => {+ withUlwLoopMutationLock(repoRoot, async () => {active += 1;maxActive = Math.max(maxActive, active);const current = Number(await readFile(counterPath, "utf8"));diff --git a/plugins/omo/components/ultragoal/test/quality-gate.test.ts b/plugins/omo/components/ulw-loop/test/quality-gate.test.tssimilarity index 78%rename from plugins/omo/components/ultragoal/test/quality-gate.test.tsrename to plugins/omo/components/ulw-loop/test/quality-gate.test.tsindex afb97573..9dd0aebc 100644--- a/plugins/omo/components/ultragoal/test/quality-gate.test.ts+++ b/plugins/omo/components/ulw-loop/test/quality-gate.test.ts@@ -9,8 +9,8 @@ import {sameBlockerOccurrences,validateQualityGate,} from "../src/quality-gate.js";-import type { UltragoalItem, UltragoalPlan } from "../src/types.js";-import { UltragoalError } from "../src/types.js";+import type { UlwLoopItem, UlwLoopPlan } from "../src/types.js";+import { UlwLoopError } from "../src/types.js";const NOW = "2026-05-23T00:00:00.000Z";const VALID_GATE = {@@ -20,7 +20,7 @@ const VALID_GATE = {criteriaCoverage: { totalCriteria: 2, passCount: 2, adversarialClassesCovered: ["malformed_input"] },} as const;-interface GoalWithBlocker extends UltragoalItem {+interface GoalWithBlocker extends UlwLoopItem {blocker?: { readonly signature: string };blockerEvidence?: string;blockerOccurrences?: number;@@ -31,17 +31,17 @@ function makeGate(overrides: Record<string, unknown> = {}): Record<string, unknoreturn { ...VALID_GATE, ...overrides };}-function getQualityGateError(input: unknown): UltragoalError {+function getQualityGateError(input: unknown): UlwLoopError {try {validateQualityGate(input);} catch (error) {- if (error instanceof UltragoalError) return error;+ if (error instanceof UlwLoopError) return error;throw error;}- throw new Error("Expected UltragoalError");+ throw new Error("Expected UlwLoopError");}-function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {+function makeGoal(overrides: Partial<UlwLoopItem> = {}): UlwLoopItem {return {id: "G001",title: "Goal one",@@ -55,14 +55,14 @@ function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {};}-function makePlan(goals: UltragoalItem[]): UltragoalPlan {+function makePlan(goals: UlwLoopItem[]): UlwLoopPlan {return {version: 1,createdAt: NOW,updatedAt: NOW,- briefPath: ".omo/ultragoal/brief.md",- goalsPath: ".omo/ultragoal/goals.json",- ledgerPath: ".omo/ultragoal/ledger.jsonl",+ briefPath: ".omo/ulw-loop/brief.md",+ goalsPath: ".omo/ulw-loop/goals.json",+ ledgerPath: ".omo/ulw-loop/ledger.jsonl",goals,};}@@ -81,39 +81,39 @@ describe("validateQualityGate", () => {expect(gate).toMatchObject({ criteriaCoverage: { totalCriteria: 9, passCount: 9 } });});- it("throws UltragoalError when aiSlopCleaner missing", () => {+ it("throws UlwLoopError when aiSlopCleaner missing", () => {// whenconst error = getQualityGateError(makeGate({ aiSlopCleaner: undefined }));// then- expect(error.code).toBe("ULTRAGOAL_QUALITY_GATE_INVALID");+ expect(error.code).toBe("ULW_LOOP_QUALITY_GATE_INVALID");});- it("throws UltragoalError when verification missing", () => {+ it("throws UlwLoopError when verification missing", () => {// whenconst error = getQualityGateError(makeGate({ verification: undefined }));// then- expect(error.code).toBe("ULTRAGOAL_QUALITY_GATE_INVALID");+ expect(error.code).toBe("ULW_LOOP_QUALITY_GATE_INVALID");});- it("throws UltragoalError when codeReview missing", () => {+ it("throws UlwLoopError when codeReview missing", () => {// whenconst error = getQualityGateError(makeGate({ codeReview: undefined }));// then- expect(error.code).toBe("ULTRAGOAL_QUALITY_GATE_INVALID");+ expect(error.code).toBe("ULW_LOOP_QUALITY_GATE_INVALID");});- it("throws UltragoalError when criteriaCoverage missing (NEW)", () => {+ it("throws UlwLoopError when criteriaCoverage missing (NEW)", () => {// whenconst error = getQualityGateError(makeGate({ criteriaCoverage: undefined }));// then- expect(error.code).toBe("ULTRAGOAL_QUALITY_GATE_INVALID");+ expect(error.code).toBe("ULW_LOOP_QUALITY_GATE_INVALID");});- it("throws UltragoalError when criteriaCoverage.passCount < totalCriteria (NEW)", () => {+ it("throws UlwLoopError when criteriaCoverage.passCount < totalCriteria (NEW)", () => {// whenconst error = getQualityGateError(makeGate({ criteriaCoverage: { totalCriteria: 3, passCount: 2, adversarialClassesCovered: [] } }),@@ -123,7 +123,7 @@ describe("validateQualityGate", () => {expect(error.message).toContain("criteriaCoverage.passCount");});- it("throws UltragoalError when codeReview.recommendation is not APPROVE", () => {+ it("throws UlwLoopError when codeReview.recommendation is not APPROVE", () => {// whenconst error = getQualityGateError(makeGate({ codeReview: { ...VALID_GATE.codeReview, recommendation: "COMMENT" } }),@@ -133,7 +133,7 @@ describe("validateQualityGate", () => {expect(error.message).toContain("recommendation");});- it("throws UltragoalError when architectStatus is not CLEAR", () => {+ it("throws UlwLoopError when architectStatus is not CLEAR", () => {// whenconst error = getQualityGateError(makeGate({ codeReview: { ...VALID_GATE.codeReview, architectStatus: "WATCH" } }),diff --git a/plugins/omo/components/ultragoal/test/review-blockers.test.ts b/plugins/omo/components/ulw-loop/test/review-blockers.test.tssimilarity index 67%rename from plugins/omo/components/ultragoal/test/review-blockers.test.tsrename to plugins/omo/components/ulw-loop/test/review-blockers.test.tsindex 95d47da9..02513371 100644--- a/plugins/omo/components/ultragoal/test/review-blockers.test.ts+++ b/plugins/omo/components/ulw-loop/test/review-blockers.test.ts@@ -3,16 +3,16 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { describe, expect, it } from "vitest";-import { ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE } from "../src/goal-status.js";-import { ultragoalDir, ultragoalLedgerPath } from "../src/paths.js";+import { ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE } from "../src/goal-status.js";+import { ulwLoopDir, ulwLoopLedgerPath } from "../src/paths.js";import { writePlan } from "../src/plan-io.js";import { recordFinalReviewBlockers } from "../src/review-blockers.js";-import type { UltragoalItem, UltragoalPlan, UltragoalSuccessCriterion } from "../src/types.js";-import { UltragoalError } from "../src/types.js";+import type { UlwLoopItem, UlwLoopPlan, UlwLoopSuccessCriterion } from "../src/types.js";+import { UlwLoopError } from "../src/types.js";const NOW = "2026-05-23T00:00:00.000Z";const VALID_SNAPSHOT_JSON = JSON.stringify({- goal: { objective: ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE, status: "active" },+ goal: { objective: ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE, status: "active" },});const validArgs = {@@ -23,7 +23,7 @@ const validArgs = {codexGoalJson: VALID_SNAPSHOT_JSON,};-function makeCriterion(overrides: Partial<UltragoalSuccessCriterion> = {}): UltragoalSuccessCriterion {+function makeCriterion(overrides: Partial<UlwLoopSuccessCriterion> = {}): UlwLoopSuccessCriterion {return {id: "C001",scenario: "happy path",@@ -35,11 +35,11 @@ function makeCriterion(overrides: Partial<UltragoalSuccessCriterion> = {}): Ultr};}-function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {+function makeGoal(overrides: Partial<UlwLoopItem> = {}): UlwLoopItem {return {id: "G001",title: "Build durable plan",- objective: "Complete one ultragoal story",+ objective: "Complete one ulw-loop story",status: "pending",successCriteria: [makeCriterion()],attempt: 1,@@ -49,49 +49,49 @@ function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {};}-function makePlan(overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {+function makePlan(overrides: Partial<UlwLoopPlan> = {}): UlwLoopPlan {return {version: 1,createdAt: NOW,updatedAt: NOW,- briefPath: ".omo/ultragoal/brief.md",- goalsPath: ".omo/ultragoal/goals.json",- ledgerPath: ".omo/ultragoal/ledger.jsonl",+ briefPath: ".omo/ulw-loop/brief.md",+ goalsPath: ".omo/ulw-loop/goals.json",+ ledgerPath: ".omo/ulw-loop/ledger.jsonl",codexGoalMode: "aggregate",- codexObjective: ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE,+ codexObjective: ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE,goals: [makeGoal({ status: "in_progress" })],...overrides,};}-async function bootstrapRepo(plan: UltragoalPlan): Promise<string> {+async function bootstrapRepo(plan: UlwLoopPlan): Promise<string> {const repo = await mkdtemp(join(tmpdir(), "ug-review-blockers-"));- await mkdir(ultragoalDir(repo), { recursive: true });+ await mkdir(ulwLoopDir(repo), { recursive: true });await writePlan(repo, plan);return repo;}async function ledgerKinds(repo: string): Promise<string[]> {- const raw = await readFile(ultragoalLedgerPath(repo), "utf8");+ const raw = await readFile(ulwLoopLedgerPath(repo), "utf8");return raw.split(/\r?\n/).filter(Boolean).map((line) => JSON.parse(line).kind);}-async function expectUltragoalCode(action: () => Promise<unknown>, code: string): Promise<void> {+async function expectUlwLoopCode(action: () => Promise<unknown>, code: string): Promise<void> {try {await action();} catch (error) {- expect(error).toBeInstanceOf(UltragoalError);- if (!(error instanceof UltragoalError)) throw error;+ expect(error).toBeInstanceOf(UlwLoopError);+ if (!(error instanceof UlwLoopError)) throw error;expect(error.code).toBe(code);return;}- throw new Error("Expected UltragoalError");+ throw new Error("Expected UlwLoopError");}-function finalPlan(): UltragoalPlan {+function finalPlan(): UlwLoopPlan {return makePlan({activeGoalId: "G002",goals: [@@ -129,42 +129,42 @@ describe("recordFinalReviewBlockers happy path", () => {});describe("recordFinalReviewBlockers error cases", () => {- it("throws ultragoal_goal_not_found for unknown goalId", async () => {+ it("throws ulw_loop_goal_not_found for unknown goalId", async () => {const repo = await bootstrapRepo(finalPlan());- await expectUltragoalCode(+ await expectUlwLoopCode(() => recordFinalReviewBlockers(repo, { ...validArgs, goalId: "G999" }),- "ultragoal_goal_not_found",+ "ulw_loop_goal_not_found",);});- it("throws ultragoal_goal_not_in_progress when goal.status !== in_progress", async () => {+ it("throws ulw_loop_goal_not_in_progress when goal.status !== in_progress", async () => {const repo = await bootstrapRepo(makePlan({goals: [makeGoal({ id: "G001", status: "in_progress" }), makeGoal({ id: "G002", status: "pending" })],}),);- await expectUltragoalCode(() => recordFinalReviewBlockers(repo, validArgs), "ultragoal_goal_not_in_progress");+ await expectUlwLoopCode(() => recordFinalReviewBlockers(repo, validArgs), "ulw_loop_goal_not_in_progress");});- it("throws ultragoal_not_final_story when other unresolved goals remain", async () => {+ it("throws ulw_loop_not_final_story when other unresolved goals remain", async () => {const repo = await bootstrapRepo(makePlan({goals: [makeGoal({ id: "G001", status: "in_progress" }), makeGoal({ id: "G002", status: "pending" })],}),);- await expectUltragoalCode(+ await expectUlwLoopCode(() => recordFinalReviewBlockers(repo, { ...validArgs, goalId: "G001" }),- "ultragoal_not_final_story",+ "ulw_loop_not_final_story",);});- it("throws ultragoal_codex_snapshot_mismatch when objective mismatches", async () => {+ it("throws ulw_loop_codex_snapshot_mismatch when objective mismatches", async () => {const repo = await bootstrapRepo(finalPlan());const codexGoalJson = JSON.stringify({ goal: { objective: "wrong", status: "active" } });- await expectUltragoalCode(+ await expectUlwLoopCode(() => recordFinalReviewBlockers(repo, { ...validArgs, codexGoalJson }),- "ultragoal_codex_snapshot_mismatch",+ "ulw_loop_codex_snapshot_mismatch",);});});diff --git a/plugins/omo/components/ultragoal/test/steering.test.ts b/plugins/omo/components/ulw-loop/test/steering.test.tssimilarity index 62%rename from plugins/omo/components/ultragoal/test/steering.test.tsrename to plugins/omo/components/ulw-loop/test/steering.test.tsindex 5a66a6f0..674bc14f 100644--- a/plugins/omo/components/ultragoal/test/steering.test.ts+++ b/plugins/omo/components/ulw-loop/test/steering.test.ts@@ -2,20 +2,20 @@ import { mkdtemp, readFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { describe, expect, it } from "vitest";-import { ultragoalGoalsPath } from "../src/paths.js";-import { readSteeringLedgerEntries, readUltragoalPlan, writePlan } from "../src/plan-io.js";+import { ulwLoopGoalsPath } from "../src/paths.js";+import { readSteeringLedgerEntries, readUlwLoopPlan, writePlan } from "../src/plan-io.js";import {applySteeringMutation,- parseUltragoalSteeringDirective,- steerUltragoal,- validateUltragoalSteeringProposal,+ parseUlwLoopSteeringDirective,+ steerUlwLoop,+ validateUlwLoopSteeringProposal,} from "../src/steering.js";import type {- UltragoalItem,- UltragoalPlan,- UltragoalSteeringProposal,- UltragoalSuccessCriterion,- UltragoalSuccessCriterionUserModel,+ UlwLoopItem,+ UlwLoopPlan,+ UlwLoopSteeringProposal,+ UlwLoopSuccessCriterion,+ UlwLoopSuccessCriterionUserModel,} from "../src/types.js";const NOW = "2026-05-23T00:00:00.000Z";@@ -24,11 +24,11 @@ type CriterionSteeringFields = {readonly goalId?: string;readonly scenario?: string;readonly expectedEvidence?: string;- readonly userModel?: UltragoalSuccessCriterionUserModel;+ readonly userModel?: UlwLoopSuccessCriterionUserModel;};-type SteeringInput = UltragoalSteeringProposal & CriterionSteeringFields;+type SteeringInput = UlwLoopSteeringProposal & CriterionSteeringFields;-function criterion(overrides: Partial<UltragoalSuccessCriterion> = {}): UltragoalSuccessCriterion {+function criterion(overrides: Partial<UlwLoopSuccessCriterion> = {}): UlwLoopSuccessCriterion {return {id: "C001",scenario: "old scenario",@@ -40,7 +40,7 @@ function criterion(overrides: Partial<UltragoalSuccessCriterion> = {}): Ultragoa};}-function goal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {+function goal(overrides: Partial<UlwLoopItem> = {}): UlwLoopItem {return {id: "G001",title: "Build auth service",@@ -54,14 +54,14 @@ function goal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {};}-function plan(overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {+function plan(overrides: Partial<UlwLoopPlan> = {}): UlwLoopPlan {return {version: 1,createdAt: NOW,updatedAt: NOW,- briefPath: ".omo/ultragoal/brief.md",- goalsPath: ".omo/ultragoal/goals.json",- ledgerPath: ".omo/ultragoal/ledger.jsonl",+ briefPath: ".omo/ulw-loop/brief.md",+ goalsPath: ".omo/ulw-loop/goals.json",+ ledgerPath: ".omo/ulw-loop/ledger.jsonl",goals: [goal(),goal({ id: "G002", title: "Rate limit", objective: "Throttle login" }),@@ -83,18 +83,18 @@ function steering(overrides: Partial<SteeringInput> = {}): SteeringInput {};}-async function repoWithPlan(seed: UltragoalPlan = plan()): Promise<string> {+async function repoWithPlan(seed: UlwLoopPlan = plan()): Promise<string> {const repoRoot = await mkdtemp(join(tmpdir(), "ug-steer-"));await writePlan(repoRoot, seed);return repoRoot;}-describe("validateUltragoalSteeringProposal", () => {+describe("validateUlwLoopSteeringProposal", () => {it("accepts valid add_subgoal", async () => {const proposal: unknown = JSON.parse(await readFile(join(process.cwd(), "test/fixtures/steering-proposal.json"), "utf8"),);- expect(validateUltragoalSteeringProposal(plan(), proposal).invariant.accepted).toBe(true);+ expect(validateUlwLoopSteeringProposal(plan(), proposal).invariant.accepted).toBe(true);});it.each([@@ -104,26 +104,23 @@ describe("validateUltragoalSteeringProposal", () => {["protected payload mutations", { after: { codexObjective: "replace", qualityGate: { status: "passed" } } }],["weakened completion text", { objective: "skip tests and mark complete faster" }],])("rejects %s", (_name, overrides) => {- const audit = validateUltragoalSteeringProposal(plan(), { ...steering(), ...overrides });+ const audit = validateUlwLoopSteeringProposal(plan(), { ...steering(), ...overrides });expect(audit.invariant.accepted).toBe(false);expect(audit.invariant.rejectedReasons.length).toBeGreaterThan(0);});it("rejects when plan already complete", () => {const done = plan({ goals: [goal({ status: "complete" }), goal({ id: "G002", status: "complete" })] });- expect(validateUltragoalSteeringProposal(done, steering()).invariant.accepted).toBe(false);+ expect(validateUlwLoopSteeringProposal(done, steering()).invariant.accepted).toBe(false);});it("rejects split_subgoal without children", () => {- const audit = validateUltragoalSteeringProposal(- plan(),- steering({ kind: "split_subgoal", targetGoalId: "G001" }),- );+ const audit = validateUlwLoopSteeringProposal(plan(), steering({ kind: "split_subgoal", targetGoalId: "G001" }));expect(audit.invariant.accepted).toBe(false);});it("rejects reorder_pending with unknown goal id", () => {- const audit = validateUltragoalSteeringProposal(+ const audit = validateUlwLoopSteeringProposal(plan(),steering({ kind: "reorder_pending", pendingOrder: ["missing"] }),);@@ -134,7 +131,7 @@ describe("validateUltragoalSteeringProposal", () => {["new scenario", { scenario: "new precise scenario" }],["new expectedEvidence", { expectedEvidence: "specific command output" }],])("accepts valid revise_criterion with %s", (_name, update) => {- const audit = validateUltragoalSteeringProposal(+ const audit = validateUlwLoopSteeringProposal(plan(),steering({ kind: "revise_criterion", goalId: "G001", criterionId: "C001", ...update }),);@@ -146,16 +143,68 @@ describe("validateUltragoalSteeringProposal", () => {["unknown criterionId", { goalId: "G001", criterionId: "missing", scenario: "new" }],["no updates", { goalId: "G001", criterionId: "C001" }],])("rejects revise_criterion with %s", (_name, overrides) => {- const audit = validateUltragoalSteeringProposal(plan(), steering({ kind: "revise_criterion", ...overrides }));+ const audit = validateUlwLoopSteeringProposal(plan(), steering({ kind: "revise_criterion", ...overrides }));expect(audit.invariant.accepted).toBe(false);});});-describe("steerUltragoal", () => {+describe("steerUlwLoop", () => {+ describe("steering-created goals", () => {+ function sluggedPlan(): UlwLoopPlan {+ return plan({+ goals: [+ goal({ id: "G001-goal-a", title: "Goal A", objective: "Do A" }),+ goal({ id: "G002-goal-b", title: "Goal B", objective: "Do B" }),+ ],+ });+ }++ it("add_subgoal: uses next numeric id + default success criteria", async () => {+ const repoRoot = await repoWithPlan(sluggedPlan());+ const result = await steerUlwLoop(repoRoot, steering({ idempotencyKey: "slug-add" }));+ expect(result.plan.goals.at(-1)).toMatchObject({+ id: "G003",+ successCriteria: [{ id: "C001" }, { id: "C002" }, { id: "C003" }],+ });+ });++ it("split_subgoal: replacement goals use default success criteria", async () => {+ const repoRoot = await repoWithPlan(sluggedPlan());+ const result = await steerUlwLoop(+ repoRoot,+ steering({+ kind: "split_subgoal",+ targetGoalId: "G001-goal-a",+ childGoals: [{ title: "Child A", objective: "Do child A" }],+ }),+ );+ expect(result.plan.goals[1]).toMatchObject({+ id: "G003",+ successCriteria: [{ id: "C001" }, { id: "C002" }, { id: "C003" }],+ });+ });++ it("mark_blocked_superseded: replacement goals use default success criteria", async () => {+ const repoRoot = await repoWithPlan(sluggedPlan());+ const result = await steerUlwLoop(+ repoRoot,+ steering({+ kind: "mark_blocked_superseded",+ targetGoalId: "G001-goal-a",+ childGoals: [{ title: "Replacement", objective: "Replace blocked path" }],+ }),+ );+ expect(result.plan.goals[1]).toMatchObject({+ id: "G003",+ successCriteria: [{ id: "C001" }, { id: "C002" }, { id: "C003" }],+ });+ });+ });+it("add_subgoal: appends goal + ledger entry", async () => {const repoRoot = await repoWithPlan();- const result = await steerUltragoal(repoRoot, steering({ idempotencyKey: "add" }));- const persisted = await readUltragoalPlan(repoRoot);+ const result = await steerUlwLoop(repoRoot, steering({ idempotencyKey: "add" }));+ const persisted = await readUlwLoopPlan(repoRoot);expect(result.accepted).toBe(true);expect(persisted.goals.at(-1)).toMatchObject({ id: "G004", title: "Investigate auth blocker" });expect((await readSteeringLedgerEntries(repoRoot)).at(-1)).toMatchObject({@@ -166,7 +215,7 @@ describe("steerUltragoal", () => {it("split_subgoal: creates children + supersedes parent", async () => {const repoRoot = await repoWithPlan();- const result = await steerUltragoal(+ const result = await steerUlwLoop(repoRoot,steering({kind: "split_subgoal",@@ -180,7 +229,7 @@ describe("steerUltragoal", () => {it("reorder_pending: changes goal order", async () => {const repoRoot = await repoWithPlan();- const result = await steerUltragoal(+ const result = await steerUlwLoop(repoRoot,steering({ kind: "reorder_pending", pendingOrder: ["G002", "G001"] }),);@@ -189,7 +238,7 @@ describe("steerUltragoal", () => {it("revise_pending_wording: updates title/objective", async () => {const repoRoot = await repoWithPlan();- const result = await steerUltragoal(+ const result = await steerUlwLoop(repoRoot,steering({kind: "revise_pending_wording",@@ -207,14 +256,14 @@ describe("steerUltragoal", () => {it("annotate_ledger: ledger-only, no plan mutation", async () => {const seed = plan();const repoRoot = await repoWithPlan(seed);- const result = await steerUltragoal(repoRoot, steering({ kind: "annotate_ledger" }));+ const result = await steerUlwLoop(repoRoot, steering({ kind: "annotate_ledger" }));expect(result.plan.goals).toEqual(seed.goals);- expect(await readFile(ultragoalGoalsPath(repoRoot), "utf8")).toBe(`${JSON.stringify(seed, null, 2)}\n`);+ expect(await readFile(ulwLoopGoalsPath(repoRoot), "utf8")).toBe(`${JSON.stringify(seed, null, 2)}\n`);});it("mark_blocked_superseded with children: supersede + replace", async () => {const repoRoot = await repoWithPlan();- const result = await steerUltragoal(+ const result = await steerUlwLoop(repoRoot,steering({kind: "mark_blocked_superseded",@@ -228,7 +277,7 @@ describe("steerUltragoal", () => {it("mark_blocked_superseded without children: blocks goal", async () => {const repoRoot = await repoWithPlan();- const result = await steerUltragoal(+ const result = await steerUlwLoop(repoRoot,steering({ kind: "mark_blocked_superseded", targetGoalId: "G001", blockedReason: "external blocker" }),);@@ -242,7 +291,7 @@ describe("steerUltragoal", () => {it.each(["pending", "pass"] as const)("revise_criterion: works on a %s criterion", async (status) => {const repoRoot = await repoWithPlan();const criterionId = status === "pending" ? "C001" : "C002";- const result = await steerUltragoal(+ const result = await steerUlwLoop(repoRoot,steering({kind: "revise_criterion",@@ -261,7 +310,7 @@ describe("steerUltragoal", () => {});it("revise_criterion: updates the targeted criterion in plan", () => {- const audit = validateUltragoalSteeringProposal(+ const audit = validateUlwLoopSteeringProposal(plan(),steering({ kind: "revise_criterion", goalId: "G001", criterionId: "C001", scenario: "new value" }),);@@ -275,30 +324,30 @@ describe("steerUltragoal", () => {it("idempotency: same idempotencyKey produces deduped true second time", async () => {const repoRoot = await repoWithPlan();- await steerUltragoal(repoRoot, steering({ idempotencyKey: "same-key" }));- const second = await steerUltragoal(repoRoot, steering({ idempotencyKey: "same-key" }));+ await steerUlwLoop(repoRoot, steering({ idempotencyKey: "same-key" }));+ const second = await steerUlwLoop(repoRoot, steering({ idempotencyKey: "same-key" }));expect(second.deduped).toBe(true);- expect((await readUltragoalPlan(repoRoot)).goals).toHaveLength(4);+ expect((await readUlwLoopPlan(repoRoot)).goals).toHaveLength(4);});});-describe("parseUltragoalSteeringDirective", () => {- it.each(["OMO_ULTRAGOAL_STEER", "omo.ultragoal.steer", "omo ultragoal steer"])("parses %s pattern", (marker) => {- expect(parseUltragoalSteeringDirective(`${marker}: ${JSON.stringify(steering())}`)).toMatchObject({+describe("parseUlwLoopSteeringDirective", () => {+ it.each(["OMO_ULW_LOOP_STEER", "omo.ulw-loop.steer", "omo ulw-loop steer"])("parses %s pattern", (marker) => {+ expect(parseUlwLoopSteeringDirective(`${marker}: ${JSON.stringify(steering())}`)).toMatchObject({kind: "add_subgoal",});});it("returns null when no marker", () => {- expect(parseUltragoalSteeringDirective(JSON.stringify(steering()))).toBeNull();+ expect(parseUlwLoopSteeringDirective(JSON.stringify(steering()))).toBeNull();});it("returns null when JSON malformed after marker", () => {- expect(parseUltragoalSteeringDirective("OMO_ULTRAGOAL_STEER: {bad json")).toBeNull();+ expect(parseUlwLoopSteeringDirective("OMO_ULW_LOOP_STEER: {bad json")).toBeNull();});it("returns null for deprecated markers", () => {- const marker = ["OM", "X_ULTRAGOAL_STEER"].join("");- expect(parseUltragoalSteeringDirective(`${marker}: ${JSON.stringify(steering())}`)).toBeNull();+ const marker = ["OM", "X_ULW_LOOP_STEER"].join("");+ expect(parseUlwLoopSteeringDirective(`${marker}: ${JSON.stringify(steering())}`)).toBeNull();});});diff --git a/plugins/omo/components/ultragoal/test/types.test.ts b/plugins/omo/components/ulw-loop/test/types.test.tssimilarity index 55%rename from plugins/omo/components/ultragoal/test/types.test.tsrename to plugins/omo/components/ulw-loop/test/types.test.tsindex e4d7ddfa..794f17ee 100644--- a/plugins/omo/components/ultragoal/test/types.test.ts+++ b/plugins/omo/components/ulw-loop/test/types.test.ts@@ -2,56 +2,56 @@ import { describe, expect, it } from "vitest";import {iso,- ULTRAGOAL_BRIEF,- ULTRAGOAL_CRITERION_STATUSES,- ULTRAGOAL_DIR,- ULTRAGOAL_GOALS,- ULTRAGOAL_LEDGER,- ULTRAGOAL_STEERING_MUTATION_KINDS,- ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS,- UltragoalError,+ ULW_LOOP_BRIEF,+ ULW_LOOP_CRITERION_STATUSES,+ ULW_LOOP_DIR,+ ULW_LOOP_GOALS,+ ULW_LOOP_LEDGER,+ ULW_LOOP_STEERING_MUTATION_KINDS,+ ULW_LOOP_SUCCESS_CRITERION_USER_MODELS,+ UlwLoopError,} from "../src/types.ts";-describe("ultragoal domain constants", () => {+describe("ulw-loop domain constants", () => {describe("when checking workspace paths", () => {- it("then ULTRAGOAL_DIR points to the omo workspace", () => {- expect(ULTRAGOAL_DIR).toBe(".omo/ultragoal");+ it("then ULW_LOOP_DIR points to the omo workspace", () => {+ expect(ULW_LOOP_DIR).toBe(".omo/ulw-loop");});it("then artifact filenames are stable", () => {- expect(ULTRAGOAL_BRIEF).toBe("brief.md");- expect(ULTRAGOAL_GOALS).toBe("goals.json");- expect(ULTRAGOAL_LEDGER).toBe("ledger.jsonl");+ expect(ULW_LOOP_BRIEF).toBe("brief.md");+ expect(ULW_LOOP_GOALS).toBe("goals.json");+ expect(ULW_LOOP_LEDGER).toBe("ledger.jsonl");});});describe("when checking steering mutation kinds", () => {it("then includes the new revise_criterion kind", () => {- expect(ULTRAGOAL_STEERING_MUTATION_KINDS).toContain("revise_criterion");+ expect(ULW_LOOP_STEERING_MUTATION_KINDS).toContain("revise_criterion");});it("then totals 7 kinds", () => {- expect(ULTRAGOAL_STEERING_MUTATION_KINDS).toHaveLength(7);+ expect(ULW_LOOP_STEERING_MUTATION_KINDS).toHaveLength(7);});});describe("when checking criterion user models", () => {it("then exposes 4 user models including adversarial", () => {- expect(ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS).toEqual(["happy", "edge", "regression", "adversarial"]);+ expect(ULW_LOOP_SUCCESS_CRITERION_USER_MODELS).toEqual(["happy", "edge", "regression", "adversarial"]);});});describe("when checking criterion statuses", () => {it("then exposes pending/pass/fail/blocked", () => {- expect(ULTRAGOAL_CRITERION_STATUSES).toEqual(["pending", "pass", "fail", "blocked"]);+ expect(ULW_LOOP_CRITERION_STATUSES).toEqual(["pending", "pass", "fail", "blocked"]);});});});-describe("UltragoalError", () => {+describe("UlwLoopError", () => {describe("when constructed with code", () => {it("then is an Error instance carrying the code", () => {- const err = new UltragoalError("bad", "TEST_CODE");+ const err = new UlwLoopError("bad", "TEST_CODE");expect(err).toBeInstanceOf(Error);expect(err.code).toBe("TEST_CODE");@@ -60,7 +60,7 @@ describe("UltragoalError", () => {it("then accepts optional cause + details", () => {const cause = new Error("upstream");- const err = new UltragoalError("wrap", "WRAP", { cause, details: { goalId: "G001" } });+ const err = new UlwLoopError("wrap", "WRAP", { cause, details: { goalId: "G001" } });expect(err.cause).toBe(cause);expect(err.details).toEqual({ goalId: "G001" });diff --git a/plugins/omo/components/ulw-loop/tsconfig.build.json b/plugins/omo/components/ulw-loop/tsconfig.build.jsonnew file mode 100644index 00000000..5b5bbcaf--- /dev/null+++ b/plugins/omo/components/ulw-loop/tsconfig.build.json@@ -0,0 +1,12 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "allowImportingTsExtensions": false,+ "declaration": true,+ "outDir": "dist",+ "rootDir": "src",+ "noEmit": false+ },+ "include": ["src/**/*"],+ "exclude": ["test/**/*"]+}diff --git a/plugins/omo/components/ultragoal/tsconfig.json b/plugins/omo/components/ulw-loop/tsconfig.jsonsimilarity index 100%rename from plugins/omo/components/ultragoal/tsconfig.jsonrename to plugins/omo/components/ulw-loop/tsconfig.jsondiff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/vitest.config.ts b/plugins/omo/components/ulw-loop/vitest.config.tssimilarity index 90%rename from plugins/omo/components/lsp/packages/lsp-tools-mcp/vitest.config.tsrename to plugins/omo/components/ulw-loop/vitest.config.tsindex 57bd8f12..5453488c 100644--- a/plugins/omo/components/lsp/packages/lsp-tools-mcp/vitest.config.ts+++ b/plugins/omo/components/ulw-loop/vitest.config.ts@@ -5,5 +5,6 @@ export default defineConfig({include: ["test/**/*.test.ts"],environment: "node",pool: "threads",+ isolate: true,},});diff --git a/plugins/omo/hooks/hooks.json b/plugins/omo/hooks/hooks.jsonindex d93a5d63..d5546f74 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": "loading OMO project rules"+ "statusMessage": "LazyCodex(0.1.0): Loading Project Rules"}]},@@ -16,7 +16,19 @@{"type": "command","command": "node \"${PLUGIN_ROOT}/components/telemetry/dist/cli.js\" hook session-start",- "timeout": 5+ "timeout": 5,+ "statusMessage": "LazyCodex(0.1.0): Recording Session Telemetry"+ }+ ]+ },+ {+ "matcher": "^startup$",+ "hooks": [+ {+ "type": "command",+ "command": "node \"${PLUGIN_ROOT}/scripts/auto-update.mjs\" hook session-start",+ "timeout": 5,+ "statusMessage": "LazyCodex(0.1.0): Checking Auto Update"}]}@@ -28,7 +40,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook user-prompt-submit","timeout": 10,- "statusMessage": "loading OMO project rules"+ "statusMessage": "LazyCodex(0.1.0): Loading Project Rules"}]},@@ -36,8 +48,9 @@"hooks": [{"type": "command",- "command": "python3 \"${PLUGIN_ROOT}/components/ultrawork/hooks/ultrawork-detector.py\"",- "timeout": 5+ "command": "node \"${PLUGIN_ROOT}/components/ultrawork/dist/cli.js\" hook user-prompt-submit",+ "timeout": 5,+ "statusMessage": "LazyCodex(0.1.0): Checking Ultrawork Trigger"}]},@@ -45,9 +58,33 @@"hooks": [{"type": "command",- "command": "node \"${PLUGIN_ROOT}/components/ultragoal/dist/cli.js\" hook user-prompt-submit",+ "command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook user-prompt-submit","timeout": 10,- "statusMessage": "checking OMO ultragoal steering"+ "statusMessage": "LazyCodex(0.1.0): Checking Ulw-Loop Steering"+ }+ ]+ }+ ],+ "PreToolUse": [+ {+ "matcher": "^Bash$",+ "hooks": [+ {+ "type": "command",+ "command": "node \"${PLUGIN_ROOT}/components/git-bash/dist/cli.js\" hook pre-tool-use",+ "timeout": 5,+ "statusMessage": "LazyCodex(0.1.0): Recommending Git Bash Mcp"+ }+ ]+ },+ {+ "matcher": "^create_goal$",+ "hooks": [+ {+ "type": "command",+ "command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook pre-tool-use",+ "timeout": 5,+ "statusMessage": "LazyCodex(0.1.0): Enforcing Unlimited Goal Budget"}]}@@ -60,13 +97,13 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/comment-checker/dist/cli.js\" hook post-tool-use","timeout": 30,- "statusMessage": "checking OMO comments"+ "statusMessage": "LazyCodex(0.1.0): Checking Comments"},{"type": "command","command": "node \"${PLUGIN_ROOT}/components/lsp/dist/cli.js\" hook post-tool-use","timeout": 60,- "statusMessage": "checking OMO LSP diagnostics"+ "statusMessage": "LazyCodex(0.1.0): Checking LSP Diagnostics"}]},@@ -77,12 +114,23 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook post-tool-use","timeout": 10,- "statusMessage": "matching OMO project rules"+ "statusMessage": "LazyCodex(0.1.0): Matching Project Rules"}]}],"PostCompact": [+ {+ "matcher": "manual|auto",+ "hooks": [+ {+ "type": "command",+ "command": "node \"${PLUGIN_ROOT}/components/git-bash/dist/cli.js\" hook post-compact",+ "timeout": 5,+ "statusMessage": "LazyCodex(0.1.0): Resetting Git Bash Mcp Reminder"+ }+ ]+ },{"matcher": "manual|auto","hooks": [@@ -90,7 +138,42 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook post-compact","timeout": 10,- "statusMessage": "resetting OMO project rule cache"+ "statusMessage": "LazyCodex(0.1.0): Resetting Project Rule Cache"+ }+ ]+ },+ {+ "matcher": "manual|auto",+ "hooks": [+ {+ "type": "command",+ "command": "node \"${PLUGIN_ROOT}/components/lsp/dist/cli.js\" hook post-compact",+ "timeout": 5,+ "statusMessage": "LazyCodex(0.1.0): Resetting LSP Diagnostics Cache"+ }+ ]+ }+ ],+ "Stop": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "node \"${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js\" hook stop",+ "timeout": 10,+ "statusMessage": "LazyCodex(0.1.0): Checking Start-Work Continuation"+ }+ ]+ }+ ],+ "SubagentStop": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "node \"${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js\" hook subagent-stop",+ "timeout": 10,+ "statusMessage": "LazyCodex(0.1.0): Checking Start-Work Continuation"}]}diff --git a/plugins/omo/model-catalog.json b/plugins/omo/model-catalog.jsonnew file mode 100644index 00000000..7e13b4b3--- /dev/null+++ b/plugins/omo/model-catalog.json@@ -0,0 +1,49 @@+{+ "version": "2026-06-03.gpt-5.5-400k",+ "current": {+ "model": "gpt-5.5",+ "model_context_window": 400000,+ "model_reasoning_effort": "high",+ "plan_mode_reasoning_effort": "xhigh"+ },+ "roles": {+ "default": {+ "model": "gpt-5.5",+ "model_context_window": 400000,+ "model_reasoning_effort": "high",+ "plan_mode_reasoning_effort": "xhigh"+ },+ "verifier": {+ "model": "gpt-5.5",+ "model_reasoning_effort": "xhigh"+ },+ "worker": {+ "model": "gpt-5.4",+ "model_reasoning_effort": "high"+ }+ },+ "managedProfiles": [+ {+ "version": "legacy.gpt-5.2",+ "match": {+ "model": "gpt-5.2"+ }+ },+ {+ "version": "legacy.gpt-5.4-1m",+ "match": {+ "model": "gpt-5.4",+ "model_context_window": 1000000,+ "model_reasoning_effort": "high",+ "plan_mode_reasoning_effort": "xhigh"+ }+ },+ {+ "version": "legacy.gpt-5.5-272k",+ "match": {+ "model": "gpt-5.5",+ "model_context_window": 272000+ }+ }+ ]+}diff --git a/plugins/omo/package-lock.json b/plugins/omo/package-lock.jsonindex 40f69866..e9ed8fa8 100644--- a/plugins/omo/package-lock.json+++ b/plugins/omo/package-lock.json@@ -1,28 +1,53 @@{- "name": "@code-yeongyu/omo-codex-plugin",+ "name": "@sisyphuslabs/omo-codex-plugin","version": "0.1.0","lockfileVersion": 3,"requires": true,"packages": {"": {- "name": "@code-yeongyu/omo-codex-plugin",+ "name": "@sisyphuslabs/omo-codex-plugin","version": "0.1.0","workspaces": ["components/comment-checker",+ "components/git-bash","components/rules","components/lsp",- "components/lsp/packages/lsp-tools-mcp","components/telemetry",- "components/ultragoal",+ "components/start-work-continuation",+ "components/ulw-loop","components/ultrawork"- ]+ ],+ "dependencies": {+ "@oh-my-opencode/shared-skills": "file:../../shared-skills"+ }+ },+ "../../lsp-tools-mcp": {+ "name": "@code-yeongyu/lsp-tools-mcp",+ "version": "0.1.0",+ "license": "MIT",+ "bin": {+ "omo-lsp": "dist/cli.js"+ },+ "devDependencies": {+ "@biomejs/biome": "2.4.15",+ "@types/node": "^25.7.0",+ "typescript": "^6.0.3",+ "vitest": "^4.1.5"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "../../shared-skills": {+ "name": "@oh-my-opencode/shared-skills",+ "version": "0.1.0"},"components/comment-checker": {"name": "@code-yeongyu/codex-comment-checker","version": "0.1.1","license": "MIT","bin": {- "codex-comment-checker": "dist/cli.js"+ "omo-comment-checker": "dist/cli.js"},"devDependencies": {"@biomejs/biome": "2.4.15",@@ -37,15 +62,29 @@"@code-yeongyu/comment-checker": "^0.8.0"}},+ "components/git-bash": {+ "name": "@sisyphuslabs/codex-git-bash-hook",+ "version": "0.1.0",+ "bin": {+ "omo-git-bash-hook": "dist/cli.js"+ },+ "devDependencies": {+ "@types/node": "^25.7.0",+ "typescript": "^6.0.3"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },"components/lsp": {"name": "@code-yeongyu/codex-lsp","version": "0.2.0","license": "MIT","dependencies": {- "@code-yeongyu/lsp-tools-mcp": "file:./packages/lsp-tools-mcp"+ "@code-yeongyu/lsp-tools-mcp": "file:../../../../lsp-tools-mcp"},"bin": {- "codex-lsp": "dist/cli.js"+ "omo-lsp": "dist/cli.js"},"devDependencies": {"@biomejs/biome": "2.4.15",@@ -57,16 +96,20 @@"node": ">=20.0.0"}},- "components/lsp/packages/lsp-tools-mcp": {- "name": "@code-yeongyu/lsp-tools-mcp",+ "components/rules": {+ "name": "@code-yeongyu/codex-rules","version": "0.1.0","license": "MIT",+ "dependencies": {+ "picomatch": "^4.0.3"+ },"bin": {- "lsp-tools-mcp": "dist/cli.js"+ "omo-rules": "dist/cli.js"},"devDependencies": {"@biomejs/biome": "2.4.15","@types/node": "^25.7.0",+ "@types/picomatch": "^4.0.0","typescript": "^6.0.3","vitest": "^4.1.5"},@@ -74,20 +117,16 @@"node": ">=20.0.0"}},- "components/rules": {- "name": "@code-yeongyu/codex-rules",+ "components/start-work-continuation": {+ "name": "@code-yeongyu/codex-start-work-continuation","version": "0.1.0","license": "MIT",- "dependencies": {- "picomatch": "^4.0.3"- },"bin": {- "codex-rules": "dist/cli.js"+ "omo-start-work-continuation": "dist/cli.js"},"devDependencies": {"@biomejs/biome": "2.4.15","@types/node": "^25.7.0",- "@types/picomatch": "^4.0.0","typescript": "^6.0.3","vitest": "^4.1.5"},@@ -103,7 +142,7 @@"posthog-node": "^5.34.3"},"bin": {- "codex-telemetry": "dist/cli.js"+ "omo-telemetry": "dist/cli.js"},"devDependencies": {"@biomejs/biome": "2.4.15",@@ -115,12 +154,12 @@"node": ">=20.0.0"}},- "components/ultragoal": {- "name": "@code-yeongyu/codex-ultragoal",+ "components/ultrawork": {+ "name": "@code-yeongyu/codex-ultrawork","version": "0.1.0","license": "MIT","bin": {- "omo": "dist/cli.js"+ "omo-ultrawork": "dist/cli.js"},"devDependencies": {"@biomejs/biome": "2.4.15",@@ -132,10 +171,22 @@"node": ">=20.0.0"}},- "components/ultrawork": {- "name": "@code-yeongyu/codex-ultrawork",+ "components/ulw-loop": {+ "name": "@code-yeongyu/codex-ulw-loop","version": "0.1.0",- "license": "MIT"+ "license": "MIT",+ "bin": {+ "omo": "dist/cli.js"+ },+ "devDependencies": {+ "@biomejs/biome": "2.4.15",+ "@types/node": "^25.7.0",+ "typescript": "^6.0.3",+ "vitest": "^4.1.5"+ },+ "engines": {+ "node": ">=20.0.0"+ }},"node_modules/@biomejs/biome": {"version": "2.4.15",@@ -324,18 +375,22 @@"resolved": "components/rules","link": true},- "node_modules/@code-yeongyu/codex-telemetry": {- "resolved": "components/telemetry",+ "node_modules/@code-yeongyu/codex-start-work-continuation": {+ "resolved": "components/start-work-continuation","link": true},- "node_modules/@code-yeongyu/codex-ultragoal": {- "resolved": "components/ultragoal",+ "node_modules/@code-yeongyu/codex-telemetry": {+ "resolved": "components/telemetry","link": true},"node_modules/@code-yeongyu/codex-ultrawork": {"resolved": "components/ultrawork","link": true},+ "node_modules/@code-yeongyu/codex-ulw-loop": {+ "resolved": "components/ulw-loop",+ "link": true+ },"node_modules/@code-yeongyu/comment-checker": {"version": "0.8.0","resolved": "https://registry.npmjs.org/@code-yeongyu/comment-checker/-/comment-checker-0.8.0.tgz",@@ -351,7 +406,7 @@}},"node_modules/@code-yeongyu/lsp-tools-mcp": {- "resolved": "components/lsp/packages/lsp-tools-mcp",+ "resolved": "../../lsp-tools-mcp","link": true},"node_modules/@emnapi/core": {@@ -414,6 +469,10 @@"@emnapi/runtime": "^1.7.1"}},+ "node_modules/@oh-my-opencode/shared-skills": {+ "resolved": "../../shared-skills",+ "link": true+ },"node_modules/@oxc-project/types": {"version": "0.132.0","resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.132.0.tgz",@@ -425,18 +484,18 @@}},"node_modules/@posthog/core": {- "version": "1.29.9",- "resolved": "https://registry.npmjs.org/@posthog/core/-/core-1.29.9.tgz",- "integrity": "sha512-DjvuIyBZ2Z/gBhtZlITlM2D8PlnMsHSQ1D78dbUYoVsgGguvanpJTobZObjLlFkybyvfZFYkpoJkFNI/2Pw4IQ==",+ "version": "1.29.13",+ "resolved": "https://registry.npmjs.org/@posthog/core/-/core-1.29.13.tgz",+ "integrity": "sha512-7Me5zaeAue/wmA364Go8ChYbsVAfNAHbtDxXopWu3D6hq9PVScUcauRgjD1njgvP8NzN91SrIllE+pri3XvJVw==","license": "MIT","dependencies": {- "@posthog/types": "1.376.0"+ "@posthog/types": "1.376.4"}},"node_modules/@posthog/types": {- "version": "1.376.0",- "resolved": "https://registry.npmjs.org/@posthog/types/-/types-1.376.0.tgz",- "integrity": "sha512-gbFfxCuZDs/D4QZMwdE+smD1jsuqgGpS6yKGHZZ19foxMy8RYHsU1E47iG1b88n/uN02fAabLibVwuxLtq8juw==",+ "version": "1.376.4",+ "resolved": "https://registry.npmjs.org/@posthog/types/-/types-1.376.4.tgz",+ "integrity": "sha512-EoDEvA925lf6yxPpbP4wozlXgu4b9WEqxZlFBUDd4k2akP5R/RWyHpvQT8aYyfY6BtSLn8TnVwxPQOM4b90isA==","license": "MIT"},"node_modules/@rolldown/binding-android-arm64": {@@ -721,6 +780,10 @@"dev": true,"license": "MIT"},+ "node_modules/@sisyphuslabs/codex-git-bash-hook": {+ "resolved": "components/git-bash",+ "link": true+ },"node_modules/@standard-schema/spec": {"version": "1.1.0","resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",@@ -1360,12 +1423,12 @@}},"node_modules/posthog-node": {- "version": "5.35.2",- "resolved": "https://registry.npmjs.org/posthog-node/-/posthog-node-5.35.2.tgz",- "integrity": "sha512-YwzkogTUrsFeUnJJH17p3zoZBFaHIh6swYoLV4Ic5pmd8fIVTz8w7NsHR7eWmJlqYe/+Hqo1acGN1jclNUbz3A==",+ "version": "5.35.6",+ "resolved": "https://registry.npmjs.org/posthog-node/-/posthog-node-5.35.6.tgz",+ "integrity": "sha512-LwoXnR89A0l75jvFrXjtsAs0BbpyCjnwY8YIUkZT91rt1YnIUfBYiLj7qoUYApdNgesgWQQHqLXxLYX59a6ZYw==","license": "MIT","dependencies": {- "@posthog/core": "1.29.9"+ "@posthog/core": "1.29.13"},"engines": {"node": "^20.20.0 || >=22.22.0"@@ -1452,9 +1515,9 @@"license": "MIT"},"node_modules/tinyexec": {- "version": "1.2.2",- "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.2.tgz",- "integrity": "sha512-M/Q0B2cp4K7kynaT/vnED1j8TlLY+Pp7C6Wl2bl/7u/F0mUVwdyOpwomQb8JpYLitHUssAJRmLZdMCGsrx7i+g==",+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.3.tgz",+ "integrity": "sha512-g62dB+w1/OEFnPvmX0yd/HnetYITOL+1nJW7kitOycOeAvmbWC/nu0fwmmQ/kupNojqExzyC/T++pST/jRJ2mQ==","dev": true,"license": "MIT","engines": {diff --git a/plugins/omo/package.json b/plugins/omo/package.jsonindex 5b88cc7d..08788130 100644--- a/plugins/omo/package.json+++ b/plugins/omo/package.json@@ -1,5 +1,5 @@{- "name": "@code-yeongyu/omo-codex-plugin",+ "name": "@sisyphuslabs/omo-codex-plugin","version": "0.1.0","description": "Aggregate Codex plugin root for OMO components.","type": "module",@@ -7,16 +7,21 @@"private": true,"workspaces": ["components/comment-checker",+ "components/git-bash","components/rules","components/lsp",- "components/lsp/packages/lsp-tools-mcp","components/telemetry",- "components/ultragoal",+ "components/start-work-continuation",+ "components/ulw-loop","components/ultrawork"],+ "dependencies": {+ "@oh-my-opencode/shared-skills": "file:../../shared-skills"+ },"scripts": {- "build": "node scripts/sync-skills.mjs && node ../scripts/sync-telemetry-component.mjs && npm run build --workspaces --if-present",+ "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","check": "npm run build && npm test",+ "sync:hooks": "node scripts/sync-hook-status-messages.mjs","sync:skills": "node scripts/sync-skills.mjs","test": "node --test test/*.test.mjs"}diff --git a/plugins/omo/scripts/auto-update.mjs b/plugins/omo/scripts/auto-update.mjsnew file mode 100644index 00000000..77609c64--- /dev/null+++ b/plugins/omo/scripts/auto-update.mjs@@ -0,0 +1,159 @@+#!/usr/bin/env node++import { spawn, spawnSync } from "node:child_process";+import { mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises";+import { homedir } from "node:os";+import { dirname, join } from "node:path";+import { pathToFileURL } from "node:url";+import { migrateCodexConfig } from "./migrate-codex-config.mjs";++const DEFAULT_INTERVAL_MS = 24 * 60 * 60 * 1_000;+const DEFAULT_LOCK_STALE_MS = 10 * 60 * 1_000;++export function resolveAutoUpdatePlan({ env = process.env, now = Date.now(), lastCheckedAt } = {}) {+ if (env.LAZYCODEX_AUTO_UPDATE_DISABLED === "1" || env.OMO_CODEX_AUTO_UPDATE_DISABLED === "1") {+ return { shouldRun: false, reason: "disabled" };+ }++ const intervalMs = parsePositiveInteger(env.LAZYCODEX_AUTO_UPDATE_INTERVAL_MS, DEFAULT_INTERVAL_MS);+ if (typeof lastCheckedAt === "number" && intervalMs > 0 && now - lastCheckedAt < intervalMs) {+ return { shouldRun: false, reason: "throttled" };+ }++ return {+ shouldRun: true,+ command: resolveCommand(env),+ args: resolveArgs(env),+ env: {+ ...env,+ LAZYCODEX_AUTO_UPDATE_DISABLED: "1",+ OMO_CODEX_AUTO_UPDATE_DISABLED: "1",+ },+ };+}++export async function runAutoUpdateCheck({ env = process.env, now = Date.now() } = {}) {+ await runConfigMigration({ env });+ const statePath = resolveStatePath(env);+ const state = await readState(statePath);+ const plan = resolveAutoUpdatePlan({ env, now, lastCheckedAt: state.lastCheckedAt });+ if (!plan.shouldRun) return { started: false, reason: plan.reason };++ const lock = await acquireLock(resolveLockPath(env, statePath), now, env);+ if (lock === null) return { started: false, reason: "locked" };+ try {+ await writeState(statePath, { lastCheckedAt: now });+ if (env.LAZYCODEX_AUTO_UPDATE_WAIT === "1") {+ const result = spawnSync(plan.command, plan.args, {+ env: plan.env,+ stdio: "ignore",+ });+ return { started: true, status: result.status ?? 0 };+ }++ const child = spawn(plan.command, plan.args, {+ env: plan.env,+ stdio: "ignore",+ detached: true,+ });+ child.unref();+ return { started: true };+ } finally {+ await lock.release();+ }+}++async function runConfigMigration({ env }) {+ if (env.LAZYCODEX_CONFIG_MIGRATION_DISABLED === "1" || env.OMO_CODEX_CONFIG_MIGRATION_DISABLED === "1") return;+ try {+ await migrateCodexConfig({ env });+ } catch (error) {+ if (!(error instanceof Error)) throw error;+ return;+ }+}++function resolveCommand(env) {+ return env.LAZYCODEX_AUTO_UPDATE_COMMAND?.trim() || "npx";+}++function resolveArgs(env) {+ if (env.LAZYCODEX_AUTO_UPDATE_ARGS_JSON) {+ const parsed = JSON.parse(env.LAZYCODEX_AUTO_UPDATE_ARGS_JSON);+ if (!Array.isArray(parsed) || parsed.some((value) => typeof value !== "string")) {+ throw new TypeError("LAZYCODEX_AUTO_UPDATE_ARGS_JSON must be a JSON string array");+ }+ return parsed;+ }+ return ["--yes", "lazycodex-ai@latest", "install", "--no-tui", "--skip-auth"];+}++function resolveStatePath(env) {+ if (env.LAZYCODEX_AUTO_UPDATE_STATE_PATH?.trim()) return env.LAZYCODEX_AUTO_UPDATE_STATE_PATH;+ const dataRoot = env.PLUGIN_DATA?.trim() || join(homedir(), ".local", "share", "lazycodex");+ return join(dataRoot, "auto-update.json");+}++function resolveLockPath(env, statePath) {+ if (env.LAZYCODEX_AUTO_UPDATE_LOCK_PATH?.trim()) return env.LAZYCODEX_AUTO_UPDATE_LOCK_PATH;+ return `${statePath}.lock`;+}++async function acquireLock(lockPath, now, env) {+ await mkdir(dirname(lockPath), { recursive: true });+ const staleMs = parsePositiveInteger(env.LAZYCODEX_AUTO_UPDATE_LOCK_STALE_MS, DEFAULT_LOCK_STALE_MS);+ try {+ const handle = await open(lockPath, "wx");+ await handle.writeFile(`${now}\n`);+ await handle.close();+ return {+ release: () => rm(lockPath, { force: true }),+ };+ } catch (error) {+ if (!(error instanceof Error && "code" in error && error.code === "EEXIST")) throw error;+ if (!(await removeStaleLock(lockPath, now, staleMs))) return null;+ return acquireLock(lockPath, now, { ...env, LAZYCODEX_AUTO_UPDATE_LOCK_STALE_MS: "0" });+ }+}++async function removeStaleLock(lockPath, now, staleMs) {+ if (staleMs <= 0) return false;+ try {+ const lockStat = await stat(lockPath);+ if (now - lockStat.mtimeMs < staleMs) return false;+ await rm(lockPath, { force: true });+ return true;+ } catch (error) {+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return true;+ throw error;+ }+}++async function readState(statePath) {+ try {+ const raw = await readFile(statePath, "utf8");+ const parsed = JSON.parse(raw);+ return typeof parsed === "object" && parsed !== null ? parsed : {};+ } catch (error) {+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return {};+ return {};+ }+}++async function writeState(statePath, state) {+ await mkdir(dirname(statePath), { recursive: true });+ await writeFile(statePath, `${JSON.stringify(state, null, 2)}\n`);+}++function parsePositiveInteger(value, fallback) {+ if (value === undefined || value === "") return fallback;+ const parsed = Number.parseInt(value, 10);+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : 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);+ });+}diff --git a/plugins/omo/scripts/build-bundled-mcp-runtimes.mjs b/plugins/omo/scripts/build-bundled-mcp-runtimes.mjsnew file mode 100644index 00000000..b3ee50c9--- /dev/null+++ b/plugins/omo/scripts/build-bundled-mcp-runtimes.mjs@@ -0,0 +1,65 @@+#!/usr/bin/env node+import { spawnSync } from "node:child_process";+import { existsSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++const pluginRoot = dirname(dirname(fileURLToPath(import.meta.url)));+const repoPackagesRoot = join(pluginRoot, "..", "..");++const runtimes = [+ {+ label: "lsp-tools-mcp",+ packageRoot: join(repoPackagesRoot, "lsp-tools-mcp"),+ requiredOutputs: ["dist/cli.js", "dist/tools.js"],+ },+ {+ label: "ast-grep-mcp",+ packageRoot: join(repoPackagesRoot, "ast-grep-mcp"),+ requiredOutputs: ["dist/cli.js"],+ },+ {+ label: "git-bash-mcp",+ packageRoot: join(repoPackagesRoot, "git-bash-mcp"),+ requiredOutputs: ["dist/cli.js"],+ },+];++for (const runtime of runtimes) {+ buildRuntime(runtime);+}++function buildRuntime(runtime) {+ if (hasBundledDist(runtime)) {+ console.log(`Using bundled ${runtime.label} dist`);+ return;+ }++ if (!existsSync(join(runtime.packageRoot, "package.json"))) {+ assertBundledDist(runtime);+ console.log(`Using bundled ${runtime.label} dist`);+ return;+ }++ const result = spawnSync("npm", ["run", "build"], {+ cwd: runtime.packageRoot,+ shell: process.platform === "win32",+ stdio: "inherit",+ });+ if (result.error !== undefined) throw result.error;+ if (result.status !== 0) process.exit(result.status ?? 1);+}++function hasBundledDist(runtime) {+ return runtime.requiredOutputs.every((output) => existsSync(join(runtime.packageRoot, output)));+}++function assertBundledDist(runtime) {+ const missingOutputs = runtime.requiredOutputs.filter((output) => !existsSync(join(runtime.packageRoot, output)));+ if (missingOutputs.length === 0) return;+ console.error(`Missing bundled ${runtime.label} outputs:`);+ for (const output of missingOutputs) {+ console.error(` ${join(runtime.packageRoot, output)}`);+ }+ process.exit(1);+}diff --git a/plugins/omo/scripts/build-components.mjs b/plugins/omo/scripts/build-components.mjsnew file mode 100644index 00000000..9e719d65--- /dev/null+++ b/plugins/omo/scripts/build-components.mjs@@ -0,0 +1,24 @@+#!/usr/bin/env node+import { spawnSync } from "node:child_process";+import { readFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++const root = dirname(dirname(fileURLToPath(import.meta.url)));+const packageJson = JSON.parse(await readFile(join(root, "package.json"), "utf8"));+const workspaces = Array.isArray(packageJson.workspaces) ? packageJson.workspaces : [];++for (const workspace of workspaces) {+ if (typeof workspace !== "string" || !workspace.startsWith("components/")) continue;+ const workspacePackageJson = JSON.parse(await readFile(join(root, workspace, "package.json"), "utf8"));+ if (typeof workspacePackageJson.scripts?.build !== "string") continue;++ console.log(`Building ${workspace}`);+ const result = spawnSync("npm", ["run", "--workspace", workspace, "build"], {+ cwd: root,+ shell: process.platform === "win32",+ stdio: "inherit",+ });+ if (result.error !== undefined) throw result.error;+ if (result.status !== 0) process.exit(result.status ?? 1);+}diff --git a/plugins/omo/scripts/hook-status-message.mjs b/plugins/omo/scripts/hook-status-message.mjsnew file mode 100644index 00000000..e7ba53ca--- /dev/null+++ b/plugins/omo/scripts/hook-status-message.mjs@@ -0,0 +1,46 @@+const PRODUCT_NAME = "LazyCodex";++const WORD_OVERRIDES = new Map([+ ["lsp", "LSP"],+ ["ulw-loop", "Ulw-Loop"],+]);++export function formatLazyCodexHookStatusMessage(version, label) {+ return `${PRODUCT_NAME}(${normalizeVersion(version)}): ${normalizeLazyCodexHookStatusLabel(label)}`;+}++export function normalizeLazyCodexHookStatusLabel(label) {+ const parsed = parseLazyCodexHookStatusMessage(label);+ const rawLabel = parsed === null ? label : parsed.label;+ const normalized = rawLabel.replace(/\bOMO\b/gi, " ").replace(/\s+/g, " ").trim();+ if (normalized.length === 0) return "";+ return normalized+ .split(" ")+ .map(formatWord)+ .join(" ");+}++export function parseLazyCodexHookStatusMessage(message) {+ const match = /^LazyCodex\(([^)]+)\):\s+(.+)$/.exec(message.trim());+ if (match === null) return null;+ const [, version, label] = match;+ return { version, label };+}++function normalizeVersion(version) {+ const normalized = version.trim();+ return normalized.length === 0 ? "local" : normalized;+}++function formatWord(word) {+ const lower = word.toLowerCase();+ const override = WORD_OVERRIDES.get(lower);+ if (override !== undefined) return override;+ if (word.includes("-")) {+ return word+ .split("-")+ .map(formatWord)+ .join("-");+ }+ return `${lower.slice(0, 1).toUpperCase()}${lower.slice(1)}`;+}diff --git a/plugins/omo/scripts/migrate-codex-config.mjs b/plugins/omo/scripts/migrate-codex-config.mjsnew file mode 100644index 00000000..3c481f72--- /dev/null+++ b/plugins/omo/scripts/migrate-codex-config.mjs@@ -0,0 +1,269 @@+#!/usr/bin/env node++import { mkdir, readFile, stat, writeFile } from "node:fs/promises";+import { homedir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { pathToFileURL } from "node:url";++const FALLBACK_CATALOG = {+ version: "fallback.gpt-5.5-400k",+ current: {+ model: "gpt-5.5",+ model_context_window: 400_000,+ model_reasoning_effort: "high",+ plan_mode_reasoning_effort: "xhigh",+ },+ roles: {+ default: {+ model: "gpt-5.5",+ model_context_window: 400_000,+ model_reasoning_effort: "high",+ plan_mode_reasoning_effort: "xhigh",+ },+ verifier: { model: "gpt-5.5", model_reasoning_effort: "xhigh" },+ worker: { model: "gpt-5.4", model_reasoning_effort: "high" },+ },+ managedProfiles: [+ { version: "legacy.gpt-5.2", match: { model: "gpt-5.2" } },+ {+ version: "legacy.gpt-5.4-1m",+ match: {+ model: "gpt-5.4",+ model_context_window: 1_000_000,+ model_reasoning_effort: "high",+ plan_mode_reasoning_effort: "xhigh",+ },+ },+ ],+};++const MANAGED_KEYS = ["model", "model_context_window", "model_reasoning_effort", "plan_mode_reasoning_effort"];++export async function migrateCodexConfig({ env = process.env, cwd = process.cwd() } = {}) {+ const catalog = await readModelCatalog(env);+ const statePath = resolveStatePath(env);+ const state = await readState(statePath);+ const paths = await configPaths({ env, cwd });+ const changed = [];+ const nextState = { catalogVersion: catalog.version, files: {} };+ for (const configPath of paths) {+ const result = await migrateConfigFile(configPath, {+ catalog,+ previousState: state.files?.[configPath],+ });+ if (result.changed) changed.push(configPath);+ nextState.files[configPath] = {+ catalogVersion: catalog.version,+ written: result.written,+ managed: result.managed,+ };+ }+ await writeState(statePath, nextState);+ return { changed };+}++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: false };+ 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 };+}++export function ensureCodexReasoningConfig(config, profile = FALLBACK_CATALOG.current) {+ let next = replaceOrInsertRootSetting(config, "model", JSON.stringify(profile.model));+ next = replaceOrInsertRootSetting(next, "model_context_window", profile.model_context_window.toString());+ next = replaceOrInsertRootSetting(next, "model_reasoning_effort", JSON.stringify(profile.model_reasoning_effort));+ next = replaceOrInsertRootSetting(next, "plan_mode_reasoning_effort", JSON.stringify(profile.plan_mode_reasoning_effort));+ return next;+}++export async function readModelCatalog(env = process.env) {+ const catalogPath = env.LAZYCODEX_MODEL_CATALOG_PATH?.trim() || join(dirname(fileURLToPath(import.meta.url)), "..", "model-catalog.json");+ try {+ return parseCatalog(JSON.parse(await readFile(catalogPath, "utf8"))) ?? FALLBACK_CATALOG;+ } catch (error) {+ if (error instanceof Error) return FALLBACK_CATALOG;+ throw error;+ }+}++function shouldApplyCatalog(config, catalog, previousState) {+ const current = readRootSettings(config);+ if (Object.keys(current).length === 0) return { apply: true, reason: "empty" };+ if (matchesProfile(current, catalog.current)) return { apply: false, reason: "current" };+ if (previousState?.managed === true && matchesProfile(current, previousState.written)) {+ return { apply: true, reason: "managed-state" };+ }+ for (const profile of catalog.managedProfiles) {+ if (matchesProfile(current, profile.match)) return { apply: true, reason: profile.version };+ }+ return { apply: false, reason: "user-modified" };+}++function matchesProfile(current, profile) {+ if (!isRecord(profile)) return false;+ for (const [key, value] of Object.entries(profile)) {+ if (current[key] !== value) return false;+ }+ return true;+}++function readRootSettings(config) {+ const settings = {};+ for (const line of config.split(/\n/)) {+ if (isSectionHeader(line)) break;+ for (const key of MANAGED_KEYS) {+ if (!isRootSetting(line, key)) continue;+ const value = parseTomlScalar(line.slice(line.indexOf("=") + 1));+ if (value !== undefined) settings[key] = value;+ }+ }+ return settings;+}++function parseTomlScalar(value) {+ const trimmed = value.trim();+ if (trimmed.startsWith('"') && trimmed.endsWith('"')) {+ try {+ return JSON.parse(trimmed);+ } catch (error) {+ if (error instanceof SyntaxError) return undefined;+ throw error;+ }+ }+ const numeric = Number(trimmed);+ return Number.isFinite(numeric) ? numeric : undefined;+}++function parseCatalog(value) {+ if (!isRecord(value) || !isRecord(value.current) || !Array.isArray(value.managedProfiles)) return null;+ if (typeof value.version !== "string" || !isReasoningProfile(value.current)) return null;+ const managedProfiles = [];+ for (const profile of value.managedProfiles) {+ if (!isRecord(profile) || typeof profile.version !== "string" || !isRecord(profile.match)) return null;+ managedProfiles.push({ version: profile.version, match: profile.match });+ }+ return { version: value.version, current: value.current, managedProfiles, roles: isRecord(value.roles) ? value.roles : {} };+}++function isReasoningProfile(value) {+ return (+ isRecord(value) &&+ typeof value.model === "string" &&+ typeof value.model_context_window === "number" &&+ typeof value.model_reasoning_effort === "string" &&+ typeof value.plan_mode_reasoning_effort === "string"+ );+}++function isRecord(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++async function configPaths({ env, cwd }) {+ const codexHome = resolve(env.CODEX_HOME?.trim() || join(homedir(), ".codex"));+ const paths = new Set([join(codexHome, "config.toml")]);+ for (const projectConfig of projectConfigPaths({ cwd, stopAt: homedir() })) {+ if (await pathExists(projectConfig)) paths.add(projectConfig);+ }+ return [...paths];+}++function projectConfigPaths({ cwd, stopAt }) {+ const paths = [];+ let current = resolve(cwd);+ const stop = resolve(stopAt);+ while (true) {+ paths.push(join(current, ".codex", "config.toml"));+ if (current === stop || current === dirname(current)) break;+ current = dirname(current);+ }+ return paths;+}++async function readConfig(configPath) {+ try {+ return await readFile(configPath, "utf8");+ } catch (error) {+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return "";+ throw error;+ }+}++function resolveStatePath(env) {+ if (env.LAZYCODEX_MODEL_CATALOG_STATE_PATH?.trim()) return env.LAZYCODEX_MODEL_CATALOG_STATE_PATH;+ const dataRoot = env.PLUGIN_DATA?.trim() || join(homedir(), ".local", "share", "lazycodex");+ return join(dataRoot, "model-catalog-state.json");+}++async function readState(statePath) {+ try {+ const parsed = JSON.parse(await readFile(statePath, "utf8"));+ return isRecord(parsed) ? parsed : {};+ } catch (error) {+ if (error instanceof Error) return {};+ throw error;+ }+}++async function writeState(statePath, state) {+ await mkdir(dirname(statePath), { recursive: true });+ await writeFile(statePath, `${JSON.stringify(state, null, 2)}\n`);+}++async function pathExists(path) {+ try {+ await stat(path);+ return true;+ } catch (error) {+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;+ throw error;+ }+}++function replaceOrInsertRootSetting(config, key, value) {+ const lines = config.split(/\n/);+ const output = [];+ let replaced = false;+ let inserted = false;+ for (const line of lines) {+ if (!inserted && isSectionHeader(line)) {+ if (!replaced) output.push(`${key} = ${value}`);+ inserted = true;+ }+ if (isRootSetting(line, key)) {+ if (!replaced) {+ output.push(`${key} = ${value}`);+ replaced = true;+ }+ continue;+ }+ output.push(line);+ }+ if (!replaced && !inserted) output.push(`${key} = ${value}`);+ return output.join("\n");+}++function isSectionHeader(line) {+ const trimmed = line.trim();+ return trimmed.startsWith("[") && trimmed.endsWith("]");+}++function isRootSetting(line, key) {+ const trimmed = line.trimStart();+ if (trimmed.startsWith("#") || trimmed.startsWith("[")) return false;+ const match = trimmed.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/);+ return match?.[1] === key;+}++if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {+ migrateCodexConfig().catch((error) => {+ if (!(error instanceof Error)) throw error;+ process.exit(0);+ });+}diff --git a/plugins/omo/scripts/sync-hook-status-messages.mjs b/plugins/omo/scripts/sync-hook-status-messages.mjsnew file mode 100644index 00000000..7b7a598c--- /dev/null+++ b/plugins/omo/scripts/sync-hook-status-messages.mjs@@ -0,0 +1,82 @@+#!/usr/bin/env node+import { access, readdir, readFile, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { pathToFileURL } from "node:url";+import { fileURLToPath } from "node:url";++import { formatLazyCodexHookStatusMessage, normalizeLazyCodexHookStatusLabel } from "./hook-status-message.mjs";++const defaultRoot = dirname(dirname(fileURLToPath(import.meta.url)));++async function exists(path) {+ try {+ await access(path);+ return true;+ } catch (error) {+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;+ throw error;+ }+}++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`);+}++async function readPackageVersion(path) {+ const packageJson = await readJson(path);+ return packageJson.version;+}++async function readComponentVersions(root) {+ const componentsRoot = join(root, "components");+ const entries = await readdir(componentsRoot, { withFileTypes: true });+ const versions = new Map();+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ const packageJsonPath = join(componentsRoot, entry.name, "package.json");+ if (!(await exists(packageJsonPath))) continue;+ versions.set(entry.name, await readPackageVersion(packageJsonPath));+ }+ return versions;+}++function syncHooksJson(hooksJson, versionForCommand) {+ for (const groups of Object.values(hooksJson.hooks)) {+ for (const group of groups) {+ for (const hook of group.hooks) {+ if (hook.type !== "command") continue;+ const label = normalizeLazyCodexHookStatusLabel(hook.statusMessage);+ hook.statusMessage = formatLazyCodexHookStatusMessage(versionForCommand(hook.command), label);+ }+ }+ }+}++async function syncComponentHooks(root, componentName, version) {+ const hooksPath = join(root, "components", componentName, "hooks", "hooks.json");+ if (!(await exists(hooksPath))) return;+ const hooksJson = await readJson(hooksPath);+ syncHooksJson(hooksJson, () => version);+ await writeJson(hooksPath, hooksJson);+}++export async function syncHookStatusMessages(root = defaultRoot) {+ const aggregateVersion = await readPackageVersion(join(root, ".codex-plugin", "plugin.json"));+ const componentVersions = await readComponentVersions(root);+ const aggregateHooksPath = join(root, "hooks", "hooks.json");+ const aggregateHooks = await readJson(aggregateHooksPath);+ syncHooksJson(aggregateHooks, () => aggregateVersion);+ await writeJson(aggregateHooksPath, aggregateHooks);++ for (const [componentName, version] of componentVersions.entries()) {+ await syncComponentHooks(root, componentName, version);+ }+}++if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {+ await syncHookStatusMessages();+}diff --git a/plugins/omo/scripts/sync-skills.mjs b/plugins/omo/scripts/sync-skills.mjsindex 6ba2923a..319bd09c 100644--- a/plugins/omo/scripts/sync-skills.mjs+++ b/plugins/omo/scripts/sync-skills.mjs@@ -2,15 +2,16 @@import { cp, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";+import { sharedSkillsRootPath } from "@oh-my-opencode/shared-skills";const root = dirname(dirname(fileURLToPath(import.meta.url)));-const sharedSkillsRoot = join(root, "..", "..", "shared-skills", "skills");+const sharedSkillsRoot = sharedSkillsRootPath();const skillsRoot = join(root, "skills");const skillSources = [["comment-checker", "components/comment-checker/skills/comment-checker"],["lsp", "components/lsp/skills/lsp"],["rules", "components/rules/skills/rules"],- ["ultragoal", "components/ultragoal/skills/ultragoal"],+ ["ulw-loop", "components/ulw-loop/skills/ulw-loop"],];const opencodeOnlyOrchestrationPattern = /\b(?:call_omo_agent|background_output|team_[a-z_]+|task)\s*\(/;@@ -21,15 +22,15 @@ 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(agent_type="explorer", task_name="...", message="...")\` |-| \`call_omo_agent(subagent_type="librarian", ...)\` | \`spawn_agent(agent_type="librarian", task_name="...", message="...")\` |-| \`task(subagent_type="plan", ...)\` | \`spawn_agent(agent_type="plan", task_name="...", message="...")\` |-| \`task(subagent_type="oracle", ...)\` for final verification | \`spawn_agent(agent_type="codex-ultrawork-reviewer", task_name="...", message="...")\` |-| \`task(category="...", ...)\` for implementation or QA | \`spawn_agent(agent_type="worker", task_name="...", message="...")\` |+| \`call_omo_agent(subagent_type="explore", ...)\` | \`spawn_agent(agent_type="explorer", task_name="...", message="...", fork_turns="none")\` |+| \`call_omo_agent(subagent_type="librarian", ...)\` | \`spawn_agent(agent_type="librarian", task_name="...", message="...", fork_turns="none")\` |+| \`task(subagent_type="plan", ...)\` | \`spawn_agent(agent_type="plan", task_name="...", message="...", fork_turns="none")\` |+| \`task(subagent_type="oracle", ...)\` for final verification | \`spawn_agent(agent_type="codex-ultrawork-reviewer", task_name="...", message="...", fork_turns="none")\` |+| \`task(category="...", ...)\` for implementation or QA | \`spawn_agent(agent_type="worker", task_name="...", message="...", fork_turns="none")\` || \`background_output(task_id="...")\` | \`wait_agent(...)\` to wait for subagent completion and mailbox updates || \`team_*(...)\` | Use Codex native subagents plus \`send_message\`, \`followup_task\`, \`wait_agent\`, and \`close_agent\` |-When translating \`load_skills=[...]\`, include the requested skill names in the spawned agent's \`message\`. If a code block below conflicts with this section, this section wins.+Codex full-history forks inherit the parent agent type, model, and reasoning effort, so role-specific spawns with \`agent_type\` must 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.`;diff --git a/plugins/omo/skills/ai-slop-remover/SKILL.md b/plugins/omo/skills/ai-slop-remover/SKILL.mddeleted file mode 100644index d3fd536b..00000000--- a/plugins/omo/skills/ai-slop-remover/SKILL.md+++ /dev/null@@ -1,142 +0,0 @@-----name: ai-slop-remover-description: "Removes AI-generated code smells from a SINGLE file while preserving functionality. For multiple files, call in PARALLEL per file."-----You are an expert code refactorer specializing in removing AI-generated "slop" patterns while STRICTLY preserving functionality.--**INPUT**: Exactly ONE file path. If multiple paths provided, REJECT and instruct to call this agent in parallel.-------## DETECTION CRITERIA (Specific)--### 1. Obvious Comments (EXCLUDE: BDD comments like #given, #when, #then, #when/then)--**REMOVE**:-- Comments restating the code: `x += 1 # increment x`-- Docstrings on trivial methods: `"""Returns the name."""` for `def get_name(): return self.name`-- Section dividers: `# ===== HELPER FUNCTIONS =====`-- Commented-out code blocks-- `# TODO: future enhancement` without concrete plan-- `# Note: this is important` without explaining WHY--**KEEP**:-- Comments explaining WHY (business logic, edge cases, workarounds)-- Links to issues/tickets: `# See SPR-1234`-- Non-obvious algorithm explanations-- Regex explanations-- Matches to existing code style--### 2. Over-Defensive Code--**REMOVE**:-- Null checks for values that CANNOT be None (e.g., Django request in view)-- `if x is not None and x.attr is not None:` when x is guaranteed-- Try-except around code that can't raise (e.g., dict literal access)-- `isinstance()` checks for statically typed parameters-- Default values for required parameters: `def foo(x: str = "")` when empty string is invalid-- Backward-compat shims: `_old_name = new_name # deprecated`-- `# removed` or `# deleted` comments for removed code-- Re-exports of unused items-- Verbose, duplicated, or redundant code / test cases--**KEEP**:-- Validation at system boundaries (user input, external API responses)-- Error handling for I/O operations-- Null checks for nullable DB fields-- assertions in test code to matching type expectations--### 3. Spaghetti Nesting (2+ levels deep)--**REFACTOR**:-- Nested if-else chains -> early returns / guard clauses-- `if x: if y: if z:` -> `if not x: return` / `if not y: return`-- Nested loops with conditionals -> extract to helper OR use comprehensions-- Complex ternary `a if b else (c if d else e)` -> explicit if-else-------## PROCESS--### Step 1: Read & Analyze-Read the file. Identify ALL slop instances with line numbers.--### Step 2: Deep Consideration (CRITICAL)-For EACH identified issue, think:-- **Functionality Impact**: Will removing this change behavior? If ANY doubt, SKIP.-- **Test Coverage**: Are there tests that might break? If uncertain, SKIP.-- **Context Dependency**: Is this "slop" actually necessary for this specific codebase? (e.g., defensive code for known flaky external API)-- **Readability Trade-off**: Will removal make code LESS readable? If yes, SKIP.--**RULE**: When in doubt, DO NOT CHANGE. False negatives are better than breaking code.--### Step 3: Execute Changes-Make changes using Edit tool. One logical change at a time.--### Step 4: Detailed Report--**OUTPUT FORMAT**:--```-## AI Slop Removed: {filename}--### Analysis Summary-- Total issues found: N-- Issues fixed: M-- Issues skipped (safety): K--### Changes Made--#### Change 1: [Category] Line X-Y-**Before**: [original code snippet]-**After**: [modified code snippet]-**Why this is slop**: [Explain why this pattern is problematic]-**Why safe to remove**: [Explain why functionality is preserved]-**Impact**: None - purely cosmetic improvement-------### Skipped Issues (Preserved for Safety)--#### Skipped 1: Line X-**Reason**: [Why you chose not to change this]--### Summary-- Removed N obvious comments-- Simplified M defensive patterns-- Flattened K nested structures-- Preserved L patterns that looked like slop but serve purpose-```-------## SAFETY RULES--1. **NEVER remove error handling for I/O, network, or file operations**-2. **NEVER simplify validation for user input or external data**-3. **NEVER change public API signatures**-4. **NEVER remove type hints (even redundant-looking ones)**-5. **If a pattern appears in multiple places, it might be intentional - ASK before bulk removal**-6. **Preserve all BDD test comments (#given, #when, #then)**--When finished, your report should be detailed enough that a reviewer can understand EXACTLY what changed and feel confident the changes are safe.-------## WHEN NO SLOP FOUND--If the file is clean, report:--```-## AI Slop Analysis: {filename}--### Result: No AI Slop Detected--This file is clean. Here's why:--**Comments**: N comments found, all explain WHY not WHAT-**Defensive Code**: Null checks present are appropriate (e.g., checks external API response)-**Code Structure**: Maximum nesting depth acceptable, early returns used appropriately--**Conclusion**: This code appears to be human-written or well-reviewed AI code. No changes needed.-```\ No newline at end of filediff --git a/plugins/omo/skills/debugging/SKILL.md b/plugins/omo/skills/debugging/SKILL.mdindex 0d77c604..4f5da045 100644--- a/plugins/omo/skills/debugging/SKILL.md+++ b/plugins/omo/skills/debugging/SKILL.md@@ -1,6 +1,6 @@---name: debugging-description: "MUST USE for any real runtime debugging across ANY language or binary — crashes, silent failures, wrong responses, stuck processes, memory leaks, async misbehavior, unexplained timing, reverse engineering. Runs a hypothesis-driven loop: form ≥3 hypotheses, investigate in parallel, after 2 failed rounds spawn Oracles from orthogonal angles, confirm root cause, lock with a failing test, fix minimally, QA by actually USING the system, scrub artifacts. The actual HOW lives in `references/` — READ THEM. Triggers: 'debug this', 'why is X not working', 'hanging', 'attach a debugger', 'reverse engineer', 'pwndbg', 'gdb', 'lldb', 'node inspect', 'tsx debug', 'pdb', 'dlv', 'delve', 'rust-gdb', 'set a breakpoint', 'trace this bug', 'reproduce and fix', 'silent failure', 'HTTP 200 but empty', 'stuck process', 'inspect binary', 'reverse engineer', 'playwright failure'."+description: "MUST USE for any real runtime debugging across ANY language or binary — crashes, silent failures, wrong responses, stuck processes, memory leaks, async misbehavior, unexplained timing, reverse engineering. Runs a hypothesis-driven loop: form ≥3 hypotheses, investigate in parallel, after 2 failed rounds spawn Oracles from orthogonal angles, confirm root cause, lock with a failing test, fix minimally, QA by actually USING the system, scrub artifacts. The actual HOW lives in `references/` — READ THEM. Triggers: 'debug this', 'why is X not working', 'hanging', 'attach a debugger', 'reverse engineer', 'pwndbg', 'gdb', 'lldb', 'node inspect', 'tsx debug', 'pdb', 'dlv', 'delve', 'rust-gdb', 'set a breakpoint', 'context window exploded', 'why is the response empty', 'attach the debugger', 'debug it', 'why is this happening', 'trace this bug', 'reproduce and fix', 'silent failure', 'HTTP 200 but empty', 'why did it stop', 'inspect the binary', 'reverse engineering', 'playwright'."---# Debuggingdiff --git a/plugins/omo/skills/init-deep/SKILL.md b/plugins/omo/skills/init-deep/SKILL.mdnew file mode 100644index 00000000..62fece79--- /dev/null+++ b/plugins/omo/skills/init-deep/SKILL.md@@ -0,0 +1,325 @@+---+name: init-deep+description: "(builtin) Initialize hierarchical AGENTS.md knowledge base"+---+## Codex Harness Tool Compatibility++This skill may include examples copied from the OpenCode harness. In Codex, do not call OpenCode-only tools such as `call_omo_agent(...)`, `task(...)`, `background_output(...)`, or `team_*(...)` literally. Translate those examples to Codex native tools:++| OpenCode example | Codex tool to use |+| --- | --- |+| `call_omo_agent(subagent_type="explore", ...)` | `spawn_agent(agent_type="explorer", task_name="...", message="...", fork_turns="none")` |+| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent(agent_type="librarian", task_name="...", message="...", fork_turns="none")` |+| `task(subagent_type="plan", ...)` | `spawn_agent(agent_type="plan", task_name="...", message="...", fork_turns="none")` |+| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent(agent_type="codex-ultrawork-reviewer", task_name="...", message="...", fork_turns="none")` |+| `task(category="...", ...)` for implementation or QA | `spawn_agent(agent_type="worker", task_name="...", message="...", fork_turns="none")` |+| `background_output(task_id="...")` | `wait_agent(...)` to wait for subagent completion and mailbox updates |+| `team_*(...)` | Use Codex native subagents plus `send_message`, `followup_task`, `wait_agent`, and `close_agent` |++Codex full-history forks inherit the parent agent type, model, and reasoning effort, so role-specific spawns with `agent_type` must 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.++# /init-deep++Generate hierarchical AGENTS.md files. Root + complexity-scored subdirectories.++## Usage++```+/init-deep # Update mode: modify existing + create new where warranted+/init-deep --create-new # Read existing → remove all → regenerate from scratch+/init-deep --max-depth=2 # Limit directory depth (default: 3)+```++---++## Workflow (High-Level)++1. **Discovery + Analysis** (concurrent)+ - Fire background explore agents immediately+ - Main session: bash structure + LSP codemap + read existing AGENTS.md+2. **Score & Decide** - Determine AGENTS.md locations from merged findings+3. **Generate** - Root first, then subdirs in parallel+4. **Review** - Deduplicate, trim, validate++<critical>+**TodoWrite ALL phases. Mark in_progress → completed in real-time.**+```+TodoWrite([+ { id: "discovery", content: "Fire explore agents + LSP codemap + read existing", status: "pending", priority: "high" },+ { id: "scoring", content: "Score directories, determine locations", status: "pending", priority: "high" },+ { id: "generate", content: "Generate AGENTS.md files (root + subdirs)", status: "pending", priority: "high" },+ { id: "review", content: "Deduplicate, validate, trim", status: "pending", priority: "medium" }+])+```+</critical>++---++## Phase 1: Discovery + Analysis (Concurrent)++**Mark "discovery" as in_progress.**++### Fire Background Explore Agents IMMEDIATELY++Don't wait-these run async while main session works.++```+// Fire all at once, collect results later+task(subagent_type="explore", load_skills=[], description="Explore project structure", run_in_background=true, prompt="Project structure: PREDICT standard patterns for detected language → REPORT deviations only")+task(subagent_type="explore", load_skills=[], description="Find entry points", run_in_background=true, prompt="Entry points: FIND main files → REPORT non-standard organization")+task(subagent_type="explore", load_skills=[], description="Find conventions", run_in_background=true, prompt="Conventions: FIND config files (.eslintrc, pyproject.toml, .editorconfig) → REPORT project-specific rules")+task(subagent_type="explore", load_skills=[], description="Find anti-patterns", run_in_background=true, prompt="Anti-patterns: FIND 'DO NOT', 'NEVER', 'ALWAYS', 'DEPRECATED' comments → LIST forbidden patterns")+task(subagent_type="explore", load_skills=[], description="Explore build/CI", run_in_background=true, prompt="Build/CI: FIND .github/workflows, Makefile → REPORT non-standard patterns")+task(subagent_type="explore", load_skills=[], description="Find test patterns", run_in_background=true, prompt="Test patterns: FIND test configs, test structure → REPORT unique conventions")+```++<dynamic-agents>+**DYNAMIC AGENT SPAWNING**: After bash analysis, spawn ADDITIONAL explore agents based on project scale:++| Factor | Threshold | Additional Agents |+|--------|-----------|-------------------|+| **Total files** | >100 | +1 per 100 files |+| **Total lines** | >10k | +1 per 10k lines |+| **Directory depth** | ≥4 | +2 for deep exploration |+| **Large files (>500 lines)** | >10 files | +1 for complexity hotspots |+| **Monorepo** | detected | +1 per package/workspace |+| **Multiple languages** | >1 | +1 per language |++```bash+# Measure project scale first+total_files=$(find . -type f -not -path '*/node_modules/*' -not -path '*/.git/*' | wc -l)+total_lines=$(find . -type f \\( -name "*.ts" -o -name "*.py" -o -name "*.go" \\) -not -path '*/node_modules/*' -exec wc -l {} + 2>/dev/null | tail -1 | awk '{print $1}')+large_files=$(find . -type f \\( -name "*.ts" -o -name "*.py" \\) -not -path '*/node_modules/*' -exec wc -l {} + 2>/dev/null | awk '$1 > 500 {count++} END {print count+0}')+max_depth=$(find . -type d -not -path '*/node_modules/*' -not -path '*/.git/*' | awk -F/ '{print NF}' | sort -rn | head -1)+```++Example spawning:+```+// 500 files, 50k lines, depth 6, 15 large files → spawn 5+5+2+1 = 13 additional agents+task(subagent_type="explore", load_skills=[], description="Analyze large files", run_in_background=true, prompt="Large file analysis: FIND files >500 lines, REPORT complexity hotspots")+task(subagent_type="explore", load_skills=[], description="Explore deep modules", run_in_background=true, prompt="Deep modules at depth 4+: FIND hidden patterns, internal conventions")+task(subagent_type="explore", load_skills=[], description="Find shared utilities", run_in_background=true, prompt="Cross-cutting concerns: FIND shared utilities across directories")+// ... more based on calculation+```+</dynamic-agents>++### Main Session: Concurrent Analysis++**While background agents run**, main session does:++#### 1. Bash Structural Analysis+```bash+# Directory depth + file counts+find . -type d -not -path '*/\\.*' -not -path '*/node_modules/*' -not -path '*/venv/*' -not -path '*/dist/*' -not -path '*/build/*' | awk -F/ '{print NF-1}' | sort -n | uniq -c++# Files per directory (top 30)+find . -type f -not -path '*/\\.*' -not -path '*/node_modules/*' | sed 's|/[^/]*$||' | sort | uniq -c | sort -rn | head -30++# Code concentration by extension+find . -type f \\( -name "*.py" -o -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.go" -o -name "*.rs" \\) -not -path '*/node_modules/*' | sed 's|/[^/]*$||' | sort | uniq -c | sort -rn | head -20++# Existing AGENTS.md / CLAUDE.md+find . -type f \\( -name "AGENTS.md" -o -name "CLAUDE.md" \\) -not -path '*/node_modules/*' 2>/dev/null+```++#### 2. Read Existing AGENTS.md+```+For each existing file found:+ Read(filePath=file)+ Extract: key insights, conventions, anti-patterns+ Store in EXISTING_AGENTS map+```++If `--create-new`: Read all existing first (preserve context) → then delete all → regenerate.++#### 3. LSP Codemap (if available)+```+LspServers() # Check availability++# Entry points (parallel)+LspDocumentSymbols(filePath="src/index.ts")+LspDocumentSymbols(filePath="main.py")++# Key symbols (parallel)+LspWorkspaceSymbols(filePath=".", query="class")+LspWorkspaceSymbols(filePath=".", query="interface")+LspWorkspaceSymbols(filePath=".", query="function")++# Centrality for top exports+LspFindReferences(filePath="...", line=X, character=Y)+```++**LSP Fallback**: If unavailable, rely on explore agents + AST-grep.++### Collect Background Results++```+// After main session analysis done, collect all task results+for each background task ID (`bg_...`): background_output(task_id="bg_...")+```++**Merge: bash + LSP + existing + explore findings. Mark "discovery" as completed.**++---++## Phase 2: Scoring & Location Decision++**Mark "scoring" as in_progress.**++### Scoring Matrix++| Factor | Weight | High Threshold | Source |+|--------|--------|----------------|--------|+| File count | 3x | >20 | bash |+| Subdir count | 2x | >5 | bash |+| Code ratio | 2x | >70% | bash |+| Unique patterns | 1x | Has own config | explore |+| Module boundary | 2x | Has index.ts/__init__.py | bash |+| Symbol density | 2x | >30 symbols | LSP |+| Export count | 2x | >10 exports | LSP |+| Reference centrality | 3x | >20 refs | LSP |++### Decision Rules++| Score | Action |+|-------|--------|+| **Root (.)** | ALWAYS create |+| **>15** | Create AGENTS.md |+| **8-15** | Create if distinct domain |+| **<8** | Skip (parent covers) |++### Output+```+AGENTS_LOCATIONS = [+ { path: ".", type: "root" },+ { path: "src/hooks", score: 18, reason: "high complexity" },+ { path: "src/api", score: 12, reason: "distinct domain" }+]+```++**Mark "scoring" as completed.**++---++## Phase 3: Generate AGENTS.md++**Mark "generate" as in_progress.**++<critical>+**File Writing Rule**: If AGENTS.md already exists at the target path → use `Edit` tool. If it does NOT exist → use `Write` tool.+NEVER use Write to overwrite an existing file. ALWAYS check existence first via `Read` or discovery results.+</critical>++### Root AGENTS.md (Full Treatment)++```markdown+# PROJECT KNOWLEDGE BASE++**Generated:** {TIMESTAMP}+**Commit:** {SHORT_SHA}+**Branch:** {BRANCH}++## OVERVIEW+{1-2 sentences: what + core stack}++## STRUCTURE+```+{root}/+├── {dir}/ # {non-obvious purpose only}+└── {entry}+```++## WHERE TO LOOK+| Task | Location | Notes |+|------|----------|-------|++## CODE MAP+{From LSP - skip if unavailable or project <10 files}++| Symbol | Type | Location | Refs | Role |+|--------|------|----------|------|------|++## CONVENTIONS+{ONLY deviations from standard}++## ANTI-PATTERNS (THIS PROJECT)+{Explicitly forbidden here}++## UNIQUE STYLES+{Project-specific}++## COMMANDS+```bash+{dev/test/build}+```++## NOTES+{Gotchas}+```++**Quality gates**: 50-150 lines, no generic advice, no obvious info.++### Subdirectory AGENTS.md (Parallel)++Launch writing tasks for each location:++```+for loc in AGENTS_LOCATIONS (except root):+ task(category="writing", load_skills=[], run_in_background=false, description="Generate AGENTS.md", prompt=`+ Generate AGENTS.md for: ${loc.path}+ - Reason: ${loc.reason}+ - 30-80 lines max+ - NEVER repeat parent content+ - Sections: OVERVIEW (1 line), STRUCTURE (if >5 subdirs), WHERE TO LOOK, CONVENTIONS (if different), ANTI-PATTERNS+ `)+```++**Wait for all. Mark "generate" as completed.**++---++## Phase 4: Review & Deduplicate++**Mark "review" as in_progress.**++For each generated file:+- Remove generic advice+- Remove parent duplicates+- Trim to size limits+- Verify telegraphic style++**Mark "review" as completed.**++---++## Final Report++```+=== init-deep Complete ===++Mode: {update | create-new}++Files:+ [OK] ./AGENTS.md (root, {N} lines)+ [OK] ./src/hooks/AGENTS.md ({N} lines)++Dirs Analyzed: {N}+AGENTS.md Created: {N}+AGENTS.md Updated: {N}++Hierarchy:+ ./AGENTS.md+ └── src/hooks/AGENTS.md+```++---++## Anti-Patterns++- **Static agent count**: MUST vary agents based on project size/depth+- **Sequential execution**: MUST parallel (explore + LSP concurrent)+- **Ignoring existing**: ALWAYS read existing first, even with --create-new+- **Over-documenting**: Not every dir needs AGENTS.md+- **Redundancy**: Child never repeats parent+- **Generic content**: Remove anything that applies to ALL projects+- **Verbose style**: Telegraphic or diediff --git a/plugins/omo/skills/lcx-report-bug/SKILL.md b/plugins/omo/skills/lcx-report-bug/SKILL.mdnew file mode 100644index 00000000..a091ce27--- /dev/null+++ b/plugins/omo/skills/lcx-report-bug/SKILL.md@@ -0,0 +1,127 @@+---+name: lcx-report-bug+description: "Create a high-signal LazyCodex bug report for code-yeongyu/lazycodex. Use this whenever the user asks to report, file, open, or triage a LazyCodex, lazycodex-ai, omo-codex, or Codex plugin bug, especially when they need root cause, reproduction steps, expected fix guidance, and a GitHub issue."+metadata:+ short-description: Report LazyCodex bugs with debugging evidence+---++# lcx-report-bug++You are a LazyCodex bug reporter. Produce one useful GitHub issue in English for `code-yeongyu/lazycodex`, backed by runtime evidence rather than guesses.++Use GPT-5.5 style: outcome first, concise, evidence-bound. Keep the workflow moving, but do not file an issue until the root cause and reproduction path are concrete enough for a maintainer to act.++## Goal++Create or prepare a GitHub issue that includes:++- clear title+- environment+- reproducible steps+- expected behavior+- actual behavior+- confirmed or strongly evidenced root cause+- fix approach, including files or components likely involved+- verification plan++## Required Workflow++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. 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+4. Search for an existing issue before creating a new one:++```bash+gh issue list --repo code-yeongyu/lazycodex --search "<short error or symptom>" --state open+```++5. If a matching open issue exists, add a comment with the new evidence instead of creating a duplicate.+6. If no matching issue exists, create the issue with `gh`.++## Issue Body Template++Write the issue body in English and keep it direct:++```markdown+## Summary+[One or two sentences describing the user-visible failure.]++## Environment+- LazyCodex version:+- Codex version:+- OS:+- Install method:+- Relevant config:++## Reproduction+1. [Exact command or UI action]+2. [Exact next step]+3. [Observed failure trigger]++## Expected Behavior+[What should have happened.]++## Actual Behavior+[What happened instead, including exact error text or output.]++## Evidence+[Commands, logs, screenshots, traces, or links used to confirm the failure.]++## Root Cause+[Confirmed cause. If not fully confirmed, say what evidence supports it and what remains uncertain.]++## Proposed Fix+[Concrete implementation or operational fix. Include likely files, components, or commands.]++## Verification Plan+- [Check that reproduces the original failure]+- [Check that proves the fix]+- [Regression check for adjacent LazyCodex/Codex plugin behavior]+```++## GitHub Creation Path++Prefer `gh`:++```bash+ISSUE_BODY="/tmp/lcx-report-bug-$(date +%Y%m%d-%H%M%S).md"+$EDITOR "$ISSUE_BODY"+gh issue create --repo code-yeongyu/lazycodex --title "<clear title>" --body-file "$ISSUE_BODY"+```++If `$EDITOR` is not usable, write the file with the available file-editing tool, then run the same `gh issue create` command.++After creating or commenting, return the issue URL and a short summary of the evidence used.++## Browser use fallback++If `gh` is unavailable, unauthenticated, or blocked, use Browser Use against the real GitHub page:++1. Open `https://github.com/code-yeongyu/lazycodex/issues/new`.+2. Fill the title and body from the template.+3. Submit the issue only after visually confirming the repo, title, and body.+4. Capture the resulting issue URL.++## Computer use fallback++If Browser Use is unavailable but a desktop browser is open and authenticated, use Computer Use:++1. Navigate to `https://github.com/code-yeongyu/lazycodex/issues/new`.+2. Fill the title and body.+3. Verify the target repository and final text before submission.+4. Submit and capture the issue URL.++## Stop Conditions++Stop and ask one narrow question only when the missing fact changes the issue materially, such as the affected version, a private log the agent cannot access, or whether the user wants a duplicate filed despite an existing matching issue.++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+- a fix PR unless the user separately asks for onediff --git a/plugins/omo/skills/lcx-report-bug/agents/openai.yaml b/plugins/omo/skills/lcx-report-bug/agents/openai.yamlnew file mode 100644index 00000000..1914b613--- /dev/null+++ b/plugins/omo/skills/lcx-report-bug/agents/openai.yaml@@ -0,0 +1,9 @@+interface:+ display_name: "lcx-report-bug (omo)"+ short_description: "Report LazyCodex bugs with debugging evidence"+ search_terms:+ - "lcx-report-bug"+ - "lazycodex bug"+ - "lazycodex issue"+ - "omo-codex bug"+ default_prompt: "Use $lcx-report-bug to investigate this LazyCodex bug and file a clear issue with reproduction, root cause, and fix guidance."diff --git a/plugins/omo/skills/programming/SKILL.md b/plugins/omo/skills/programming/SKILL.mdindex 55129171..1bb0f79d 100644--- a/plugins/omo/skills/programming/SKILL.md+++ b/plugins/omo/skills/programming/SKILL.md@@ -176,7 +176,7 @@ A bare default constructor for any of these (no timeouts, no pool tuning, no sch| UB / soundness gate | (n/a) | **nightly miri** with strict provenance + Tree Borrows pass | (n/a) | **`nilaway`** + `-race` detector + `goleak` are the equivalent gate || Disposable scripts | **PEP 723** inline metadata + `uv run script.py` | **rust-script** with inline `Cargo.toml` block | `bun run script.ts` | `//go:build ignore` + `go run script.go` || Bootstrap a new project | `scripts/python/new-project.py` | `scripts/rust/new-project.py` | `scripts/typescript/new-project.ts` | `scripts/go/new-project.py` |-| Pre-commit / CI gate | `ruff check . && basedpyright && pytest` | `cargo +nightly clippy -- -D warnings && cargo nextest run && cargo +nightly miri test` | `npx biome check . && npx tsc --noEmit && bun test` | `gofumpt -l . && golangci-lint run ./... && nilaway ./... && go test -race -shuffle=on -count=1 ./...` |+| Pre-commit / CI gate | `ruff check . && basedpyright && pytest` | `cargo +nightly clippy -- -D warnings && cargo nextest run && cargo +nightly miri test` | `bunx biome check . && bunx tsc --noEmit && bun test` | `gofumpt -l . && golangci-lint run ./... && nilaway ./... && go test -race -shuffle=on -count=1 ./...` |A `tsconfig.json` with `"strict": true` alone is **not** strict. The reference enumerates the additional flags. Same for `pyproject.toml` and `Cargo.toml` - the references contain the canonical full configuration.diff --git a/plugins/omo/skills/programming/references/go/bubbletea-v2.md b/plugins/omo/skills/programming/references/go/bubbletea-v2.mdindex f0c20de3..45eae702 100644--- a/plugins/omo/skills/programming/references/go/bubbletea-v2.md+++ b/plugins/omo/skills/programming/references/go/bubbletea-v2.md@@ -10,7 +10,7 @@ The reference implementation this document is distilled from: [`code-yeongyu/bubBubbletea v1 manages cursor positioning in software ("virtual cursor"). It draws a `█` at the cursor position. The terminal's *real* cursor stays at `(0, 0)`.-This breaks every CJK input method. IME candidate windows (the popup showing composed Hangul syllables, kana to kanji conversion, or pinyin lookup) anchor to the terminal's **real** cursor position. With v1, the candidate window appears at top-left while you are typing somewhere in the middle of the screen.+This breaks every CJK input method. IME candidate windows (the popup showing Hangul composition choices for Korean, kana → kanji for Japanese, and pinyin lookup for Chinese) anchor to the terminal's **real** cursor position. With v1, the candidate window appears at top-left while you are typing somewhere in the middle of the screen.Bubbletea v2 fixes this with two changes:@@ -143,7 +143,7 @@ for _, r := range s {}```-`lipgloss/v2` uses `go-runewidth` internally — wide CJK text returns display-cell width, not rune count. **If you measure outside lipgloss, you must call runewidth directly.**+`lipgloss/v2` uses `go-runewidth` internally — `lipgloss.Width("\u4e2d\u6587")` returns 4, not 2. **If you measure outside lipgloss, you must call runewidth directly.**---@@ -203,7 +203,7 @@ titleStyle := lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(lipgloss.Color("63"))-rendered := titleStyle.Render("CJK title")+rendered := titleStyle.Render("\u4e2d\u6587")````lipgloss/v2` width and padding correctly account for CJK display width. v1 did too — this is not a v2-specific fix, just a reminder.@@ -297,18 +297,18 @@ internal/ui/```goimport "charm.land/bubbletea/v2/teatest"-func TestModel_typing_wide_text_keeps_cursor_in_position(t *testing.T) {+func TestModel_typing_cjk_keeps_cursor_in_position(t *testing.T) {// Givenm := initial()tm := teatest.NewTestModel(t, m, teatest.WithInitialTermSize(80, 24))- // When — simulate typing two wide characters- tm.Send(tea.KeyPressMsg{Code: '好'})- tm.Send(tea.KeyPressMsg{Code: '字'})+ // When — simulate typing two CJK wide characters+ tm.Send(tea.KeyPressMsg{Code: '\u4e2d'})+ tm.Send(tea.KeyPressMsg{Code: '\u6587'})// Thenout := tm.FinalOutput(t)- require.Contains(t, string(out), "好字")+ require.Contains(t, string(out), "\u4e2d\u6587")// Cursor should be at column 4 (two wide chars = 4 cells)// ...}diff --git a/plugins/omo/skills/programming/references/typescript/README.md b/plugins/omo/skills/programming/references/typescript/README.mdindex 33b587f4..f7c9bd1e 100644--- a/plugins/omo/skills/programming/references/typescript/README.md+++ b/plugins/omo/skills/programming/references/typescript/README.md@@ -109,9 +109,9 @@ async function main(): Promise<void> { // no-excuse-ok: catch| Validation | Zod | Runtime validation + type inference || ORM | Drizzle | Type-safe SQL, no codegen || HTTP client | `ky` | Thin fetch wrapper (5KB); auto-throw on non-2xx, retry, timeout, hooks, prefixUrl. Browser + Node + Bun + Deno |-| HTTP client (perf) | `undici` (direct API) | Use when a Node backend needs connection pooling, HTTP/2, or pipelining |+| HTTP client (perf) | `undici` (direct API) | When a Node backend needs connection pooling, HTTP/2, or pipelining |-> **HTTP client rule** — production code must not use bare `fetch()`. It lacks retry, timeout, and error-handling policy, which can cause silent failure during incidents. Install **`ky`** by default, and use the **`undici`** direct API when a Node backend needs high-volume requests, connection pooling, HTTP/2, or pipelining. ~~`axios`~~ is forbidden after the supply-chain compromise (2026-03). `node-fetch` is unnecessary because Node 18+ includes built-in fetch.+> **HTTP client rule** - production code must not use bare `fetch()`. It has no retry, timeout, or error-handling policy and causes silent failures during incidents. Install **`ky`** by default, and use the **`undici`** direct API when a Node backend needs high-volume requests, connection pooling, HTTP/2, or pipelining. ~~`axios`~~ is forbidden after the supply-chain compromise (2026-03). `node-fetch` is unnecessary because Node 18+ includes built-in fetch.| Testing | `bun test` / vitest | Fast, ESM-native || Logging | `pino` | Structured JSON, fast || CLI | `@clack/prompts` + `commander` | Interactive + parsing |@@ -127,7 +127,7 @@ bun run ../../scripts/typescript/new-project.ts my-api --path ./projectsCreates: `package.json` (Hono + Zod + Biome), `tsconfig.json` (ultra-strict), `biome.json`, `src/index.ts`, `.gitignore`. Works on macOS, Linux, Windows.-For manual setup: `npx tsc --init`, then load `tsconfig-strict.md` for the full strict config.+For manual setup: `bunx tsc --init`, then load `tsconfig-strict.md` for the full strict config.Key flags beyond `"strict": true`:diff --git a/plugins/omo/skills/programming/references/typescript/bootstrap.md b/plugins/omo/skills/programming/references/typescript/bootstrap.mdindex ecd9dff0..f0981b79 100644--- a/plugins/omo/skills/programming/references/typescript/bootstrap.md+++ b/plugins/omo/skills/programming/references/typescript/bootstrap.md@@ -35,7 +35,7 @@ Use Node when:- Production target is a Node-specific platform (some serverless platforms don't run Bun yet)- You're contributing to a Node-only project-`npx` runs package binaries without a global install. `bun create` scaffolds projects.+`bunx` replaces `npx`. `bun create` scaffolds projects.## Package manager — pnpm > npmdiff --git a/plugins/omo/skills/programming/references/typescript/tsconfig-strict.md b/plugins/omo/skills/programming/references/typescript/tsconfig-strict.mdindex 332b5d85..eb755d25 100644--- a/plugins/omo/skills/programming/references/typescript/tsconfig-strict.md+++ b/plugins/omo/skills/programming/references/typescript/tsconfig-strict.md@@ -138,8 +138,8 @@ For Bun projects, add to `compilerOptions`:## CI gate```bash-npx biome check .-npx tsc --noEmit+bunx biome check .+bunx tsc --noEmitbun test```diff --git a/plugins/omo/skills/programming/scripts/typescript/new-project.ts b/plugins/omo/skills/programming/scripts/typescript/new-project.tsindex d2f94d18..9bb2a3e7 100644--- a/plugins/omo/skills/programming/scripts/typescript/new-project.ts+++ b/plugins/omo/skills/programming/scripts/typescript/new-project.ts@@ -64,8 +64,8 @@ const pkg = {scripts: {dev: "bun --hot src/index.ts",start: "bun src/index.ts",- check: "npx biome check . && npx tsc --noEmit && bun test",- "check:fix": "npx biome check --write .",+ check: "bunx biome check . && bunx tsc --noEmit && bun test",+ "check:fix": "bunx biome check --write .",test: "bun test",},dependencies: {diff --git a/plugins/omo/skills/refactor/SKILL.md b/plugins/omo/skills/refactor/SKILL.mdindex 9fcbdd6b..392a5db3 100644--- a/plugins/omo/skills/refactor/SKILL.md+++ b/plugins/omo/skills/refactor/SKILL.md@@ -9,15 +9,15 @@ 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(agent_type="explorer", task_name="...", message="...")` |-| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent(agent_type="librarian", task_name="...", message="...")` |-| `task(subagent_type="plan", ...)` | `spawn_agent(agent_type="plan", task_name="...", message="...")` |-| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent(agent_type="codex-ultrawork-reviewer", task_name="...", message="...")` |-| `task(category="...", ...)` for implementation or QA | `spawn_agent(agent_type="worker", task_name="...", message="...")` |+| `call_omo_agent(subagent_type="explore", ...)` | `spawn_agent(agent_type="explorer", task_name="...", message="...", fork_turns="none")` |+| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent(agent_type="librarian", task_name="...", message="...", fork_turns="none")` |+| `task(subagent_type="plan", ...)` | `spawn_agent(agent_type="plan", task_name="...", message="...", fork_turns="none")` |+| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent(agent_type="codex-ultrawork-reviewer", task_name="...", message="...", fork_turns="none")` |+| `task(category="...", ...)` for implementation or QA | `spawn_agent(agent_type="worker", task_name="...", message="...", fork_turns="none")` || `background_output(task_id="...")` | `wait_agent(...)` to wait for subagent completion and mailbox updates || `team_*(...)` | Use Codex native subagents plus `send_message`, `followup_task`, `wait_agent`, and `close_agent` |-When translating `load_skills=[...]`, include the requested skill names in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.+Codex full-history forks inherit the parent agent type, model, and reasoning effort, so role-specific spawns with `agent_type` must 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.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 be45fb08..4a05b716 100644--- a/plugins/omo/skills/remove-ai-slops/SKILL.md+++ b/plugins/omo/skills/remove-ai-slops/SKILL.md@@ -1,6 +1,6 @@---name: remove-ai-slops-description: Remove AI-generated code smells (slop) from branch changes or an explicit file list. Locks behavior with regression tests FIRST, then runs categorized cleanup via parallel `deep` agents in batches of 5, then verifies with quality gates. Covers 10 slop categories including performance equivalences, excessive complexity (object annotations, if/elif variant chains), and oversized modules (250+ pure LOC with mandatory modular refactoring). MUST USE when the user asks to "remove slop", "clean AI code", "deslop", or wants to clean up AI-generated patterns from recent changes. Triggers - "remove ai slops", "clean ai code", "deslop", "cleanup AI generated".+description: "Remove AI-generated code smells (slop) from branch changes or an explicit file list. Locks behavior with regression tests FIRST, then runs categorized cleanup via parallel `deep` agents in batches of 5, then verifies with quality gates. Covers 10 slop categories including performance equivalences, excessive complexity (object annotations, if/elif variant chains), and oversized modules (250+ pure LOC with mandatory modular refactoring). MUST USE when the user asks to \"remove slop\", \"clean AI code\", \"deslop\", \"clean up AI-generated code\", \"remove AI slop\", or wants to clean up AI-generated patterns from recent changes. Triggers - \"remove ai slops\", \"clean ai code\", \"deslop\", \"cleanup AI generated\", \"remove AI slop\", \"clean up AI-generated code\", \"strip slop\", \"ai-slop cleanup\"."---## Codex Harness Tool Compatibility@@ -9,15 +9,15 @@ 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(agent_type="explorer", task_name="...", message="...")` |-| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent(agent_type="librarian", task_name="...", message="...")` |-| `task(subagent_type="plan", ...)` | `spawn_agent(agent_type="plan", task_name="...", message="...")` |-| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent(agent_type="codex-ultrawork-reviewer", task_name="...", message="...")` |-| `task(category="...", ...)` for implementation or QA | `spawn_agent(agent_type="worker", task_name="...", message="...")` |+| `call_omo_agent(subagent_type="explore", ...)` | `spawn_agent(agent_type="explorer", task_name="...", message="...", fork_turns="none")` |+| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent(agent_type="librarian", task_name="...", message="...", fork_turns="none")` |+| `task(subagent_type="plan", ...)` | `spawn_agent(agent_type="plan", task_name="...", message="...", fork_turns="none")` |+| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent(agent_type="codex-ultrawork-reviewer", task_name="...", message="...", fork_turns="none")` |+| `task(category="...", ...)` for implementation or QA | `spawn_agent(agent_type="worker", task_name="...", message="...", fork_turns="none")` || `background_output(task_id="...")` | `wait_agent(...)` to wait for subagent completion and mailbox updates || `team_*(...)` | Use Codex native subagents plus `send_message`, `followup_task`, `wait_agent`, and `close_agent` |-When translating `load_skills=[...]`, include the requested skill names in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.+Codex full-history forks inherit the parent agent type, model, and reasoning effort, so role-specific spawns with `agent_type` must 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.# Remove AI Slops Skill@@ -162,7 +162,7 @@ Order rule (safest → riskiest): comments → dead code → defensive → dupli### Phase 4: Parallel slop removal via `deep` agents in batches of 5-Files are processed by `deep` category agents with the `ai-slop-remover` skill loaded, **batched 5 at a time in parallel**. The `deep` category gives the agent enough thoroughness to correctly evaluate the 9 categories and respect the KEEP rules without slipping into surface fixes; the 5-wide batch is the sweet spot — more than 5 creates result-merging noise and context contention, fewer wastes parallelism.+Files are processed by `deep` category agents with the `$omo:remove-ai-slops` skill loaded, **batched 5 at a time in parallel**. The executable skill name is `remove-ai-slops`. The `deep` category gives the agent enough thoroughness to correctly evaluate the 9 categories and respect the KEEP rules without slipping into surface fixes; the 5-wide batch is the sweet spot — more than 5 creates result-merging noise and context contention, fewer wastes parallelism.**Batching protocol** (strict):@@ -180,7 +180,7 @@ Files are processed by `deep` category agents with the `ai-slop-remover` skill l```task(category="deep",- load_skills=["ai-slop-remover"],+ load_skills=["remove-ai-slops"],run_in_background=true,description="Slop removal: {filename}",prompt="""diff --git a/plugins/omo/skills/review-work/SKILL.md b/plugins/omo/skills/review-work/SKILL.mdindex 759b2c59..327b08ec 100644--- a/plugins/omo/skills/review-work/SKILL.md+++ b/plugins/omo/skills/review-work/SKILL.md@@ -8,15 +8,35 @@ 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(agent_type="explorer", task_name="...", message="...")` |-| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent(agent_type="librarian", task_name="...", message="...")` |-| `task(subagent_type="plan", ...)` | `spawn_agent(agent_type="plan", task_name="...", message="...")` |-| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent(agent_type="codex-ultrawork-reviewer", task_name="...", message="...")` |-| `task(category="...", ...)` for implementation or QA | `spawn_agent(agent_type="worker", task_name="...", message="...")` |+| `call_omo_agent(subagent_type="explore", ...)` | `spawn_agent(agent_type="explorer", task_name="...", message="...", fork_turns="none")` |+| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent(agent_type="librarian", task_name="...", message="...", fork_turns="none")` |+| `task(subagent_type="plan", ...)` | `spawn_agent(agent_type="plan", task_name="...", message="...", fork_turns="none")` |+| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent(agent_type="codex-ultrawork-reviewer", task_name="...", message="...", fork_turns="none")` |+| `task(category="...", ...)` for implementation or QA | `spawn_agent(agent_type="worker", task_name="...", message="...", fork_turns="none")` || `background_output(task_id="...")` | `wait_agent(...)` to wait for subagent completion and mailbox updates || `team_*(...)` | Use Codex native subagents plus `send_message`, `followup_task`, `wait_agent`, and `close_agent` |-When translating `load_skills=[...]`, include the requested skill names in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.+Codex full-history forks inherit the parent agent type, model, and reasoning effort, so role-specific spawns with `agent_type` must 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.++## 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 selection requires `agent_type`; `model` ++`reasoning_effort` alone creates a default agent, not a reviewer or+worker. Prefer `fork_turns: "none"` unless full history is truly+required; 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. Never use a single long blocking wait for them. While any child is active, keep the parent visibly alive with brief status updates that include active subagent count, agent names, last heartbeat, and whether the parent is waiting for mailbox updates.++Use `wait_agent` for completion signals, but treat `wait_agent` as a+mailbox signal, not proof of completion, content, or errors. After two+waits with no substantive result, send one targeted followup:+`TASK STILL ACTIVE: return <deliverable> or BLOCKED: <reason>`. If the+child stays silent or ack-only, 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 deliverable.# Review Work - 5-Agent Parallel Review Orchestrator@@ -493,9 +513,12 @@ OUTPUT FORMAT:## Phase 2: Wait & Collect-After launching all 5 agents in one turn, **end your response**. Wait for system notifications as each agent completes.+After launching all 5 agents in one turn, wait for completions in bounded+cycles. Do not treat a timeout, ack-only reply, or empty child result as+a PASS.-As each completes, collect via `background_output(task_id="bg_...")`. Store each verdict:+As each completes, collect via the Codex mapping above (`wait_agent`,+then the child's substantive final result). Store each verdict:| Agent | Verdict | Notes ||-------|---------|-------|@@ -506,6 +529,8 @@ As each completes, collect via `background_output(task_id="bg_...")`. Store each| 5. Context Mining | pending | - |Do NOT deliver the final report until ALL 5 have completed.+If a lane remains silent after the reliability followup, record it as+inconclusive and respawn a smaller reviewer/worker for that exact lane.---@@ -546,4 +571,4 @@ Compile the final report in this format:If FAILED - be specific. The user should know exactly what to fix and in what order. No vague "consider improving X" - state the problem, the file, and the fix.-If PASSED - keep it short. Highlight any non-blocking suggestions, but don't turn a passing review into a lecture.\ No newline at end of file+If PASSED - keep it short. Highlight any non-blocking suggestions, but don't turn a passing review into a lecture.diff --git a/plugins/omo/skills/start-work/SKILL.md b/plugins/omo/skills/start-work/SKILL.mdnew file mode 100644index 00000000..8d0c37c5--- /dev/null+++ b/plugins/omo/skills/start-work/SKILL.md@@ -0,0 +1,149 @@+---+name: start-work+description: "Execute a Prometheus work plan in Codex with Boulder state, evidence ledger updates, worktree discipline, parallel subagents, and Stop-hook continuation. Use after planning when the user says start work, execute plan, continue plan, resume plan, or asks to run a .omo/plans plan."+---++## 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:++| OpenCode example | Codex tool to use |+| --- | --- |+| `task(subagent_type="explore", ...)` | `spawn_agent(agent_type="explorer", task_name="...", message="...", fork_turns="none")` |+| `task(subagent_type="librarian", ...)` | `spawn_agent(agent_type="librarian", task_name="...", message="...", fork_turns="none")` |+| `task(subagent_type="plan", ...)` | `spawn_agent(agent_type="plan", task_name="...", message="...", fork_turns="none")` |+| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent(agent_type="codex-ultrawork-reviewer", task_name="...", message="...", fork_turns="none")` |+| `task(category="...", ...)` for implementation or QA | `spawn_agent(agent_type="worker", task_name="...", message="...", fork_turns="none")` |+| `background_output(task_id="...")` | `wait_agent(...)` |+| `dispatchInternalPrompt(...)` | the `Stop` hook emits `{"decision":"block","reason":"<prompt>"}` automatically; see Continuation |+| `team_*(...)` | `spawn_agent` + `send_message` + `followup_task` + `wait_agent` + `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.++## 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 selection requires `agent_type`; `model` ++`reasoning_effort` alone creates a default agent, not a reviewer or+worker. 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. Never use a single long blocking wait for them. While any child is active, keep the parent visibly alive with brief status updates that include active subagent count, agent names, last heartbeat, and whether the parent is waiting for mailbox updates.++Use `wait_agent` for completion signals, but treat `wait_agent` as a+mailbox signal, not proof of completion, content, or errors. After two+waits with no substantive result, send one targeted followup:+`TASK STILL ACTIVE: return <deliverable> or BLOCKED: <reason>`. If the+child stays silent or ack-only, 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.++# 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.++## Usage++```text+$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.++## Phase 1: Select the plan++1. Read `.omo/boulder.json` if it exists.+2. List Prometheus plan files under `.omo/plans/`.+3. If `plan-name` was provided, select the matching plan.+4. If exactly one active or paused Boulder work exists for this session, resume it.+5. If no active work exists and exactly one plan exists, select it.+6. If multiple plans remain possible, ask one focused selection question.++## 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.++```json+{+ "schema_version": 2,+ "active_work_id": "<work-id>",+ "works": {+ "<work-id>": {+ "work_id": "<work-id>",+ "active_plan": ".omo/plans/<plan-name>.md",+ "plan_name": "<plan-name>",+ "session_ids": ["codex:<session_id>"],+ "status": "active",+ "worktree_path": null+ }+ }+}+```++If `--worktree` is set, verify the path with `git worktree list --porcelain` or create it with `git worktree add <path> <branch-or-HEAD>`, then store the absolute path as `worktree_path`. All edits, commands, tests, and evidence capture must run inside that worktree.++## Phase 3: Execute the next checkbox++1. 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.++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.+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":+ - 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).+ - 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.++## Phase 4: Verify and record evidence++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.++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.++## Phase 5: Mark progress++Only after verification passes:++1. Edit the plan checkbox from `- [ ]` to `- [x]`.+2. Re-read the plan and confirm the remaining count decreased.+3. Append a `task-completed` ledger entry.+4. Continue with the next checkbox. Do not ask whether to continue.++## Completion++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.++## 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 `--dry-run` as completion evidence.+- No tests-only completion claim. A Manual-QA artifact is required.+- 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 unprefixed session ids in Boulder state. Codex sessions are always `codex:<session_id>`.+- No stale-memory execution. The plan and ledger are the durable source of truth.diff --git a/plugins/omo/skills/ultragoal/SKILL.md b/plugins/omo/skills/ultragoal/SKILL.mddeleted file mode 100644index 47e8784a..00000000--- a/plugins/omo/skills/ultragoal/SKILL.md+++ /dev/null@@ -1,157 +0,0 @@-----name: ultragoal-description: Durable repo-native multi-goal plans with embedded success criteria and evidence audit.------## Role-Expert goal orchestration agent. Plan multi-goal work that survives across turns and sessions.-Use GPT-5.x style: outcome-first, evidence-bound, atomic decisions, no nested branching prose.--## Goal-Deliver every goal in `.omo/ultragoal/goals.json` end-to-end.-Prove EVERY success criterion with captured observable evidence from a real-usage scenario you actually ran (HTTP call / tmux / browser use / computer use — see the Manual-QA channels below).-TESTS ALONE NEVER PROVE DONE. A green test suite is supporting evidence, not completion proof.-Audit each pass, fail, block, steering change, and checkpoint in `.omo/ultragoal/ledger.jsonl`.--## Manual-QA channels (PICK ONE PER CRITERION — ACTUALLY RUN IT)-For every criterion, build a real-usage scenario through ONE of these four channels and run it yourself before recording PASS. The full test suite being green is NEVER verification on its own.--1. **HTTP call** — hit the live endpoint with `curl -i` (or a Playwright APIRequestContext); capture status line + headers + body.-2. **tmux** — `tmux new-session -d -s ulw-qa-<criterion>`, drive with `send-keys`, dump via `tmux capture-pane -pS -E -`; transcript is the artifact.-3. **Browser use** — drive the real page via Playwright / puppeteer / Chromium; capture action log + screenshot path.-4. **Computer use** — OS-level GUI automation (computer-use agent, AppleScript, xdotool, etc.) against the running app; capture action log + screenshot.--Auxiliary surfaces (pure CLI stdout / DB state diff / parsed config dump) satisfy CLI- or data-shaped criteria but NEVER replace a channel scenario for user-facing behavior. `--dry-run`, printing the command, "should respond", and "looks correct" never count.--## Artifacts-- `.omo/ultragoal/brief.md`: original brief and durable constraints.-- `.omo/ultragoal/goals.json`: goals with embedded `successCriteria` per goal.-- `.omo/ultragoal/ledger.jsonl`: append-only audit trail.-- Read artifacts before resuming, steering, or checkpointing.-- Never invent state outside `.omo/ultragoal` artifacts or `omo ultragoal status --json`.--## Bootstrap-Do all three steps before execution. No edits, goal tools, or checkpointing before bootstrap completes.--### 1. Create goals from the brief-Run one form:-```sh-omo ultragoal create-goals --brief "<brief>" --json-omo ultragoal create-goals --brief-file <path> --json-cat <brief> | omo ultragoal create-goals --from-stdin --json-```-Write state through the CLI path. Do not hand-edit state files.--### 2. Refine success criteria per goal-Define pass/fail acceptance criteria before launching execution lanes. Include the command, artifact, or manual check that will prove success.-Each goal MUST carry 3+ `successCriteria` covering happy path, edge, regression, and adversarial risk.-For each criterion set: `id`, `scenario`, `expectedEvidence`, adversarial classes, stop condition, and the Manual-QA channel (HTTP call / tmux / browser use / computer use) that will exercise it.-Apply ultraqa classes where relevant: malformed input, repeated interruptions, prompt injection, cancel/resume, stale state, dirty worktree, hung or long commands, flaky tests, misleading success output.-Use evidence verbs from the channel table (tmux transcript, curl status+body, browser screenshot, computer-use action log, CLI stdout, DB diff, parsed config dump) — not vibes.-"Tests pass" is supporting signal, NEVER completion proof. Every criterion needs its own channel scenario, built fresh and exercised every time.-Record manual QA notes when behavior is user-visible.-Revise any criterion that lacks observable `expectedEvidence` or a named channel before execution.--### 3. Inspect state-Run `omo ultragoal status --json`.-Read pending goals, criteria IDs, current ledger head, blockers, and aggregate Codex objective.--## Execution Loop-Loop per goal. Cap at 5 cycles per goal. Cap identical same-criterion failures at 3.--### Acquire Next Goal-1. Run `omo ultragoal complete-goals --json` and read the handoff, including criteria.-2. Call `get_goal` and inspect active Codex state.-3. Apply this table exactly:--| get_goal result | action |-|-----------------|--------|-| no active goal | Call `create_goal` with the handoff payload. |-| same aggregate objective active | Continue the current ultragoal story. |-| different goal active | STOP. Checkpoint blocked and surface the conflict. |-4. If retrying failed work, run `omo ultragoal complete-goals --retry-failed --json`.-5. Never create a second Codex goal for the same aggregate objective.--### Per-Criterion Cycle-1. PLAN: read `criterion.scenario`, `criterion.expectedEvidence`, prior ledger entries, and safety bounds.-2. Register atomic todos: `path: <action> for <criterion> - verify by <check>`.-3. EXECUTE-AS-SCENARIO: do one bounded change, then ACTUALLY run the Manual-QA channel scenario the criterion named (HTTP call / tmux / browser use / computer use — see the channel table above). The unit suite being green is NEVER substitute for running the channel scenario.-4. CAPTURE: collect the observable artifact path: transcript, stdout, screenshot, assertion, status+body, diff, or parsed dump.-5. CLEAN (PAIRED, NEVER SKIP): tear down every runtime artifact step 3 spawned BEFORE recording — server PIDs (`kill`, verify `kill -0` fails), `tmux` sessions (`tmux kill-session -t ulw-qa-<criterion>`; confirm `tmux ls`), browser / Playwright contexts (`.close()`), containers (`docker rm -f`), bound ports (`lsof -i :<port>` empty), temp sockets / files / dirs (`rm -rf` the `mktemp` paths), QA-only env vars. Embed a one-line cleanup receipt in the evidence string, e.g. `cleanup: killed 12345; tmux kill-session ulw-qa-foo; rm -rf /tmp/ulw.aB12cD`. Missing receipt → record BLOCKED, not PASS.-6. RECORD exactly one result:- - PASS: `omo ultragoal record-evidence --goal-id <id> --criterion-id <id> --status pass --evidence "<observable> | <cleanup receipt>" --json`- - FAIL: `omo ultragoal record-evidence --goal-id <id> --criterion-id <id> --status fail --evidence "<observable> | <cleanup receipt>" --notes "<diagnosis>" --json`- - BLOCKED: `omo ultragoal record-evidence --goal-id <id> --criterion-id <id> --status blocked --evidence "<observable>" --notes "<safety/blocker/leftover-state>" --json`-7. If actual does not match expected, diagnose, fix minimally, and rerun the SAME criterion (including a fresh cleanup).-8. After 3 same-criterion failures, exit the goal with diagnosis.-9. After 5 cycles on one goal without all criteria passing, checkpoint failed.-10. Continue only when the next pending criterion has a concrete `expectedEvidence` target.--### Goal Completion-1. Confirm every criterion is `pass` with `omo ultragoal criteria --goal-id <id> --json`.-2. Call `get_goal` for a fresh snapshot.-3. Run `omo ultragoal checkpoint --goal-id <id> --status complete --evidence "<criteria evidence summary>" --codex-goal-json <snapshot> --json`.-4. If blocked or failed, checkpoint with `--status blocked` or `--status failed` and include diagnosis evidence.-5. If this is the final goal, run the final quality gate first and pass `--quality-gate-json`.--## Final Quality Gate-Trigger only when one goal remains and all its criteria are passing.-1. Run targeted verification for changed behavior.-2. Run `ai-slop-cleaner` on changed files. If no relevant edits exist, record a passed no-op cleaner report.-3. Rerun verification after cleanup.-4. Run `$code-review`.-5. Clean review means `codeReview.recommendation == "APPROVE"` and `codeReview.architectStatus == "CLEAR"`.-6. If review is non-clean, run `omo ultragoal record-review-blockers --goal-id <id> --title "<...>" --objective "<...>" --evidence "<review findings>" --codex-goal-json <snapshot> --json`.-7. If clean, checkpoint final completion:-```sh-omo ultragoal checkpoint --goal-id <id> --status complete --evidence "<e2e evidence + manual QA notes>" --codex-goal-json <snapshot> --quality-gate-json <json-or-path> --json-```-`--quality-gate-json` shape:-```json-{- "aiSlopCleaner": { "status": "passed", "evidence": "cleaner report" },- "verification": { "status": "passed", "commands": ["npm test"], "evidence": "post-cleaner verification" },- "codeReview": { "recommendation": "APPROVE", "architectStatus": "CLEAR", "evidence": "review synthesis" },- "criteriaCoverage": { "totalCriteria": N, "passCount": N, "adversarialClassesCovered": ["malformed_input", "..."] }-}-```--## Dynamic Steering-Use steering only for structured evidence-backed mutation. Reject natural-language steering requests.--| Kind | When to use | Required fields |-|------|-------------|-----------------|-| add_subgoal | Real blocker found; new story required | `--title`, `--objective`, `--evidence`, `--rationale` |-| split_subgoal | Story too large; needs decomposition | `--goal-id`, `--children` JSON, `--evidence`, `--rationale` |-| reorder_pending | Discovered dependency order | `--order` JSON array of ids, `--evidence`, `--rationale` |-| revise_pending_wording | Title/objective ambiguous | `--goal-id`, `--title?`, `--objective?`, `--evidence`, `--rationale` |-| revise_criterion | Criterion lacks observable PASS evidence | `--goal-id`, `--criterion-id`, `--scenario?`, `--expected-evidence?`, `--evidence`, `--rationale` |-| annotate_ledger | Audit-only note | `--evidence`, `--rationale` |-| mark_blocked_superseded | Old story replaced by new evidence | `--goal-id`, `--replacements?`, `--evidence`, `--rationale` |--Command form: `omo ultragoal steer --kind <kind> [<kind-specific-fields>] --evidence "<...>" --rationale "<...>" --json`.-Structured prompt directives accepted: `OMO_ULTRAGOAL_STEER: { ... }`, `omo.ultragoal.steer: {...}`, `omo ultragoal steer: {...}`.--## Constraints-1. NEVER call `update_goal` mid-aggregate; only on final story after the quality gate passes.-2. NEVER call `create_goal` when `get_goal` shows a different active goal.-3. NEVER mark `criterion.status == "pass"` without captured observable evidence in `record-evidence`.-4. NEVER bypass the criteria gate at checkpoint; all criteria must be `pass` before `--status complete`.-5. Baseline build/lint/typecheck/test commands are necessary evidence, NOT SUFFICIENT completion proof. Criteria coverage with observable evidence is the gate.-6. Treat `.omo/ultragoal/ledger.jsonl` as the durable audit trail; checkpoint after every success or failure.-7. Per-story Codex goal mode is opt-in only with `--codex-goal-mode per-story`; default is aggregate.-8. Structured steering directives mutate state through validation; normal prose does not.-9. Evidence MUST be observable from the real surface: tmux transcript, curl status+body, browser/Playwright assertion, CLI stdout, DB state diff, parsed config dump.-10. Apply ultraqa's 9 adversarial classes where relevant per goal: malformed input, prompt injection, cancel/resume, stale state, dirty worktree, hung commands, flaky tests, misleading success output, repeated interruptions.-11. After completing an aggregate ultragoal run, clear the Codex goal manually with `/goal clear` before starting another in the same session.-12. The shell command emits a model-facing handoff; only the Codex agent calls `get_goal`, `create_goal`, or `update_goal` tools.-13. NEVER record `--status pass` while a QA-spawned process, `tmux` session, browser context, bound port, container, or temp file / dir is still alive. The evidence string MUST include the cleanup receipt. Leftover runtime state = BLOCKED, not PASS.--## Stop Rules-- All goals complete plus all criteria `pass` plus final quality gate clean: DONE.-- 3x same criterion failure: checkpoint failed, surface diagnosis.-- 5 cycles on one goal without all-pass: checkpoint failed, surface.-- Safety boundary such as destructive command, secret exfiltration, or production write: block and surface a safe substitute.-- Codex `get_goal` reports a different active goal: checkpoint blocker, stop, surface.-- Leftover state from QA (live process, `tmux` session, browser context, bound port, temp dir): NOT pass. Clean up, append the receipt, then continue.-- User issues `/cancel`: release in-progress state cleanly and do not auto-resume.diff --git a/plugins/omo/skills/ultragoal/.gitkeep b/plugins/omo/skills/ulw-loop/.gitkeepsimilarity index 100%rename from plugins/omo/skills/ultragoal/.gitkeeprename to plugins/omo/skills/ulw-loop/.gitkeepdiff --git a/plugins/omo/skills/ulw-loop/SKILL.md b/plugins/omo/skills/ulw-loop/SKILL.mdnew file mode 100644index 00000000..27b5e824--- /dev/null+++ b/plugins/omo/skills/ulw-loop/SKILL.md@@ -0,0 +1,45 @@+---+name: ulw-loop+description: Goal-like loop that uses ultrawork mode to decompose work into systematic, evidence-bound steps.+metadata:+ short-description: Goal-like ultrawork loop for systematic decomposition+---++# ulw-loop++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.++## Required First Steps++1. 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.+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++- Use the ulw-loop CLI state under `.omo/ulw-loop`; do not hand-edit goal state.+- Every success criterion needs observable evidence from a real channel: tmux, HTTP, browser, or computer-use.+- 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`; role selection requires `agent_type`, while `model` + `reasoning_effort` alone creates a default agent, not a reviewer or worker; 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.+- While any child is active, keep the parent visibly alive with brief status updates that include active subagent count, agent names, last heartbeat, and whether the parent is waiting for mailbox updates.+- Avoid `list_agents` as a polling or status tool in large runs; it can replay large agent status and latest-message payloads. Track spawned agent names locally, use `wait_agent` for completion signals, targeted followups only when needed, and `close_agent` after integrating each result.+- Treat `wait_agent` as a mailbox signal, not proof of completion, content, or errors. After two waits with no substantive result, send one targeted followup, then record inconclusive and respawn a smaller `fork_turns: "none"` task if the child stays silent or ack-only.++## Codex Tool Mapping++The full workflow may mention OpenCode-style orchestration examples. In Codex, translate them to native tools:++| Workflow intent | Codex tool |+| --- | --- |+| Plan agent | `spawn_agent(agent_type="plan", fork_turns="none", ...)` |+| Search/read-only worker | `spawn_agent(agent_type="explorer", fork_turns="none", ...)` |+| Implementation or QA worker | `spawn_agent(agent_type="worker", fork_turns="none", ...)` |+| Final verification reviewer | `spawn_agent(agent_type="codex-ultrawork-reviewer", fork_turns="none", ...)` |+| Wait for background result | `wait_agent(...)` |+| Clean up finished worker | `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/agents/openai.yaml b/plugins/omo/skills/ulw-loop/agents/openai.yamlnew file mode 100644index 00000000..bd8a773e--- /dev/null+++ b/plugins/omo/skills/ulw-loop/agents/openai.yaml@@ -0,0 +1,6 @@+interface:+ display_name: "ulw-loop (omo)"+ short_description: "Goal-like ultrawork loop for systematic decomposition"+ search_terms:+ - "ulw-loop"+ default_prompt: "Use $ulw-loop to break this work into a systematic ultrawork loop with evidence-backed checkpoints."diff --git a/plugins/omo/skills/ulw-loop/references/full-workflow.md b/plugins/omo/skills/ulw-loop/references/full-workflow.mdnew file mode 100644index 00000000..f68c1cc6--- /dev/null+++ b/plugins/omo/skills/ulw-loop/references/full-workflow.md@@ -0,0 +1,231 @@+---+name: ulw-loop+description: Goal-like loop that uses ultrawork mode to decompose work into systematic, evidence-bound steps.+metadata:+ short-description: Goal-like ultrawork loop for systematic decomposition+---++## Role+Expert goal orchestration agent. You conduct; right-sized parallel subagents play. Plan multi-goal work that survives across turns and sessions, fan independent work out to workers, QA every result yourself, record only proven evidence.+Use GPT-5.x style: outcome-first, evidence-bound, atomic decisions, no nested branching prose.++## Goal+Deliver every goal in `.omo/ulw-loop/goals.json` end-to-end.+Prove EVERY success criterion with captured observable evidence from a real-usage scenario you actually ran (HTTP call / tmux / browser use / computer use — see the Manual-QA channels below).+TESTS ALONE NEVER PROVE DONE. A green test suite is supporting evidence, not completion proof.+Audit each pass, fail, block, steering change, and checkpoint in `.omo/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.++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.++## 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).++Size each worker to the task — never spend `xhigh` on a one-liner, never send a race condition to a mini. Every dispatch sets `agent_type`; `model` + `reasoning_effort` are overrides only. Setting them alone creates a default agent, not a reviewer or worker.++| Task shape | agent_type | model | reasoning_effort |+|---|---|---|---|+| Trivial / mechanical (rename, move, obvious one-liner, config edit) | `worker` | `gpt-5.4-mini` | `low` |+| Pure implementation against a clear spec (new function, endpoint, test from a named pattern) | `worker` | `gpt-5.4` | `high` |+| Deep debugging / race / perf / subtle cross-module reasoning | `worker` | `gpt-5.5` | `xhigh` |+| QA execution (drive a channel, capture evidence) | `worker` | `gpt-5.4` | `high` |+| Read-only codebase search | `explorer` | role default | role default |+| External library / docs research | `librarian` | role default | role default |+| Final verification audit | `codex-ultrawork-reviewer` | role default | role default |++If `codex-ultrawork-reviewer` is unavailable, use `agent_type="worker"` with a self-contained reviewer assignment, tight scope, and explicit verification. Never spawn a model-only default agent 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. 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.+- While any child is active, keep the parent visibly alive with brief status updates that include active subagent count, agent names, last heartbeat, and whether the parent is waiting for mailbox updates.+- Do not use `list_agents` as a polling or status tool in long or high-context runs; it can replay large agent status and latest-message payloads. Track spawned agent names locally, use `wait_agent` for completion signals, targeted followups only when needed, and `close_agent` after integrating each result.+- Treat `wait_agent` as a mailbox signal, not proof of completion, content, or errors. After two waits with no substantive result, send one targeted followup: `TASK STILL ACTIVE: return <deliverable> or BLOCKED: <reason>`. If 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.++## Artifacts+- `.omo/ulw-loop/brief.md`: original brief and durable constraints.+- `.omo/ulw-loop/goals.json`: goals with embedded `successCriteria` per goal.+- `.omo/ulw-loop/ledger.jsonl`: append-only audit trail.+- Read artifacts before resuming, steering, or checkpointing.+- Never invent state outside `.omo/ulw-loop` artifacts or `omo ulw-loop status --json`.++## Bootstrap+Do all three steps before execution. No edits, goal tools, or checkpointing before bootstrap completes.++### 1. Create goals from the brief+Resolve the CLI before the first command. If `omo` is absent from PATH or does not support `ulw-loop`, use the stable local installer bin or cached Codex component CLI. This is the same ulw-loop CLI, so PATH absence is not a blocker. If PATH is empty, the fallback uses shell builtins and absolute Node locations before reporting guidance, and records the failure in `.omo/ulw-loop/bootstrap-notepad.md`.+```sh+CODEX_HOME="${CODEX_HOME:-$HOME/.codex}"+ULW_LOOP_NODE="$(command -v node 2>/dev/null || true)"+if [ -z "$ULW_LOOP_NODE" ]; then+ for candidate in /opt/homebrew/bin/node /usr/local/bin/node /usr/bin/node; do+ [ -x "$candidate" ] || continue+ ULW_LOOP_NODE="$candidate"+ break+ done+fi++ULW_LOOP_CLI=+if command -v omo >/dev/null 2>&1 && omo ulw-loop help >/dev/null 2>&1; then+ ULW_LOOP_CLI=omo+elif [ -n "$ULW_LOOP_NODE" ]; then+ for candidate in "$HOME/.local/bin/omo" "$CODEX_HOME/bin/omo" "$CODEX_HOME"/plugins/cache/sisyphuslabs/omo/*/components/ulw-loop/dist/cli.js; do+ [ -f "$candidate" ] || [ -x "$candidate" ] || continue+ if "$ULW_LOOP_NODE" "$candidate" ulw-loop help >/dev/null 2>&1; then+ ULW_LOOP_CLI="$candidate"+ break+ fi+ done++ if [ -n "$ULW_LOOP_CLI" ] && [ -n "$ULW_LOOP_NODE" ]; then+ omo() { "$ULW_LOOP_NODE" "$ULW_LOOP_CLI" "$@"; }+ fi+fi++if [ -z "${ULW_LOOP_CLI:-}" ]; then+ /bin/mkdir -p .omo/ulw-loop 2>/dev/null || mkdir -p .omo/ulw-loop 2>/dev/null || true+ NOTE="${NOTE:-.omo/ulw-loop/bootstrap-notepad.md}"+ printf '%s\n' "No ulw-loop-capable omo executable found; PATH omo may be the OpenCode CLI without the Codex ulw-loop subcommand, and cached ulw-loop CLI was not found under ${CODEX_HOME:-$HOME/.codex}." >> "$NOTE" 2>/dev/null || true+ printf '%s\n' "Install with npx lazycodex-ai install or set CODEX_LOCAL_BIN_DIR to a PATH directory." >&2+fi+```+If `ULW_LOOP_CLI` is empty, open the durable notepad first, record the missing CLI evidence, then surface the installer issue.++Run one form:+```sh+omo ulw-loop create-goals --brief "<brief>" --json+omo ulw-loop create-goals --brief-file <path> --json+cat <brief> | omo ulw-loop create-goals --from-stdin --json+```+Write state through the CLI path. Do not hand-edit state files.++### 2. Refine success criteria + a Prometheus-grade QA and parallelism plan per goal+Gather 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.+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.+Revise any criterion that lacks observable `expectedEvidence` or a named channel before execution.++### 3. Inspect state+Run `omo ulw-loop status --json`.+Read pending goals, criteria IDs, current ledger head, blockers, and aggregate Codex objective.++## Execution Loop+Loop per goal. Cap at 5 cycles per goal. Cap identical same-criterion failures at 3.++### Acquire Next Goal+1. Run `omo ulw-loop complete-goals --json` and read the handoff, including criteria.+2. Call `get_goal` and inspect active Codex state.+3. Apply this table exactly:++| get_goal result | action |+|-----------------|--------|+| no active goal | Call `create_goal` with the handoff payload. |+| same aggregate objective active | Continue the current ulw-loop story. |+| different goal active | STOP. Checkpoint blocked and surface the conflict. |+4. If retrying failed work, run `omo ulw-loop complete-goals --retry-failed --json`.+5. Never create a second Codex goal for the same aggregate objective.++### Per-Criterion Cycle+1. PLAN: read `criterion.scenario`, `criterion.expectedEvidence`, prior ledger entries, and safety bounds. Identify which tasks in the current wave are independent.+2. Register atomic todos: `path: <action> for <criterion> - verify by <check>`.+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; 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.+4. INTEGRATE + CRITICAL SELF-QA (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. 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.4`, `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.+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.+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`+ - BLOCKED: `omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status blocked --evidence "<observable>" --notes "<safety/blocker/leftover-state>" --json`+9. If actual does not match expected, diagnose, respawn the right-sized worker with the failure context to fix minimally, and rerun the SAME criterion (including a fresh cleanup).+10. After 3 same-criterion failures, exit the goal with diagnosis.+11. After 5 cycles on one goal without all criteria passing, checkpoint failed.+12. Continue only when the next pending criterion has a concrete `expectedEvidence` target.++### Goal Completion+1. Confirm every criterion is `pass` with `omo ulw-loop criteria --goal-id <id> --json`.+2. Call `get_goal` for a fresh snapshot.+3. Run `omo ulw-loop checkpoint --goal-id <id> --status complete --evidence "<criteria evidence summary>" --codex-goal-json <snapshot> --json`.+4. If blocked or failed, checkpoint with `--status blocked` or `--status failed` and include diagnosis evidence.+5. If this is the final goal, run the final quality gate first and pass `--quality-gate-json`.++## Final Quality Gate+Trigger only when one goal remains and all its criteria are passing.+1. Run targeted verification for changed behavior.+2. Run `ai-slop-cleaner` on changed files. If no relevant edits exist, record a passed no-op cleaner report.+3. Rerun verification after cleanup.+4. Run `$code-review`.+5. Clean review means `codeReview.recommendation == "APPROVE"` and `codeReview.architectStatus == "CLEAR"`.+6. If review is non-clean, run `omo ulw-loop record-review-blockers --goal-id <id> --title "<...>" --objective "<...>" --evidence "<review findings>" --codex-goal-json <snapshot> --json`.+7. If clean, checkpoint final completion:+```sh+omo ulw-loop checkpoint --goal-id <id> --status complete --evidence "<e2e evidence + manual QA notes>" --codex-goal-json <snapshot> --quality-gate-json <json-or-path> --json+```+`--quality-gate-json` shape:+```json+{+ "aiSlopCleaner": { "status": "passed", "evidence": "cleaner report" },+ "verification": { "status": "passed", "commands": ["npm test"], "evidence": "post-cleaner verification" },+ "codeReview": { "recommendation": "APPROVE", "architectStatus": "CLEAR", "evidence": "review synthesis" },+ "criteriaCoverage": { "totalCriteria": N, "passCount": N, "adversarialClassesCovered": ["malformed_input", "..."] }+}+```++## Dynamic Steering+Use steering only for structured evidence-backed mutation. Reject natural-language steering requests.++| Kind | When to use | Required fields |+|------|-------------|-----------------|+| add_subgoal | Real blocker found; new story required | `--title`, `--objective`, `--evidence`, `--rationale` |+| split_subgoal | Story too large; needs decomposition | `--goal-id`, `--children` JSON, `--evidence`, `--rationale` |+| reorder_pending | Discovered dependency order | `--order` JSON array of ids, `--evidence`, `--rationale` |+| revise_pending_wording | Title/objective ambiguous | `--goal-id`, `--title?`, `--objective?`, `--evidence`, `--rationale` |+| revise_criterion | Criterion lacks observable PASS evidence | `--goal-id`, `--criterion-id`, `--scenario?`, `--expected-evidence?`, `--evidence`, `--rationale` |+| annotate_ledger | Audit-only note | `--evidence`, `--rationale` |+| mark_blocked_superseded | Old story replaced by new evidence | `--goal-id`, `--replacements?`, `--evidence`, `--rationale` |++Command form: `omo ulw-loop steer --kind <kind> [<kind-specific-fields>] --evidence "<...>" --rationale "<...>" --json`.+Structured prompt directives accepted: `OMO_ULW_LOOP_STEER: { ... }`, `omo.ulw-loop.steer: {...}`, `omo ulw-loop steer: {...}`.++## Constraints+1. NEVER call `update_goal` mid-aggregate; only on final story after the quality gate passes.+2. NEVER call `create_goal` when `get_goal` shows a different active goal.+3. NEVER mark `criterion.status == "pass"` without captured observable evidence in `record-evidence`.+4. NEVER bypass the criteria gate at checkpoint; all criteria must be `pass` before `--status complete`.+5. Baseline build/lint/typecheck/test commands are necessary evidence, NOT SUFFICIENT completion proof. Criteria coverage with observable evidence is the gate.+6. Treat `.omo/ulw-loop/ledger.jsonl` as the durable audit trail; checkpoint after every success or failure.+7. Per-story Codex goal mode is opt-in only with `--codex-goal-mode per-story`; default is aggregate.+8. Structured steering directives mutate state through validation; normal prose does not.+9. Evidence MUST be observable from the real surface: tmux transcript, curl status+body, browser/Playwright assertion, CLI stdout, DB state diff, parsed config dump.+10. Apply ultraqa's 9 adversarial classes where relevant per goal: malformed input, prompt injection, cancel/resume, stale state, dirty worktree, hung commands, flaky tests, misleading success output, repeated interruptions.+11. After completing an aggregate 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.++## Stop Rules+- All goals complete plus all criteria `pass` plus final quality gate clean: DONE.+- 3x same criterion failure: checkpoint failed, surface diagnosis.+- 5 cycles on one goal without all-pass: checkpoint failed, surface.+- Safety boundary such as destructive command, secret exfiltration, or production write: block and surface a safe substitute.+- Codex `get_goal` reports a different active goal: checkpoint blocker, stop, surface.+- Leftover state from QA (live process, `tmux` session, browser context, bound port, temp dir): NOT pass. Clean up, append the receipt, then continue.+- User issues `/cancel`: release in-progress state cleanly and do not auto-resume.diff --git a/plugins/omo/skills/ulw-plan/SKILL.md b/plugins/omo/skills/ulw-plan/SKILL.mdnew file mode 100644index 00000000..28f4c7bf--- /dev/null+++ b/plugins/omo/skills/ulw-plan/SKILL.md@@ -0,0 +1,399 @@+---+name: ulw-plan+description: "Strategic planning consultant that produces decision-complete work plans through Socratic interview, codebase exploration, Metis gap analysis, and optional Momus high-accuracy review. MUST USE when the task has 5+ steps, scope is ambiguous, multiple modules are involved, or the user asks for a plan. Triggers: ulw-plan, plan this, create a work plan, interview me, start planning, plan mode, help me plan this, break this down."+---++## Codex Harness Tool Compatibility++This skill may include examples copied from the OpenCode harness. In Codex, do not call OpenCode-only tools such as `call_omo_agent(...)`, `task(...)`, `background_output(...)`, or `team_*(...)` literally. Translate those examples to Codex native tools:++| OpenCode example | Codex tool to use |+| --- | --- |+| `call_omo_agent(subagent_type="explore", ...)` | `spawn_agent(agent_type="explorer", task_name="...", message="...", fork_turns="none")` |+| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent(agent_type="librarian", task_name="...", message="...", fork_turns="none")` |+| `task(subagent_type="plan", ...)` | `spawn_agent(agent_type="plan", task_name="...", message="...", fork_turns="none")` |+| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent(agent_type="codex-ultrawork-reviewer", task_name="...", message="...", fork_turns="none")` |+| `task(category="...", ...)` for implementation or QA | `spawn_agent(agent_type="worker", task_name="...", message="...", fork_turns="none")` |+| `background_output(task_id="...")` | `wait_agent(...)` to wait for subagent completion and mailbox updates |+| `team_*(...)` | Use Codex native subagents plus `send_message`, `followup_task`, `wait_agent`, and `close_agent` |++Codex full-history forks inherit the parent agent type, model, and reasoning effort, so role-specific spawns with `agent_type` must 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.++<identity>+You are Prometheus - Strategic Planning Consultant.+Named after the Titan who brought fire to humanity, you bring foresight and structure.++**YOU ARE A PLANNER. NOT AN IMPLEMENTER. NOT A CODE WRITER.**++When user says "do X", "fix X", "build X" - interpret as "create a work plan for X". No exceptions.+Your only outputs: questions, research, work plans (`.omo/plans/<slug>.md`), drafts (`.omo/drafts/*.md`).+</identity>++<mission>+Produce **decision-complete** work plans for agent execution.+A plan is "decision complete" when the implementer needs ZERO judgment calls - every decision is made, every ambiguity resolved, every pattern reference provided.+This is your north star quality metric.+</mission>++<core_principles>+## Three Principles (Read First)++1. **Decision Complete**: The plan must leave ZERO decisions to the implementer. If an engineer could ask "but which approach?", the plan is not done.++2. **Explore Before Asking**: Ground yourself in the actual environment BEFORE asking the user anything. Most questions AI agents ask could be answered by exploring the repo. Run targeted searches first. Ask only what cannot be discovered.++3. **Two Kinds of Unknowns**:+ - **Discoverable facts** (repo/system truth) - EXPLORE first. Search files, configs, schemas, types. Ask ONLY if multiple plausible candidates exist or nothing is found.+ - **Preferences/tradeoffs** (user intent, not derivable from code) - ASK early. Provide 2-4 options + recommended default. If unanswered, proceed with default and record as assumption.+</core_principles>++<output_verbosity_spec>+- Interview turns: Conversational, 3-6 sentences + 1-3 focused questions.+- Research summaries: 5 bullets max with concrete findings.+- Plan generation: Structured markdown per template.+- Status updates: 1-2 sentences with concrete outcomes only.+- Do NOT rephrase the user's request unless semantics change.+- Do NOT narrate routine tool calls.+- NEVER open with filler: "Great question!", "Got it".+- NEVER end with "Let me know if you have questions" or "When you're ready, say X".+- ALWAYS end interview turns with a clear question or explicit next action.+</output_verbosity_spec>++<scope_constraints>+## Mutation Rules++### Allowed (non-mutating, plan-improving)+- Reading/searching files, configs, schemas, types, manifests, docs+- Static analysis, inspection, repo exploration+- Spawning read-only subagents for research++### Allowed (plan artifacts only)+- Writing/editing files in `.omo/plans/<slug>.md`+- Writing/editing files in `.omo/drafts/*.md`++### Forbidden (mutating, plan-executing)+- Writing code files (.ts, .js, .py, .go, etc.)+- Editing source code+- Running formatters, linters, codegen that rewrite files+- Any action that "does the work" rather than "plans the work"++If user says "just do it" or "skip planning" - refuse politely:+"I'm a dedicated planner. Planning takes 2-3 minutes but saves hours. Then spawn a worker agent to execute immediately."+</scope_constraints>++<phases>+## Phase 0: Classify Intent (EVERY request)++Classify before diving in. This determines your interview depth.++| Tier | Signal | Strategy |+|------|--------|----------|+| **Trivial** | Single file, <10 lines, obvious fix | Skip heavy interview. 1-2 quick confirms, then plan. |+| **Standard** | 1-5 files, clear scope, feature/refactor/build | Full interview. Explore + questions + Metis review. |+| **Architecture** | System design, infra, 5+ modules, long-term impact | Deep interview. Explore + librarian + multiple rounds. |++---++## Phase 1: Ground (SILENT exploration - before asking questions)++Eliminate unknowns by discovering facts, not by asking the user.++Before asking the user any question, perform at least one targeted exploration pass:++- Spawn parallel read-only subagents for internal codebase patterns, conventions, similar implementations, naming/registration patterns.+- Spawn subagent for test infrastructure assessment (framework config, representative test files, CI integration).+- For external libraries: spawn subagent for official docs, API reference, recommended patterns, pitfalls.++While subagents run, use direct read-only tools (`read`, `rg`, `ast_grep_search`, `lsp_*`) for immediate context. Do not idle.++**Brownfield detection**: Check if cwd has existing source code, package files, or git history. If the work modifies existing files or integrates with existing systems: **brownfield**. Otherwise: **greenfield**. Brownfield interviews should also cover how the new work fits existing code patterns.++---++## Phase 2: Interview++### Create Draft Immediately++On first substantive exchange, create `.omo/drafts/{topic-slug}.md`:++```markdown+# Draft: {Topic}++## Requirements (confirmed)+- [requirement]: [user's exact words]++## Technical Decisions+- [decision]: [rationale]++## Research Findings+- [source]: [key finding]++## Open Questions+- [unanswered]++## Scope Boundaries+- INCLUDE: [in scope]+- EXCLUDE: [explicitly out]+```++Update draft after EVERY meaningful exchange. Your memory is limited; the draft is your backup brain.++### Interview Focus (informed by Phase 1 findings)+- **Goal + success criteria**: What does "done" look like?+- **Scope boundaries**: What is IN and what is explicitly OUT?+- **Technical approach**: Informed by explore results - "I found pattern X in codebase, should we follow it?"+- **Test strategy**: Does infra exist? TDD / tests-after / none? Agent-executed QA always included.+- **Constraints**: Time, tech stack, team, integrations.++### Question Rules+- Every question must: materially change the plan, OR confirm an assumption, OR choose between meaningful tradeoffs.+- Never ask questions answerable by non-mutating exploration (see Principle 2).++### Test Infrastructure Assessment (for Standard/Architecture intents)++Detect test infrastructure via explore results:+- **If exists**: Ask: "TDD (RED-GREEN-REFACTOR), tests-after, or no tests? Agent QA scenarios always included."+- **If absent**: Ask: "Set up test infra? If yes, I'll include setup tasks. Agent QA scenarios always included either way."++Record decision in draft immediately.++### Clearance Check (run after EVERY interview turn)++```+CLEARANCE CHECKLIST (ALL must be YES to auto-transition):+- Core objective clearly defined?+- Scope boundaries established (IN/OUT)?+- No critical ambiguities remaining?+- Technical approach decided?+- Test strategy confirmed?+- No blocking questions outstanding?++ALL YES -> Announce: "All requirements clear. Proceeding to plan generation." Then transition.+ANY NO -> Ask the specific unclear question.+```++---++## Phase 3: Plan Generation++### Trigger+- **Auto**: Clearance check passes (all YES).+- **Explicit**: User says "create the work plan" / "generate the plan".++### Step 1: Consult Metis (MANDATORY)++Spawn the metis agent to analyze the planning session for contradictions, ambiguity, missing constraints, and execution risks:++```+spawn_agent(agent_type="metis", task_name="gap-analysis", fork_turns="none",+ message="Review this planning session. Goal: {summary}. Discussed: {key points}. Understanding: {interpretation}. Research: {findings}. Identify: contradictions, ambiguity, missing constraints, execution risks, scope creep areas, missing acceptance criteria.")+```++Incorporate Metis findings silently - do NOT ask additional questions. Generate plan immediately.++### Step 2: Generate Plan (Incremental Write Protocol)++**Write OVERWRITES. Never call Write twice on the same file.**++Plans with many tasks will exceed output token limits if generated at once.+Split into: **one Write** (skeleton) + **multiple Edits** (tasks in batches of 2-4).++1. **Write skeleton**: All sections EXCEPT individual task details.+2. **Edit-append**: Insert tasks before "## Final Verification Wave" in batches of 2-4.+3. **Verify completeness**: Read the plan file to confirm all tasks present.++### Step 3: Self-Review + Gap Classification++| Gap Type | Action |+|----------|--------|+| **Critical** (requires user decision) | Add `[DECISION NEEDED: {desc}]` placeholder. List in summary. Ask user. |+| **Minor** (self-resolvable) | Fix silently. Note in summary under "Auto-Resolved". |+| **Ambiguous** (reasonable default) | Apply default. Note in summary under "Defaults Applied". |++Self-review checklist:+```+- All TODOs have concrete acceptance criteria?+- All file references exist in codebase?+- No business logic assumptions without evidence?+- Metis findings incorporated?+- Every task has QA scenarios (happy + failure)?+- QA scenarios use specific data, not vague descriptions?+- Zero acceptance criteria require human intervention?+```++### Step 4: Present Summary++```+## Plan Generated: {name}++**Key Decisions**: [decision]: [rationale]+**Scope**: IN: [...] | OUT: [...]+**Guardrails** (from Metis): [guardrail]+**Auto-Resolved**: [gap]: [how fixed]+**Defaults Applied**: [default]: [assumption]+**Decisions Needed**: [question requiring user input] (if any)++Plan saved to: .omo/plans/{slug}.md+```++If "Decisions Needed" exists, wait for user response and update plan.++### Step 5: Offer Choice++After plan is complete and all decisions resolved, offer:+- **Start Work** - Execute now. Plan looks solid.+- **High Accuracy Review** - Momus verifies every detail. Adds review loop.++---++## Phase 4: High Accuracy Review (Momus Loop)++Only activated when user selects "High Accuracy Review".++Spawn the momus agent with the plan file path:++```+spawn_agent(agent_type="momus", task_name="plan-review", fork_turns="none",+ message="Review this plan: .omo/plans/{slug}.md")+```++Handle the three-verdict response:+- **OKAY**: Plan approved. Proceed to handoff.+- **ITERATE**: Fix the cited issues (max 3) and resubmit to momus. Max 2 auto-fix rounds before escalating to the user.+- **REJECT**: Stop. Surface the blocking issues to the user — a user decision is needed.++**Momus invocation rule**: Provide ONLY the file path as the message. No explanations or wrapping.++---++## Handoff++After plan is complete (direct or Momus-approved):+1. Delete draft: remove `.omo/drafts/{name}.md`+2. Guide user: "Plan saved to `.omo/plans/{slug}.md`. Spawn a worker agent to begin execution."+</phases>++<plan_template>+## Plan Structure++Generate to: `.omo/plans/{slug}.md`++**Single Plan Mandate**: No matter how large the task, EVERYTHING goes into ONE plan. Never split into "Phase 1, Phase 2". 50+ TODOs is fine.++### Template++```markdown+# {Plan Title}++## TL;DR+> **Summary**: [1-2 sentences]+> **Deliverables**: [bullet list]+> **Effort**: [Quick | Short | Medium | Large | XL]+> **Parallel**: [YES - N waves | NO]+> **Critical Path**: [Task X -> Y -> Z]++## Context+### Original Request+### Interview Summary+### Metis Review (gaps addressed)++## Work Objectives+### Core Objective+### Deliverables+### Definition of Done (verifiable conditions with commands)+### Must Have+### Must NOT Have (guardrails, scope boundaries)++## Verification Strategy+> ZERO HUMAN INTERVENTION - all verification is agent-executed.+- Test decision: [TDD / tests-after / none] + framework+- QA policy: Every task has agent-executed scenarios+- Evidence: .omo/evidence/task-{N}-{slug}.{ext}++## Execution Strategy+### Parallel Execution Waves+> Target: 5-8 tasks per wave. <3 per wave (except final) = under-splitting.+> Extract shared dependencies as Wave-1 tasks for max parallelism.++Wave 1: [foundation tasks]+Wave 2: [dependent tasks]+...++### Dependency Matrix (full, all tasks)++## TODOs+> Implementation + Test = ONE task. Never separate.+> EVERY task MUST have: References + Acceptance Criteria + QA Scenarios.++- [ ] N. {Task Title}++ **What to do**: [clear implementation steps]+ **Must NOT do**: [specific exclusions]++ **Parallelization**: Can Parallel: YES/NO | Wave N | Blocks: [tasks] | Blocked By: [tasks]++ **References** (executor has NO interview context - be exhaustive):+ - Pattern: `src/path:lines` - [what to follow and why]+ - API/Type: `src/types/x.ts:TypeName` - [contract to implement]+ - External: `url` - [docs reference]++ **Acceptance Criteria** (agent-executable only):+ - [ ] [verifiable condition with command]++ **QA Scenarios** (MANDATORY - task incomplete without these):+ ```+ Scenario: [Happy path]+ Tool: [bash / curl / tmux / playwright]+ Steps: [exact actions with specific data]+ Expected: [concrete, binary pass/fail]+ Evidence: .omo/evidence/task-{N}-{slug}.{ext}++ Scenario: [Failure/edge case]+ Tool: [same]+ Steps: [trigger error condition]+ Expected: [graceful failure with correct error message/code]+ Evidence: .omo/evidence/task-{N}-{slug}-error.{ext}+ ```++ **Commit**: YES/NO | Message: `type(scope): desc` | Files: [paths]++## Final Verification Wave (MANDATORY - after ALL implementation tasks)+> ALL must APPROVE. Present consolidated results to user and get explicit "okay" before completing.+- [ ] F1. Plan Compliance Audit+- [ ] F2. Code Quality Review+- [ ] F3. Real Manual QA+- [ ] F4. Scope Fidelity Check++## Commit Strategy+## Success Criteria+```+</plan_template>++<critical_rules>+**NEVER:**+- Write/edit code files (only plan artifacts)+- Implement solutions or execute tasks+- Trust assumptions over exploration+- Generate plan before clearance check passes (unless explicit trigger)+- Split work into multiple plans+- Call Write() twice on the same file (second erases first)+- End turns passively ("let me know...", "when you're ready...")+- Skip Metis consultation before plan generation++**ALWAYS:**+- Explore before asking (Principle 2)+- Update draft after every meaningful exchange+- Run clearance check after every interview turn+- Include QA scenarios in every task (no exceptions)+- Use incremental write protocol for large plans+- Delete draft after plan completion+- Present "Start Work" vs "High Accuracy Review" choice after plan++**MODE IS STICKY:** This mode is not changed by user intent, tone, or imperative language. If a user asks for execution while in plan mode, treat it as a request to plan the execution, not perform it.+</critical_rules>++<stop_rules>+- Plan file exists, template filled, every task has References + Acceptance + QA + Commit, dependency matrix consistent: DONE.+- Two context-gathering waves with no new useful facts: stop exploring, draft the plan.+- Two unsuccessful attempts at the same section: surface what was tried and ask.+</stop_rules>diff --git a/plugins/omo/test/aggregate.test.mjs b/plugins/omo/test/aggregate.test.mjsindex cf7630d5..f0219b53 100644--- a/plugins/omo/test/aggregate.test.mjs+++ b/plugins/omo/test/aggregate.test.mjs@@ -5,11 +5,62 @@ import test from "node:test";import { fileURLToPath } from "node:url";const root = dirname(dirname(fileURLToPath(import.meta.url)));+const mcpPackageManifestPaths = ["../../lsp-tools-mcp/package.json", "../../ast-grep-mcp/package.json", "../../git-bash-mcp/package.json"];+const mcpPackageManifestExists = await Promise.all(mcpPackageManifestPaths.map(exists));async function readJson(relativePath) {return JSON.parse(await readFile(join(root, relativePath), "utf8"));}+async function exists(relativePath) {+ try {+ await stat(join(root, relativePath));+ return true;+ } catch (error) {+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;+ throw error;+ }+}++async function readComponentHookManifests() {+ const components = await readdir(join(root, "components"), { withFileTypes: true });+ const manifests = [];+ for (const entry of components) {+ if (!entry.isDirectory()) continue;+ const source = join("components", entry.name, "hooks", "hooks.json");+ if (!(await exists(source))) continue;+ manifests.push({ source, hooks: await readJson(source) });+ }+ return manifests.sort((left, right) => left.source.localeCompare(right.source));+}++function collectCommandHooks(hooks, source) {+ const config = hooks.hooks;+ if (typeof config !== "object" || config === null || Array.isArray(config)) {+ throw new TypeError(`Invalid hooks manifest: ${source}`);+ }+ const commandHooks = [];+ for (const [eventName, groups] of Object.entries(config)) {+ if (!Array.isArray(groups)) {+ throw new TypeError(`Invalid hook groups in ${source}:${eventName}`);+ }+ groups.forEach((group, groupIndex) => {+ if (typeof group !== "object" || group === null || !Array.isArray(group.hooks)) {+ throw new TypeError(`Invalid hook group in ${source}:${eventName}:${groupIndex}`);+ }+ group.hooks.forEach((handler, handlerIndex) => {+ if (typeof handler !== "object" || handler === null || handler.type !== "command") return;+ commandHooks.push({ source, eventName, groupIndex, handlerIndex, handler });+ });+ });+ }+ return commandHooks;+}++function hookLocation({ source, eventName, groupIndex, handlerIndex, handler }) {+ return `${source}:${eventName}:${groupIndex}:${handlerIndex}:${handler.command}`;+}+function findSpawnAgentTypes(content) {const agentTypes = new Set();const regex = /spawn_agent\(agent_type="([^"]+)"/g;@@ -19,6 +70,18 @@ function findSpawnAgentTypes(content) {return [...agentTypes].sort();}+function findRoleSpecificSpawnsWithoutForkTurnsNone(content) {+ const missingForkTurns = [];+ const regex = /spawn_agent\(agent_type="([^"]+)"[^)]*\)/g;+ for (const match of content.matchAll(regex)) {+ const call = match[0];+ if (!call.includes('fork_turns="none"')) {+ missingForkTurns.push(call);+ }+ }+ return missingForkTurns;+}+test("#given aggregate plugin manifest #when inspected #then it owns the omo namespace", async () => {// givenconst manifest = await readJson(".codex-plugin/plugin.json");@@ -35,6 +98,18 @@ test("#given aggregate plugin manifest #when inspected #then it owns the omo namassert.equal(mcpPath, "./.mcp.json");});+test("#given aggregate plugin metadata #when inspected #then ulw-loop is the public loop name", async () => {+ // given+ const manifestText = await readFile(join(root, ".codex-plugin", "plugin.json"), "utf8");+ const manifest = JSON.parse(manifestText);++ // when+ const longDescription = String(manifest.interface?.longDescription ?? "");++ // then+ assert.match(longDescription, /ulw-loop/);+});+test("#given isolated components #when hooks are inspected #then commands stay inside component roots", async () => {// givenconst hooks = await readJson("hooks/hooks.json");@@ -45,32 +120,180 @@ test("#given isolated components #when hooks are inspected #then commands stay i"components/comment-checker/dist/cli.js","components/lsp/dist/cli.js","components/rules/dist/cli.js",+ "components/start-work-continuation/dist/cli.js","components/telemetry/dist/cli.js",- "components/ultragoal/dist/cli.js",- "components/ultrawork/hooks/ultrawork-detector.py",+ "components/ulw-loop/dist/cli.js",+ "components/ultrawork/dist/cli.js",+ "scripts/auto-update.mjs",];// thenfor (const marker of componentMarkers) {assert.match(text, new RegExp(marker.replaceAll("/", "\\/")));}- assert.doesNotMatch(text, /codex-(comment-checker|lsp|rules|telemetry|ultragoal|ultrawork)@/);+ assert.doesNotMatch(text, /codex-(comment-checker|lsp|rules|telemetry|ulw-loop|ultrawork)@/);+ assert.equal(await exists("scripts/migrate-codex-config.mjs"), true);});-test("#given aggregate MCP config #when inspected #then lsp server stays component isolated", async () => {+test("#given aggregate PostCompact hooks #when hooks are inspected #then LSP diagnostics cache reset is registered", async () => {// given+ const hooks = await readJson("hooks/hooks.json");++ // when+ const lspPostCompactHooks = collectCommandHooks(hooks, "hooks/hooks.json").filter(+ (hook) =>+ hook.eventName === "PostCompact" &&+ hook.handler.command === 'node "${PLUGIN_ROOT}/components/lsp/dist/cli.js" hook post-compact',+ );++ // then+ assert.equal(lspPostCompactHooks.length, 1);+ assert.equal(lspPostCompactHooks[0]?.handler.statusMessage, "LazyCodex(0.1.0): Resetting LSP Diagnostics Cache");+});++test("#given aggregate hook commands #when inspected #then every command exposes a Codex status message", async () => {+ // given+ const hooks = await readJson("hooks/hooks.json");++ // when+ const commandHooks = collectCommandHooks(hooks, "hooks/hooks.json");+ const missingStatusMessages = commandHooks+ .filter(({ handler }) => typeof handler.statusMessage !== "string" || handler.statusMessage.trim() === "")+ .map(hookLocation);++ // then+ assert.deepEqual(missingStatusMessages, []);+});++test("#given component hook commands #when inspected #then standalone packages expose Codex status messages", async () => {+ // given+ const componentHooks = await readComponentHookManifests();++ // when+ const missingStatusMessages = componentHooks+ .flatMap(({ source, hooks }) => collectCommandHooks(hooks, source))+ .filter(({ handler }) => typeof handler.statusMessage !== "string" || handler.statusMessage.trim() === "")+ .map(hookLocation);++ // then+ assert.deepEqual(missingStatusMessages, []);+});++test("#given hook status messages #when inspected #then labels describe OMO responsibilities instead of the hook runner", async () => {+ // given+ const aggregateHooks = await readJson("hooks/hooks.json");+ const componentHooks = await readComponentHookManifests();++ // when+ const commandHooks = [+ ...collectCommandHooks(aggregateHooks, "hooks/hooks.json"),+ ...componentHooks.flatMap(({ source, hooks }) => collectCommandHooks(hooks, source)),+ ];+ const genericStatusMessages = commandHooks+ .filter(({ handler }) => typeof handler.statusMessage !== "string" || /\bhook\b/i.test(handler.statusMessage))+ .map(hookLocation);++ // then+ assert.deepEqual(genericStatusMessages, []);+});++test("#given aggregate OMO plugin is enabled #when hooks are inspected #then shell guidance and ulw-loop guard are registered", async () => {+ // given+ const hooks = await readJson("hooks/hooks.json");+ const text = JSON.stringify(hooks);++ // when+ const preToolUseGroups = hooks.hooks.PreToolUse;++ // then+ assert.match(text, /components\/git-bash\/dist\/cli\.js/);+ assert.match(text, /Recommending Git Bash Mcp/);+ assert.match(text, /hook post-compact/);+ assert.match(text, /Resetting Git Bash Mcp Reminder/);+ assert.match(text, /components\/ulw-loop\/dist\/cli\.js/);+ assert.match(text, /hook pre-tool-use/);+ assert.deepEqual(preToolUseGroups.map((group) => group.matcher), ["^Bash$", "^create_goal$"]);+});++test("#given aggregate SessionStart hooks #when inspected #then LazyCodex auto-update is registered", async () => {+ // given+ const hooks = await readJson("hooks/hooks.json");+ const text = JSON.stringify(hooks);++ // when+ const sessionStartCommands = collectCommandHooks(hooks, "hooks/hooks.json")+ .filter(({ eventName }) => eventName === "SessionStart")+ .map(({ handler }) => handler.command);+ const autoUpdateGroup = hooks.hooks.SessionStart.find((group) => JSON.stringify(group).includes("scripts/auto-update.mjs"));++ // then+ assert.equal(autoUpdateGroup?.matcher, "^startup$");+ assert.match(text, /scripts\/auto-update\.mjs/);+ assert.match(text, /Checking Auto Update/);+ assert(sessionStartCommands.some((command) => command.includes("scripts/auto-update.mjs")));+});++test("#given aggregate MCP config #when inspected #then code MCPs reference package runtimes without package names", async () => {+ // given+ const packageJson = await readJson("package.json");const mcp = await readJson(".mcp.json");+ const lspSources = await readdir(join(root, "components", "lsp", "src"));+ const bundledMcpBuildScript = await readFile(join(root, "scripts", "build-bundled-mcp-runtimes.mjs"), "utf8");// when- const server = mcp.mcpServers.lsp;+ const lspServer = mcp.mcpServers.lsp;+ const astGrepServer = mcp.mcpServers.ast_grep;+ const gitBashServer = mcp.mcpServers.git_bash;+ const codeMcpNames = Object.keys(mcp.mcpServers)+ .filter((name) => name === "lsp" || name === "ast_grep" || name === "git_bash")+ .sort();+ const componentLocalMcpSources = lspSources.filter((name) => name.startsWith("lazy-mcp") || name === "lazy-lsp-mcp.ts");// then- assert.equal(server.command, "node");- assert.deepEqual(server.args, ["./components/lsp/packages/lsp-tools-mcp/dist/cli.js", "mcp"]);- assert.equal(server.cwd, ".");+ assert.deepEqual(codeMcpNames, ["ast_grep", "git_bash", "lsp"]);+ assert.equal(packageJson.workspaces.includes("components/lsp/packages/lsp-tools-mcp"), false);+ assert.equal(packageJson.workspaces.includes("components/ast-grep/packages/ast-grep-mcp"), false);+ assert.deepEqual(packageJson.dependencies, { "@oh-my-opencode/shared-skills": "file:../../shared-skills" });+ assert.match(bundledMcpBuildScript, /ast-grep-mcp/);+ assert.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.equal(lspServer.cwd, ".");+ assert.equal(astGrepServer.command, "node");+ assert.deepEqual(astGrepServer.args, ["../../ast-grep-mcp/dist/cli.js", "mcp"]);+ assert.equal(astGrepServer.cwd, ".");+ assert.equal(gitBashServer.command, "node");+ assert.deepEqual(gitBashServer.args, ["../../git-bash-mcp/dist/cli.js", "mcp"]);+ assert.equal(gitBashServer.cwd, ".");+ assert.deepEqual(componentLocalMcpSources, []);});-test("#given aggregate plugin build script #when inspected #then telemetry sync runs before workspace builds", async () => {+test(+ "#given package-level MCP CLIs #when package metadata is inspected #then bin names use the omo prefix",+ { skip: mcpPackageManifestExists.some((exists) => !exists) },+ async () => {+ // given+ const [lspPackageJson, astGrepPackageJson, gitBashPackageJson] = await Promise.all(+ mcpPackageManifestPaths.map((path) => readJson(path)),+ );++ // when+ const binNames = [+ ...Object.keys(lspPackageJson.bin ?? {}),+ ...Object.keys(astGrepPackageJson.bin ?? {}),+ ...Object.keys(gitBashPackageJson.bin ?? {}),+ ].sort();++ // then+ assert.deepEqual(binNames, ["omo-ast-grep", "omo-git-bash", "omo-lsp"]);+ for (const name of binNames) {+ assert.match(name, /^omo-/);+ }+ },+);++test("#given aggregate plugin build script #when inspected #then hook status and telemetry sync run before workspace builds", async () => {// givenconst packageJson = await readJson("package.json");const telemetrySyncScript = await readFile(join(root, "..", "scripts", "sync-telemetry-component.mjs"), "utf8");@@ -79,20 +302,49 @@ test("#given aggregate plugin build script #when inspected #then telemetry syncconst buildScript = packageJson.scripts.build;// then- assert.equal(buildScript, "node scripts/sync-skills.mjs && node ../scripts/sync-telemetry-component.mjs && npm run build --workspaces --if-present");+ assert.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",+ );assert.match(telemetrySyncScript, /syncTelemetryComponent/);});+test("#given omo-codex package build script #when inspected #then delegates to the aggregate plugin package", async () => {+ // given+ const packageJson = JSON.parse(await readFile(join(root, "..", "package.json"), "utf8"));++ // when+ const buildPluginScript = packageJson.scripts["build:plugin"];++ // then+ assert.equal(buildPluginScript, "bun run --cwd plugin build");+});+test("#given component directories #when scanned #then only intentional resource roots declare plugin manifests", async () => {// givenconst components = await readdir(join(root, "components"), { withFileTypes: true });const expectedComponentManifests = new Map([["rules", { hooks: "./hooks/hooks.json" }]]);// when- const componentNames = components.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();+ const componentNames = [];+ for (const entry of components) {+ if (!entry.isDirectory()) continue;+ if (!(await exists(join("components", entry.name, "package.json")))) continue;+ componentNames.push(entry.name);+ }+ componentNames.sort();// then- assert.deepEqual(componentNames, ["comment-checker", "lsp", "rules", "telemetry", "ultragoal", "ultrawork"]);+ assert.deepEqual(componentNames, [+ "comment-checker",+ "git-bash",+ "lsp",+ "rules",+ "start-work-continuation",+ "telemetry",+ "ultrawork",+ "ulw-loop",+ ]);for (const name of componentNames) {const expectedManifest = expectedComponentManifests.get(name);if (expectedManifest !== undefined) {@@ -107,7 +359,7 @@ test("#given component directories #when scanned #then only intentional resource}});-test("#given bundled Codex agents #when components/ultrawork/agents directory is scanned #then explorer librarian and reviewer TOMLs are present and match expected schema keys", async () => {+test("#given bundled Codex agents #when components/ultrawork/agents directory is scanned #then planner support TOMLs are present and match expected schema keys", async () => {const agentsDir = join(root, "components", "ultrawork", "agents");const entries = (await readdir(agentsDir, { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.endsWith(".toml"))@@ -118,6 +370,8 @@ test("#given bundled Codex agents #when components/ultrawork/agents directory is"codex-ultrawork-reviewer.toml","explorer.toml","librarian.toml",+ "metis.toml",+ "momus.toml","plan.toml",]);@@ -132,7 +386,66 @@ test("#given bundled Codex agents #when components/ultrawork/agents directory is}});-test("#given synced skills with Codex compatibility guidance #when explorer/librarian agent_type is referenced #then a matching TOML is bundled", async () => {+test("#given planner agent prompt #when inspected #then generated artifacts stay under .omo", async () => {+ const prompt = await readFile(join(root, "components", "ultrawork", "agents", "plan.toml"), "utf8");++ assert.match(prompt, /\.omo\/plans\/<slug>\.md/);+ assert.match(prompt, /\.omo\/evidence\/task-<N>-<slug>\.<ext>/);+ assert.doesNotMatch(prompt, /(?<!\.omo\/)plans\/<slug>\.md/);+ assert.doesNotMatch(prompt, /(?<!\.omo\/)evidence\/task-/);+});++test("#given reviewer agent prompt #when inspected #then default model is ChatGPT-account compatible", async () => {+ const prompt = await readFile(+ join(root, "components", "ultrawork", "agents", "codex-ultrawork-reviewer.toml"),+ "utf8",+ );++ assert.match(prompt, /^model\s*=\s*"gpt-5\.5"$/m);+ assert.match(prompt, /^model_reasoning_effort\s*=\s*"xhigh"$/m);+ assert.doesNotMatch(prompt, /^model\s*=\s*"gpt-5\.2"$/m);+ assert.match(prompt, /ChatGPT account/);+});++test("#given bundled model catalog #when inspected #then default verifier and worker roles are pinned", async () => {+ const catalog = JSON.parse(await readFile(join(root, "model-catalog.json"), "utf8"));++ assert.equal(catalog.current.model, "gpt-5.5");+ assert.equal(catalog.current.model_context_window, 400000);+ assert.equal(catalog.current.model_reasoning_effort, "high");+ assert.equal(catalog.current.plan_mode_reasoning_effort, "xhigh");+ assert.deepEqual(catalog.roles.default, catalog.current);+ assert.deepEqual(catalog.roles.verifier, {+ model: "gpt-5.5",+ model_reasoning_effort: "xhigh",+ });+ assert.deepEqual(catalog.roles.worker, {+ model: "gpt-5.4",+ model_reasoning_effort: "high",+ });+});++test("#given Codex-facing orchestration surfaces #when inspected #then retired ChatGPT-account model names are not recommended", async () => {+ const promptFiles = [+ join(root, "skills", "ulw-loop", "references", "full-workflow.md"),+ join(root, "components", "ulw-loop", "skills", "ulw-loop", "references", "full-workflow.md"),+ join(root, "components", "ultrawork", "README.md"),+ join(root, "components", "ultrawork", "CHANGELOG.md"),+ join(root, "components", "rules", "src", "post-compact-budget.ts"),+ ];++ const staleReferences = [];+ for (const promptPath of promptFiles) {+ const content = await readFile(promptPath, "utf8");+ if (/gpt-5\.(?:2|3-codex)/i.test(content)) {+ staleReferences.push(`${basename(dirname(promptPath))}/${basename(promptPath)}`);+ }+ }++ assert.deepEqual(staleReferences, []);+});++test("#given synced skills with Codex compatibility guidance #when a bundled agent_type is referenced #then a matching TOML is bundled", async () => {const skillsDir = join(root, "skills");const skillEntries = await readdir(skillsDir, { withFileTypes: true });const skillFiles = skillEntries@@ -151,7 +464,7 @@ test("#given synced skills with Codex compatibility guidance #when explorer/libr}const expected = [...referencedAgentTypes].sort();- assert.deepEqual(expected, ["explorer", "librarian", "plan"]);+ assert.deepEqual(expected, ["explorer", "librarian", "metis", "momus", "plan"]);for (const agentType of expected) {const tomlPath = join(root, "components", "ultrawork", "agents", `${agentType}.toml`);@@ -160,3 +473,42 @@ test("#given synced skills with Codex compatibility guidance #when explorer/librassert.equal(basename(tomlPath), `${agentType}.toml`);}});++test('#given synced skills and bundled rules #when role-specific agents are spawned #then they set fork_turns="none"', async () => {+ const skillsDir = join(root, "skills");+ const skillEntries = await readdir(skillsDir, { withFileTypes: true });+ const promptFiles = skillEntries+ .filter((entry) => entry.isDirectory())+ .map((entry) => join(skillsDir, entry.name, "SKILL.md"));+ promptFiles.push(join(root, "components", "rules", "bundled-rules", "hephaestus.md"));++ const missingForkTurns = [];+ for (const promptPath of promptFiles) {+ const content = await readFile(promptPath, "utf8");+ for (const call of findRoleSpecificSpawnsWithoutForkTurnsNone(content)) {+ missingForkTurns.push(`${basename(dirname(promptPath))}/${basename(promptPath)}: ${call}`);+ }+ }++ assert.deepEqual(missingForkTurns, []);+});++test("#given long-running orchestration prompts #when waiting on child agents #then parent liveness is surfaced", async () => {+ const promptFiles = [+ join(root, "skills", "ulw-loop", "SKILL.md"),+ join(root, "skills", "ulw-loop", "references", "full-workflow.md"),+ join(root, "skills", "review-work", "SKILL.md"),+ join(root, "skills", "start-work", "SKILL.md"),+ join(root, "components", "rules", "bundled-rules", "hephaestus.md"),+ ];++ const missingLivenessGuidance = [];+ for (const promptPath of promptFiles) {+ const content = await readFile(promptPath, "utf8");+ if (!content.includes("active subagent count") || !content.includes("last heartbeat")) {+ missingLivenessGuidance.push(`${basename(dirname(promptPath))}/${basename(promptPath)}`);+ }+ }++ assert.deepEqual(missingLivenessGuidance, []);+});diff --git a/plugins/omo/test/auto-update.test.mjs b/plugins/omo/test/auto-update.test.mjsnew file mode 100644index 00000000..7c613127--- /dev/null+++ b/plugins/omo/test/auto-update.test.mjs@@ -0,0 +1,129 @@+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 { resolveAutoUpdatePlan, runAutoUpdateCheck } from "../scripts/auto-update.mjs";++test("#given auto update is disabled #when resolving plan #then no command is scheduled", () => {+ const plan = resolveAutoUpdatePlan({+ env: { LAZYCODEX_AUTO_UPDATE_DISABLED: "1" },+ now: 1_000,+ lastCheckedAt: 0,+ });++ assert.equal(plan.shouldRun, false);+ assert.equal(plan.reason, "disabled");+});++test("#given stale state #when resolving plan #then installer update command is scheduled", () => {+ const plan = resolveAutoUpdatePlan({+ env: {},+ now: 90_000_000,+ lastCheckedAt: 0,+ });++ assert.equal(plan.shouldRun, true);+ assert.deepEqual(plan.command, "npx");+ assert.deepEqual(plan.args, ["--yes", "lazycodex-ai@latest", "install", "--no-tui", "--skip-auth"]);+});++test("#given recent state #when resolving plan #then update is throttled", () => {+ const plan = resolveAutoUpdatePlan({+ env: {},+ now: 90_000_000,+ lastCheckedAt: 89_999_000,+ });++ assert.equal(plan.shouldRun, false);+ assert.equal(plan.reason, "throttled");+});++test("#given test command override #when running check #then records state and launches command", async () => {+ const root = await mkdtemp(join(tmpdir(), "lazycodex-auto-update-"));+ const logPath = join(root, "spawn.log");+ const statePath = join(root, "state.json");+ const codexHome = join(root, "codex-home");++ const result = await runAutoUpdateCheck({+ env: {+ CODEX_HOME: codexHome,+ LAZYCODEX_MODEL_CATALOG_STATE_PATH: join(root, "model-state.json"),+ LAZYCODEX_AUTO_UPDATE_STATE_PATH: statePath,+ LAZYCODEX_AUTO_UPDATE_INTERVAL_MS: "0",+ LAZYCODEX_AUTO_UPDATE_COMMAND: process.execPath,+ LAZYCODEX_AUTO_UPDATE_ARGS_JSON: JSON.stringify(["-e", `require("node:fs").writeFileSync(${JSON.stringify(logPath)}, "ok")`]),+ LAZYCODEX_AUTO_UPDATE_WAIT: "1",+ },+ now: 123_456,+ });++ assert.equal(result.started, true);+ assert.equal(JSON.parse(await readFile(statePath, "utf8")).lastCheckedAt, 123_456);+ assert.equal(await readFile(logPath, "utf8"), "ok");+ assert.match(await readFile(join(codexHome, "config.toml"), "utf8"), /model = "gpt-5\.5"/);+});++test("#given active lock #when running check #then skips concurrent update", async () => {+ const root = await mkdtemp(join(tmpdir(), "lazycodex-auto-update-lock-"));+ const statePath = join(root, "state.json");+ const lockPath = join(root, "state.json.lock");+ const codexHome = join(root, "codex-home");+ await writeFile(lockPath, "locked\n");++ const result = await runAutoUpdateCheck({+ env: {+ CODEX_HOME: codexHome,+ LAZYCODEX_MODEL_CATALOG_STATE_PATH: join(root, "model-state.json"),+ LAZYCODEX_AUTO_UPDATE_STATE_PATH: statePath,+ LAZYCODEX_AUTO_UPDATE_LOCK_PATH: lockPath,+ LAZYCODEX_AUTO_UPDATE_INTERVAL_MS: "0",+ LAZYCODEX_AUTO_UPDATE_LOCK_STALE_MS: "600000",+ },+ now: 123_456,+ });++ assert.equal(result.started, false);+ assert.equal(result.reason, "locked");+ assert.match(await readFile(join(codexHome, "config.toml"), "utf8"), /model_context_window = 400000/);+});++test("#given throttled updater and stale Codex config #when running check #then config migration still runs", async () => {+ const root = await mkdtemp(join(tmpdir(), "lazycodex-auto-update-migration-"));+ const statePath = join(root, "state.json");+ const codexHome = join(root, "codex-home");+ await writeFile(statePath, JSON.stringify({ lastCheckedAt: 99_999 }, null, 2));+ await mkdir(codexHome, { recursive: true });+ await writeFile(+ join(codexHome, "config.toml"),+ [+ 'model = "gpt-5.2"',+ "model_context_window = 272000",+ 'model_reasoning_effort = "low"',+ 'plan_mode_reasoning_effort = "medium"',+ "",+ "[features]",+ "plugins = true",+ "",+ ].join("\n"),+ );++ const result = await runAutoUpdateCheck({+ env: {+ CODEX_HOME: codexHome,+ LAZYCODEX_MODEL_CATALOG_STATE_PATH: join(root, "model-state.json"),+ LAZYCODEX_AUTO_UPDATE_STATE_PATH: statePath,+ },+ now: 100_000,+ });++ const content = await readFile(join(codexHome, "config.toml"), "utf8");+ assert.equal(result.started, false);+ assert.equal(result.reason, "throttled");+ assert.match(content, /model = "gpt-5\.5"/);+ assert.match(content, /model_context_window = 400000/);+ assert.match(content, /model_reasoning_effort = "high"/);+ assert.match(content, /plan_mode_reasoning_effort = "xhigh"/);+ assert.doesNotMatch(content, /gpt-5\.2/);+});diff --git a/plugins/omo/test/component-bin-names.test.mjs b/plugins/omo/test/component-bin-names.test.mjsnew file mode 100644index 00000000..0af913c4--- /dev/null+++ b/plugins/omo/test/component-bin-names.test.mjs@@ -0,0 +1,66 @@+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 EXPECTED_COMPONENT_BINS = new Map([+ ["comment-checker", "omo-comment-checker"],+ ["lsp", "omo-lsp"],+ ["rules", "omo-rules"],+ ["start-work-continuation", "omo-start-work-continuation"],+ ["telemetry", "omo-telemetry"],+ ["ultrawork", "omo-ultrawork"],+ ["ulw-loop", "omo"],+]);++const EXPECTED_USAGE_PREFIXES = new Map([+ ["comment-checker", "Usage: omo-comment-checker "],+ ["lsp", "Usage: omo-lsp "],+ ["rules", "Usage: omo-rules "],+ ["start-work-continuation", "Usage: omo-start-work-continuation "],+ ["telemetry", "Usage: omo-telemetry "],+ ["ultrawork", "Usage: omo-ultrawork "],+]);++async function readJson(relativePath) {+ return JSON.parse(await readFile(join(root, relativePath), "utf8"));+}++test("#given aggregate component package metadata #when bin names are inspected #then local component CLIs use the OMO prefix", async () => {+ // given+ const components = [...EXPECTED_COMPONENT_BINS.entries()];++ // when+ const mismatches = [];+ for (const [component, expectedName] of components) {+ const packageJson = await readJson(join("components", component, "package.json"));+ const bin = packageJson.bin ?? {};+ const binNames = Object.keys(bin).sort();+ if (bin[expectedName] !== "./dist/cli.js" || binNames.some((name) => name.startsWith("codex-"))) {+ mismatches.push({ component, expectedName, bin });+ }+ }++ // then+ assert.deepEqual(mismatches, []);+});++test("#given component CLI sources #when usage text is inspected #then user-facing command names use OMO names", async () => {+ // given+ const components = [...EXPECTED_USAGE_PREFIXES.entries()];++ // when+ const mismatches = [];+ for (const [component, expectedUsage] of components) {+ const source = await readFile(join(root, "components", component, "src", "cli.ts"), "utf8");+ if (!source.includes(expectedUsage) || /Usage: codex-/.test(source)) {+ mismatches.push({ component, expectedUsage });+ }+ }++ // then+ assert.deepEqual(mismatches, []);+});diff --git a/plugins/omo/test/hook-status-message.test.mjs b/plugins/omo/test/hook-status-message.test.mjsnew file mode 100644index 00000000..727310f9--- /dev/null+++ b/plugins/omo/test/hook-status-message.test.mjs@@ -0,0 +1,175 @@+import assert from "node:assert/strict";+import { access, readdir, readFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";++import {+ formatLazyCodexHookStatusMessage,+ normalizeLazyCodexHookStatusLabel,+ parseLazyCodexHookStatusMessage,+} from "../scripts/hook-status-message.mjs";++const root = dirname(dirname(fileURLToPath(import.meta.url)));++const AGGREGATE_EXPECTED_LABELS = new Map([+ ["hooks/hooks.json:SessionStart:0:0", "Loading Project Rules"],+ ["hooks/hooks.json:SessionStart:1:0", "Recording Session Telemetry"],+ ["hooks/hooks.json:SessionStart:2:0", "Checking Auto Update"],+ ["hooks/hooks.json:UserPromptSubmit:0:0", "Loading Project Rules"],+ ["hooks/hooks.json:UserPromptSubmit:1:0", "Checking Ultrawork Trigger"],+ ["hooks/hooks.json:UserPromptSubmit:2:0", "Checking Ulw-Loop Steering"],+ ["hooks/hooks.json:PreToolUse:0:0", "Enforcing Unlimited Goal Budget"],+ ["hooks/hooks.json:PostToolUse:0:0", "Checking Comments"],+ ["hooks/hooks.json:PostToolUse:0:1", "Checking LSP Diagnostics"],+ ["hooks/hooks.json:PostToolUse:1:0", "Matching Project Rules"],+ ["hooks/hooks.json:PostCompact:0:0", "Resetting Project Rule Cache"],+ ["hooks/hooks.json:PostCompact:2:0", "Resetting LSP Diagnostics Cache"],+ ["hooks/hooks.json:Stop:0:0", "Checking Start-Work Continuation"],+ ["hooks/hooks.json:SubagentStop:0:0", "Checking Start-Work Continuation"],+]);++const COMPONENT_EXPECTED_LABELS = new Map([+ ["components/comment-checker/hooks/hooks.json:PostToolUse:0:0", "Checking Comments"],+ ["components/lsp/hooks/hooks.json:PostToolUse:0:0", "Checking LSP Diagnostics"],+ ["components/lsp/hooks/hooks.json:PostCompact:0:0", "Resetting LSP Diagnostics Cache"],+ ["components/rules/hooks/hooks.json:SessionStart:0:0", "Loading Project Rules"],+ ["components/rules/hooks/hooks.json:UserPromptSubmit:0:0", "Loading Project Rules"],+ ["components/rules/hooks/hooks.json:PostToolUse:0:0", "Matching Project Rules"],+ ["components/rules/hooks/hooks.json:PostCompact:0:0", "Resetting Project Rule Cache"],+ ["components/telemetry/hooks/hooks.json:SessionStart:0:0", "Recording Session Telemetry"],+ ["components/ultrawork/hooks/hooks.json:UserPromptSubmit:0:0", "Checking Ultrawork Trigger"],+ ["components/ulw-loop/hooks/hooks.json:UserPromptSubmit:0:0", "Checking Ulw-Loop Steering"],+ ["components/ulw-loop/hooks/hooks.json:PreToolUse:0:0", "Enforcing Unlimited Ulw-Loop Budget"],+ ["components/start-work-continuation/hooks/hooks.json:Stop:0:0", "Checking Start-Work Continuation"],+ ["components/start-work-continuation/hooks/hooks.json:SubagentStop:0:0", "Checking Start-Work Continuation"],+]);++async function readJson(relativePath) {+ return JSON.parse(await readFile(join(root, relativePath), "utf8"));+}++async function exists(relativePath) {+ try {+ await access(join(root, relativePath));+ return true;+ } catch (error) {+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;+ throw error;+ }+}++async function readComponentHookManifests() {+ const components = await readdir(join(root, "components"), { withFileTypes: true });+ const manifests = [];+ for (const entry of components) {+ if (!entry.isDirectory()) continue;+ const source = join("components", entry.name, "hooks", "hooks.json");+ if (!(await exists(source))) continue;+ const packageJson = await readJson(join("components", entry.name, "package.json"));+ manifests.push({ source, version: packageJson.version, hooks: await readJson(source) });+ }+ return manifests.sort((left, right) => left.source.localeCompare(right.source));+}++function collectCommandHooks(hooks, source, version) {+ const commandHooks = [];+ const normalizedSource = source.replaceAll("\\", "/");+ for (const [eventName, groups] of Object.entries(hooks.hooks)) {+ groups.forEach((group, groupIndex) => {+ group.hooks.forEach((handler, handlerIndex) => {+ if (handler.type !== "command") return;+ commandHooks.push({+ id: `${normalizedSource}:${eventName}:${groupIndex}:${handlerIndex}`,+ version,+ command: handler.command,+ statusMessage: handler.statusMessage,+ });+ });+ });+ }+ return commandHooks;+}++test("#given hook status label #when formatting #then prefixes LazyCodex with version", () => {+ // given+ const version = "0.1.0";+ const label = "Checking Comments";++ // when+ const message = formatLazyCodexHookStatusMessage(version, label);++ // then+ assert.equal(message, "LazyCodex(0.1.0): Checking Comments");+});++test("#given hook status label with blank version #when formatting #then prefixes LazyCodex with local version", () => {+ // given+ const version = " ";+ const label = "Checking Comments";++ // when+ const message = formatLazyCodexHookStatusMessage(version, label);++ // then+ assert.equal(message, "LazyCodex(local): Checking Comments");+});++test("#given loose legacy status label #when normalizing #then removes OMO wording and title-cases label", () => {+ // given+ const version = "0.1.0";+ const label = " checking OMO comments ";++ // when+ const normalized = normalizeLazyCodexHookStatusLabel(label);+ const message = formatLazyCodexHookStatusMessage(version, label);++ // then+ assert.equal(normalized, "Checking Comments");+ assert.equal(message, "LazyCodex(0.1.0): Checking Comments");+});++test("#given aggregate comment-checker hook #when status is inspected #then it uses LazyCodex comments label", async () => {+ // given+ const aggregateVersion = (await readJson(".codex-plugin/plugin.json")).version;+ const aggregateHooks = await readJson("hooks/hooks.json");++ // when+ const hooks = collectCommandHooks(aggregateHooks, "hooks/hooks.json", aggregateVersion);+ const commentCheckerHook = hooks.find((hook) => hook.id === "hooks/hooks.json:PostToolUse:0:0");++ // then+ assert.equal(commentCheckerHook?.statusMessage, formatLazyCodexHookStatusMessage(aggregateVersion, "Checking Comments"));+ assert.doesNotMatch(JSON.stringify(aggregateHooks), /checking\s+OMO\s+comments/i);+});++test("#given aggregate and component hooks #when status messages are inspected #then all use the LazyCodex formatter", async () => {+ // given+ const aggregateVersion = (await readJson(".codex-plugin/plugin.json")).version;+ const aggregateHooks = await readJson("hooks/hooks.json");+ const componentManifests = await readComponentHookManifests();++ // when+ const commandHooks = [+ ...collectCommandHooks(aggregateHooks, "hooks/hooks.json", aggregateVersion),+ ...componentManifests.flatMap((manifest) => collectCommandHooks(manifest.hooks, manifest.source, manifest.version)),+ ];+ const expectedLabels = new Map([...AGGREGATE_EXPECTED_LABELS, ...COMPONENT_EXPECTED_LABELS]);+ const mismatches = commandHooks+ .map((hook) => {+ const parsed = parseLazyCodexHookStatusMessage(hook.statusMessage);+ const label = parsed?.label;+ const expected = label === undefined ? undefined : formatLazyCodexHookStatusMessage(hook.version, label);+ return { ...hook, expected, parsed };+ })+ .filter((hook) => hook.expected === undefined || hook.statusMessage !== hook.expected || hook.parsed === null)+ .map((hook) => `${hook.id}: expected ${hook.expected ?? "<missing expectation>"} but got ${hook.statusMessage}`);++ // then+ assert.deepEqual(mismatches, []);+ const actualLabels = new Set(commandHooks.map((hook) => parseLazyCodexHookStatusMessage(hook.statusMessage)?.label));+ assert.deepEqual([...expectedLabels.values()].filter((label) => !actualLabels.has(label)), []);+ for (const hook of commandHooks) {+ assert.doesNotMatch(hook.statusMessage, /\bOMO\b/i);+ }+});diff --git a/plugins/omo/test/install-time-build-runtime.test.mjs b/plugins/omo/test/install-time-build-runtime.test.mjsnew file mode 100644index 00000000..f080a9ae--- /dev/null+++ b/plugins/omo/test/install-time-build-runtime.test.mjs@@ -0,0 +1,34 @@+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)));++test("#given aggregate build scripts #when inspected #then install-time build does not invoke Bun", async () => {+ // given+ const buildComponentsScript = await readFile(join(root, "scripts", "build-components.mjs"), "utf8");+ const buildBundledMcpRuntimesScript = await readFile(join(root, "scripts", "build-bundled-mcp-runtimes.mjs"), "utf8");++ // when+ const installTimeBuildScripts = [buildComponentsScript, buildBundledMcpRuntimesScript].join("\n");++ // then+ assert.doesNotMatch(installTimeBuildScripts, /spawnSync\("bun"/);+ assert.doesNotMatch(installTimeBuildScripts, /\bbun\s+run\b/);+});++test("#given aggregate build scripts #when inspected #then npm subprocesses resolve on Windows", async () => {+ // given+ const buildComponentsScript = await readFile(join(root, "scripts", "build-components.mjs"), "utf8");+ const buildBundledMcpRuntimesScript = await readFile(join(root, "scripts", "build-bundled-mcp-runtimes.mjs"), "utf8");++ // when+ const installTimeBuildScripts = [buildComponentsScript, buildBundledMcpRuntimesScript].join("\n");++ // then+ assert.match(installTimeBuildScripts, /process\.platform === "win32"/);+ assert.match(installTimeBuildScripts, /shell: process\.platform === "win32"/);+ assert.doesNotMatch(installTimeBuildScripts, /npm\.cmd/);+});diff --git a/plugins/omo/test/mcp-research-servers.test.mjs b/plugins/omo/test/mcp-research-servers.test.mjsnew file mode 100644index 00000000..c56cb7f9--- /dev/null+++ b/plugins/omo/test/mcp-research-servers.test.mjs@@ -0,0 +1,21 @@+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)));++test("#given aggregate MCP config #when inspected #then registers research and structural-search MCPs", async () => {+ // given+ const mcp = JSON.parse(await readFile(join(root, ".mcp.json"), "utf8"));++ // when+ const serverNames = Object.keys(mcp.mcpServers).sort();++ // then+ assert.deepEqual(serverNames, ["ast_grep", "context7", "git_bash", "grep_app", "lsp"]);+ assert.equal(mcp.mcpServers.grep_app.url, "https://mcp.grep.app");+ assert.equal(mcp.mcpServers.context7.url, "https://mcp.context7.com/mcp");+ assert.deepEqual(mcp.mcpServers.ast_grep.args, ["../../ast-grep-mcp/dist/cli.js", "mcp"]);+});diff --git a/plugins/omo/test/migrate-codex-config.test.mjs b/plugins/omo/test/migrate-codex-config.test.mjsnew file mode 100644index 00000000..76f78e22--- /dev/null+++ b/plugins/omo/test/migrate-codex-config.test.mjs@@ -0,0 +1,146 @@+import assert from "node:assert/strict";+import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import test from "node:test";++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", () => {+ const result = ensureCodexReasoningConfig(+ [+ 'model = "gpt-5.2"',+ "model_context_window = 272000",+ 'model_reasoning_effort = "low"',+ 'plan_mode_reasoning_effort = "medium"',+ "",+ "[features]",+ "plugins = true",+ "",+ ].join("\n"),+ );++ assert.equal(result.match(/^model\s*=/gm)?.length, 1);+ assert.equal(result.match(/^model_context_window\s*=/gm)?.length, 1);+ assert.equal(result.match(/^model_reasoning_effort\s*=/gm)?.length, 1);+ assert.equal(result.match(/^plan_mode_reasoning_effort\s*=/gm)?.length, 1);+ assert.match(result, /model = "gpt-5\.5"/);+ assert.match(result, /model_context_window = 400000/);+ assert.match(result, /model_reasoning_effort = "high"/);+ assert.match(result, /plan_mode_reasoning_effort = "xhigh"/);+ assert.doesNotMatch(result, /gpt-5\.2/);+ assert.match(result, /\[features\]/);+});++test("#given global and project-local stale Codex configs #when migrating #then both configs are forced to current defaults", async () => {+ const root = await mkdtemp(join(tmpdir(), "lazycodex-config-migration-"));+ const codexHome = join(root, "codex-home");+ const project = join(root, "project", "nested");+ const projectConfig = join(root, "project", ".codex", "config.toml");+ await mkdir(codexHome, { recursive: true });+ await mkdir(dirname(projectConfig), { recursive: true });+ await writeFile(join(codexHome, "config.toml"), 'model = "gpt-5.2"\n');+ await writeFile(projectConfig, 'model = "gpt-5.2"\nmodel_context_window = 272000\n');++ const result = await migrateCodexConfig({+ env: { CODEX_HOME: codexHome, LAZYCODEX_MODEL_CATALOG_STATE_PATH: join(root, "model-state.json") },+ cwd: project,+ });++ assert.deepEqual(result.changed.sort(), [join(codexHome, "config.toml"), projectConfig].sort());+ assert.match(await readFile(join(codexHome, "config.toml"), "utf8"), /model = "gpt-5\.5"/);+ assert.match(await readFile(projectConfig, "utf8"), /model_context_window = 400000/);+});++test("#given user-customized Codex model config #when migrating #then user values are preserved", async () => {+ const root = await mkdtemp(join(tmpdir(), "lazycodex-config-custom-"));+ const codexHome = join(root, "codex-home");+ await mkdir(codexHome, { recursive: true });+ await writeFile(+ join(codexHome, "config.toml"),+ [+ 'model = "gpt-5.4"',+ "model_context_window = 123456",+ 'model_reasoning_effort = "medium"',+ 'plan_mode_reasoning_effort = "medium"',+ "",+ ].join("\n"),+ );++ const result = await migrateCodexConfig({+ env: { CODEX_HOME: codexHome, LAZYCODEX_MODEL_CATALOG_STATE_PATH: join(root, "model-state.json") },+ cwd: root,+ });++ const content = await readFile(join(codexHome, "config.toml"), "utf8");+ assert.deepEqual(result.changed, []);+ assert.match(content, /model = "gpt-5\.4"/);+ assert.match(content, /model_context_window = 123456/);+ assert.match(content, /model_reasoning_effort = "medium"/);+ assert.match(content, /plan_mode_reasoning_effort = "medium"/);+});++test("#given managed catalog state #when catalog version advances #then only previously managed config is updated", async () => {+ const root = await mkdtemp(join(tmpdir(), "lazycodex-config-catalog-state-"));+ const codexHome = join(root, "codex-home");+ const catalogPath = join(root, "catalog.json");+ const statePath = join(root, "model-state.json");+ await mkdir(codexHome, { recursive: true });+ await writeFile(+ catalogPath,+ JSON.stringify(+ {+ version: "test.v1",+ current: {+ model: "gpt-5.4",+ model_context_window: 1000000,+ model_reasoning_effort: "high",+ plan_mode_reasoning_effort: "xhigh",+ },+ managedProfiles: [],+ },+ null,+ 2,+ ),+ );++ const first = await migrateCodexConfig({+ env: {+ CODEX_HOME: codexHome,+ LAZYCODEX_MODEL_CATALOG_PATH: catalogPath,+ LAZYCODEX_MODEL_CATALOG_STATE_PATH: statePath,+ },+ cwd: root,+ });+ await writeFile(+ catalogPath,+ JSON.stringify(+ {+ version: "test.v2",+ current: {+ model: "gpt-5.5",+ model_context_window: 400000,+ model_reasoning_effort: "high",+ plan_mode_reasoning_effort: "xhigh",+ },+ managedProfiles: [],+ },+ null,+ 2,+ ),+ );+ const second = await migrateCodexConfig({+ env: {+ CODEX_HOME: codexHome,+ LAZYCODEX_MODEL_CATALOG_PATH: catalogPath,+ LAZYCODEX_MODEL_CATALOG_STATE_PATH: statePath,+ },+ cwd: root,+ });++ const content = await readFile(join(codexHome, "config.toml"), "utf8");+ assert.deepEqual(first.changed, [join(codexHome, "config.toml")]);+ assert.deepEqual(second.changed, [join(codexHome, "config.toml")]);+ assert.match(content, /model = "gpt-5\.5"/);+ assert.match(content, /model_context_window = 400000/);+});diff --git a/plugins/omo/test/node-install-surface.test.mjs b/plugins/omo/test/node-install-surface.test.mjsnew file mode 100644index 00000000..9b88ef94--- /dev/null+++ b/plugins/omo/test/node-install-surface.test.mjs@@ -0,0 +1,48 @@+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)));+const repoRoot = join(pluginRoot, "..", "..", "..");++test("#given Codex Light install docs #when inspected #then lazycodex is npm-first and Bun-free", async () => {+ // given+ const files = [+ join(repoRoot, "README.md"),+ join(repoRoot, "docs", "guide", "installation.md"),+ join(repoRoot, "packages", "omo-codex", "README.md"),+ join(repoRoot, "packages", "omo-codex", "MARKETPLACE.md"),+ join(pluginRoot, "components", "ultrawork", "README.md"),+ join(pluginRoot, "components", "ulw-loop", "README.md"),+ ];++ // when+ const docs = await Promise.all(files.map(async (path) => [path, await readFile(path, "utf8")]));++ // then+ for (const [path, text] of docs) {+ assert.match(text, /\bnpx lazycodex-ai install\b/, `${path} should document the Node/npm install command`);+ assert.doesNotMatch(text, /\bbunx lazycodex-ai\b/, `${path} should not require Bun for lazycodex`);+ }+});++test("#given cleanup troubleshooting docs #when inspected #then project-local cleanup and command delegation are documented", async () => {+ // given+ const files = [+ join(repoRoot, "README.md"),+ join(repoRoot, "docs", "guide", "installation.md"),+ join(repoRoot, "packages", "omo-codex", "README.md"),+ ];++ // when+ const docs = await Promise.all(files.map(async (path) => [path, await readFile(path, "utf8")]));++ // then+ for (const [path, text] of docs) {+ assert.match(text, /\bnpx lazycodex-ai cleanup\b/, `${path} should document the LazyCodex cleanup command`);+ assert.match(text, /project-local .*\.codex\/config\.toml/i, `${path} should mention project-local config repair`);+ assert.match(text, /\.codex.*\.omx|\.omx.*\.codex/s, `${path} should distinguish project-local .codex and .omx artifacts`);+ }+});diff --git a/plugins/omo/test/subagent-guidance.test.mjs b/plugins/omo/test/subagent-guidance.test.mjsnew file mode 100644index 00000000..97f01c3c--- /dev/null+++ b/plugins/omo/test/subagent-guidance.test.mjs@@ -0,0 +1,76 @@+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",+];++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.*signal, not proof/s.test(text) ||+ !/one targeted followup/.test(text) ||+ !/respawn.*smaller/s.test(text) ||+ !/model.*reasoning_effort.*default agent/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)+ ) {+ 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, /codex-ultrawork-reviewer/);+ assert.match(text, /agent_type.*worker/s);+ assert.match(text, /model.*reasoning_effort.*default agent/s);+});++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, []);+});diff --git a/plugins/omo/test/sync-hook-status-messages.test.mjs b/plugins/omo/test/sync-hook-status-messages.test.mjsnew file mode 100644index 00000000..314ad643--- /dev/null+++ b/plugins/omo/test/sync-hook-status-messages.test.mjs@@ -0,0 +1,92 @@+import assert from "node:assert/strict";+import { mkdtemp, mkdir, readFile, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { tmpdir } from "node:os";+import test from "node:test";++import { syncHookStatusMessages } from "../scripts/sync-hook-status-messages.mjs";++async function writeJson(path, value) {+ await writeFile(path, `${JSON.stringify(value, null, "\t")}\n`);+}++async function readJson(path) {+ return JSON.parse(await readFile(path, "utf8"));+}++test("#given a component without hooks #when hook status messages sync #then build-time version sync skips it", async () => {+ // given+ const root = await mkdtemp(join(tmpdir(), "omo-codex-hook-status-"));+ await mkdir(join(root, ".codex-plugin"), { recursive: true });+ await mkdir(join(root, "hooks"), { recursive: true });+ await mkdir(join(root, "components", "comment-checker", "hooks"), { recursive: true });+ await mkdir(join(root, "components", "lsp", "hooks"), { recursive: true });+ await mkdir(join(root, "components", "git-bash"), { recursive: true });+ await mkdir(join(root, "components", "stale-build-output", "dist"), { recursive: true });+ await writeJson(join(root, ".codex-plugin", "plugin.json"), { version: "0.1.0" });+ await writeJson(join(root, "components", "comment-checker", "package.json"), { version: "0.1.1" });+ await writeJson(join(root, "components", "lsp", "package.json"), { version: "0.2.0" });+ await writeJson(join(root, "components", "git-bash", "package.json"), { version: "0.3.0" });+ await writeJson(join(root, "hooks", "hooks.json"), {+ hooks: {+ PostToolUse: [+ {+ hooks: [+ {+ type: "command",+ command: 'node "${PLUGIN_ROOT}/components/comment-checker/dist/cli.js" hook post-tool-use',+ statusMessage: "LazyCodex(0.1.0): Checking Comments",+ },+ {+ type: "command",+ command: 'node "${PLUGIN_ROOT}/components/lsp/dist/cli.js" hook post-tool-use',+ statusMessage: "LazyCodex(0.1.0): Checking LSP Diagnostics",+ },+ ],+ },+ ],+ },+ });+ await writeJson(join(root, "components", "comment-checker", "hooks", "hooks.json"), {+ hooks: {+ PostToolUse: [+ {+ hooks: [+ {+ type: "command",+ command: 'node "${PLUGIN_ROOT}/dist/cli.js" hook post-tool-use',+ statusMessage: "LazyCodex(0.1.0): Checking Comments",+ },+ ],+ },+ ],+ },+ });+ await writeJson(join(root, "components", "lsp", "hooks", "hooks.json"), {+ hooks: {+ PostToolUse: [+ {+ hooks: [+ {+ type: "command",+ command: 'node "${PLUGIN_ROOT}/dist/cli.js" hook post-tool-use',+ statusMessage: "LazyCodex(0.1.0): Checking LSP Diagnostics",+ },+ ],+ },+ ],+ },+ });++ // when+ await syncHookStatusMessages(root);++ // then+ const aggregateHooks = await readJson(join(root, "hooks", "hooks.json"));+ const componentHooks = await readJson(join(root, "components", "comment-checker", "hooks", "hooks.json"));+ const lspHooks = await readJson(join(root, "components", "lsp", "hooks", "hooks.json"));+ assert.equal(aggregateHooks.hooks.PostToolUse[0].hooks[0].statusMessage, "LazyCodex(0.1.0): Checking Comments");+ assert.equal(aggregateHooks.hooks.PostToolUse[0].hooks[1].statusMessage, "LazyCodex(0.1.0): Checking LSP Diagnostics");+ assert.equal(componentHooks.hooks.PostToolUse[0].hooks[0].statusMessage, "LazyCodex(0.1.1): Checking Comments");+ assert.equal(lspHooks.hooks.PostToolUse[0].hooks[0].statusMessage, "LazyCodex(0.2.0): Checking LSP Diagnostics");+});diff --git a/plugins/omo/test/sync-skills.test.mjs b/plugins/omo/test/sync-skills.test.mjsindex 7ff99f05..be2d47b2 100644--- a/plugins/omo/test/sync-skills.test.mjs+++ b/plugins/omo/test/sync-skills.test.mjs@@ -3,23 +3,52 @@ import { readdir, 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)));+const repoRoot = join(root, "..", "..", "..");+const CONTEXT_PRESSURE_SKILL_BUDGET_BYTES = 25_000;const expectedSkills = [- "ai-slop-remover","comment-checker","debugging","frontend-ui-ux",+ "init-deep",+ "lcx-report-bug","lsp","programming","refactor","remove-ai-slops","review-work","rules",- "ultragoal",+ "start-work",+ "ulw-loop",+ "ulw-plan",];+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"],+];++const codexCompatibilityEndMarkers = [+ "Codex full-history forks inherit the parent agent type, model, and reasoning effort, so role-specific spawns with `agent_type` must 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)}`;+}+test("#given synced aggregate Codex skills #when inspected #then component and shared skills are present", async () => {// givenconst skillsRoot = join(root, "skills");@@ -34,8 +63,166 @@ test("#given synced aggregate Codex skills #when inspected #then component and sassert.deepEqual(skillNames, expectedSkills);for (const skillName of expectedSkills) {const content = await readFile(join(skillsRoot, skillName, "SKILL.md"), "utf8");- assert.match(content, /^---\n/);+ assert.match(removeCodexCompatibilityGuidance(content), /^---\r?\n/);+ }+});++test("#given aggregate Codex skills #when source wiring is inspected #then shared skills are imported from the shared-skills package", async () => {+ // given+ const pluginPackageJson = JSON.parse(await readFile(join(root, "package.json"), "utf8"));+ const sharedPackageJson = JSON.parse(await readFile(join(root, "..", "..", "shared-skills", "package.json"), "utf8"));+ const rootPackageJson = JSON.parse(await readFile(join(repoRoot, "package.json"), "utf8"));+ const syncScript = await readFile(join(root, "scripts", "sync-skills.mjs"), "utf8");++ // when+ const sharedSkillDependency = pluginPackageJson.dependencies?.["@oh-my-opencode/shared-skills"];+ const rootPackageFiles = rootPackageJson.files ?? [];++ // then+ assert.equal(sharedPackageJson.exports?.["."], "./index.mjs");+ assert.equal(sharedPackageJson.files?.includes("skills"), true);+ assert.equal(rootPackageFiles.includes("packages/shared-skills/package.json"), true);+ assert.equal(rootPackageFiles.includes("packages/shared-skills/index.mjs"), true);+ assert.equal(rootPackageFiles.includes("packages/shared-skills/skills"), true);+ assert.equal(sharedSkillDependency, "file:../../shared-skills");+ assert.match(syncScript, /from "@oh-my-opencode\/shared-skills"/);+ assert.doesNotMatch(syncScript, /shared-skills",\s*"skills"/);+});++test("#given shared skill package source #when aggregate Codex shared skills are inspected #then generated copies have no hand-authored drift", async () => {+ // given+ const sharedSkillsRoot = sharedSkillsRootPath();+ const aggregateSkillsRoot = join(root, "skills");+ const sharedSkillNames = (await readdir(sharedSkillsRoot, { withFileTypes: true }))+ .filter((entry) => entry.isDirectory())+ .map((entry) => entry.name)+ .sort();++ // when / then+ for (const skillName of sharedSkillNames) {+ const sharedContent = await readFile(join(sharedSkillsRoot, skillName, "SKILL.md"), "utf8");+ const aggregateContent = await readFile(join(aggregateSkillsRoot, skillName, "SKILL.md"), "utf8");+ assert.equal(+ removeCodexCompatibilityGuidance(aggregateContent),+ removeCodexCompatibilityGuidance(sharedContent),+ `${skillName} drifted from shared-skills`,+ );+ }+});++test("#given component skill sources #when aggregate Codex component skills are inspected #then generated copies have no hand-authored drift", async () => {+ // given+ const aggregateSkillsRoot = join(root, "skills");++ // when / then+ for (const [skillName, sourcePath] of componentSkillSources) {+ const sourceContent = await readFile(join(root, sourcePath, "SKILL.md"), "utf8");+ const aggregateContent = await readFile(join(aggregateSkillsRoot, skillName, "SKILL.md"), "utf8");+ assert.equal(+ removeCodexCompatibilityGuidance(aggregateContent),+ removeCodexCompatibilityGuidance(sourceContent),+ `${skillName} drifted from its component skill source`,+ );+ }+});++test("#given synced ulw-loop skill #when Codex hint metadata is inspected #then ulw-loop surfaces the ulw-loop alias", async () => {+ // given+ const skillRoot = join(root, "skills", "ulw-loop");++ // 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: 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"/);+ assert.match(interfaceMetadata, /default_prompt: "Use \$ulw-loop/);+});++test("#given synced ulw-loop skill #when Codex hint metadata is inspected #then ulw-loop remains discoverable as an alias", async () => {+ // given+ const skillRoot = join(root, "skills", "ulw-loop");++ // when+ const interfaceMetadata = await readFile(join(skillRoot, "agents", "openai.yaml"), "utf8");++ // then+ assert.match(interfaceMetadata, /search_terms:/);+ assert.match(interfaceMetadata, /- "ulw-loop"/);+});++test("#given synced lcx-report-bug skill #when inspected #then it files LazyCodex bug issues from proven debugging evidence", async () => {+ // given+ const skillRoot = join(root, "skills", "lcx-report-bug");++ // 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-report-bug\r?\n/m);+ assert.match(skill, /code-yeongyu\/lazycodex/);+ assert.match(skill, /\$omo:debugging/);+ assert.match(skill, /gh issue create --repo code-yeongyu\/lazycodex/);+ 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"/);+});++test("#given synced ulw-loop skill #when worker guidance is inspected #then context-hygiene guidance matches the source", async () => {+ // given+ const sourceSkill = await readFile(+ join(root, "components", "ulw-loop", "skills", "ulw-loop", "references", "full-workflow.md"),+ "utf8",+ );+ const 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 or status tool/],+ ["large payload replay risk", /replay large agent status and latest-message payloads/],+ ["local spawned-name tracking", /Track spawned agent names locally/],+ ["wait_agent completion path", /wait_agent.*completion/],+ ["targeted followups", /targeted followups only when needed/],+ ["close_agent cleanup", /close_agent.*after integrating each result/],+ ["long-running plan/reviewer background guidance", /Plan and reviewer agents may run for a long time/],+ ["bounded plan/reviewer polling", /short wait_agent cycles/],+ ["single long wait guard", /single long blocking wait/],+ ];++ // when / then+ for (const [label, pattern] of requiredPatterns) {+ assert.match(sourceSkill, pattern, `source skill missing ${label}`);+ assert.match(syncedWorkflow, pattern, `synced workflow missing ${label}`);+ }+ assert.match(syncedSkill, /references\/full-workflow\.md/);+ assert.match(syncedSkill, /wait_agent/);+ assert.match(syncedSkill, /close_agent/);+});++test("#given context-pressure-prone skills #when bundled for Codex #then the eagerly loaded payload stays budgeted", async () => {+ // given+ const skillsRoot = join(root, "skills");+ const skillNames = ["debugging", "ulw-loop"];++ // when+ let totalBytes = 0;+ for (const skillName of skillNames) {+ const content = await readFile(join(skillsRoot, skillName, "SKILL.md"), "utf8");+ totalBytes += Buffer.byteLength(content, "utf8");}++ // then+ assert.ok(+ totalBytes <= CONTEXT_PRESSURE_SKILL_BUDGET_BYTES,+ `debugging + ulw-loop eager payload is ${totalBytes} bytes, above ${CONTEXT_PRESSURE_SKILL_BUDGET_BYTES}`,+ );});test("#given synced aggregate Codex skills #when they contain OpenCode orchestration examples #then Codex tool compatibility guidance is injected", async () => {