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.19.1
github-actions[bot]3efc603ac474
diff --git a/plugins/omo/.codex-plugin/plugin.json b/plugins/omo/.codex-plugin/plugin.jsonindex f9df9995..dca0776a 100644--- a/plugins/omo/.codex-plugin/plugin.json+++ b/plugins/omo/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "omo",- "version": "4.19.0",+ "version": "4.19.1","description": "One Codex plugin namespace for Yeongyu's local Codex components.","author": {"name": "Yeongyu Kim",diff --git a/plugins/omo/components/bootstrap/dist/cli.js b/plugins/omo/components/bootstrap/dist/cli.jsindex fd5d4437..481dabd1 100755--- a/plugins/omo/components/bootstrap/dist/cli.js+++ b/plugins/omo/components/bootstrap/dist/cli.js@@ -438,7 +438,7 @@ async function readOptionalFile(path) {}// components/bootstrap/src/worker.ts-import { appendFile as appendFile2, mkdir as mkdir8, readFile as readFile13 } from "node:fs/promises";+import { appendFile as appendFile2, mkdir as mkdir8, readFile as readFile14 } from "node:fs/promises";import { homedir as homedir4 } from "node:os";import { dirname as dirname9, join as join22, resolve as resolve7 } from "node:path";import { fileURLToPath as fileURLToPath2 } from "node:url";@@ -864,7 +864,7 @@ async function defaultVersionProbe2(binaryPath) {}// components/bootstrap/src/setup.ts-import { copyFile as copyFile2, mkdir as mkdir7, readdir as readdir5, rm as rm10, stat as stat5 } from "node:fs/promises";+import { copyFile as copyFile2, mkdir as mkdir7, readFile as readFile13, readdir as readdir5, rm as rm10, stat as stat5 } from "node:fs/promises";import { join as join21 } from "node:path";// ../src/install/link-cached-plugin-agents.ts@@ -1457,6 +1457,10 @@ var MANAGED_REASONING_DEFAULT_UPGRADES = new Map([{previous: { model: "gpt-5.6-sol", effort: "xhigh" },current: { model: "gpt-5.6-sol", effort: "max" }+ },+ {+ previous: { model: "gpt-5.6-sol", effort: "max" },+ current: { model: "gpt-5.6-sol", effort: "high" }}]],@@ -1466,6 +1470,37 @@ var MANAGED_REASONING_DEFAULT_UPGRADES = new Map([{previous: { model: "gpt-5.6-sol", effort: "high" },current: { model: "gpt-5.6-luna", effort: "max" }+ },+ {+ previous: { model: "gpt-5.6-luna", effort: "max" },+ current: { model: "gpt-5.6-terra", effort: "high" }+ }+ ]+ ],+ [+ "lazycodex-worker-high",+ [+ {+ previous: { model: "gpt-5.6-sol", effort: "max" },+ current: { model: "gpt-5.6-sol", effort: "medium" }+ }+ ]+ ],+ [+ "lazycodex-code-reviewer",+ [+ {+ previous: { model: "gpt-5.6-sol", effort: "xhigh" },+ current: { model: "gpt-5.6-terra", effort: "medium" }+ }+ ]+ ],+ [+ "lazycodex-clone-fidelity-reviewer",+ [+ {+ previous: { model: "gpt-5.6-sol", effort: "xhigh" },+ current: { model: "gpt-5.6-terra", effort: "high" }}]],@@ -1484,6 +1519,10 @@ var MANAGED_REASONING_DEFAULT_UPGRADES = new Map([{previous: { model: "gpt-5.6-sol", effort: "xhigh" },current: { model: "gpt-5.6-sol", effort: "high" }+ },+ {+ previous: { model: "gpt-5.6-sol", effort: "high" },+ current: { model: "gpt-5.6-sol", effort: "low" }}]]@@ -2303,10 +2342,6 @@ async function existingNonSymlink(path) {}}-// ../src/install/codex-config-toml.ts-import { mkdir as mkdir6, readFile as readFile10 } from "node:fs/promises";-import { dirname as dirname8 } from "node:path";-// ../src/install/codex-config-agents.tsvar LEGACY_MANAGED_CODEX_AGENT_NAMES_TO_PURGE = ["codex-ultrawork-reviewer"];var CURRENT_MANAGED_CODEX_AGENT_NAMES = [@@ -2336,6 +2371,12 @@ function removeStaleManagedAgentBlocks(config, keepAgentNames) {`);}+function hasForeignAgentRegistration(config, agentConfig) {+ const section = findTomlSection(config, `agents.${tomlKeySegment(agentConfig.name)}`);+ if (!section)+ return false;+ return !section.text.includes(`config_file = ${JSON.stringify(agentConfig.configFile)}`);+}function ensureAgentConfig(config, agentConfig) {const header = `agents.${tomlKeySegment(agentConfig.name)}`;const section = findTomlSection(config, header);@@ -2350,6 +2391,10 @@ function tomlKeySegment(value) {return /^[A-Za-z0-9_-]+$/.test(value) ? value : JSON.stringify(value);}+// ../src/install/codex-config-toml.ts+import { mkdir as mkdir6, readFile as readFile10 } from "node:fs/promises";+import { dirname as dirname8 } from "node:path";+// ../src/install/codex-config-atomic-write.tsimport { lstat as lstat8, readlink as readlink4, realpath, rename as rename3, unlink, writeFile as writeFile6 } from "node:fs/promises";import { basename as basename5, dirname as dirname6, isAbsolute as isAbsolute4, join as join15, resolve as resolve5 } from "node:path";@@ -3520,13 +3565,15 @@ async function updateConfigStep(options, inputs, degraded) {const configPath = join21(options.codexHome, "config.toml");try {await assertWritableConfigIfPresent(configPath);+ const existingConfig = await readConfigIfPresent(configPath);+ const agentConfigs = inputs.agentConfigs.filter((agentConfig) => !hasForeignAgentRegistration(existingConfig, agentConfig));const trustedHookStates = await trustedHookStatesForPlugin({marketplaceName: SETUP_MARKETPLACE_NAME,pluginName: SETUP_PLUGIN_NAME,pluginRoot: options.pluginRoot});await updateCodexConfig({- agentConfigs: inputs.agentConfigs,+ agentConfigs,autonomousPermissions: false,configPath,gitBashEnabled: inputs.gitBashEnabled,@@ -3559,6 +3606,15 @@ async function assertWritableConfigIfPresent(configPath) {function errorCode(error) {return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : undefined;}+async function readConfigIfPresent(configPath) {+ try {+ return await readFile13(configPath, "utf8");+ } catch (error) {+ if (errorCode(error) === "ENOENT")+ return "";+ throw error;+ }+}async function linkComponentBinsStep(options, degraded) {const binDir = resolveCodexInstallerBinDir({ codexHome: options.codexHome, env: options.env });try {@@ -3678,7 +3734,7 @@ function resolvePluginDataRoot(env) {}async function readPluginVersion(pluginRoot) {try {- const parsed = JSON.parse(await readFile13(join22(pluginRoot, ".codex-plugin", "plugin.json"), "utf8"));+ const parsed = JSON.parse(await readFile14(join22(pluginRoot, ".codex-plugin", "plugin.json"), "utf8"));if (typeof parsed !== "object" || parsed === null)return;const version = parsed["version"];diff --git a/plugins/omo/components/bootstrap/hooks/hooks.json b/plugins/omo/components/bootstrap/hooks/hooks.jsonindex d4592619..5d7c1f01 100644--- a/plugins/omo/components/bootstrap/hooks/hooks.json+++ b/plugins/omo/components/bootstrap/hooks/hooks.json@@ -8,7 +8,7 @@"command": "node \"${PLUGIN_ROOT}/components/bootstrap/dist/cli.js\" hook session-start","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\bootstrap.ps1\"","timeout": 30,- "statusMessage": "(OmO 4.19.0) Checking Bootstrap Provisioning"+ "statusMessage": "(OmO 4.19.1) Checking Bootstrap Provisioning"}]}diff --git a/plugins/omo/components/bootstrap/package.json b/plugins/omo/components/bootstrap/package.jsonindex ecb07f81..974e94ff 100644--- a/plugins/omo/components/bootstrap/package.json+++ b/plugins/omo/components/bootstrap/package.json@@ -1,6 +1,6 @@{"name": "@sisyphuslabs/codex-bootstrap",- "version": "4.19.0",+ "version": "4.19.1","description": "Codex SessionStart bootstrap component that provisions LazyCodex runtime dependencies from a detached worker.","type": "module","private": true,diff --git a/plugins/omo/components/bootstrap/src/setup.ts b/plugins/omo/components/bootstrap/src/setup.tsindex 5d47f462..1a034211 100644--- a/plugins/omo/components/bootstrap/src/setup.ts+++ b/plugins/omo/components/bootstrap/src/setup.ts@@ -1,4 +1,4 @@-import { copyFile, mkdir, readdir, rm, stat } from "node:fs/promises";+import { copyFile, mkdir, readFile, readdir, rm, stat } from "node:fs/promises";import { join } from "node:path";// These relative imports resolve at BUILD time in the monorepo; esbuild@@ -10,6 +10,7 @@ import {linkCachedPluginAgents,} from "../../../../src/install/link-cached-plugin-agents.ts";import { linkCachedPluginBins, linkRootRuntimeBin } from "../../../../src/install/codex-cache-bins.ts";+import { hasForeignAgentRegistration } from "../../../../src/install/codex-config-agents.ts";import { updateCodexConfig } from "../../../../src/install/codex-config-toml.ts";import { stampGitBashMcpEnv } from "../../../../src/install/codex-git-bash-mcp-env.ts";import { trustedHookStatesForPlugin } from "../../../../src/install/codex-hook-trust.ts";@@ -141,6 +142,16 @@ async function updateConfigStep(const configPath = join(options.codexHome, "config.toml");try {await assertWritableConfigIfPresent(configPath);+ // Orca mirrors the system [agents.*] entries into its runtime CODEX_HOME+ // without copying the agents directory. Re-stamping our own registration+ // for such a role would collide with the mirrored entry once Codex+ // discovers <codexHome>/agents/<name>.toml (two different file paths for+ // one role name -> upstream warning), so foreign pre-existing blocks are+ // left untouched; directory discovery still loads the linked toml.+ const existingConfig = await readConfigIfPresent(configPath);+ const agentConfigs = inputs.agentConfigs.filter(+ (agentConfig) => !hasForeignAgentRegistration(existingConfig, agentConfig),+ );// Re-stamping trusted hook hashes after an upgrade is what makes the// next session's hooks trusted again once the user re-approved the// bootstrap hook itself.@@ -150,7 +161,7 @@ async function updateConfigStep(pluginRoot: options.pluginRoot,});await updateCodexConfig({- agentConfigs: inputs.agentConfigs,+ agentConfigs,// Hard invariant: the bootstrap worker NEVER writes permission keys// (approval/sandbox/network policies stay installer-flag-only).autonomousPermissions: false,@@ -189,6 +200,15 @@ function errorCode(error: unknown): string | undefined {return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : undefined;}+async function readConfigIfPresent(configPath: string): Promise<string> {+ try {+ return await readFile(configPath, "utf8");+ } catch (error) {+ if (errorCode(error) === "ENOENT") return "";+ throw error;+ }+}+async function linkComponentBinsStep(options: WorkerSetupOptions, degraded: BootstrapDegradedEntry[]): Promise<void> {const binDir = resolveCodexInstallerBinDir({ codexHome: options.codexHome, env: options.env });try {diff --git a/plugins/omo/components/codegraph/dist/cli.js b/plugins/omo/components/codegraph/dist/cli.jsindex 48489da8..83450dfc 100755--- a/plugins/omo/components/codegraph/dist/cli.js+++ b/plugins/omo/components/codegraph/dist/cli.js@@ -1,15 +1,15 @@#!/usr/bin/env node// components/codegraph/src/cli.ts-import { realpathSync as realpathSync6 } from "node:fs";-import { basename as basename5, resolve as resolve7 } from "node:path";+import { realpathSync as realpathSync7 } from "node:fs";+import { basename as basename5, resolve as resolve8 } from "node:path";import { stderr as processStderr4 } from "node:process";import { fileURLToPath as fileURLToPath4 } from "node:url";// components/codegraph/src/hook.tsimport { execFile as execFile4, spawn } from "node:child_process";import { homedir as homedir13 } from "node:os";-import { join as join13 } from "node:path";+import { join as join14 } from "node:path";import {cwd as processCwd2,env as processEnv2,@@ -56,6 +56,7 @@ var SAFE_AMBIENT_ENV_KEYS = new Set([var SAFE_CODEGRAPH_RUNTIME_ENV_KEYS = new Set(["CODEGRAPH_ALLOW_UNSAFE_NODE","CODEGRAPH_BIN",+ "CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS","CODEGRAPH_FAKE_LOG","CODEGRAPH_NO_DAEMON","CODEGRAPH_NODE_BIN",@@ -67,7 +68,7 @@ function buildCodegraphEnv(options = {}) {const homeDir = options.homeDir ?? homedir();return {[CODEGRAPH_INSTALL_DIR_ENV]: join(homeDir, ".omo", "codegraph"),- [CODEGRAPH_NO_DAEMON_ENV]: "1",+ ...options.daemon === true ? {} : { [CODEGRAPH_NO_DAEMON_ENV]: "1" },[CODEGRAPH_NO_DOWNLOAD_ENV]: "1",[CODEGRAPH_TELEMETRY_ENV]: "0",[DO_NOT_TRACK_ENV]: "1"@@ -399,6 +400,9 @@ var ANSI_ESCAPE_PATTERN = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;var CODEGRAPH_STATUS_PROJECT_PATTERN = /^.*?\bProject:\s*(.+?)\s*$/im;var CODEGRAPH_STATUS_UNINITIALIZED_PATTERN = /^.*?\bNot initialized\s*$/im;var CODEGRAPH_INIT_HINT_PATTERN = /Run\s+["'`]codegraph init["'`]\s+(?:in that project first|to initialize)\.?/i;+var CODEGRAPH_PROJECT_NOT_INDEXED_PATTERN = /The project at (.+?) isn't indexed with codegraph\b/i;+var CODEGRAPH_NO_PROJECT_LOADED_PATTERN = /No CodeGraph project is loaded for this session\./i;+var CODEGRAPH_NO_PROJECT_SEARCHED_FROM_PATTERN = /^Searched for a \.codegraph\/ directory starting from:\s*(.+?)\s*$/im;function getCodegraphUninitializedProject(input) {const output = textFromUnknown(input.toolOutput);if (!isCodegraphTool(input.toolName))@@ -439,6 +443,16 @@ function extractProjectPath(output) {const uninitializedProject = uninitializedMatch?.[1]?.trim();if (uninitializedProject && uninitializedProject.length > 0)return uninitializedProject;+ const notIndexedMatch = normalizedOutput.match(CODEGRAPH_PROJECT_NOT_INDEXED_PATTERN);+ const notIndexedProject = notIndexedMatch?.[1]?.trim();+ if (notIndexedProject && notIndexedProject.length > 0)+ return notIndexedProject;+ if (CODEGRAPH_NO_PROJECT_LOADED_PATTERN.test(normalizedOutput)) {+ const searchedFromMatch = normalizedOutput.match(CODEGRAPH_NO_PROJECT_SEARCHED_FROM_PATTERN);+ const searchedFromProject = searchedFromMatch?.[1]?.trim();+ if (searchedFromProject && searchedFromProject.length > 0)+ return searchedFromProject;+ }if (!looksLikeCodegraphUninitializedOutput(normalizedOutput))return null;const statusMatch = normalizedOutput.match(CODEGRAPH_STATUS_PROJECT_PATTERN);@@ -1597,8 +1611,9 @@ function parseJsoncSafe(content) {var HARNESS_IDS = ["codex", "opencode", "omo"];var SETTING_HARNESS_SUPPORT = {"codegraph.auto_provision": HARNESS_IDS,+ "codegraph.daemon": ["codex", "opencode"],"codegraph.enabled": HARNESS_IDS,- "codegraph.excluded_roots": ["codex"],+ "codegraph.excluded_roots": ["codex", "opencode"],"codegraph.install_dir": HARNESS_IDS,"codegraph.telemetry": HARNESS_IDS,"codegraph.watch_debounce_ms": ["opencode", "omo"]@@ -1615,6 +1630,7 @@ var BUILT_IN_DEFAULTS = {var HARNESS_BLOCK_KEYS = HARNESS_IDS.map((harness) => `[${harness}]`);var CODEGRAPH_SETTING_KEYS = ["auto_provision",+ "daemon","enabled","excluded_roots","install_dir",@@ -1688,6 +1704,10 @@ function setCodegraphSetting(config, key, value) {if (typeof value === "boolean")config.auto_provision = value;return;+ case "daemon":+ if (typeof value === "boolean")+ config.daemon = value;+ return;case "enabled":if (typeof value === "boolean")config.enabled = value;@@ -2007,77 +2027,131 @@ function isNonFatalCodegraphGcError(error) {// components/codegraph/src/hook-sweep.tsimport { fileURLToPath } from "node:url";-// ../../utils/src/codegraph/process-sweeper.ts+// ../../utils/src/process-sweep/sweeper.tsimport { existsSync as existsSync7, mkdirSync as mkdirSync2, statSync as statSync2, utimesSync, writeFileSync as writeFileSync2 } from "node:fs";import { homedir as homedir10 } from "node:os";-import { dirname as dirname4, join as join10 } from "node:path";--// ../../utils/src/codegraph/process-exec.ts-import { execFile } from "node:child_process";+import { dirname as dirname5, join as join11 } from "node:path";-// ../../utils/src/codegraph/process-match.ts-import { posix, win32 } from "node:path";-var SERVE_WRAPPER_SUFFIX = "/components/codegraph/dist/serve.js";-var UPSTREAM_PACKAGE_SEGMENT = "/@colbymchenry/codegraph/";-function parsePosixProcessTable(output) {- const processes = [];- for (const line of output.split(/\r?\n/)) {- const match = /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(line);- if (match === null)- continue;- const pid = Number(match[1]);- const ppid = Number(match[2]);- const command = match[3];- if (!isValidProcessId(pid) || !Number.isInteger(ppid) || ppid < 0 || command === undefined)- continue;- processes.push({ command, pid, ppid });+// ../../utils/src/codegraph/daemon-lock.ts+import { readFileSync as readFileSync4, realpathSync as realpathSync4 } from "node:fs";+import { dirname as dirname4, join as join9, resolve as resolve5 } from "node:path";+function parseDaemonLock(raw) {+ const trimmed = raw.trim();+ if (trimmed.length === 0)+ return null;+ try {+ const parsed = JSON.parse(trimmed);+ if (typeof parsed === "object" && parsed !== null && "pid" in parsed) {+ const pid = parsed.pid;+ if (typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0) {+ const record = parsed;+ return {+ pid,+ ...typeof record["socketPath"] === "string" ? { socketPath: record["socketPath"] } : {},+ ...typeof record["startedAt"] === "number" ? { startedAt: record["startedAt"] } : {},+ ...typeof record["version"] === "string" ? { version: record["version"] } : {}+ };+ }+ }+ return null;+ } catch (error) {+ if (!(error instanceof SyntaxError))+ throw error;}- return processes;+ const legacyPid = Number(trimmed);+ if (Number.isSafeInteger(legacyPid) && legacyPid > 0)+ return { pid: legacyPid };+ return null;}-function parseWindowsProcessTable(output) {- const parsed = parseJson(output);- const entries = Array.isArray(parsed) ? parsed : parsed === undefined ? [] : [parsed];- const processes = [];- for (const entry of entries) {- if (!isRecord3(entry))+function daemonLockCandidates(projectRoot) {+ const dirs = new Set;+ const resolved = resolve5(projectRoot);+ collectAncestors(resolved, dirs);+ collectAncestors(realpathIfPossible2(resolved), dirs);+ return [...dirs].map((dir) => join9(dir, ".codegraph", "daemon.pid"));+}+function evaluateDaemonStaleness(pid, projectRoot) {+ let sawLock = false;+ for (const lockPath of daemonLockCandidates(projectRoot)) {+ const raw = readLockIfPresent(lockPath);+ if (raw === undefined)continue;- const pid = numberField(entry, "ProcessId");- const ppid = numberField(entry, "ParentProcessId");- const command = stringField(entry, "CommandLine");- if (pid === undefined || ppid === undefined || command === undefined || command.trim().length === 0)- continue;- processes.push({ command, pid, ppid });+ if (raw === null)+ return { stale: false, reason: "lock-unreadable" };+ sawLock = true;+ const lock = parseDaemonLock(raw);+ if (lock === null)+ return { stale: false, reason: "lock-unparseable" };+ if (lock.pid === pid)+ return { stale: false, reason: "lock-pid-match" };+ }+ return sawLock ? { stale: true, reason: "lock-pid-mismatch" } : { stale: true, reason: "lock-absent" };+}+function readLockIfPresent(lockPath) {+ try {+ return readFileSync4(lockPath, "utf8");+ } catch (error) {+ if (error instanceof Error && "code" in error && error.code === "ENOENT")+ return;+ if (error instanceof Error && "code" in error && error.code === "ENOTDIR")+ return;+ return null;}- return processes;}-function selectZombieCodegraphProcesses(processes, options) {- const platform = options.platform ?? process.platform;- const livePids = new Set(processes.map((processInfo) => processInfo.pid));- const roots = normalizeRoots(options.ownedRoots, platform);- const zombies = [];- for (const processInfo of processes) {- const match = matchOwnedCodegraphCommand(processInfo.command, roots, platform);- if (match === null)- continue;- if (!isOrphaned(processInfo, livePids))- continue;- zombies.push({ ...processInfo, matchedRoot: match.root, matchKind: match.kind });+function collectAncestors(start, output) {+ let current = start;+ for (;; ) {+ output.add(current);+ const parent = dirname4(current);+ if (parent === current)+ return;+ current = parent;}- return zombies;}-function matchOwnedCodegraphCommand(command, roots, platform) {- const normalizedCommand = normalizeForComparison2(command, platform);- for (const root of roots) {- if (root.length === 0)+function realpathIfPossible2(path) {+ try {+ return realpathSync4(path);+ } catch (error) {+ if (error instanceof Error)+ return path;+ throw error;+ }+}++// ../../utils/src/process-sweep/command-match.ts+import { posix, win32 } from "node:path";+function splitCommandTokens(command) {+ const tokens = [];+ let current = "";+ let quote = null;+ let tokenStarted = false;+ for (const char of command) {+ if (quote !== null) {+ if (char === quote) {+ quote = null;+ } else {+ current += char;+ }+ continue;+ }+ if (char === '"' || char === "'") {+ quote = char;+ tokenStarted = true;continue;- const serveWrapper = `${root}${SERVE_WRAPPER_SUFFIX}`;- if (hasExecutableToken(normalizedCommand, serveWrapper))- return { kind: "serve-wrapper", root };- if (upstreamPackagePathIsUnderRoot(normalizedCommand, root)) {- return { kind: "upstream-codegraph", root };}+ if (/\s/.test(char)) {+ if (tokenStarted || current.length > 0) {+ tokens.push(current);+ current = "";+ tokenStarted = false;+ }+ continue;+ }+ current += char;}- return null;+ if (tokenStarted || current.length > 0)+ tokens.push(current);+ return tokens;}function hasExecutableToken(command, expectedPath) {let searchFrom = 0;@@ -2093,24 +2167,19 @@ function hasExecutableToken(command, expectedPath) {}}function tokenLooksExecutable(command, tokenStart) {- const prefix = command.slice(0, tokenStart).trimEnd();+ let prefix = command.slice(0, tokenStart).trimEnd();if (prefix.length === 0)return true;- const previousTokenStart = findTokenStart(prefix, prefix.length - 1);- const previousToken = prefix.slice(previousTokenStart);- const executableName = previousToken.split("/").at(-1) ?? previousToken;- return /^node\d*(\.exe)?$/.test(executableName) || /^bun(\.exe)?$/.test(executableName);-}-function upstreamPackagePathIsUnderRoot(command, root) {- let searchFrom = 0;for (;; ) {- const packageIndex = command.indexOf(UPSTREAM_PACKAGE_SEGMENT, searchFrom);- if (packageIndex < 0)+ const previousTokenStart = findTokenStart(prefix, prefix.length - 1);+ const previousToken = prefix.slice(previousTokenStart);+ if (!previousToken.startsWith("-")) {+ const executableName = previousToken.split("/").at(-1) ?? previousToken;+ return /^node\d*(\.exe)?$/i.test(executableName) || /^bun(\.exe)?$/i.test(executableName);+ }+ prefix = prefix.slice(0, previousTokenStart).trimEnd();+ if (prefix.length === 0)return false;- const tokenStart = findTokenStart(command, packageIndex);- if (command.slice(tokenStart).startsWith(`${root}/`) && tokenLooksExecutable(command, tokenStart))- return true;- searchFrom = packageIndex + UPSTREAM_PACKAGE_SEGMENT.length;}}function findTokenStart(command, index) {@@ -2144,6 +2213,39 @@ function normalizeForComparison2(value, platform) {const normalized = value.replaceAll("\\", "/").replace(/\/+$/, "");return platform === "win32" ? normalized.toLowerCase() : normalized;}++// ../../utils/src/process-sweep/process-table.ts+function parsePosixProcessTable(output) {+ const processes = [];+ for (const line of output.split(/\r?\n/)) {+ const match = /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(line);+ if (match === null)+ continue;+ const pid = Number(match[1]);+ const ppid = Number(match[2]);+ const command = match[3];+ if (!isValidProcessId(pid) || !Number.isInteger(ppid) || ppid < 0 || command === undefined)+ continue;+ processes.push({ command, pid, ppid });+ }+ return processes;+}+function parseWindowsProcessTable(output) {+ const parsed = parseJson(output);+ const entries = Array.isArray(parsed) ? parsed : parsed === undefined ? [] : [parsed];+ const processes = [];+ for (const entry of entries) {+ if (!isRecord3(entry))+ continue;+ const pid = numberField(entry, "ProcessId");+ const ppid = numberField(entry, "ParentProcessId");+ const command = stringField(entry, "CommandLine");+ if (pid === undefined || ppid === undefined || command === undefined || command.trim().length === 0)+ continue;+ processes.push({ command, pid, ppid });+ }+ return processes;+}function isOrphaned(processInfo, livePids) {return processInfo.ppid === 1 || !livePids.has(processInfo.ppid);}@@ -2171,13 +2273,113 @@ function isRecord3(value) {return typeof value === "object" && value !== null;}-// ../../utils/src/codegraph/process-exec.ts-function enumerateCodegraphProcesses(platform = process.platform) {+// ../../utils/src/process-sweep/codegraph-family.ts+var SERVE_WRAPPER_SUFFIX = "/components/codegraph/dist/serve.js";+var UPSTREAM_PACKAGE_SEGMENT = "/@colbymchenry/codegraph/";+function selectZombieCodegraphProcesses(processes, options) {+ const platform = options.platform ?? process.platform;+ const livePids = new Set(processes.map((processInfo) => processInfo.pid));+ const roots = normalizeRoots(options.ownedRoots, platform);+ const zombies = [];+ for (const processInfo of processes) {+ const daemon = matchDaemonCommand(processInfo.command, roots, platform);+ if (daemon !== null) {+ if (!isOrphaned(processInfo, livePids))+ continue;+ zombies.push({+ ...processInfo,+ daemonProjectRoot: daemon.projectRoot,+ matchedRoot: daemon.root,+ matchKind: "upstream-daemon"+ });+ continue;+ }+ const match = matchOwnedCodegraphCommand(processInfo.command, roots, platform);+ if (match === null)+ continue;+ if (!isOrphaned(processInfo, livePids))+ continue;+ zombies.push({ ...processInfo, matchedRoot: match.root, matchKind: match.kind });+ }+ return zombies;+}+var STANDALONE_LAUNCHER_SUFFIXES = ["/bin/codegraph", "/bin/codegraph.exe"];+var BUNDLE_SCRIPT_SUFFIX = "/lib/dist/bin/codegraph.js";+function matchDaemonCommand(command, roots, platform) {+ const projectRoot = extractDaemonProjectRoot(splitCommandTokens(command));+ if (projectRoot === null)+ return null;+ const normalizedCommand = normalizeForComparison2(command, platform);+ for (const root of roots) {+ if (root.length === 0)+ continue;+ if (upstreamPackagePathIsUnderRoot(normalizedCommand, root))+ return { projectRoot, root };+ for (const suffix of STANDALONE_LAUNCHER_SUFFIXES) {+ if (hasExecutableToken(normalizedCommand, `${root}${suffix}`))+ return { projectRoot, root };+ }+ if (hasExecutableToken(normalizedCommand, `${root}${BUNDLE_SCRIPT_SUFFIX}`))+ return { projectRoot, root };+ }+ return null;+}+function extractDaemonProjectRoot(tokens) {+ if (!tokens.includes("serve") || !tokens.includes("--mcp"))+ return null;+ const pathIndex = tokens.indexOf("--path");+ if (pathIndex < 0)+ return null;+ const value = tokens[pathIndex + 1];+ if (value === undefined || value.length === 0 || value.startsWith("--"))+ return null;+ return value;+}+function matchOwnedCodegraphCommand(command, roots, platform) {+ const normalizedCommand = normalizeForComparison2(command, platform);+ for (const root of roots) {+ if (root.length === 0)+ continue;+ const serveWrapper = `${root}${SERVE_WRAPPER_SUFFIX}`;+ if (hasExecutableToken(normalizedCommand, serveWrapper))+ return { kind: "serve-wrapper", root };+ if (upstreamPackagePathIsUnderRoot(normalizedCommand, root)) {+ return { kind: "upstream-codegraph", root };+ }+ }+ return null;+}+function upstreamPackagePathIsUnderRoot(command, root) {+ let searchFrom = 0;+ for (;; ) {+ const packageIndex = command.indexOf(UPSTREAM_PACKAGE_SEGMENT, searchFrom);+ if (packageIndex < 0)+ return false;+ const tokenStart = findTokenStart(command, packageIndex);+ if (command.slice(tokenStart).startsWith(`${root}/`) && tokenLooksExecutable(command, tokenStart))+ return true;+ searchFrom = packageIndex + UPSTREAM_PACKAGE_SEGMENT.length;+ }+}++// ../../utils/src/process-sweep/exec.ts+import { execFile } from "node:child_process";+function enumerateProcesses(platform = process.platform) {return platform === "win32" ? enumerateWindowsProcesses() : enumeratePosixProcesses();}-function createDefaultCodegraphProcessKiller(platform = process.platform) {+function createDefaultProcessKiller(platform = process.platform) {return platform === "win32" ? createWindowsKiller() : createPosixKiller();}+function defaultIsProcessAlive(pid) {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ if (!(error instanceof Error))+ throw error;+ return processKillErrorMeansAlive(error);+ }+}function enumeratePosixProcesses() {return execFileText("ps", ["-eo", "pid=,ppid=,command="]).then(parsePosixProcessTable);}@@ -2191,16 +2393,7 @@ function enumerateWindowsProcesses() {}function createPosixKiller() {return {- isAlive: (pid) => {- try {- process.kill(pid, 0);- return true;- } catch (error) {- if (!(error instanceof Error))- throw error;- return processKillErrorMeansAlive(error);- }- },+ isAlive: defaultIsProcessAlive,kill: (pid) => {process.kill(pid, "SIGKILL");return Promise.resolve();@@ -2213,16 +2406,7 @@ function createPosixKiller() {}function createWindowsKiller() {return {- isAlive: (pid) => {- try {- process.kill(pid, 0);- return true;- } catch (error) {- if (!(error instanceof Error))- throw error;- return processKillErrorMeansAlive(error);- }- },+ isAlive: defaultIsProcessAlive,kill: (pid) => execFileVoid("taskkill.exe", ["/PID", String(pid), "/T", "/F"]),terminate: (pid) => execFileVoid("taskkill.exe", ["/PID", String(pid), "/T"])};@@ -2252,10 +2436,10 @@ function processKillErrorMeansAlive(error) {return false;}-// ../../utils/src/codegraph/process-roots.ts-import { existsSync as existsSync6, readdirSync as readdirSync2, realpathSync as realpathSync4 } from "node:fs";+// ../../utils/src/process-sweep/roots.ts+import { existsSync as existsSync6, readdirSync as readdirSync2, realpathSync as realpathSync5 } from "node:fs";import { homedir as homedir9 } from "node:os";-import { join as join9, resolve as resolve5 } from "node:path";+import { join as join10, resolve as resolve6 } from "node:path";function discoverCodegraphOwnedRoots(options = {}) {const env = options.env ?? process.env;const homeDir = options.homeDir ?? env["HOME"] ?? env["USERPROFILE"] ?? homedir9();@@ -2265,33 +2449,33 @@ function discoverCodegraphOwnedRoots(options = {}) {addRoot(roots, options.pluginRoot);for (const root of options.extraRoots ?? [])addRoot(roots, root);- for (const root of readCodexPluginCacheRoots(options.codexHome ?? env["CODEX_HOME"] ?? join9(homeDir, ".codex"))) {+ for (const root of readCodexPluginCacheRoots(options.codexHome ?? env["CODEX_HOME"] ?? join10(homeDir, ".codex"))) {addRoot(roots, root);}return [...roots];}function readCodexPluginCacheRoots(codexHome) {- const cacheRoot = join9(codexHome, "plugins", "cache");+ const cacheRoot = join10(codexHome, "plugins", "cache");if (!existsSync6(cacheRoot))return [];const roots = [];for (const publisher of safeReadDir(cacheRoot)) {if (!OMO_CODEX_PLUGIN_CACHE_PUBLISHERS.has(publisher))continue;- const omoRoot = join9(cacheRoot, publisher, "omo");+ const omoRoot = join10(cacheRoot, publisher, "omo");if (!existsSync6(omoRoot))continue;for (const version of safeReadDir(omoRoot))- roots.push(join9(omoRoot, version));+ roots.push(join10(omoRoot, version));}return roots;}function addRoot(roots, root) {if (root === undefined || root.trim().length === 0)return;- const resolved = resolve5(root);+ const resolved = resolve6(root);roots.add(resolved);- roots.add(realpathIfPossible2(resolved));+ roots.add(realpathIfPossible3(resolved));}function safeReadDir(path) {try {@@ -2302,12 +2486,12 @@ function safeReadDir(path) {throw error;}}-function realpathIfPossible2(path) {+function realpathIfPossible3(path) {try {- return realpathSync4(path);+ return realpathSync5(path);} catch (error) {if (error instanceof Error)- return resolve5(path);+ return resolve6(path);throw error;}}@@ -2319,70 +2503,109 @@ function isNonFatalFsError(error) {}var OMO_CODEX_PLUGIN_CACHE_PUBLISHERS = new Set(["sisyphuslabs"]);-// ../../utils/src/codegraph/process-sweeper.ts+// ../../utils/src/process-sweep/sweeper.tsvar DEFAULT_GRACE_MS = 2000;var DEFAULT_THROTTLE_MS = 60 * 60 * 1000;-var SWEEP_STAMP_FILE = "zombie-sweep.stamp";-async function sweepCodegraphZombies(options = {}) {- const homeDir = options.homeDir ?? options.env?.["HOME"] ?? options.env?.["USERPROFILE"] ?? homedir10();- const stampFile = join10(codegraphDataRoot(homeDir), SWEEP_STAMP_FILE);+async function runProcessFamilySweep(config, options) {const nowMs = options.nowMs ?? Date.now();const dryRun = options.dryRun === true;- const ownedRoots = options.ownedRoots ?? discoverCodegraphOwnedRoots(options);- if (options.force !== true && isSweepThrottled(stampFile, nowMs, options.throttleMs ?? DEFAULT_THROTTLE_MS)) {- return emptyResult("throttled", dryRun, ownedRoots, stampFile);+ if (options.force !== true && isSweepThrottled(config.stampFile, nowMs, options.throttleMs ?? DEFAULT_THROTTLE_MS)) {+ return { action: "throttled", candidates: [], dryRun, failed: [], killed: [], spared: [], stampFile: config.stampFile };}try {- const provider = options.processProvider ?? (() => enumerateCodegraphProcesses(options.platform));- const candidates = selectZombieCodegraphProcesses(await provider(), {- ownedRoots,- ...options.platform === undefined ? {} : { platform: options.platform }- });- const result = dryRun ? { failed: [], killed: [] } : await killCandidates(candidates, options.killer ?? createDefaultCodegraphProcessKiller(options.platform), options);+ const plan = await config.collect();+ const { failed, killed } = dryRun ? { failed: [], killed: [] } : await killTargets(plan.killList, options.killer ?? createDefaultProcessKiller(options.platform), options, config.familyLabel);if (!dryRun)- writeSweepStamp(stampFile, nowMs);- return { action: "swept", candidates, dryRun, failed: result.failed, killed: result.killed, ownedRoots, stampFile };+ writeSweepStamp(config.stampFile, nowMs);+ return {+ action: "swept",+ candidates: plan.candidates,+ dryRun,+ failed,+ killed,+ spared: plan.spared,+ stampFile: config.stampFile+ };} catch (error) {- options.log?.(`CodeGraph zombie sweep skipped: ${error instanceof Error ? error.message : String(error)}`);- return emptyResult("failed", dryRun, ownedRoots, stampFile);+ options.log?.(`${config.familyLabel} skipped: ${error instanceof Error ? error.message : String(error)}`);+ return { action: "failed", candidates: [], dryRun, failed: [], killed: [], spared: [], stampFile: config.stampFile };}}-async function killCandidates(candidates, killer, options) {+var CODEGRAPH_SWEEP_STAMP_FILE = "zombie-sweep.stamp";+async function sweepCodegraphZombies(options = {}) {+ const homeDir = options.homeDir ?? options.env?.["HOME"] ?? options.env?.["USERPROFILE"] ?? homedir10();+ const stampFile = join11(codegraphDataRoot(homeDir), CODEGRAPH_SWEEP_STAMP_FILE);+ const ownedRoots = options.ownedRoots ?? discoverCodegraphOwnedRoots(options);+ const result = await runProcessFamilySweep({+ familyLabel: "CodeGraph zombie sweep",+ stampFile,+ collect: async () => {+ const provider = options.processProvider ?? (() => enumerateProcesses(options.platform));+ const candidates = selectZombieCodegraphProcesses(await provider(), {+ ownedRoots,+ ...options.platform === undefined ? {} : { platform: options.platform }+ });+ const { killList, spared } = partitionByDaemonStaleness(candidates, options.log);+ return { candidates, killList, spared };+ }+ }, options);+ return { ...result, ownedRoots };+}+function partitionByDaemonStaleness(candidates, log) {+ const killList = [];+ const spared = [];+ for (const candidate of candidates) {+ if (candidate.matchKind !== "upstream-daemon") {+ killList.push(candidate);+ continue;+ }+ const staleness = evaluateDaemonStaleness(candidate.pid, candidate.daemonProjectRoot ?? candidate.matchedRoot);+ if (staleness.stale) {+ log?.(`CodeGraph zombie sweep sweeping stale daemon pid ${candidate.pid} (${staleness.reason})`);+ killList.push(candidate);+ continue;+ }+ log?.(`CodeGraph zombie sweep spared live daemon pid ${candidate.pid} (${staleness.reason})`);+ spared.push(candidate);+ }+ return { killList, spared };+}+async function killTargets(targets, killer, options, familyLabel) {const failed = [];const killed = [];- for (const candidate of candidates) {- const terminated = await safelyTerminate(candidate.pid, killer, failed, options.log);+ for (const target of targets) {+ const terminated = await safelyTerminate(target.pid, killer, failed, options.log, familyLabel);if (!terminated)continue;await delay(options.graceMs ?? DEFAULT_GRACE_MS);- if (!await killer.isAlive(candidate.pid)) {- killed.push(candidate);+ if (!await killer.isAlive(target.pid)) {+ killed.push(target);continue;}- if (await safelyKill(candidate.pid, killer, failed, options.log))- killed.push(candidate);+ if (await safelyKill(target.pid, killer, failed, options.log, familyLabel))+ killed.push(target);}return { failed, killed };}-async function safelyTerminate(pid, killer, failed, log) {+async function safelyTerminate(pid, killer, failed, log, familyLabel) {try {await killer.terminate(pid);return true;} catch (error) {const message = error instanceof Error ? error.message : String(error);failed.push({ error: message, pid, stage: "terminate" });- log?.(`CodeGraph zombie sweep failed to terminate pid ${pid}: ${message}`);+ log?.(`${familyLabel} failed to terminate pid ${pid}: ${message}`);return false;}}-async function safelyKill(pid, killer, failed, log) {+async function safelyKill(pid, killer, failed, log, familyLabel) {try {await killer.kill(pid);return true;} catch (error) {const message = error instanceof Error ? error.message : String(error);failed.push({ error: message, pid, stage: "kill" });- log?.(`CodeGraph zombie sweep failed to kill pid ${pid}: ${message}`);+ log?.(`${familyLabel} failed to kill pid ${pid}: ${message}`);return false;}}@@ -2392,15 +2615,12 @@ function isSweepThrottled(stampFile, nowMs, throttleMs) {return nowMs - statSync2(stampFile).mtimeMs < throttleMs;}function writeSweepStamp(stampFile, nowMs) {- mkdirSync2(dirname4(stampFile), { recursive: true });+ mkdirSync2(dirname5(stampFile), { recursive: true });writeFileSync2(stampFile, `${new Date(nowMs).toISOString()}`);const stampDate = new Date(nowMs);utimesSync(stampFile, stampDate, stampDate);}-function emptyResult(action, dryRun, ownedRoots, stampFile) {- return { action, candidates: [], dryRun, failed: [], killed: [], ownedRoots, stampFile };-}function delay(ms) {if (ms <= 0)return Promise.resolve();@@ -2428,56 +2648,55 @@ function defaultPluginRoot() {import { execFile as execFile3 } from "node:child_process";import { appendFileSync as appendFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync3 } from "node:fs";import { homedir as homedir12 } from "node:os";-import { extname, join as join12 } from "node:path";+import { extname, join as join13 } from "node:path";import { cwd as processCwd, env as processEnv, execPath as processExecPath, stderr as processStderr } from "node:process";-// ../../utils/src/codegraph/provision.ts-import { createHash as createHash2, randomUUID } from "node:crypto";-import { execFile as execFile2 } from "node:child_process";-import { chmod, mkdir, readdir, readFile, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";-import { existsSync as existsSync8 } from "node:fs";-import { homedir as homedir11, hostname } from "node:os";-import { basename as basename3, join as join11 } from "node:path";-import { promisify } from "node:util";-// ../../utils/src/codegraph/manifest.ts+var CODEGRAPH_PINNED_VERSION = "1.4.1";var CODEGRAPH_PROVISION_MANIFEST = {assets: {"darwin-arm64": {executableName: "codegraph",- sha256: "95bb27bf6382b69659e158e0c04d71cc394778951e1317d582be7807e7866908",- url: "https://github.com/colbymchenry/codegraph/releases/download/v1.0.1/codegraph-darwin-arm64.tar.gz"+ sha256: "4a679ae5a5cb9fff900dd59bb786da6a581b7f68f4cf713bdedd137e347d34dc",+ url: "https://github.com/colbymchenry/codegraph/releases/download/v1.4.1/codegraph-darwin-arm64.tar.gz"},"darwin-x64": {executableName: "codegraph",- sha256: "3311cc1d1f0f0ad742709b6a43d8a9187b1ef0af0dd30e0b58008dc673e29478",- url: "https://github.com/colbymchenry/codegraph/releases/download/v1.0.1/codegraph-darwin-x64.tar.gz"+ sha256: "436f96943cfd926ea6d0a8454f18833d21254d5fd9b3d224317b1426132def95",+ url: "https://github.com/colbymchenry/codegraph/releases/download/v1.4.1/codegraph-darwin-x64.tar.gz"},"linux-arm64": {executableName: "codegraph",- sha256: "e16f612bc96c2ebccd04574cbed500c9939147c80666ad6bb024398dff7992ae",- url: "https://github.com/colbymchenry/codegraph/releases/download/v1.0.1/codegraph-linux-arm64.tar.gz"+ sha256: "0d62c5eb2722f8d19d20f7a1bd974445e18d5294cb59be116a0c3d55ce87591f",+ url: "https://github.com/colbymchenry/codegraph/releases/download/v1.4.1/codegraph-linux-arm64.tar.gz"},"linux-x64": {executableName: "codegraph",- sha256: "d45a068f44596a85c7ba7d0ef924eaf7103fbbf3cafbeb668127daff60a52228",- url: "https://github.com/colbymchenry/codegraph/releases/download/v1.0.1/codegraph-linux-x64.tar.gz"+ sha256: "fb585ff5018d6faaa46d282b61f4f689bc7967ed8a1b467a5c556dd7ced9b542",+ url: "https://github.com/colbymchenry/codegraph/releases/download/v1.4.1/codegraph-linux-x64.tar.gz"},"win32-arm64": {executableName: "codegraph.cmd",- sha256: "8d57ced73b24d35f758f2ede2318e80e1d7241987f37a999e3d80edb6fddf961",- url: "https://registry.npmjs.org/@colbymchenry/codegraph-win32-arm64/-/codegraph-win32-arm64-1.0.1.tgz"+ sha256: "e2a2a28c802a79804c7df203afa50bd461309c6c180ce3f76079fdc7cddc7697",+ url: "https://registry.npmjs.org/@colbymchenry/codegraph-win32-arm64/-/codegraph-win32-arm64-1.4.1.tgz"},"win32-x64": {executableName: "codegraph.cmd",- sha256: "52607fe73b05e741fd1087da2ceca9d3c8f565e36bf1a7070600bdbdf3931e32",- url: "https://registry.npmjs.org/@colbymchenry/codegraph-win32-x64/-/codegraph-win32-x64-1.0.1.tgz"+ sha256: "4f08700fda5f4a03ad5b2956135c5788d739a351b3433db2b5820e5d5224c30d",+ url: "https://registry.npmjs.org/@colbymchenry/codegraph-win32-x64/-/codegraph-win32-x64-1.4.1.tgz"}},- version: "1.0.1"+ version: CODEGRAPH_PINNED_VERSION};// ../../utils/src/codegraph/provision.ts+import { createHash as createHash2, randomUUID } from "node:crypto";+import { execFile as execFile2 } from "node:child_process";+import { chmod, mkdir, readdir, readFile, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";+import { existsSync as existsSync8 } from "node:fs";+import { homedir as homedir11, hostname } from "node:os";+import { basename as basename3, join as join12 } from "node:path";+import { promisify } from "node:util";var DEFAULT_LOCK_WAIT_MS = 5000;var DEFAULT_LOCK_STALE_MS = 120000;var DEFAULT_DOWNLOAD_TIMEOUT_MS = 60000;@@ -2486,10 +2705,10 @@ function platformKey() {return `${process.platform}-${process.arch}`;}function markerPath(installDir, version) {- return join11(installDir, ".provisioned", `codegraph-${version}.json`);+ return join12(installDir, ".provisioned", `codegraph-${version}.json`);}function defaultInstallDir() {- return join11(homedir11(), ".omo", "codegraph");+ return join12(homedir11(), ".omo", "codegraph");}function sha256(bytes) {return createHash2("sha256").update(bytes).digest("hex");@@ -2509,7 +2728,7 @@ async function removeEmptyDirectory(path) {}}function sleep(ms) {- return new Promise((resolve6) => setTimeout(resolve6, ms));+ return new Promise((resolve7) => setTimeout(resolve7, ms));}async function defaultDownloader(asset, timeoutMs = DEFAULT_DOWNLOAD_TIMEOUT_MS) {const response = await fetch(asset.url, { signal: AbortSignal.timeout(timeoutMs) });@@ -2523,7 +2742,7 @@ function forcedBadChecksumOptions(options) {const key = options.platformKey ?? platformKey();return {downloader: async () => new TextEncoder().encode("checksum mismatch"),- installDir: options.installDir ?? join11(options.lockDir, "codegraph-force-bad-checksum"),+ installDir: options.installDir ?? join12(options.lockDir, "codegraph-force-bad-checksum"),manifest: {assets: {[key]: { executableName: process.platform === "win32" ? "codegraph.cmd" : "codegraph", sha256: "0000", url: "memory://bad" }@@ -2551,7 +2770,7 @@ async function readMarker(path) {}async function acquireLock(lockPath, waitMs, staleMs) {const startedAt = Date.now();- await mkdir(join11(lockPath, ".."), { recursive: true });+ await mkdir(join12(lockPath, ".."), { recursive: true });while (Date.now() - startedAt <= waitMs) {try {await mkdir(lockPath);@@ -2576,14 +2795,14 @@ async function installExtractedBundle(extractDir, installDir, executableName) {const roots = await readdir(extractDir);if (roots.length !== 1)throw new Error(`CodeGraph archive should contain one root directory, found ${roots.length}`);- const bundleDir = join11(extractDir, roots[0] ?? "");+ const bundleDir = join12(extractDir, roots[0] ?? "");const bundleEntries = await readdir(bundleDir);await mkdir(installDir, { recursive: true });for (const entry of bundleEntries) {- await rm(join11(installDir, entry), { force: true, recursive: true });- await rename(join11(bundleDir, entry), join11(installDir, entry));+ await rm(join12(installDir, entry), { force: true, recursive: true });+ await rename(join12(bundleDir, entry), join12(installDir, entry));}- const destination = join11(installDir, "bin", executableName);+ const destination = join12(installDir, "bin", executableName);if (!existsSync8(destination))throw new Error(`CodeGraph archive did not contain bin/${executableName}`);await chmod(destination, 493);@@ -2591,9 +2810,9 @@ async function installExtractedBundle(extractDir, installDir, executableName) {}async function installAsset(layout) {const { asset, downloader, installDir, version } = layout;- const stagingDir = join11(installDir, ".staging", randomUUID());- const archivePath = join11(stagingDir, basename3(asset.url));- const extractDir = join11(stagingDir, "extract");+ const stagingDir = join12(installDir, ".staging", randomUUID());+ const archivePath = join12(stagingDir, basename3(asset.url));+ const extractDir = join12(stagingDir, "extract");try {await mkdir(extractDir, { recursive: true });const bytes = await downloader(asset);@@ -2607,13 +2826,13 @@ async function installAsset(layout) {await writeFile(archivePath, bytes);await extractTarGz(archivePath, extractDir);const destination = await installExtractedBundle(extractDir, installDir, asset.executableName);- await mkdir(join11(installDir, ".provisioned"), { recursive: true });+ await mkdir(join12(installDir, ".provisioned"), { recursive: true });await writeFile(markerPath(installDir, version), `${JSON.stringify({ binPath: destination, version })}`);return destination;} finally {await rm(stagingDir, { force: true, recursive: true });- await removeEmptyDirectory(join11(installDir, ".staging"));+ await removeEmptyDirectory(join12(installDir, ".staging"));}}async function ensureCodegraphProvisioned(options) {@@ -2626,7 +2845,7 @@ async function ensureCodegraphProvisioned(options) {const existing = await readMarker(marker);if (existing !== null)return { binPath: existing, provisioned: true };- const lockPath = join11(options.lockDir, `codegraph-${hostname()}.lock`);+ const lockPath = join12(options.lockDir, `codegraph-${hostname()}.lock`);const release = await acquireLock(lockPath, options.lockWaitMs ?? DEFAULT_LOCK_WAIT_MS, options.lockStaleMs ?? DEFAULT_LOCK_STALE_MS);if (release === null)return { error: "timed out waiting for codegraph provisioning lock", provisioned: false };@@ -2652,7 +2871,7 @@ async function ensureCodegraphProvisioned(options) {// components/codegraph/src/session-start-worker.tsvar SESSION_START_CWD_ENV = "OMO_CODEGRAPH_SESSION_START_CWD";-var CODEGRAPH_VERSION = "1.0.1";+var CODEGRAPH_VERSION = CODEGRAPH_PINNED_VERSION;var COMMAND_TIMEOUT_MS = 60000;var WINDOWS_CMD_EXTENSIONS = new Set([".bat", ".cmd"]);var WINDOWS_NODE_SCRIPT_EXTENSIONS = new Set([".cjs", ".js", ".mjs"]);@@ -2716,15 +2935,15 @@ async function resolveOrProvisionCommand(deps, config, env, homeDir, nodeSupportreturn { kind: "unsupported-node" };if (config.auto_provision === false)return { error: "codegraph binary unavailable and auto_provision is disabled", kind: "unavailable", source: resolved.source };- const installDir = trustedInstallDir ?? join12(homeDir, ".omo", "codegraph");- const provisioned = await deps.ensureProvisioned({ installDir, lockDir: join12(installDir, ".locks"), version: CODEGRAPH_VERSION });+ const installDir = trustedInstallDir ?? join13(homeDir, ".omo", "codegraph");+ const provisioned = await deps.ensureProvisioned({ installDir, lockDir: join13(installDir, ".locks"), version: CODEGRAPH_VERSION });if (!provisioned.provisioned || provisioned.binPath === undefined) {return { error: provisioned.error ?? "provisioning did not produce a binary", kind: "unavailable", source: resolved.source };}return { kind: "resolved", resolution: { argsPrefix: [], command: provisioned.binPath, exists: true, source: "provisioned" } };}function codegraphEnvForConfig(config, homeDir) {- const env = buildCodegraphEnv({ homeDir });+ const env = buildCodegraphEnv({ daemon: false, homeDir });return config.trustedCodegraphInstallDir === undefined ? env : { ...env, CODEGRAPH_INSTALL_DIR: config.trustedCodegraphInstallDir };}function canUseResolvedCommand(resolved, nodeSupport) {@@ -2785,9 +3004,9 @@ function resolveCodegraphCommandInvocation(command, args, platform = process.plareturn { args: ["/d", "/s", "/c", command, ...args], command: "cmd.exe" };}function appendOutcome(homeDir, outcome) {- const logDir = join12(homeDir, ".omo", "codegraph");+ const logDir = join13(homeDir, ".omo", "codegraph");mkdirSync3(logDir, { recursive: true });- appendFileSync2(join12(logDir, "session-start.jsonl"), `${JSON.stringify({ ...outcome, timestamp: new Date().toISOString() })}+ appendFileSync2(join13(logDir, "session-start.jsonl"), `${JSON.stringify({ ...outcome, timestamp: new Date().toISOString() })}`);}function safeLogOutcome(logOutcome, outcome) {@@ -2804,7 +3023,7 @@ function safeLogOutcome(logOutcome, outcome) {function provisionedBinFromInstallDir(installDir) {if (installDir === undefined)return null;- const candidate = join12(installDir, "bin", process.platform === "win32" ? "codegraph.cmd" : "codegraph");+ const candidate = join13(installDir, "bin", process.platform === "win32" ? "codegraph.cmd" : "codegraph");return existsSync9(candidate) ? candidate : null;}function resolveExitCode(error) {@@ -2865,6 +3084,7 @@ async function executeCodegraphSessionStartHook(options = {}) {return { action: "skipped-excluded", exitCode: 0 };}const isInitialized = await (options.statusProbe ?? isCodegraphProjectInitialized)({+ daemon: config.codegraph?.daemon === true,env,homeDir,projectRoot,@@ -2895,7 +3115,7 @@ async function isCodegraphProjectInitialized(options) {return false;const invocation = resolveCodegraphCommandInvocation(resolved.command, [...resolved.argsPrefix, "status", "--json"]);const codegraphEnv = {- ...buildCodegraphEnv({ homeDir: options.homeDir }),+ ...buildCodegraphEnv({ daemon: options.daemon, homeDir: options.homeDir }),...options.trustedCodegraphInstallDir === undefined ? {} : { CODEGRAPH_INSTALL_DIR: options.trustedCodegraphInstallDir }};const status = await runStatusProbe(options.projectRoot, invocation.command, invocation.args, buildCodegraphChildEnv({ ambientEnv: options.env, codegraphEnv, runtimeEnv: options.env }));@@ -2937,7 +3157,7 @@ function codegraphStatusSaysInitialized(stdout) {function provisionedBinFromInstallDir2(installDir) {if (installDir === undefined)return null;- return join13(installDir, "bin", process.platform === "win32" ? "codegraph.cmd" : "codegraph");+ return join14(installDir, "bin", process.platform === "win32" ? "codegraph.cmd" : "codegraph");}async function executeCodegraphPostToolUseHook(options = {}) {const env = options.env ?? processEnv2;@@ -3027,9 +3247,9 @@ function defaultWorkerCliPath() {}// components/codegraph/src/serve.ts-import { existsSync as existsSync10, realpathSync as realpathSync5 } from "node:fs";+import { existsSync as existsSync10, realpathSync as realpathSync6 } from "node:fs";import { homedir as homedir14 } from "node:os";-import { basename as basename4, join as join14, resolve as resolve6 } from "node:path";+import { basename as basename4, join as join15, resolve as resolve7 } from "node:path";import {cwd as processCwd3,env as processEnv3,@@ -3090,7 +3310,7 @@ ${body}` : `${body}await writeChunk(output, payload);}function writeChunk(output, chunk) {- return new Promise((resolve6, reject) => {+ return new Promise((resolve7, reject) => {let settled = false;const onError = (error) => {if (settled)@@ -3110,7 +3330,7 @@ function writeChunk(output, chunk) {return;}output.removeListener("error", onError);- resolve6();+ resolve7();});} catch (error) {output.removeListener("error", onError);@@ -3202,16 +3422,35 @@ function bufferFromChunk(chunk) {// ../../mcp-stdio-core/src/server.tsvar DEFAULT_IDLE_TIMEOUT_MS = 10 * 60000;+var DEFAULT_PARENT_POLL_INTERVAL_MS = 30000;var noopLog = () => {};+function isProcessAlive(pid) {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return !hasErrorCode(error, "ESRCH");+ }+}async function runJsonRpcStdioServer(config) {const log = config.log ?? noopLog;const idleTimeoutMs = config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;- const idleTimer = createIdleTimer(idleTimeoutMs, log, config.onIdleTimeout);+ let isClosed = false;+ const idleTimer = createIdleTimer(idleTimeoutMs, log, () => {+ isClosed = true;+ config.onIdleTimeout?.();+ });+ const watchdog = createParentWatchdog(config.parentWatchdog, (parentPid, pollIntervalMs) => {+ isClosed = true;+ log("parent_exit", { parent_pid: parentPid, poll_interval_ms: pollIntervalMs });+ config.onParentExit?.();+ config.input.destroy();+ });log("stdio_started", { cwd: process.cwd(), idle_timeout_ms: idleTimeoutMs });idleTimer.arm();try {for await (const message of readStdioJsonRpcMessages(config.input)) {- if (idleTimer.closed())+ if (isClosed)break;idleTimer.arm();if (message.kind === "parse_error") {@@ -3222,8 +3461,12 @@ async function runJsonRpcStdioServer(config) {if (!await handleRequest(message, config, log))break;}+ } catch (error) {+ if (!(isClosed && hasErrorCode(error, "ERR_STREAM_PREMATURE_CLOSE")))+ throw error;} finally {idleTimer.clear();+ watchdog.clear();log("stdio_stopped");}}@@ -3279,9 +3522,33 @@ function isTerminalOutputError(error) {return false;return error.code === "EPIPE" || error.code === "ERR_STREAM_DESTROYED" || error.code === "ERR_STREAM_WRITE_AFTER_END";}-function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {+function hasErrorCode(error, code) {+ return error instanceof Error && "code" in error && error.code === code;+}+function createParentWatchdog(config, onDeadParent) {+ if (config === undefined)+ return { clear: () => {} };+ const pollIntervalMs = config.pollIntervalMs ?? DEFAULT_PARENT_POLL_INTERVAL_MS;+ if (pollIntervalMs <= 0)+ return { clear: () => {} };+ const parentPid = config.parentPid ?? process.ppid;+ const probeAlive = config.probeAlive ?? isProcessAlive;+ let fired = false;+ const timer = setInterval(() => {+ if (fired || probeAlive(parentPid))+ return;+ fired = true;+ onDeadParent(parentPid, pollIntervalMs);+ }, pollIntervalMs);+ timer.unref();+ return {+ clear: () => {+ clearInterval(timer);+ }+ };+}+function createIdleTimer(idleTimeoutMs, log, onTimeout) {let timer = null;- let isClosed = false;return {arm: () => {if (timer !== null)@@ -3289,9 +3556,8 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {if (idleTimeoutMs <= 0)return;timer = setTimeout(() => {- isClosed = true;log("idle_timeout", { idle_timeout_ms: idleTimeoutMs });- onIdleTimeout?.();+ onTimeout();}, idleTimeoutMs);timer.unref();},@@ -3300,8 +3566,7 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {return;clearTimeout(timer);timer = null;- },- closed: () => isClosed+ }};}// components/codegraph/src/serve-invocation.ts@@ -3334,6 +3599,7 @@ class CodegraphBridgeStdioError extends Error {var CODEGRAPH_NODE_DESCRIPTION = "Inspect one named symbol or file. In symbol mode, includeCode=true includes leaf-symbol source when available. Container symbols such as classes, interfaces, structs, enums, modules, and namespaces return structural outlines with member lists by design. For container source, request a specific member symbol or use file mode with symbolsOnly=false plus offset/limit.";var CODEGRAPH_NODE_INCLUDE_CODE_DESCRIPTION = "Symbol mode: include leaf-symbol source when available. Container symbols such as classes, interfaces, structs, enums, modules, and namespaces intentionally return structural outlines with members; request a specific member symbol or use file mode with symbolsOnly=false plus offset/limit for source.";var CODEGRAPH_CONTAINER_OUTLINE_GUIDANCE = "Container symbols intentionally return structural outlines with members. For source, request a specific member symbol or call codegraph_node in file mode with symbolsOnly=false plus offset/limit around the symbol location.";+var SIGKILL_ESCALATION_MS = 2000;async function runBridgedCodegraphProcess(command, args, options) {const invocation = resolveServeProcessInvocation(command, args);const child = spawn2(invocation.command, invocation.args, {@@ -3359,17 +3625,24 @@ async function runBridgedCodegraphProcess(command, args, options) {resolveExit(signal === null ? 0 : 1);});});- const clientForwardingDone = forwardClientToCodegraph(options.input, childInput, pendingResponses, (mode) => {- defaultResponseMode = mode;- });- const responseForwardingDone = forwardCodegraphToClient(childOutput, options.output, pendingResponses, () => defaultResponseMode);- const bridgeDone = Promise.all([clientForwardingDone, responseForwardingDone]);- const childAndResponsesDone = Promise.all([childExit, responseForwardingDone]).then(([exitCode]) => exitCode);const destroyChildPipes = () => {childInput.destroy();childOutput.destroy();};childExit.then(destroyChildPipes, destroyChildPipes);+ let parentWatchdogFired = false;+ const parentWatchdog = createParentWatchdog(options.parentWatchdog, () => {+ parentWatchdogFired = true;+ options.input.destroy();+ destroyChildPipes();+ terminateCodegraphChild(child);+ });+ const clientForwardingDone = forwardClientToCodegraph(options.input, childInput, pendingResponses, (mode) => {+ defaultResponseMode = mode;+ }, () => parentWatchdogFired);+ const responseForwardingDone = forwardCodegraphToClient(childOutput, options.output, pendingResponses, () => defaultResponseMode, () => parentWatchdogFired);+ const bridgeDone = Promise.all([clientForwardingDone, responseForwardingDone]);+ const childAndResponsesDone = Promise.all([childExit, responseForwardingDone]).then(([exitCode]) => exitCode);try {return await Promise.race([childAndResponsesDone, bridgeDone.then(() => childExit)]);} catch (error) {@@ -3380,39 +3653,66 @@ async function runBridgedCodegraphProcess(command, args, options) {return;});throw error;+ } finally {+ parentWatchdog.clear();}}-async function forwardClientToCodegraph(input, childInput, pendingResponses, setDefaultResponseMode) {- for await (const message of readStdioJsonRpcMessages(input)) {- if (message.kind === "parse_error") {- continue;- }- const responseMode = message.responseMode;- setDefaultResponseMode(responseMode);- const key = responseModeKey(message.payload);- if (key !== null) {- pendingResponses.set(key, {- method: jsonRpcMethod(message.payload),- responseMode,- toolName: jsonRpcToolName(message.payload)- });+function terminateCodegraphChild(child) {+ if (child.exitCode !== null || child.signalCode !== null)+ return;+ child.kill("SIGTERM");+ const escalation = setTimeout(() => {+ if (child.exitCode === null && child.signalCode === null)+ child.kill("SIGKILL");+ }, SIGKILL_ESCALATION_MS);+ escalation.unref();+}+function isWatchdogTeardownError(error) {+ if (!(error instanceof Error) || !("code" in error))+ return false;+ return error.code === "ERR_STREAM_PREMATURE_CLOSE" || error.code === "ERR_STREAM_DESTROYED" || error.code === "ERR_STREAM_WRITE_AFTER_END" || error.code === "EPIPE";+}+async function forwardClientToCodegraph(input, childInput, pendingResponses, setDefaultResponseMode, tolerateWatchdogClose) {+ try {+ for await (const message of readStdioJsonRpcMessages(input)) {+ if (message.kind === "parse_error") {+ continue;+ }+ const responseMode = message.responseMode;+ setDefaultResponseMode(responseMode);+ const key = responseModeKey(message.payload);+ if (key !== null) {+ pendingResponses.set(key, {+ method: jsonRpcMethod(message.payload),+ responseMode,+ toolName: jsonRpcToolName(message.payload)+ });+ }+ await writeLine(childInput, JSON.stringify(message.payload));}- await writeLine(childInput, JSON.stringify(message.payload));+ childInput.end();+ } catch (error) {+ if (!(tolerateWatchdogClose() && isWatchdogTeardownError(error)))+ throw error;}- childInput.end();}-async function forwardCodegraphToClient(childOutput, output, pendingResponses, defaultResponseMode) {- for await (const message of readStdioJsonRpcMessages(childOutput)) {- if (message.kind === "parse_error") {- await writeStdioJsonRpcResponse(output, errorResponse(null, -32700, "Parse error", message.message), defaultResponseMode());- continue;+async function forwardCodegraphToClient(childOutput, output, pendingResponses, defaultResponseMode, tolerateWatchdogClose) {+ try {+ for await (const message of readStdioJsonRpcMessages(childOutput)) {+ if (message.kind === "parse_error") {+ await writeStdioJsonRpcResponse(output, errorResponse(null, -32700, "Parse error", message.message), defaultResponseMode());+ continue;+ }+ const key = responseModeKey(message.payload);+ const pendingResponse = key === null ? undefined : pendingResponses.get(key);+ const responseMode = pendingResponse?.responseMode ?? defaultResponseMode();+ if (key !== null)+ pendingResponses.delete(key);+ await writeStdioJsonRpcResponse(output, clarifyCodegraphResponse(message.payload, pendingResponse), responseMode);}- const key = responseModeKey(message.payload);- const pendingResponse = key === null ? undefined : pendingResponses.get(key);- const responseMode = pendingResponse?.responseMode ?? defaultResponseMode();- if (key !== null)- pendingResponses.delete(key);- await writeStdioJsonRpcResponse(output, clarifyCodegraphResponse(message.payload, pendingResponse), responseMode);+ } catch (error) {+ if (!(tolerateWatchdogClose() && isWatchdogTeardownError(error)))+ throw error;}}function responseModeKey(payload) {@@ -3544,7 +3844,8 @@ async function runUnavailableCodegraphMcpServer(options) {serverVersion: options.serverVersion},input: options.input,- output: options.output+ output: options.output,+ parentWatchdog: options.parentWatchdog ?? {}});}async function handleUnavailableCodegraphMcpRequest(input, options) {@@ -3588,7 +3889,7 @@ var CODEGRAPH_DISABLED_HINT = `CodeGraph MCP skipped: disabled by OMO SOT config`;var CODEGRAPH_EXCLUDED_HINT = `CodeGraph MCP skipped: project excluded by OMO CodeGraph policy.`;-var CODEGRAPH_VERSION2 = "1.0.1";+var CODEGRAPH_VERSION2 = CODEGRAPH_PINNED_VERSION;var PROJECT_CWD_ENV_KEYS = ["OMO_CODEGRAPH_PROJECT_CWD", SESSION_START_CWD_ENV, "PWD"];async function runCodegraphServe(options = {}) {const env = options.env ?? processEnv3;@@ -3636,7 +3937,7 @@ async function runCodegraphServe(options = {}) {return runUnavailableMcp(buildCodegraphNodeSkipHint(nodeSupport), options);}const runProcess = options.runProcess ?? runBridgedCodegraphProcess;- const codegraphEnv = codegraphEnvForConfig2(trustedInstallDir, homeDir, options.buildEnv);+ const codegraphEnv = codegraphEnvForConfig2(trustedInstallDir, homeDir, codegraphConfig.daemon === true, options.buildEnv);const mergedEnv = buildCodegraphChildEnv({ ambientEnv: env, codegraphEnv, runtimeEnv: env });return runProcess(resolution.command, [...resolution.argsPrefix, "serve", "--mcp"], {cwd: projectCwd,@@ -3644,7 +3945,8 @@ async function runCodegraphServe(options = {}) {input: options.stdin ?? processStdin2,output: options.stdout ?? processStdout2,stderr: options.stderr ?? processStderr3,- stdio: "pipe"+ stdio: "pipe",+ parentWatchdog: options.parentWatchdog ?? {}});}async function runUnavailableMcp(reason, options) {@@ -3653,7 +3955,8 @@ async function runUnavailableMcp(reason, options) {input: options.stdin ?? processStdin2,output: options.stdout ?? processStdout2,reason,- serverVersion: CODEGRAPH_VERSION2+ serverVersion: CODEGRAPH_VERSION2,+ parentWatchdog: options.parentWatchdog ?? {}});return 0;}@@ -3662,10 +3965,10 @@ async function provisionMissingCodegraph(options) {return null;if (options.config.auto_provision === false)return null;- const installDir = options.trustedInstallDir ?? join14(options.homeDir, ".omo", "codegraph");+ const installDir = options.trustedInstallDir ?? join15(options.homeDir, ".omo", "codegraph");const result = await options.ensureProvisioned({installDir,- lockDir: join14(installDir, ".locks"),+ lockDir: join15(installDir, ".locks"),version: CODEGRAPH_VERSION2});if (!result.provisioned || result.binPath === undefined)@@ -3682,8 +3985,8 @@ function shouldSkipResolvedCommand(resolution, commandExists) {function looksLikePath2(command) {return command.includes("/") || command.includes("\\");}-function codegraphEnvForConfig2(trustedInstallDir, homeDir, buildEnv) {- const env = { ...buildEnv?.({ homeDir }) ?? buildCodegraphEnv({ homeDir }), [CODEGRAPH_NO_DAEMON_ENV]: "1" };+function codegraphEnvForConfig2(trustedInstallDir, homeDir, daemon, buildEnv) {+ const env = buildEnv?.({ daemon, homeDir }) ?? buildCodegraphEnv({ daemon, homeDir });return trustedInstallDir === undefined ? env : { ...env, CODEGRAPH_INSTALL_DIR: trustedInstallDir };}function resolveProjectCwd(env, fallback) {@@ -3691,16 +3994,16 @@ function resolveProjectCwd(env, fallback) {const candidate = env[key]?.trim();if (candidate === undefined || candidate.length === 0)continue;- const resolved = resolve6(candidate);+ const resolved = resolve7(candidate);if (existsSync10(resolved))return resolved;}- return resolve6(fallback);+ return resolve7(fallback);}function provisionedBinFromInstallDir3(installDir) {if (installDir === undefined)return null;- const candidate = join14(installDir, "bin", process.platform === "win32" ? "codegraph.cmd" : "codegraph");+ const candidate = join15(installDir, "bin", process.platform === "win32" ? "codegraph.cmd" : "codegraph");return existsSync10(candidate) ? candidate : null;}async function runCodegraphServeCli() {@@ -3720,7 +4023,7 @@ function isDirectInvocation(argvPath) {const moduleName = basename4(modulePath);if (moduleName !== "serve.js" && moduleName !== "serve.ts")return false;- return realpathSync5(resolve6(argvPath)) === realpathSync5(modulePath);+ return realpathSync6(resolve7(argvPath)) === realpathSync6(modulePath);}// components/codegraph/src/sweep-cli.ts@@ -3767,6 +4070,7 @@ function writeSweepReport(stdout, result) {failed: result.failed,killed: result.killed.map(formatProcess),ownedRoots: result.ownedRoots,+ spared: result.spared.map(formatProcess),stampFile: result.stampFile})}`);@@ -3830,7 +4134,7 @@ function isDirectInvocation2(argvPath) {const moduleName = basename5(modulePath);if (moduleName !== "cli.js" && moduleName !== "cli.ts")return false;- return realpathSync6(resolve7(argvPath)) === realpathSync6(modulePath);+ return realpathSync7(resolve8(argvPath)) === realpathSync7(modulePath);}export {runCodegraphClidiff --git a/plugins/omo/components/codegraph/dist/serve.js b/plugins/omo/components/codegraph/dist/serve.jsindex 7ad151a4..26c02b92 100755--- a/plugins/omo/components/codegraph/dist/serve.js+++ b/plugins/omo/components/codegraph/dist/serve.js@@ -50,6 +50,7 @@ var SAFE_AMBIENT_ENV_KEYS = new Set([var SAFE_CODEGRAPH_RUNTIME_ENV_KEYS = new Set(["CODEGRAPH_ALLOW_UNSAFE_NODE","CODEGRAPH_BIN",+ "CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS","CODEGRAPH_FAKE_LOG","CODEGRAPH_NO_DAEMON","CODEGRAPH_NODE_BIN",@@ -61,7 +62,7 @@ function buildCodegraphEnv(options = {}) {const homeDir = options.homeDir ?? homedir();return {[CODEGRAPH_INSTALL_DIR_ENV]: join(homeDir, ".omo", "codegraph"),- [CODEGRAPH_NO_DAEMON_ENV]: "1",+ ...options.daemon === true ? {} : { [CODEGRAPH_NO_DAEMON_ENV]: "1" },[CODEGRAPH_NO_DOWNLOAD_ENV]: "1",[CODEGRAPH_TELEMETRY_ENV]: "0",[DO_NOT_TRACK_ENV]: "1"@@ -88,6 +89,44 @@ function buildCodegraphChildEnv(options = {}) {return env;}+// ../../../../utils/src/codegraph/manifest.ts+var CODEGRAPH_PINNED_VERSION = "1.4.1";+var CODEGRAPH_PROVISION_MANIFEST = {+ assets: {+ "darwin-arm64": {+ executableName: "codegraph",+ sha256: "4a679ae5a5cb9fff900dd59bb786da6a581b7f68f4cf713bdedd137e347d34dc",+ url: "https://github.com/colbymchenry/codegraph/releases/download/v1.4.1/codegraph-darwin-arm64.tar.gz"+ },+ "darwin-x64": {+ executableName: "codegraph",+ sha256: "436f96943cfd926ea6d0a8454f18833d21254d5fd9b3d224317b1426132def95",+ url: "https://github.com/colbymchenry/codegraph/releases/download/v1.4.1/codegraph-darwin-x64.tar.gz"+ },+ "linux-arm64": {+ executableName: "codegraph",+ sha256: "0d62c5eb2722f8d19d20f7a1bd974445e18d5294cb59be116a0c3d55ce87591f",+ url: "https://github.com/colbymchenry/codegraph/releases/download/v1.4.1/codegraph-linux-arm64.tar.gz"+ },+ "linux-x64": {+ executableName: "codegraph",+ sha256: "fb585ff5018d6faaa46d282b61f4f689bc7967ed8a1b467a5c556dd7ced9b542",+ url: "https://github.com/colbymchenry/codegraph/releases/download/v1.4.1/codegraph-linux-x64.tar.gz"+ },+ "win32-arm64": {+ executableName: "codegraph.cmd",+ sha256: "e2a2a28c802a79804c7df203afa50bd461309c6c180ce3f76079fdc7cddc7697",+ url: "https://registry.npmjs.org/@colbymchenry/codegraph-win32-arm64/-/codegraph-win32-arm64-1.4.1.tgz"+ },+ "win32-x64": {+ executableName: "codegraph.cmd",+ sha256: "4f08700fda5f4a03ad5b2956135c5788d739a351b3433db2b5820e5d5224c30d",+ url: "https://registry.npmjs.org/@colbymchenry/codegraph-win32-x64/-/codegraph-win32-x64-1.4.1.tgz"+ }+ },+ version: CODEGRAPH_PINNED_VERSION+};+// ../../../../utils/src/codegraph/node-support.tsvar CODEGRAPH_MIN_NODE_MAJOR = 20;var CODEGRAPH_BLOCKED_NODE_MAJOR = 25;@@ -125,45 +164,6 @@ import { existsSync } from "node:fs";import { homedir as homedir2, hostname } from "node:os";import { basename, join as join2 } from "node:path";import { promisify } from "node:util";--// ../../../../utils/src/codegraph/manifest.ts-var CODEGRAPH_PROVISION_MANIFEST = {- assets: {- "darwin-arm64": {- executableName: "codegraph",- sha256: "95bb27bf6382b69659e158e0c04d71cc394778951e1317d582be7807e7866908",- url: "https://github.com/colbymchenry/codegraph/releases/download/v1.0.1/codegraph-darwin-arm64.tar.gz"- },- "darwin-x64": {- executableName: "codegraph",- sha256: "3311cc1d1f0f0ad742709b6a43d8a9187b1ef0af0dd30e0b58008dc673e29478",- url: "https://github.com/colbymchenry/codegraph/releases/download/v1.0.1/codegraph-darwin-x64.tar.gz"- },- "linux-arm64": {- executableName: "codegraph",- sha256: "e16f612bc96c2ebccd04574cbed500c9939147c80666ad6bb024398dff7992ae",- url: "https://github.com/colbymchenry/codegraph/releases/download/v1.0.1/codegraph-linux-arm64.tar.gz"- },- "linux-x64": {- executableName: "codegraph",- sha256: "d45a068f44596a85c7ba7d0ef924eaf7103fbbf3cafbeb668127daff60a52228",- url: "https://github.com/colbymchenry/codegraph/releases/download/v1.0.1/codegraph-linux-x64.tar.gz"- },- "win32-arm64": {- executableName: "codegraph.cmd",- sha256: "8d57ced73b24d35f758f2ede2318e80e1d7241987f37a999e3d80edb6fddf961",- url: "https://registry.npmjs.org/@colbymchenry/codegraph-win32-arm64/-/codegraph-win32-arm64-1.0.1.tgz"- },- "win32-x64": {- executableName: "codegraph.cmd",- sha256: "52607fe73b05e741fd1087da2ceca9d3c8f565e36bf1a7070600bdbdf3931e32",- url: "https://registry.npmjs.org/@colbymchenry/codegraph-win32-x64/-/codegraph-win32-x64-1.0.1.tgz"- }- },- version: "1.0.1"-};--// ../../../../utils/src/codegraph/provision.tsvar DEFAULT_LOCK_WAIT_MS = 5000;var DEFAULT_LOCK_STALE_MS = 120000;var DEFAULT_DOWNLOAD_TIMEOUT_MS = 60000;@@ -1490,8 +1490,9 @@ function parseJsoncSafe(content) {var HARNESS_IDS = ["codex", "opencode", "omo"];var SETTING_HARNESS_SUPPORT = {"codegraph.auto_provision": HARNESS_IDS,+ "codegraph.daemon": ["codex", "opencode"],"codegraph.enabled": HARNESS_IDS,- "codegraph.excluded_roots": ["codex"],+ "codegraph.excluded_roots": ["codex", "opencode"],"codegraph.install_dir": HARNESS_IDS,"codegraph.telemetry": HARNESS_IDS,"codegraph.watch_debounce_ms": ["opencode", "omo"]@@ -1508,6 +1509,7 @@ var BUILT_IN_DEFAULTS = {var HARNESS_BLOCK_KEYS = HARNESS_IDS.map((harness) => `[${harness}]`);var CODEGRAPH_SETTING_KEYS = ["auto_provision",+ "daemon","enabled","excluded_roots","install_dir",@@ -1581,6 +1583,10 @@ function setCodegraphSetting(config, key, value) {if (typeof value === "boolean")config.auto_provision = value;return;+ case "daemon":+ if (typeof value === "boolean")+ config.daemon = value;+ return;case "enabled":if (typeof value === "boolean")config.enabled = value;@@ -2043,16 +2049,35 @@ function bufferFromChunk(chunk) {// ../../../../mcp-stdio-core/src/server.tsvar DEFAULT_IDLE_TIMEOUT_MS = 10 * 60000;+var DEFAULT_PARENT_POLL_INTERVAL_MS = 30000;var noopLog = () => {};+function isProcessAlive(pid) {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return !hasErrorCode(error, "ESRCH");+ }+}async function runJsonRpcStdioServer(config) {const log = config.log ?? noopLog;const idleTimeoutMs = config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;- const idleTimer = createIdleTimer(idleTimeoutMs, log, config.onIdleTimeout);+ let isClosed = false;+ const idleTimer = createIdleTimer(idleTimeoutMs, log, () => {+ isClosed = true;+ config.onIdleTimeout?.();+ });+ const watchdog = createParentWatchdog(config.parentWatchdog, (parentPid, pollIntervalMs) => {+ isClosed = true;+ log("parent_exit", { parent_pid: parentPid, poll_interval_ms: pollIntervalMs });+ config.onParentExit?.();+ config.input.destroy();+ });log("stdio_started", { cwd: process.cwd(), idle_timeout_ms: idleTimeoutMs });idleTimer.arm();try {for await (const message of readStdioJsonRpcMessages(config.input)) {- if (idleTimer.closed())+ if (isClosed)break;idleTimer.arm();if (message.kind === "parse_error") {@@ -2063,8 +2088,12 @@ async function runJsonRpcStdioServer(config) {if (!await handleRequest(message, config, log))break;}+ } catch (error) {+ if (!(isClosed && hasErrorCode(error, "ERR_STREAM_PREMATURE_CLOSE")))+ throw error;} finally {idleTimer.clear();+ watchdog.clear();log("stdio_stopped");}}@@ -2120,9 +2149,33 @@ function isTerminalOutputError(error) {return false;return error.code === "EPIPE" || error.code === "ERR_STREAM_DESTROYED" || error.code === "ERR_STREAM_WRITE_AFTER_END";}-function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {+function hasErrorCode(error, code) {+ return error instanceof Error && "code" in error && error.code === code;+}+function createParentWatchdog(config, onDeadParent) {+ if (config === undefined)+ return { clear: () => {} };+ const pollIntervalMs = config.pollIntervalMs ?? DEFAULT_PARENT_POLL_INTERVAL_MS;+ if (pollIntervalMs <= 0)+ return { clear: () => {} };+ const parentPid = config.parentPid ?? process.ppid;+ const probeAlive = config.probeAlive ?? isProcessAlive;+ let fired = false;+ const timer = setInterval(() => {+ if (fired || probeAlive(parentPid))+ return;+ fired = true;+ onDeadParent(parentPid, pollIntervalMs);+ }, pollIntervalMs);+ timer.unref();+ return {+ clear: () => {+ clearInterval(timer);+ }+ };+}+function createIdleTimer(idleTimeoutMs, log, onTimeout) {let timer = null;- let isClosed = false;return {arm: () => {if (timer !== null)@@ -2130,9 +2183,8 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {if (idleTimeoutMs <= 0)return;timer = setTimeout(() => {- isClosed = true;log("idle_timeout", { idle_timeout_ms: idleTimeoutMs });- onIdleTimeout?.();+ onTimeout();}, idleTimeoutMs);timer.unref();},@@ -2141,8 +2193,7 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {return;clearTimeout(timer);timer = null;- },- closed: () => isClosed+ }};}// src/serve-invocation.ts@@ -2175,6 +2226,7 @@ class CodegraphBridgeStdioError extends Error {var CODEGRAPH_NODE_DESCRIPTION = "Inspect one named symbol or file. In symbol mode, includeCode=true includes leaf-symbol source when available. Container symbols such as classes, interfaces, structs, enums, modules, and namespaces return structural outlines with member lists by design. For container source, request a specific member symbol or use file mode with symbolsOnly=false plus offset/limit.";var CODEGRAPH_NODE_INCLUDE_CODE_DESCRIPTION = "Symbol mode: include leaf-symbol source when available. Container symbols such as classes, interfaces, structs, enums, modules, and namespaces intentionally return structural outlines with members; request a specific member symbol or use file mode with symbolsOnly=false plus offset/limit for source.";var CODEGRAPH_CONTAINER_OUTLINE_GUIDANCE = "Container symbols intentionally return structural outlines with members. For source, request a specific member symbol or call codegraph_node in file mode with symbolsOnly=false plus offset/limit around the symbol location.";+var SIGKILL_ESCALATION_MS = 2000;async function runBridgedCodegraphProcess(command, args, options) {const invocation = resolveServeProcessInvocation(command, args);const child = spawn(invocation.command, invocation.args, {@@ -2200,17 +2252,24 @@ async function runBridgedCodegraphProcess(command, args, options) {resolveExit(signal === null ? 0 : 1);});});- const clientForwardingDone = forwardClientToCodegraph(options.input, childInput, pendingResponses, (mode) => {- defaultResponseMode = mode;- });- const responseForwardingDone = forwardCodegraphToClient(childOutput, options.output, pendingResponses, () => defaultResponseMode);- const bridgeDone = Promise.all([clientForwardingDone, responseForwardingDone]);- const childAndResponsesDone = Promise.all([childExit, responseForwardingDone]).then(([exitCode]) => exitCode);const destroyChildPipes = () => {childInput.destroy();childOutput.destroy();};childExit.then(destroyChildPipes, destroyChildPipes);+ let parentWatchdogFired = false;+ const parentWatchdog = createParentWatchdog(options.parentWatchdog, () => {+ parentWatchdogFired = true;+ options.input.destroy();+ destroyChildPipes();+ terminateCodegraphChild(child);+ });+ const clientForwardingDone = forwardClientToCodegraph(options.input, childInput, pendingResponses, (mode) => {+ defaultResponseMode = mode;+ }, () => parentWatchdogFired);+ const responseForwardingDone = forwardCodegraphToClient(childOutput, options.output, pendingResponses, () => defaultResponseMode, () => parentWatchdogFired);+ const bridgeDone = Promise.all([clientForwardingDone, responseForwardingDone]);+ const childAndResponsesDone = Promise.all([childExit, responseForwardingDone]).then(([exitCode]) => exitCode);try {return await Promise.race([childAndResponsesDone, bridgeDone.then(() => childExit)]);} catch (error) {@@ -2221,39 +2280,66 @@ async function runBridgedCodegraphProcess(command, args, options) {return;});throw error;+ } finally {+ parentWatchdog.clear();}}-async function forwardClientToCodegraph(input, childInput, pendingResponses, setDefaultResponseMode) {- for await (const message of readStdioJsonRpcMessages(input)) {- if (message.kind === "parse_error") {- continue;- }- const responseMode = message.responseMode;- setDefaultResponseMode(responseMode);- const key = responseModeKey(message.payload);- if (key !== null) {- pendingResponses.set(key, {- method: jsonRpcMethod(message.payload),- responseMode,- toolName: jsonRpcToolName(message.payload)- });+function terminateCodegraphChild(child) {+ if (child.exitCode !== null || child.signalCode !== null)+ return;+ child.kill("SIGTERM");+ const escalation = setTimeout(() => {+ if (child.exitCode === null && child.signalCode === null)+ child.kill("SIGKILL");+ }, SIGKILL_ESCALATION_MS);+ escalation.unref();+}+function isWatchdogTeardownError(error) {+ if (!(error instanceof Error) || !("code" in error))+ return false;+ return error.code === "ERR_STREAM_PREMATURE_CLOSE" || error.code === "ERR_STREAM_DESTROYED" || error.code === "ERR_STREAM_WRITE_AFTER_END" || error.code === "EPIPE";+}+async function forwardClientToCodegraph(input, childInput, pendingResponses, setDefaultResponseMode, tolerateWatchdogClose) {+ try {+ for await (const message of readStdioJsonRpcMessages(input)) {+ if (message.kind === "parse_error") {+ continue;+ }+ const responseMode = message.responseMode;+ setDefaultResponseMode(responseMode);+ const key = responseModeKey(message.payload);+ if (key !== null) {+ pendingResponses.set(key, {+ method: jsonRpcMethod(message.payload),+ responseMode,+ toolName: jsonRpcToolName(message.payload)+ });+ }+ await writeLine(childInput, JSON.stringify(message.payload));}- await writeLine(childInput, JSON.stringify(message.payload));+ childInput.end();+ } catch (error) {+ if (!(tolerateWatchdogClose() && isWatchdogTeardownError(error)))+ throw error;}- childInput.end();}-async function forwardCodegraphToClient(childOutput, output, pendingResponses, defaultResponseMode) {- for await (const message of readStdioJsonRpcMessages(childOutput)) {- if (message.kind === "parse_error") {- await writeStdioJsonRpcResponse(output, errorResponse(null, -32700, "Parse error", message.message), defaultResponseMode());- continue;+async function forwardCodegraphToClient(childOutput, output, pendingResponses, defaultResponseMode, tolerateWatchdogClose) {+ try {+ for await (const message of readStdioJsonRpcMessages(childOutput)) {+ if (message.kind === "parse_error") {+ await writeStdioJsonRpcResponse(output, errorResponse(null, -32700, "Parse error", message.message), defaultResponseMode());+ continue;+ }+ const key = responseModeKey(message.payload);+ const pendingResponse = key === null ? undefined : pendingResponses.get(key);+ const responseMode = pendingResponse?.responseMode ?? defaultResponseMode();+ if (key !== null)+ pendingResponses.delete(key);+ await writeStdioJsonRpcResponse(output, clarifyCodegraphResponse(message.payload, pendingResponse), responseMode);}- const key = responseModeKey(message.payload);- const pendingResponse = key === null ? undefined : pendingResponses.get(key);- const responseMode = pendingResponse?.responseMode ?? defaultResponseMode();- if (key !== null)- pendingResponses.delete(key);- await writeStdioJsonRpcResponse(output, clarifyCodegraphResponse(message.payload, pendingResponse), responseMode);+ } catch (error) {+ if (!(tolerateWatchdogClose() && isWatchdogTeardownError(error)))+ throw error;}}function responseModeKey(payload) {@@ -2385,7 +2471,8 @@ async function runUnavailableCodegraphMcpServer(options) {serverVersion: options.serverVersion},input: options.input,- output: options.output+ output: options.output,+ parentWatchdog: options.parentWatchdog ?? {}});}async function handleUnavailableCodegraphMcpRequest(input, options) {@@ -2434,7 +2521,7 @@ var CODEGRAPH_DISABLED_HINT = `CodeGraph MCP skipped: disabled by OMO SOT config`;var CODEGRAPH_EXCLUDED_HINT = `CodeGraph MCP skipped: project excluded by OMO CodeGraph policy.`;-var CODEGRAPH_VERSION = "1.0.1";+var CODEGRAPH_VERSION = CODEGRAPH_PINNED_VERSION;var PROJECT_CWD_ENV_KEYS = ["OMO_CODEGRAPH_PROJECT_CWD", SESSION_START_CWD_ENV, "PWD"];async function runCodegraphServe(options = {}) {const env = options.env ?? processEnv;@@ -2482,7 +2569,7 @@ async function runCodegraphServe(options = {}) {return runUnavailableMcp(buildCodegraphNodeSkipHint(nodeSupport), options);}const runProcess = options.runProcess ?? runBridgedCodegraphProcess;- const codegraphEnv = codegraphEnvForConfig(trustedInstallDir, homeDir, options.buildEnv);+ const codegraphEnv = codegraphEnvForConfig(trustedInstallDir, homeDir, codegraphConfig.daemon === true, options.buildEnv);const mergedEnv = buildCodegraphChildEnv({ ambientEnv: env, codegraphEnv, runtimeEnv: env });return runProcess(resolution.command, [...resolution.argsPrefix, "serve", "--mcp"], {cwd: projectCwd,@@ -2490,7 +2577,8 @@ async function runCodegraphServe(options = {}) {input: options.stdin ?? processStdin,output: options.stdout ?? processStdout,stderr: options.stderr ?? processStderr,- stdio: "pipe"+ stdio: "pipe",+ parentWatchdog: options.parentWatchdog ?? {}});}async function runUnavailableMcp(reason, options) {@@ -2499,7 +2587,8 @@ async function runUnavailableMcp(reason, options) {input: options.stdin ?? processStdin,output: options.stdout ?? processStdout,reason,- serverVersion: CODEGRAPH_VERSION+ serverVersion: CODEGRAPH_VERSION,+ parentWatchdog: options.parentWatchdog ?? {}});return 0;}@@ -2528,8 +2617,8 @@ function shouldSkipResolvedCommand(resolution, commandExists) {function looksLikePath2(command) {return command.includes("/") || command.includes("\\");}-function codegraphEnvForConfig(trustedInstallDir, homeDir, buildEnv) {- const env = { ...buildEnv?.({ homeDir }) ?? buildCodegraphEnv({ homeDir }), [CODEGRAPH_NO_DAEMON_ENV]: "1" };+function codegraphEnvForConfig(trustedInstallDir, homeDir, daemon, buildEnv) {+ const env = buildEnv?.({ daemon, homeDir }) ?? buildCodegraphEnv({ daemon, homeDir });return trustedInstallDir === undefined ? env : { ...env, CODEGRAPH_INSTALL_DIR: trustedInstallDir };}function resolveProjectCwd(env, fallback) {diff --git a/plugins/omo/components/codegraph/package.json b/plugins/omo/components/codegraph/package.jsonindex 9fd8319c..f7f3b19f 100644--- a/plugins/omo/components/codegraph/package.json+++ b/plugins/omo/components/codegraph/package.json@@ -1,6 +1,6 @@{"name": "@sisyphuslabs/codex-codegraph",- "version": "4.19.0",+ "version": "4.19.1","description": "Codex plugin MCP wrapper for CodeGraph.","type": "module","private": true,@@ -25,7 +25,7 @@"typescript": "^6.0.3"},"optionalDependencies": {- "@colbymchenry/codegraph": "1.0.1"+ "@colbymchenry/codegraph": "1.4.1"},"engines": {"node": ">=20.0.0"diff --git a/plugins/omo/components/codegraph/src/hook-types.ts b/plugins/omo/components/codegraph/src/hook-types.tsindex 5aa5a519..9e571b0b 100644--- a/plugins/omo/components/codegraph/src/hook-types.ts+++ b/plugins/omo/components/codegraph/src/hook-types.ts@@ -1,6 +1,7 @@import type { Readable } from "node:stream";import type { CodexOmoConfig as SharedCodexOmoConfig } from "../../../shared/src/config-loader.ts";+import type { CODEGRAPH_PINNED_VERSION } from "../../../../../utils/src/codegraph/manifest.ts";import type { SweepCodegraphZombiesOptions } from "../../../../../utils/src/codegraph/process-sweep.ts";import type { CodegraphProvisionResult as SharedCodegraphProvisionResult } from "../../../../../utils/src/codegraph/provision.ts";import type {@@ -58,7 +59,7 @@ export interface CodegraphSessionStartOutcome {export interface CodegraphSessionStartDeps {readonly ensureGitignored: (projectRoot: string) => boolean;- readonly ensureProvisioned: (options: { readonly installDir?: string; readonly lockDir: string; readonly version: "1.0.1" }) => Promise<CodegraphProvisionResult>;+ readonly ensureProvisioned: (options: { readonly installDir?: string; readonly lockDir: string; readonly version: typeof CODEGRAPH_PINNED_VERSION }) => Promise<CodegraphProvisionResult>;readonly prepareWorkspace: (projectRoot: string, options: { readonly homeDir: string }) => CodegraphWorkspacePreparation;readonly resolveCommand: (options?: ResolveCodegraphCommandOptions) => CodegraphCommandResolution;readonly runCommand: (@@ -76,6 +77,7 @@ export interface SessionStartHookOptions {readonly env?: Record<string, string | undefined>;readonly spawnWorker?: (invocation: WorkerSpawnInvocation) => void;readonly statusProbe?: (options: {+ readonly daemon: boolean;readonly env: Record<string, string | undefined>;readonly homeDir: string;readonly projectRoot: string;diff --git a/plugins/omo/components/codegraph/src/hook.ts b/plugins/omo/components/codegraph/src/hook.tsindex 4363d757..71582763 100644--- a/plugins/omo/components/codegraph/src/hook.ts+++ b/plugins/omo/components/codegraph/src/hook.ts@@ -87,6 +87,7 @@ export async function executeCodegraphSessionStartHook(options: SessionStartHook}const isInitialized = await (options.statusProbe ?? isCodegraphProjectInitialized)({+ daemon: config.codegraph?.daemon === true,env,homeDir,projectRoot,@@ -110,6 +111,7 @@ export async function executeCodegraphSessionStartHook(options: SessionStartHook}async function isCodegraphProjectInitialized(options: {+ readonly daemon: boolean;readonly env: Record<string, string | undefined>;readonly homeDir: string;readonly projectRoot: string;@@ -124,7 +126,7 @@ async function isCodegraphProjectInitialized(options: {const invocation = resolveCodegraphCommandInvocation(resolved.command, [...resolved.argsPrefix, "status", "--json"]);const codegraphEnv = {- ...buildCodegraphEnv({ homeDir: options.homeDir }),+ ...buildCodegraphEnv({ daemon: options.daemon, homeDir: options.homeDir }),...(options.trustedCodegraphInstallDir === undefined ? {} : { CODEGRAPH_INSTALL_DIR: options.trustedCodegraphInstallDir }),};const status = await runStatusProbe(diff --git a/plugins/omo/components/codegraph/src/mcp-bridge.ts b/plugins/omo/components/codegraph/src/mcp-bridge.tsindex 3459a565..ae8edd1e 100644--- a/plugins/omo/components/codegraph/src/mcp-bridge.ts+++ b/plugins/omo/components/codegraph/src/mcp-bridge.ts@@ -1,7 +1,8 @@-import { spawn } from "node:child_process";+import { spawn, type ChildProcess } from "node:child_process";import type { Readable, Writable } from "node:stream";import {+ createParentWatchdog,errorResponse,isPlainRecord,jsonRpcId,@@ -35,6 +36,8 @@ const CODEGRAPH_NODE_INCLUDE_CODE_DESCRIPTION =const CODEGRAPH_CONTAINER_OUTLINE_GUIDANCE ="Container symbols intentionally return structural outlines with members. For source, request a specific member symbol or call codegraph_node in file mode with symbolsOnly=false plus offset/limit around the symbol location.";+const SIGKILL_ESCALATION_MS = 2_000;+export async function runBridgedCodegraphProcess(command: string,args: readonly string[],@@ -63,22 +66,45 @@ export async function runBridgedCodegraphProcess(resolveExit(signal === null ? 0 : 1);});});- const clientForwardingDone = forwardClientToCodegraph(options.input, childInput, pendingResponses, (mode) => {- defaultResponseMode = mode;+ const destroyChildPipes = (): void => {+ childInput.destroy();+ childOutput.destroy();+ };+ void childExit.then(destroyChildPipes, destroyChildPipes);+ // Parent-liveness watchdog: when the parent dies while holding our stdio+ // open, the client stream never sees EOF, so the only settle path is to+ // drop the client input, close the child pipes, and terminate the child.+ // The bridge then resolves through the normal child-exit path, and the+ // destroyed input releases its read handle so the process can actually+ // exit (same teardown pattern as runJsonRpcStdioServer's own watchdog).+ // In daemon mode the child is the upstream lightweight proxy, so killing+ // it on parent death is correct; the detached daemon is a separate process+ // and is never touched.+ let parentWatchdogFired = false;+ const parentWatchdog = createParentWatchdog(options.parentWatchdog, () => {+ parentWatchdogFired = true;+ options.input.destroy();+ destroyChildPipes();+ terminateCodegraphChild(child);});+ const clientForwardingDone = forwardClientToCodegraph(+ options.input,+ childInput,+ pendingResponses,+ (mode) => {+ defaultResponseMode = mode;+ },+ () => parentWatchdogFired,+ );const responseForwardingDone = forwardCodegraphToClient(childOutput,options.output,pendingResponses,() => defaultResponseMode,+ () => parentWatchdogFired,);const bridgeDone = Promise.all([clientForwardingDone, responseForwardingDone]);const childAndResponsesDone = Promise.all([childExit, responseForwardingDone]).then(([exitCode]) => exitCode);- const destroyChildPipes = (): void => {- childInput.destroy();- childOutput.destroy();- };- void childExit.then(destroyChildPipes, destroyChildPipes);try {return await Promise.race([childAndResponsesDone, bridgeDone.then(() => childExit)]);} catch (error) {@@ -86,32 +112,64 @@ export async function runBridgedCodegraphProcess(if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");await childExit.catch(() => undefined);throw error;+ } finally {+ parentWatchdog.clear();}}+function terminateCodegraphChild(child: ChildProcess): void {+ if (child.exitCode !== null || child.signalCode !== null) return;+ child.kill("SIGTERM");+ const escalation = setTimeout(() => {+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");+ }, SIGKILL_ESCALATION_MS);+ escalation.unref();+}++// Stream errors raised by the watchdog's own teardown (input destroy, child+// pipe destroy) while a forwarder is parked on that stream.+function isWatchdogTeardownError(error: unknown): boolean {+ if (!(error instanceof Error) || !("code" in error)) return false;+ return (+ error.code === "ERR_STREAM_PREMATURE_CLOSE" ||+ error.code === "ERR_STREAM_DESTROYED" ||+ error.code === "ERR_STREAM_WRITE_AFTER_END" ||+ error.code === "EPIPE"+ );+}+async function forwardClientToCodegraph(input: Readable,childInput: Writable,pendingResponses: Map<string, PendingClientResponse>,setDefaultResponseMode: (mode: StdioJsonRpcResponseMode) => void,+ tolerateWatchdogClose: () => boolean,): Promise<void> {- for await (const message of readStdioJsonRpcMessages(input)) {- if (message.kind === "parse_error") {- continue;- }- const responseMode = message.responseMode;- setDefaultResponseMode(responseMode);- const key = responseModeKey(message.payload);- if (key !== null) {- pendingResponses.set(key, {- method: jsonRpcMethod(message.payload),- responseMode,- toolName: jsonRpcToolName(message.payload),- });+ try {+ for await (const message of readStdioJsonRpcMessages(input)) {+ if (message.kind === "parse_error") {+ continue;+ }+ const responseMode = message.responseMode;+ setDefaultResponseMode(responseMode);+ const key = responseModeKey(message.payload);+ if (key !== null) {+ pendingResponses.set(key, {+ method: jsonRpcMethod(message.payload),+ responseMode,+ toolName: jsonRpcToolName(message.payload),+ });+ }+ await writeLine(childInput, JSON.stringify(message.payload));}- await writeLine(childInput, JSON.stringify(message.payload));+ childInput.end();+ } catch (error) {+ // The parent watchdog destroys the client input and child pipes while+ // this forwarder is parked on a read or write; that teardown is+ // self-inflicted, so settle quietly and let the child-exit path report+ // the outcome.+ if (!(tolerateWatchdogClose() && isWatchdogTeardownError(error))) throw error;}- childInput.end();}async function forwardCodegraphToClient(@@ -119,17 +177,25 @@ async function forwardCodegraphToClient(output: Writable,pendingResponses: Map<string, PendingClientResponse>,defaultResponseMode: () => StdioJsonRpcResponseMode,+ tolerateWatchdogClose: () => boolean,): Promise<void> {- for await (const message of readStdioJsonRpcMessages(childOutput)) {- if (message.kind === "parse_error") {- await writeStdioJsonRpcResponse(output, errorResponse(null, -32700, "Parse error", message.message), defaultResponseMode());- continue;+ try {+ for await (const message of readStdioJsonRpcMessages(childOutput)) {+ if (message.kind === "parse_error") {+ await writeStdioJsonRpcResponse(output, errorResponse(null, -32700, "Parse error", message.message), defaultResponseMode());+ continue;+ }+ const key = responseModeKey(message.payload);+ const pendingResponse = key === null ? undefined : pendingResponses.get(key);+ const responseMode = pendingResponse?.responseMode ?? defaultResponseMode();+ if (key !== null) pendingResponses.delete(key);+ await writeStdioJsonRpcResponse(output, clarifyCodegraphResponse(message.payload, pendingResponse), responseMode);}- const key = responseModeKey(message.payload);- const pendingResponse = key === null ? undefined : pendingResponses.get(key);- const responseMode = pendingResponse?.responseMode ?? defaultResponseMode();- if (key !== null) pendingResponses.delete(key);- await writeStdioJsonRpcResponse(output, clarifyCodegraphResponse(message.payload, pendingResponse), responseMode);+ } catch (error) {+ // The parent watchdog destroys the child pipes while this forwarder is+ // parked on a read; that close is self-inflicted, so settle quietly and+ // let the child-exit path report the outcome.+ if (!(tolerateWatchdogClose() && isWatchdogTeardownError(error))) throw error;}}diff --git a/plugins/omo/components/codegraph/src/mcp-unavailable.ts b/plugins/omo/components/codegraph/src/mcp-unavailable.tsindex b80fe091..41842898 100644--- a/plugins/omo/components/codegraph/src/mcp-unavailable.ts+++ b/plugins/omo/components/codegraph/src/mcp-unavailable.ts@@ -7,6 +7,7 @@ import {runJsonRpcStdioServer,successResponse,type JsonRpcResponse,+ type ParentWatchdogConfig,} from "../../../../../mcp-stdio-core/src/index.ts";export interface UnavailableCodegraphMcpOptions {@@ -14,6 +15,9 @@ export interface UnavailableCodegraphMcpOptions {readonly output: Writable;readonly reason: string;readonly serverVersion: string;+ // Test seam: production callers leave this unset so the watchdog uses its+ // defaults (parentPid = process.ppid, 30s poll).+ readonly parentWatchdog?: ParentWatchdogConfig;}interface UnavailableCodegraphMcpHandlerOptions {@@ -32,6 +36,7 @@ export async function runUnavailableCodegraphMcpServer(},input: options.input,output: options.output,+ parentWatchdog: options.parentWatchdog ?? {},});}diff --git a/plugins/omo/components/codegraph/src/serve.ts b/plugins/omo/components/codegraph/src/serve.tsindex c4633d80..f3cb3627 100644--- a/plugins/omo/components/codegraph/src/serve.ts+++ b/plugins/omo/components/codegraph/src/serve.ts@@ -13,10 +13,11 @@ import type { Readable, Writable } from "node:stream";import { fileURLToPath } from "node:url";import {- CODEGRAPH_NO_DAEMON_ENV,buildCodegraphChildEnv,buildCodegraphEnv,} from "../../../../../utils/src/codegraph/env.ts";+import type { ParentWatchdogConfig } from "../../../../../mcp-stdio-core/src/index.ts";+import { CODEGRAPH_PINNED_VERSION } from "../../../../../utils/src/codegraph/manifest.ts";import {buildCodegraphNodeSkipHint,evaluateCodegraphNodeSupport,@@ -48,6 +49,7 @@ export interface CodegraphServeProcessOptions {readonly output: Writable;readonly stderr: CodegraphServeStderr;readonly stdio: ServeStdio;+ readonly parentWatchdog?: ParentWatchdogConfig;}export type CodegraphServeProcessRunner = (@@ -64,7 +66,7 @@ export interface CodegraphServeStderr {}export interface RunCodegraphServeOptions {- readonly buildEnv?: (options: { readonly homeDir: string }) => Record<string, string>;+ readonly buildEnv?: (options: { readonly daemon: boolean; readonly homeDir: string }) => Record<string, string>;readonly commandExists?: (filePath: string) => boolean;readonly config?: CodexOmoConfig;readonly cwd?: string;@@ -77,6 +79,10 @@ export interface RunCodegraphServeOptions {readonly runProcess?: CodegraphServeProcessRunner;readonly stderr?: CodegraphServeStderr;readonly ensureProvisioned?: CodegraphProvisioner;+ // Test seam: production callers leave this unset so the bridge and the+ // unavailable facade use the watchdog defaults (parentPid = process.ppid,+ // 30s poll).+ readonly parentWatchdog?: ParentWatchdogConfig;}const CODEGRAPH_SKIP_HINT =@@ -84,7 +90,7 @@ const CODEGRAPH_SKIP_HINT =const CODEGRAPH_DISABLED_HINT ="CodeGraph MCP skipped: disabled by OMO SOT config. Set [codex].codegraph.enabled=true to enable it.\n";const CODEGRAPH_EXCLUDED_HINT = "CodeGraph MCP skipped: project excluded by OMO CodeGraph policy.\n";-const CODEGRAPH_VERSION = "1.0.1";+const CODEGRAPH_VERSION = CODEGRAPH_PINNED_VERSION;const PROJECT_CWD_ENV_KEYS = ["OMO_CODEGRAPH_PROJECT_CWD", SESSION_START_CWD_ENV, "PWD"] as const;export async function runCodegraphServe(options: RunCodegraphServeOptions = {}): Promise<number> {@@ -136,7 +142,7 @@ export async function runCodegraphServe(options: RunCodegraphServeOptions = {}):}const runProcess = options.runProcess ?? runBridgedCodegraphProcess;- const codegraphEnv = codegraphEnvForConfig(trustedInstallDir, homeDir, options.buildEnv);+ const codegraphEnv = codegraphEnvForConfig(trustedInstallDir, homeDir, codegraphConfig.daemon === true, options.buildEnv);const mergedEnv = buildCodegraphChildEnv({ ambientEnv: env, codegraphEnv, runtimeEnv: env });return runProcess(resolution.command, [...resolution.argsPrefix, "serve", "--mcp"], {cwd: projectCwd,@@ -145,6 +151,7 @@ export async function runCodegraphServe(options: RunCodegraphServeOptions = {}):output: options.stdout ?? processStdout,stderr: options.stderr ?? processStderr,stdio: "pipe",+ parentWatchdog: options.parentWatchdog ?? {},});}@@ -155,6 +162,7 @@ async function runUnavailableMcp(reason: string, options: RunCodegraphServeOptiooutput: options.stdout ?? processStdout,reason,serverVersion: CODEGRAPH_VERSION,+ parentWatchdog: options.parentWatchdog ?? {},});return 0;}@@ -195,9 +203,10 @@ function looksLikePath(command: string): boolean {function codegraphEnvForConfig(trustedInstallDir: string | undefined,homeDir: string,- buildEnv: ((options: { readonly homeDir: string }) => Record<string, string>) | undefined,+ daemon: boolean,+ buildEnv: ((options: { readonly daemon: boolean; readonly homeDir: string }) => Record<string, string>) | undefined,): Record<string, string> {- const env = { ...(buildEnv?.({ homeDir }) ?? buildCodegraphEnv({ homeDir })), [CODEGRAPH_NO_DAEMON_ENV]: "1" };+ const env = buildEnv?.({ daemon, homeDir }) ?? buildCodegraphEnv({ daemon, homeDir });return trustedInstallDir === undefined ? env : { ...env, CODEGRAPH_INSTALL_DIR: trustedInstallDir };}diff --git a/plugins/omo/components/codegraph/src/session-start-worker.ts b/plugins/omo/components/codegraph/src/session-start-worker.tsindex 07a08f48..2bdef6fe 100644--- a/plugins/omo/components/codegraph/src/session-start-worker.ts+++ b/plugins/omo/components/codegraph/src/session-start-worker.ts@@ -6,6 +6,7 @@ import { cwd as processCwd, env as processEnv, execPath as processExecPath, stdeimport { getCodexOmoConfig } from "../../../shared/src/config-loader.ts";import { buildCodegraphChildEnv, buildCodegraphEnv } from "../../../../../utils/src/codegraph/env.ts";+import { CODEGRAPH_PINNED_VERSION } from "../../../../../utils/src/codegraph/manifest.ts";import { evaluateCodegraphNodeSupport, type CodegraphNodeSupport } from "../../../../../utils/src/codegraph/node-support.ts";import { ensureCodegraphProvisioned } from "../../../../../utils/src/codegraph/provision.ts";import {@@ -25,7 +26,7 @@ import type {export const SESSION_START_CWD_ENV = "OMO_CODEGRAPH_SESSION_START_CWD";-const CODEGRAPH_VERSION = "1.0.1";+const CODEGRAPH_VERSION = CODEGRAPH_PINNED_VERSION;const COMMAND_TIMEOUT_MS = 60_000;const WINDOWS_CMD_EXTENSIONS = new Set([".bat", ".cmd"]);const WINDOWS_NODE_SCRIPT_EXTENSIONS = new Set([".cjs", ".js", ".mjs"]);@@ -127,7 +128,10 @@ async function resolveOrProvisionCommand(}function codegraphEnvForConfig(config: CodegraphBootstrapConfig, homeDir: string): Record<string, string> {- const env = buildCodegraphEnv({ homeDir });+ // The detached indexing worker must NEVER engage the upstream daemon, even+ // when the user opted into daemon mode for interactive MCP sessions: a+ // daemon-backed init/sync would outlive and race the worker's lifecycle.+ const env = buildCodegraphEnv({ daemon: false, homeDir });return config.trustedCodegraphInstallDir === undefined ? env : { ...env, CODEGRAPH_INSTALL_DIR: config.trustedCodegraphInstallDir };}diff --git a/plugins/omo/components/codegraph/src/sweep-cli.ts b/plugins/omo/components/codegraph/src/sweep-cli.tsindex bd2be832..3a999d35 100644--- a/plugins/omo/components/codegraph/src/sweep-cli.ts+++ b/plugins/omo/components/codegraph/src/sweep-cli.ts@@ -61,6 +61,7 @@ function writeSweepReport(stdout: HookStdout, result: SweepCodegraphZombiesResulfailed: result.failed,killed: result.killed.map(formatProcess),ownedRoots: result.ownedRoots,+ spared: result.spared.map(formatProcess),stampFile: result.stampFile,})}\n`);}diff --git a/plugins/omo/components/codegraph/test/hook-store-upgrade.test.ts b/plugins/omo/components/codegraph/test/hook-store-upgrade.test.tsnew file mode 100644index 00000000..a69fe5d9--- /dev/null+++ b/plugins/omo/components/codegraph/test/hook-store-upgrade.test.ts@@ -0,0 +1,148 @@+import { describe, expect, it } from "bun:test";+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { Readable } from "node:stream";+import { fileURLToPath } from "node:url";++import { executeCodegraphSessionStartHook, type WorkerSpawnInvocation } from "../src/hook.ts";++const pluginRoot = resolve(fileURLToPath(new URL("../../..", import.meta.url)));++// Observed verbatim from a REAL codegraph 1.4.1 binary running `status --json` (exit 0)+// against a project store built by a REAL codegraph 1.0.1 binary+// (see .omo/evidence/codegraph-daemon-process-hygiene/task-2-store-upgrade.txt).+const MIGRATED_1_0_1_STORE_STATUS_JSON = JSON.stringify({+ initialized: true,+ version: "1.4.1",+ projectPath: "/private/tmp/cg-task2/fixture",+ indexPath: "/private/tmp/cg-task2/fixture/.codegraph",+ lastIndexed: "2026-07-21T04:28:09.593Z",+ fileCount: 2,+ nodeCount: 5,+ edgeCount: 4,+ dbSizeBytes: 159744,+ backend: "node-sqlite",+ journalMode: "wal",+ nodesByKind: { file: 2, function: 3 },+ languages: ["typescript"],+ pendingChanges: { added: 0, modified: 0, removed: 0 },+ worktreeMismatch: null,+ index: {+ builtWithVersion: "1.0.1",+ builtWithExtractionVersion: 24,+ currentExtractionVersion: 24,+ reindexRecommended: false,+ state: null,+ pendingRefs: 0,+ },+});++function createAllowedWorkspace(prefix: string): string {+ return mkdtempSync(join(pluginRoot, `.tmp-${prefix}-`));+}++// On win32 execFile cannot run a #!/bin/sh script, so emit a codegraph.cmd batch file instead;+// resolveCodegraphCommandInvocation wraps .cmd in `cmd.exe /d /s /c`, exactly like the real codegraph.cmd.+function createFakeCodegraphBin(scripts: { readonly posix: string; readonly win32: string }): { readonly binPath: string; readonly dir: string } {+ const dir = mkdtempSync(join(tmpdir(), "omo-codegraph-fake-bin-"));+ if (process.platform === "win32") {+ const binPath = join(dir, "codegraph.cmd");+ writeFileSync(binPath, scripts.win32);+ return { binPath, dir };+ }+ const binPath = join(dir, "codegraph");+ writeFileSync(binPath, scripts.posix, { mode: 0o755 });+ chmodSync(binPath, 0o755);+ return { binPath, dir };+}++// Keep the probe hermetic on POSIX but viable on win32: resolveCodegraphCommandInvocation wraps+// the fake .cmd in `cmd.exe /d /s /c`, and Windows can only resolve cmd.exe when the child env+// carries the real system PATH (System32) plus SystemRoot (both whitelisted in SAFE_AMBIENT_ENV_KEYS).+// A POSIX-only PATH makes the probe spawn fail, so the hook reports not-initialized and spawns.+function probeEnv(homeDir: string, binPath: string): Record<string, string> {+ if (process.platform === "win32") {+ const env: Record<string, string> = {+ HOME: homeDir,+ OMO_CODEGRAPH_BIN: binPath,+ };+ if (process.env["PATH"] !== undefined) env["PATH"] = process.env["PATH"];+ if (process.env["SystemRoot"] !== undefined) env["SystemRoot"] = process.env["SystemRoot"];+ return env;+ }+ return { HOME: homeDir, OMO_CODEGRAPH_BIN: binPath, PATH: "/usr/bin:/bin" };+}++describe("CodeGraph SessionStart hook with a 1.0.1-era project store under the 1.4.1 binary", () => {+ it("#given a real 1.4.1 status payload for a migrated 1.0.1 store #when SessionStart probes via the default probe #then it stays silent without spawning a re-init worker", async () => {+ // given+ const stdout: string[] = [];+ const spawned: WorkerSpawnInvocation[] = [];+ const homeDir = mkdtempSync(join(tmpdir(), "omo-codegraph-upgrade-home-"));+ // The payload is a single JSON line with no cmd metacharacters (% ^ & < > |), so a plain echo is safe.+ const fake = createFakeCodegraphBin({+ posix: `#!/bin/sh\nprintf '%s\\n' '${MIGRATED_1_0_1_STORE_STATUS_JSON}'\n`,+ win32: `@echo off\r\n@echo ${MIGRATED_1_0_1_STORE_STATUS_JSON}\r\n`,+ });+ const workspace = createAllowedWorkspace("codegraph-upgrade-workspace");+ mkdirSync(join(workspace, ".codegraph"), { recursive: true });++ try {+ // when+ const result = await executeCodegraphSessionStartHook({+ config: { codegraph: { enabled: true }, sources: [], warnings: [] },+ cwd: workspace,+ env: probeEnv(homeDir, fake.binPath),+ stdin: Readable.from(["{}"]),+ stdout: { write: (chunk) => stdout.push(chunk) },+ spawnWorker: (invocation) => spawned.push(invocation),+ });++ // then+ expect(result).toEqual({ action: "skipped-initialized", exitCode: 0 });+ expect(spawned).toEqual([]);+ expect(stdout.join("")).toBe("");+ } finally {+ rmSync(homeDir, { recursive: true, force: true });+ rmSync(fake.dir, { recursive: true, force: true });+ rmSync(workspace, { recursive: true, force: true, maxRetries: 10, retryDelay: 500 });+ }+ });++ it("#given the status probe hangs past its 2s timeout #when SessionStart fires #then it exits zero promptly and spawns at most one bounded worker", async () => {+ // given+ const stdout: string[] = [];+ const spawned: WorkerSpawnInvocation[] = [];+ const homeDir = mkdtempSync(join(tmpdir(), "omo-codegraph-slow-home-"));+ const fake = createFakeCodegraphBin({+ posix: "#!/bin/sh\nsleep 30\n",+ win32: "@echo off\r\nset /p _probe_hang=\r\n",+ });+ const workspace = createAllowedWorkspace("codegraph-slow-probe-workspace");++ try {+ // when+ const startedAt = Date.now();+ const result = await executeCodegraphSessionStartHook({+ config: { codegraph: { enabled: true }, sources: [], warnings: [] },+ cwd: workspace,+ env: probeEnv(homeDir, fake.binPath),+ stdin: Readable.from(["{}"]),+ stdout: { write: (chunk) => stdout.push(chunk) },+ spawnWorker: (invocation) => spawned.push(invocation),+ });+ const elapsedMs = Date.now() - startedAt;++ // then+ expect(result.exitCode).toBe(0);+ expect(result.action).toBe("spawned");+ expect(spawned).toHaveLength(1);+ expect(elapsedMs).toBeLessThan(15_000);+ } finally {+ rmSync(homeDir, { recursive: true, force: true });+ rmSync(fake.dir, { recursive: true, force: true });+ rmSync(workspace, { recursive: true, force: true, maxRetries: 10, retryDelay: 500 });+ }+ });+});diff --git a/plugins/omo/components/codegraph/test/mcp-bridge-fixtures.ts b/plugins/omo/components/codegraph/test/mcp-bridge-fixtures.tsindex 35177701..505e3da7 100644--- a/plugins/omo/components/codegraph/test/mcp-bridge-fixtures.ts+++ b/plugins/omo/components/codegraph/test/mcp-bridge-fixtures.ts@@ -1,5 +1,34 @@import { chmodSync, writeFileSync } from "node:fs";+export const CODEGRAPH_141_DEFAULT_TOOLS: readonly Record<string, unknown>[] = [+ {+ name: "codegraph_explore",+ description:+ "PRIMARY TOOL — call FIRST for almost any question OR before an edit: how does X work, architecture, a bug, where/what is X, surveying an area, or the symbols you are about to change. Returns the verbatim source of the relevant symbols grouped by file in ONE capped call (Read-equivalent — treat the shown source as already Read; do NOT re-open those files), plus the call path among them. Query can be a natural-language question OR a bag of symbol/file names. Usually the ONLY call you need — more accurate context, in far fewer tokens and round-trips than a search/Read/Grep loop.",+ inputSchema: {+ type: "object",+ properties: {+ query: {+ type: "string",+ description:+ 'Symbol names, file names, or short code terms to explore (e.g., "AuthService loginUser session-manager", "GraphTraverser BFS impact traversal.ts"). For a flow question, name the symbols spanning the flow (e.g. "mutateElement renderScene"). A natural-language question works too — no prior codegraph_search needed.',+ },+ maxFiles: {+ type: "number",+ description: "Maximum number of files to include source code from (default: 12)",+ default: 12,+ },+ projectPath: {+ type: "string",+ description:+ "Absolute path to the project to query (or any directory inside it) — codegraph uses the nearest .codegraph/ index at or above that path. Omit to use this session's default project. Pass it to query a second codebase, or when the server root has no index of its own (e.g. a monorepo where only sub-projects are indexed, so there is no default project).",+ },+ },+ required: ["query"],+ },+ },+];+export function writeFakeNewlineCodegraph(filePath: string): void {writeFileSync(filePath,@@ -12,10 +41,10 @@ export function writeFakeNewlineCodegraph(filePath: string): void {"rl.on('line', (line) => {"," const request = JSON.parse(line);"," if (request.method === 'initialize') {",- " process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result: { capabilities: { tools: { listChanged: false } }, protocolVersion: request.params.protocolVersion, serverInfo: { name: 'codegraph', version: '1.0.1' } } }) + '\\n');",+ " process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result: { capabilities: { tools: { listChanged: false } }, protocolVersion: request.params.protocolVersion, serverInfo: { name: 'codegraph', version: '1.4.1' } } }) + '\\n');"," }"," if (request.method === 'tools/list') {",- " process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result: { tools: [{ name: 'codegraph_search' }, { name: 'codegraph_node' }, { name: 'codegraph_explore' }, { name: 'codegraph_callers' }] } }) + '\\n');",+ ` process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result: { tools: ${JSON.stringify(CODEGRAPH_141_DEFAULT_TOOLS)} } }) + '\\n');`," }","});",].join("\n"),diff --git a/plugins/omo/components/codegraph/test/package-runtime.test.ts b/plugins/omo/components/codegraph/test/package-runtime.test.tsindex cdce949f..51f0bba6 100644--- a/plugins/omo/components/codegraph/test/package-runtime.test.ts+++ b/plugins/omo/components/codegraph/test/package-runtime.test.ts@@ -43,7 +43,7 @@ describe("CodeGraph component runtime package metadata", () => {const files = packageJson.files ?? [];// then- expect(optionalDependencies["@colbymchenry/codegraph"]).toBe("1.0.1");+ expect(optionalDependencies["@colbymchenry/codegraph"]).toBe("1.4.1");expect(files).toContain("LICENSE");expect(files).toContain("NODE-RUNTIME-LICENSES.md");expect(files).toContain("NOTICE");diff --git a/plugins/omo/components/codegraph/test/serve-mcp-bridge-lifecycle.test.ts b/plugins/omo/components/codegraph/test/serve-mcp-bridge-lifecycle.test.tsindex 61b157df..9e33041a 100644--- a/plugins/omo/components/codegraph/test/serve-mcp-bridge-lifecycle.test.ts+++ b/plugins/omo/components/codegraph/test/serve-mcp-bridge-lifecycle.test.ts@@ -1,13 +1,15 @@import { describe, expect, it } from "bun:test";-import { mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync } from "node:fs";import { join } from "node:path";import { PassThrough, Writable } from "node:stream";import { fileURLToPath } from "node:url";+import { isProcessAlive } from "../../../../../mcp-stdio-core/src/index.ts";import { runCodegraphServe } from "../src/serve.ts";import {frameMcpRequest,writeFakeExitingCodegraph,+ writeFakeHeldOpenCodegraph,} from "./mcp-bridge-fixtures.ts";const componentRoot = realpathSync(@@ -66,4 +68,66 @@ describe("runCodegraphServe MCP bridge lifecycle", () => {rmSync(tempRoot, { recursive: true, force: true });}});++ it("#given a held-open Codegraph child and a dead parent #when the bridge watchdog polls #then the child is terminated and the bridge settles through the child-exit path", async () => {+ // given+ const tempRoot = mkdtempSync(+ join(componentRoot, ".tmp-codegraph-orphan-"),+ );+ const projectRoot = join(tempRoot, "project");+ const fakeCodegraph = join(tempRoot, "codegraph-held-open.cjs");+ const childPidFile = join(tempRoot, "child.pid");+ // Client stdio is held open and never sees EOF, so the parent-liveness+ // watchdog is the only settle path. The probe reports the parent alive+ // until the child has started, making the poll fire deterministically.+ const input = new PassThrough();+ const output = new PassThrough();+ output.resume();+ let childPid: number | undefined;++ try {+ mkdirSync(projectRoot, { recursive: true });+ writeFakeHeldOpenCodegraph(fakeCodegraph);+ const run = runCodegraphServe({+ cwd: tempRoot,+ env: {+ CODEGRAPH_ALLOW_UNSAFE_NODE: "1",+ CODEGRAPH_FAKE_LOG: childPidFile,+ OMO_CODEGRAPH_BIN: fakeCodegraph,+ OMO_CODEGRAPH_PROJECT_CWD: projectRoot,+ PATH: process.env["PATH"],+ },+ nodeVersion: "22.14.0",+ buildEnv: () => ({}),+ resolve: () => ({+ argsPrefix: [],+ command: fakeCodegraph,+ exists: true,+ source: "env",+ }),+ stderr: { write: () => undefined },+ stdin: input,+ stdout: output,+ parentWatchdog: {+ pollIntervalMs: 10,+ probeAlive: () => !existsSync(childPidFile),+ },+ });++ // when+ const exitCode = await run;++ // then+ expect(exitCode).not.toBe(0);+ childPid = Number(readFileSync(childPidFile, "utf8"));+ expect(isProcessAlive(childPid)).toBe(false);+ } finally {+ if (childPid !== undefined && isProcessAlive(childPid)) {+ process.kill(childPid, "SIGKILL");+ }+ input.destroy();+ output.destroy();+ rmSync(tempRoot, { recursive: true, force: true });+ }+ });});diff --git a/plugins/omo/components/codegraph/test/serve-mcp-bridge.test.ts b/plugins/omo/components/codegraph/test/serve-mcp-bridge.test.tsindex 14f804c0..4d50a825 100644--- a/plugins/omo/components/codegraph/test/serve-mcp-bridge.test.ts+++ b/plugins/omo/components/codegraph/test/serve-mcp-bridge.test.ts@@ -7,6 +7,7 @@ import { fileURLToPath } from "node:url";import { runCodegraphServe } from "../src/serve.ts";import {arrayProperty,+ CODEGRAPH_141_DEFAULT_TOOLS,findTool,frameMcpRequest,parseMcpBodies,@@ -86,19 +87,14 @@ describe("runCodegraphServe MCP protocol bridge", () => {result: {capabilities: { tools: { listChanged: false } },protocolVersion: "2025-06-18",- serverInfo: { name: "codegraph", version: "1.0.1" },+ serverInfo: { name: "codegraph", version: "1.4.1" },},},{id: 2,jsonrpc: "2.0",result: {- tools: [- { name: "codegraph_search" },- { name: "codegraph_node" },- { name: "codegraph_explore" },- { name: "codegraph_callers" },- ],+ tools: CODEGRAPH_141_DEFAULT_TOOLS,},},]);diff --git a/plugins/omo/components/codegraph/test/serve-mcp-facade.test.ts b/plugins/omo/components/codegraph/test/serve-mcp-facade.test.tsindex cd95b106..2b0c71d1 100644--- a/plugins/omo/components/codegraph/test/serve-mcp-facade.test.ts+++ b/plugins/omo/components/codegraph/test/serve-mcp-facade.test.ts@@ -47,7 +47,7 @@ describe("runCodegraphServe MCP unavailable facade", () => {result: {capabilities: { tools: { listChanged: false } },protocolVersion: "2025-06-18",- serverInfo: { name: "codegraph", version: "1.0.1" },+ serverInfo: { name: "codegraph", version: "1.4.1" },},});});diff --git a/plugins/omo/components/codegraph/test/serve-provision.test.ts b/plugins/omo/components/codegraph/test/serve-provision.test.tsindex 29466f6c..a5f825a5 100644--- a/plugins/omo/components/codegraph/test/serve-provision.test.ts+++ b/plugins/omo/components/codegraph/test/serve-provision.test.ts@@ -4,7 +4,7 @@ import { join } from "node:path";import { runCodegraphServe } from "../src/serve.ts";describe("runCodegraphServe provisioning", () => {- it("#given CodeGraph is unresolved #when serving MCP #then provisions CodeGraph before spawning", async () => {+ it("#given CodeGraph is unresolved and daemon is off by default #when serving MCP #then provisions CodeGraph before spawning with CODEGRAPH_NO_DAEMON=1", async () => {// givenconst binPath = join("/tmp/home/.omo/codegraph", "bin", "codegraph");const calls: Array<{@@ -20,7 +20,6 @@ describe("runCodegraphServe provisioning", () => {env: { PATH: "/bin" },homeDir: "/tmp/home",nodeVersion: "22.14.0",- buildEnv: () => ({}),resolve: () => ({ argsPrefix: [], command: "codegraph", exists: false, source: "path" }),ensureProvisioned: (options) =>Promise.resolve({@@ -41,8 +40,63 @@ describe("runCodegraphServe provisioning", () => {{args: ["serve", "--mcp"],command: binPath,- env: { CODEGRAPH_NO_DAEMON: "1", PATH: "/bin" },+ env: {+ CODEGRAPH_INSTALL_DIR: join("/tmp/home", ".omo", "codegraph"),+ CODEGRAPH_NO_DAEMON: "1",+ CODEGRAPH_NO_DOWNLOAD: "1",+ CODEGRAPH_TELEMETRY: "0",+ DO_NOT_TRACK: "1",+ PATH: "/bin",+ },},]);});++ it("#given CodeGraph is unresolved and codegraph.daemon=true #when serving MCP #then provisions CodeGraph and omits CODEGRAPH_NO_DAEMON so the daemon may run", async () => {+ // given+ const binPath = join("/tmp/home/.omo/codegraph", "bin", "codegraph");+ const calls: Array<{+ readonly args: readonly string[];+ readonly command: string;+ readonly env: Record<string, string | undefined>;+ }> = [];+ const stderr: string[] = [];++ // when+ const exitCode = await runCodegraphServe({+ config: { codegraph: { daemon: true, enabled: true }, sources: [], warnings: [] },+ env: { PATH: "/bin" },+ homeDir: "/tmp/home",+ nodeVersion: "22.14.0",+ resolve: () => ({ argsPrefix: [], command: "codegraph", exists: false, source: "path" }),+ ensureProvisioned: (options) =>+ Promise.resolve({+ binPath: join(options.installDir ?? "/tmp/home/.omo/codegraph", "bin", "codegraph"),+ provisioned: true,+ }),+ runProcess: (command, args, options) => {+ calls.push({ args, command, env: options.env });+ return Promise.resolve(0);+ },+ stderr: { write: (chunk: string) => stderr.push(chunk) },+ });++ // then+ expect(exitCode).toBe(0);+ expect(stderr).toEqual([]);+ expect(calls).toEqual([+ {+ args: ["serve", "--mcp"],+ command: binPath,+ env: {+ CODEGRAPH_INSTALL_DIR: join("/tmp/home", ".omo", "codegraph"),+ CODEGRAPH_NO_DOWNLOAD: "1",+ CODEGRAPH_TELEMETRY: "0",+ DO_NOT_TRACK: "1",+ PATH: "/bin",+ },+ },+ ]);+ expect(calls[0]?.env["CODEGRAPH_NO_DAEMON"]).toBeUndefined();+ });});diff --git a/plugins/omo/components/codegraph/test/serve-unavailable.test.ts b/plugins/omo/components/codegraph/test/serve-unavailable.test.tsindex 5fb2cd40..b8c93a78 100644--- a/plugins/omo/components/codegraph/test/serve-unavailable.test.ts+++ b/plugins/omo/components/codegraph/test/serve-unavailable.test.ts@@ -122,6 +122,47 @@ describe("runCodegraphServe unavailable CodeGraph paths", () => {rmSync(workspace, { recursive: true, force: true });}});++ it("#given the unavailable facade with held-open stdio and a dead parent #when the watchdog polls #then the placeholder server settles without waiting for stdin EOF", async () => {+ // given+ // win32: the real-timer watchdog + PassThrough.destroy() teardown race leaves+ // the read loop's async iterator pending on Windows, so this held-open-stdin+ // case cannot settle under bun:test (which has no fake timers). The watchdog+ // settle path IS covered deterministically by mcp-stdio-core's fake-timer test+ // (passes on win32) and by real-process QA (task-13-*); production settles via+ // stdin EOF, exercised by the other tests in this file that run on win32.+ if (process.platform === "win32") return;+ // Client stdio is held open and never sees EOF, so the parent-liveness+ // watchdog is the only settle path for the placeholder server.+ const stdin = new PassThrough();+ const stdout = new PassThrough();+ stdout.resume();+ const stderr: string[] = [];++ try {+ // when+ const exitCode = await runCodegraphServe({+ config: { codegraph: { enabled: false }, sources: [], warnings: [] },+ env: {},+ stdin,+ stdout,+ stderr: { write: (chunk: string) => stderr.push(chunk) },+ parentWatchdog: { pollIntervalMs: 10, probeAlive: () => false },+ });++ // then+ expect(exitCode).toBe(0);+ expect(stderr).toEqual([+ "CodeGraph MCP skipped: disabled by OMO SOT config. Set [codex].codegraph.enabled=true to enable it.\n",+ ]);+ } finally {+ // The held-open streams are never ended by the test; destroy them so the+ // bun test runner's event loop can drain and exit (an undestroyed+ // PassThrough keeps the process alive on win32 and hangs the suite).+ stdin.destroy();+ stdout.destroy();+ }+ });});function closedMcpStdio(): { readonly stdin: PassThrough; readonly stdout: PassThrough } {diff --git a/plugins/omo/components/codegraph/test/serve.test.ts b/plugins/omo/components/codegraph/test/serve.test.tsindex d977086c..1cd324d4 100644--- a/plugins/omo/components/codegraph/test/serve.test.ts+++ b/plugins/omo/components/codegraph/test/serve.test.ts@@ -27,12 +27,6 @@ describe("runCodegraphServe", () => {env: { CUSTOM: "drop", HOME: "/tmp/home", OPENAI_API_KEY: "sk-test-secret" },nodeVersion: "22.14.0",homeDir: "/tmp/home",- buildEnv: ({ homeDir }) => ({- CODEGRAPH_INSTALL_DIR: `${homeDir}/.omo/codegraph`,- CODEGRAPH_NO_DOWNLOAD: "1",- CODEGRAPH_TELEMETRY: "0",- DO_NOT_TRACK: "1",- }),resolve: () => ({ argsPrefix: ["shim.js"], command: "node", exists: true, source: "bundled" }),runProcess: (command: string,@@ -53,7 +47,7 @@ describe("runCodegraphServe", () => {command: "node",cwd: resolve(runCwd),env: {- CODEGRAPH_INSTALL_DIR: "/tmp/home/.omo/codegraph",+ CODEGRAPH_INSTALL_DIR: join("/tmp/home", ".omo", "codegraph"),CODEGRAPH_NO_DAEMON: "1",CODEGRAPH_NO_DOWNLOAD: "1",CODEGRAPH_TELEMETRY: "0",@@ -67,6 +61,58 @@ describe("runCodegraphServe", () => {expect(calls[0]?.env["OPENAI_API_KEY"]).toBeUndefined();});+ it("#given codegraph.daemon=true #when serving MCP #then CODEGRAPH_NO_DAEMON is omitted so the daemon may run", async () => {+ // given+ const runCwd = componentRoot;+ const calls: Array<{+ readonly args: readonly string[];+ readonly command: string;+ readonly cwd: string;+ readonly env: Record<string, string | undefined>;+ readonly stdio: "pipe";+ }> = [];++ // when+ const exitCode = await runCodegraphServe({+ config: { codegraph: { daemon: true, enabled: true }, sources: [], warnings: [] },+ cwd: runCwd,+ env: { CUSTOM: "drop", HOME: "/tmp/home", OPENAI_API_KEY: "sk-test-secret" },+ nodeVersion: "22.14.0",+ homeDir: "/tmp/home",+ resolve: () => ({ argsPrefix: ["shim.js"], command: "node", exists: true, source: "bundled" }),+ runProcess: (+ command: string,+ args: readonly string[],+ options: { readonly cwd: string; readonly env: Record<string, string | undefined>; readonly stdio: "pipe" },+ ) => {+ calls.push({ args, command, cwd: options.cwd, env: options.env, stdio: options.stdio });+ return Promise.resolve(7);+ },+ stderr: { write: () => undefined },+ });++ // then+ expect(exitCode).toBe(7);+ expect(calls).toEqual([+ {+ args: ["shim.js", "serve", "--mcp"],+ command: "node",+ cwd: resolve(runCwd),+ env: {+ CODEGRAPH_INSTALL_DIR: join("/tmp/home", ".omo", "codegraph"),+ CODEGRAPH_NO_DOWNLOAD: "1",+ CODEGRAPH_TELEMETRY: "0",+ DO_NOT_TRACK: "1",+ HOME: "/tmp/home",+ },+ stdio: "pipe",+ },+ ]);+ expect(calls[0]?.env["CODEGRAPH_NO_DAEMON"]).toBeUndefined();+ expect(calls[0]?.env["CUSTOM"]).toBeUndefined();+ expect(calls[0]?.env["OPENAI_API_KEY"]).toBeUndefined();+ });+it("#given an unsupported local Node but the unsafe override is set #when serving MCP #then it still spawns codegraph", async () => {// givenconst spawned: string[] = [];@@ -136,7 +182,7 @@ describe("runCodegraphServe", () => {expect(spawned).toEqual([{ args: ["serve", "--mcp"], command: commandPath }]);});- it("#given Windows Codex SOT install_dir has codegraph.cmd #when serving MCP #then it resolves there and exports CODEGRAPH_INSTALL_DIR", async () => {+ it("#given Windows Codex SOT install_dir has codegraph.cmd and daemon is off by default #when serving MCP #then it resolves there, exports CODEGRAPH_INSTALL_DIR, and pins CODEGRAPH_NO_DAEMON=1", async () => {await withProcessPlatform("win32", async () => {// givenconst tempRoot = mkdtempSync(join(tmpdir(), "omo-codegraph-serve-install-dir-"));@@ -191,6 +237,61 @@ describe("runCodegraphServe", () => {});});+ it("#given Windows Codex SOT install_dir with codegraph.daemon=true #when serving MCP #then CODEGRAPH_NO_DAEMON is omitted so the daemon may run", async () => {+ await withProcessPlatform("win32", async () => {+ // given+ const tempRoot = mkdtempSync(join(tmpdir(), "omo-codegraph-serve-install-dir-daemon-"));+ const installDir = join(tempRoot, "custom-codegraph");+ const binPath = join(installDir, "bin", "codegraph.cmd");+ const calls: Array<{+ readonly args: readonly string[];+ readonly command: string;+ readonly env: Record<string, string | undefined>;+ }> = [];++ try {+ mkdirSync(join(installDir, "bin"), { recursive: true });+ writeFileSync(binPath, "");++ // when+ const exitCode = await runCodegraphServe({+ config: { codegraph: { daemon: true, enabled: true, install_dir: installDir }, sources: [], trustedCodegraphInstallDir: installDir, warnings: [] },+ env: { HOME: "/tmp/home" },+ nodeVersion: "22.14.0",+ homeDir: "/tmp/home",+ resolve: (options) => {+ const provisioned = options.provisioned?.();+ return { argsPrefix: [], command: provisioned ?? "missing", exists: provisioned !== null && provisioned !== undefined, source: "provisioned" };+ },+ runProcess: (command, args, options) => {+ calls.push({ args, command, env: options.env });+ return Promise.resolve(0);+ },+ stderr: { write: () => undefined },+ });++ // then+ expect(exitCode).toBe(0);+ expect(calls).toEqual([+ {+ args: ["serve", "--mcp"],+ command: binPath,+ env: {+ CODEGRAPH_INSTALL_DIR: installDir,+ CODEGRAPH_NO_DOWNLOAD: "1",+ CODEGRAPH_TELEMETRY: "0",+ DO_NOT_TRACK: "1",+ HOME: "/tmp/home",+ },+ },+ ]);+ expect(calls[0]?.env["CODEGRAPH_NO_DAEMON"]).toBeUndefined();+ } finally {+ rmSync(tempRoot, { recursive: true, force: true });+ }+ });+ });+it("#given project cwd is under a configured excluded root #when serving MCP #then it exposes an unavailable stub without spawning CodeGraph", async () => {// givenconst excludedRoot = mkdtempSync(join(componentRoot, ".tmp-codegraph-excluded-"));diff --git a/plugins/omo/components/codegraph/test/session-start-node-support.test.ts b/plugins/omo/components/codegraph/test/session-start-node-support.test.tsindex 57be534c..3b11122f 100644--- a/plugins/omo/components/codegraph/test/session-start-node-support.test.ts+++ b/plugins/omo/components/codegraph/test/session-start-node-support.test.ts@@ -52,7 +52,7 @@ describe("CodeGraph SessionStart worker Node support", () => {const homeDir = mkdtempSync(join(tmpdir(), "omo-codegraph-worker-node-provision-home-"));const binPath = join(homeDir, ".omo", "codegraph", "bin", "codegraph");const calls: Array<{ readonly args: readonly string[]; readonly command: string }> = [];- const provisionCalls: Array<{ readonly installDir?: string; readonly lockDir: string; readonly version: "1.0.1" }> = [];+ const provisionCalls: Array<{ readonly installDir?: string; readonly lockDir: string; readonly version: "1.4.1" }> = [];const outcomes: unknown[] = [];try {@@ -90,7 +90,7 @@ describe("CodeGraph SessionStart worker Node support", () => {{ args: ["init"], command: binPath },]);expect(provisionCalls).toEqual([- { installDir: join(homeDir, ".omo", "codegraph"), lockDir: join(homeDir, ".omo", "codegraph", ".locks"), version: "1.0.1" },+ { installDir: join(homeDir, ".omo", "codegraph"), lockDir: join(homeDir, ".omo", "codegraph", ".locks"), version: "1.4.1" },]);expect(outcomes).toEqual([{ action: "initialized", exitCode: 0, projectRoot: workspace, source: "provisioned", timedOut: false }]);} finally {diff --git a/plugins/omo/components/codegraph/test/session-start-worker-flow.test.ts b/plugins/omo/components/codegraph/test/session-start-worker-flow.test.tsindex 12caf659..04e4b343 100644--- a/plugins/omo/components/codegraph/test/session-start-worker-flow.test.ts+++ b/plugins/omo/components/codegraph/test/session-start-worker-flow.test.ts@@ -152,6 +152,49 @@ describe("CodeGraph SessionStart worker flow", () => {}});+ it("#given codegraph.daemon=true #when the indexing worker runs #then its env stays daemon-less with CODEGRAPH_NO_DAEMON=1", async () => {+ // given+ const workspace = mkdtempSync(join(tmpdir(), "omo-codegraph-worker-daemon-"));+ const homeDir = mkdtempSync(join(tmpdir(), "omo-codegraph-worker-daemon-home-"));+ const calls: { readonly args: readonly string[]; readonly command: string; readonly env: Record<string, string> }[] = [];+ try {+ // when+ const result = await runCodegraphSessionStartWorker({+ config: { codegraph: { daemon: true, enabled: true, install_dir: "/tmp/codegraph-install" }, sources: [], trustedCodegraphInstallDir: "/tmp/codegraph-install", warnings: [] },+ nodeVersion: "22.14.0",+ cwd: workspace,+ env: { HOME: homeDir },+ logOutcome: () => undefined,+ deps: {+ ensureGitignored: () => true,+ ensureProvisioned: () => Promise.resolve({ binPath: "/tmp/codegraph", provisioned: true }),+ prepareWorkspace: () => ({+ dataDir: join(homeDir, ".omo/codegraph/projects/test"),+ dataRoot: join(homeDir, ".omo/codegraph"),+ linked: true,+ mode: "global-linked",+ projectLink: join(workspace, ".codegraph"),+ }),+ resolveCommand: () => ({ argsPrefix: [], command: "/tmp/codegraph", exists: true, source: "path" }),+ runCommand: (_projectRoot, command, args, options) => {+ calls.push({ args, command, env: options.env });+ return Promise.resolve({ exitCode: 0, stdout: calls.length === 1 ? '{"initialized":true}' : "", timedOut: false });+ },+ },+ });++ // then+ expect(result).toEqual({ action: "synced" });+ expect(calls.length).toBeGreaterThan(0);+ for (const call of calls) {+ expect(call.env["CODEGRAPH_NO_DAEMON"]).toBe("1");+ }+ } finally {+ rmSync(workspace, { recursive: true, force: true });+ rmSync(homeDir, { recursive: true, force: true });+ }+ });+it("#given ambient provider tokens #when default worker runner spawns CodeGraph #then child env only gets safe and controlled variables", async () => {// givenconst workspace = mkdtempSync(join(tmpdir(), "omo-codegraph-worker-env-"));diff --git a/plugins/omo/components/comment-checker/.gitignore b/plugins/omo/components/comment-checker/.gitignoredeleted file mode 100644index af760374..00000000--- a/plugins/omo/components/comment-checker/.gitignore+++ /dev/null@@ -1,7 +0,0 @@-node_modules/-*.log-.DS_Store-.env-.env.*-coverage/-.vitest/diff --git a/plugins/omo/components/comment-checker/hooks/hooks.json b/plugins/omo/components/comment-checker/hooks/hooks.jsonindex ff192940..004d9fbb 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": "(OmO 4.19.0) Checking Comments"+ "statusMessage": "(OmO 4.19.1) Checking Comments"}]}diff --git a/plugins/omo/components/comment-checker/package.json b/plugins/omo/components/comment-checker/package.jsonindex 2a1bd818..6d706bae 100644--- a/plugins/omo/components/comment-checker/package.json+++ b/plugins/omo/components/comment-checker/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-comment-checker",- "version": "4.19.0",+ "version": "4.19.1","description": "Codex plugin that runs comment-checker after edit-like PostToolUse hooks.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/git-bash-mcp/dist/cli.js b/plugins/omo/components/git-bash-mcp/dist/cli.jsindex 8ad7848f..5a9e3f73 100755--- a/plugins/omo/components/git-bash-mcp/dist/cli.js+++ b/plugins/omo/components/git-bash-mcp/dist/cli.js@@ -163,16 +163,35 @@ function bufferFromChunk(chunk) {// ../mcp-stdio-core/src/server.tsvar DEFAULT_IDLE_TIMEOUT_MS = 10 * 60000;+var DEFAULT_PARENT_POLL_INTERVAL_MS = 30000;var noopLog = () => {};+function isProcessAlive(pid) {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return !hasErrorCode(error, "ESRCH");+ }+}async function runJsonRpcStdioServer(config) {const log = config.log ?? noopLog;const idleTimeoutMs = config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;- const idleTimer = createIdleTimer(idleTimeoutMs, log, config.onIdleTimeout);+ let isClosed = false;+ const idleTimer = createIdleTimer(idleTimeoutMs, log, () => {+ isClosed = true;+ config.onIdleTimeout?.();+ });+ const watchdog = createParentWatchdog(config.parentWatchdog, (parentPid, pollIntervalMs) => {+ isClosed = true;+ log("parent_exit", { parent_pid: parentPid, poll_interval_ms: pollIntervalMs });+ config.onParentExit?.();+ config.input.destroy();+ });log("stdio_started", { cwd: process.cwd(), idle_timeout_ms: idleTimeoutMs });idleTimer.arm();try {for await (const message of readStdioJsonRpcMessages(config.input)) {- if (idleTimer.closed())+ if (isClosed)break;idleTimer.arm();if (message.kind === "parse_error") {@@ -183,8 +202,12 @@ async function runJsonRpcStdioServer(config) {if (!await handleRequest(message, config, log))break;}+ } catch (error) {+ if (!(isClosed && hasErrorCode(error, "ERR_STREAM_PREMATURE_CLOSE")))+ throw error;} finally {idleTimer.clear();+ watchdog.clear();log("stdio_stopped");}}@@ -240,9 +263,33 @@ function isTerminalOutputError(error) {return false;return error.code === "EPIPE" || error.code === "ERR_STREAM_DESTROYED" || error.code === "ERR_STREAM_WRITE_AFTER_END";}-function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {+function hasErrorCode(error, code) {+ return error instanceof Error && "code" in error && error.code === code;+}+function createParentWatchdog(config, onDeadParent) {+ if (config === undefined)+ return { clear: () => {} };+ const pollIntervalMs = config.pollIntervalMs ?? DEFAULT_PARENT_POLL_INTERVAL_MS;+ if (pollIntervalMs <= 0)+ return { clear: () => {} };+ const parentPid = config.parentPid ?? process.ppid;+ const probeAlive = config.probeAlive ?? isProcessAlive;+ let fired = false;+ const timer = setInterval(() => {+ if (fired || probeAlive(parentPid))+ return;+ fired = true;+ onDeadParent(parentPid, pollIntervalMs);+ }, pollIntervalMs);+ timer.unref();+ return {+ clear: () => {+ clearInterval(timer);+ }+ };+}+function createIdleTimer(idleTimeoutMs, log, onTimeout) {let timer = null;- let isClosed = false;return {arm: () => {if (timer !== null)@@ -250,9 +297,8 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {if (idleTimeoutMs <= 0)return;timer = setTimeout(() => {- isClosed = true;log("idle_timeout", { idle_timeout_ms: idleTimeoutMs });- onIdleTimeout?.();+ onTimeout();}, idleTimeoutMs);timer.unref();},@@ -261,8 +307,7 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {return;clearTimeout(timer);timer = null;- },- closed: () => isClosed+ }};}// ../utils/src/runtime/git-bash.ts@@ -444,6 +489,7 @@ async function runMcpStdioServer(input, output, options = {}) {handler: handleGitBashMcpRequest,handlerOptions: options,idleTimeoutMs: 0,+ parentWatchdog: options.parentWatchdog ?? {},log: options.lifecycleLog,parseErrorResponse: () => errorResponse(null, -32601, "Method not found")});diff --git a/plugins/omo/components/git-bash/hooks/hooks.json b/plugins/omo/components/git-bash/hooks/hooks.jsonindex 47558c13..a27cf396 100644--- a/plugins/omo/components/git-bash/hooks/hooks.json+++ b/plugins/omo/components/git-bash/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use","timeout": 5,- "statusMessage": "(OmO 4.19.0) Recommending Git Bash MCP"+ "statusMessage": "(OmO 4.19.1) Recommending Git Bash MCP"}]}@@ -20,7 +20,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact","timeout": 5,- "statusMessage": "(OmO 4.19.0) Resetting Git Bash MCP Reminder"+ "statusMessage": "(OmO 4.19.1) Resetting Git Bash MCP Reminder"}]}diff --git a/plugins/omo/components/git-bash/package.json b/plugins/omo/components/git-bash/package.jsonindex 487280fb..98fbf11b 100644--- a/plugins/omo/components/git-bash/package.json+++ b/plugins/omo/components/git-bash/package.json@@ -1,6 +1,6 @@{"name": "@sisyphuslabs/codex-git-bash-hook",- "version": "4.19.0",+ "version": "4.19.1","description": "Codex hook component that reminds Windows sessions to prefer the OMO git_bash MCP.","type": "module","private": true,diff --git a/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json b/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.jsonindex 72460942..ace3a4d9 100644--- a/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json+++ b/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/lazycodex-executor-verify/dist/cli.js\" hook subagent-stop","timeout": 10,- "statusMessage": "(OmO 4.19.0) Verifying LazyCodex Executor Evidence"+ "statusMessage": "(OmO 4.19.1) Verifying LazyCodex Executor Evidence"}]}diff --git a/plugins/omo/components/lazycodex-executor-verify/package.json b/plugins/omo/components/lazycodex-executor-verify/package.jsonindex 0c7c1097..446fe116 100644--- a/plugins/omo/components/lazycodex-executor-verify/package.json+++ b/plugins/omo/components/lazycodex-executor-verify/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-lazycodex-executor-verify",- "version": "4.19.0",+ "version": "4.19.1","description": "Codex SubagentStop evidence verifier for LazyCodex executor completions.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/lsp-daemon/dist/cli.js b/plugins/omo/components/lsp-daemon/dist/cli.jsindex bfb91de4..22c609ce 100644--- a/plugins/omo/components/lsp-daemon/dist/cli.js+++ b/plugins/omo/components/lsp-daemon/dist/cli.js@@ -167,16 +167,35 @@ function bufferFromChunk(chunk) {// ../mcp-stdio-core/src/server.tsvar DEFAULT_IDLE_TIMEOUT_MS = 10 * 60000;+var DEFAULT_PARENT_POLL_INTERVAL_MS = 30000;var noopLog = () => {};+function isProcessAlive(pid) {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return !hasErrorCode(error, "ESRCH");+ }+}async function runJsonRpcStdioServer(config) {const log = config.log ?? noopLog;const idleTimeoutMs = config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;- const idleTimer = createIdleTimer(idleTimeoutMs, log, config.onIdleTimeout);+ let isClosed = false;+ const idleTimer = createIdleTimer(idleTimeoutMs, log, () => {+ isClosed = true;+ config.onIdleTimeout?.();+ });+ const watchdog = createParentWatchdog(config.parentWatchdog, (parentPid, pollIntervalMs) => {+ isClosed = true;+ log("parent_exit", { parent_pid: parentPid, poll_interval_ms: pollIntervalMs });+ config.onParentExit?.();+ config.input.destroy();+ });log("stdio_started", { cwd: process.cwd(), idle_timeout_ms: idleTimeoutMs });idleTimer.arm();try {for await (const message of readStdioJsonRpcMessages(config.input)) {- if (idleTimer.closed())+ if (isClosed)break;idleTimer.arm();if (message.kind === "parse_error") {@@ -187,8 +206,12 @@ async function runJsonRpcStdioServer(config) {if (!await handleRequest(message, config, log))break;}+ } catch (error) {+ if (!(isClosed && hasErrorCode(error, "ERR_STREAM_PREMATURE_CLOSE")))+ throw error;} finally {idleTimer.clear();+ watchdog.clear();log("stdio_stopped");}}@@ -244,9 +267,33 @@ function isTerminalOutputError(error) {return false;return error.code === "EPIPE" || error.code === "ERR_STREAM_DESTROYED" || error.code === "ERR_STREAM_WRITE_AFTER_END";}-function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {+function hasErrorCode(error, code) {+ return error instanceof Error && "code" in error && error.code === code;+}+function createParentWatchdog(config, onDeadParent) {+ if (config === undefined)+ return { clear: () => {} };+ const pollIntervalMs = config.pollIntervalMs ?? DEFAULT_PARENT_POLL_INTERVAL_MS;+ if (pollIntervalMs <= 0)+ return { clear: () => {} };+ const parentPid = config.parentPid ?? process.ppid;+ const probeAlive = config.probeAlive ?? isProcessAlive;+ let fired = false;+ const timer = setInterval(() => {+ if (fired || probeAlive(parentPid))+ return;+ fired = true;+ onDeadParent(parentPid, pollIntervalMs);+ }, pollIntervalMs);+ timer.unref();+ return {+ clear: () => {+ clearInterval(timer);+ }+ };+}+function createIdleTimer(idleTimeoutMs, log, onTimeout) {let timer = null;- let isClosed = false;return {arm: () => {if (timer !== null)@@ -254,9 +301,8 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {if (idleTimeoutMs <= 0)return;timer = setTimeout(() => {- isClosed = true;log("idle_timeout", { idle_timeout_ms: idleTimeoutMs });- onIdleTimeout?.();+ onTimeout();}, idleTimeoutMs);timer.unref();},@@ -265,8 +311,7 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {return;clearTimeout(timer);timer = null;- },- closed: () => isClosed+ }};}// ../lsp-core/src/lsp/client-wrapper.ts@@ -3057,8 +3102,13 @@ class LspClient extends LspClientConnection {if (!pushFallbackOnly)continue;const remainingMs = deadlineAt - Date.now();- if (remainingMs <= 0)+ if (remainingMs <= 0) {+ if (!this.isDiagnosticPullSupported() && snapshot.publishGeneration === 0) {+ const cached = this.documents.getPullCache(snapshot);+ return { items: cached === null ? [] : [...cached.diagnostics] };+ }return this.freshnessTimeout(absPath);+ }const waitMs = push.status === "wait" ? Math.min(push.waitMs, remainingMs) : remainingMs;await waitForDiagnosticsActivity(this.documents.waitForDiagnosticsActivity(snapshot, waitMs), signal);}@@ -5065,6 +5115,81 @@ import { connect } from "node:net";import { homedir as homedir3 } from "node:os";import { join as join7 } from "node:path";+// src/daemon-request-error.ts+class DaemonRequestError extends Error {+ requestWritten;+ constructor(message, requestWritten) {+ super(message);+ this.name = "DaemonRequestError";+ this.requestWritten = requestWritten;+ }+}++class DaemonAuthenticationRejectedError extends DaemonRequestError {+ constructor() {+ super("daemon authentication failed before dispatch", true);+ this.name = "DaemonAuthenticationRejectedError";+ }+}++class DaemonRequestCancelledError extends DaemonRequestError {+ constructor(requestWritten) {+ super("daemon request cancelled", requestWritten);+ this.name = "DaemonRequestCancelledError";+ }+}++class DaemonRequestTimedOutError extends DaemonRequestError {+ timeoutMs;+ constructor(requestWritten, timeoutMs) {+ super("daemon request timed out", requestWritten);+ this.name = "DaemonRequestTimedOutError";+ this.timeoutMs = timeoutMs;+ }+}++// src/daemon-failure-result.ts+function daemonFailureResult(paths, error) {+ if (error instanceof DaemonRequestCancelledError)+ return daemonCancelledResult(paths);+ if (error instanceof DaemonRequestTimedOutError)+ return daemonTimedOutResult(paths, error.timeoutMs);+ return daemonUnreachableResult(paths, error);+}+function daemonCancelledResult(paths) {+ const text2 = [+ "LSP daemon request cancelled: the caller aborted this request (for example, the turn was interrupted).",+ "The daemon stays available; no LSP work was applied. Retry when you are ready.",+ `Socket: ${paths.socket}`+ ].join(`+`);+ return { content: [{ type: "text", text: text2 }], isError: true };+}+function daemonTimedOutResult(paths, timeoutMs) {+ const text2 = [+ `LSP daemon request timed out after ${timeoutMs}ms: the daemon did not respond in time.`,+ "The daemon stays available but may be busy. Retry when you are ready.",+ `Socket: ${paths.socket}`,+ `Logs: ${paths.log}`+ ].join(`+`);+ return { content: [{ type: "text", text: text2 }], isError: true };+}+function daemonUnreachableResult(paths, error) {+ const text2 = [+ `LSP daemon unreachable: ${errorText(error)}.`,+ "The MCP server is a thin proxy and never runs language servers in-process.",+ `Socket: ${paths.socket}`,+ `Logs: ${paths.log}`,+ "The daemon is auto-started on demand and will be retried on the next request."+ ].join(`+`);+ return { content: [{ type: "text", text: text2 }], isError: true };+}+function errorText(error) {+ return error instanceof Error ? error.message : String(error);+}+// src/ensure-daemon.tsimport { spawn as spawn2 } from "node:child_process";import { closeSync as closeSync2, mkdirSync as mkdirSync3, openSync as openSync2 } from "node:fs";@@ -5724,29 +5849,6 @@ function parseContext(value) {// src/daemon-client.tsvar DEFAULT_REQUEST_TIMEOUT_MS = 30000;var nextProxyRequestId = 1;--class DaemonRequestError extends Error {- requestWritten;- constructor(message, requestWritten) {- super(message);- this.name = "DaemonRequestError";- this.requestWritten = requestWritten;- }-}--class DaemonAuthenticationRejectedError extends DaemonRequestError {- constructor() {- super("daemon authentication failed before dispatch", true);- this.name = "DaemonAuthenticationRejectedError";- }-}--class DaemonRequestCancelledError extends DaemonRequestError {- constructor(requestWritten) {- super("daemon request cancelled", requestWritten);- this.name = "DaemonRequestCancelledError";- }-}async function callToolViaDaemon(name, args, options) {const context = requireContext(options.context);const paths = options.paths ?? daemonPaths();@@ -5775,7 +5877,7 @@ async function callToolViaDaemon(name, args, options) {break;}}- return daemonUnreachableResult(paths, lastError);+ return daemonFailureResult(paths, lastError);}function callDiagnosticsViaDaemon(filePath, options) {return callToolViaDaemon("diagnostics", { filePath, severity: "error" }, options);@@ -5820,17 +5922,6 @@ function ensureDaemonAvailable(paths, ensure, signal) {Promise.resolve().then(() => ensure(paths, signal)).then(() => finish(() => resolve9()), (error) => finish(() => reject(signal.aborted ? new DaemonRequestCancelledError(false) : error)));});}-function daemonUnreachableResult(paths, error) {- const text2 = [- `LSP daemon unreachable: ${errorText(error)}.`,- "The MCP server is a thin proxy and never runs language servers in-process.",- `Socket: ${paths.socket}`,- `Logs: ${paths.log}`,- "The daemon is auto-started on demand and will be retried on the next request."- ].join(`-`);- return { content: [{ type: "text", text: text2 }], isError: true };-}function sendToolCall(paths, token, name, args, options) {return new Promise((resolve9, reject) => {const socket = connect(paths.socket);@@ -5870,7 +5961,7 @@ function sendToolCall(paths, token, name, args, options) {};const timer = setTimeout(() => {sendCancel();- finish(() => reject(new DaemonRequestError("daemon request timed out", requestWritten)));+ finish(() => reject(new DaemonRequestTimedOutError(requestWritten, options.timeoutMs)));}, options.timeoutMs);timer.unref();if (options.signal?.aborted) {@@ -5929,9 +6020,6 @@ function allocateProxyRequestId() {function isRetryableTool(name) {return name !== "rename" && name !== "lsp_rename";}-function errorText(error) {- return error instanceof Error ? error.message : String(error);-}// src/proxy.tsvar DEFAULT_STARTUP_TIMEOUT_MS = 1e4;@@ -5988,6 +6076,7 @@ async function runMcpStdioProxy(options = {}) {input,output,idleTimeoutMs: 0,+ parentWatchdog: options.parentWatchdog ?? {},handler: (request, requestOptions) => {clearStartupWatchdog();return runWithRequestContext(context, () => handleProxyRequest(request, requestOptions));@@ -6081,7 +6170,7 @@ import { dirname as dirname11 } from "node:path";// src/lock.tsimport { closeSync as closeSync3, mkdirSync as mkdirSync4, openSync as openSync3, readFileSync as readFileSync6, unlinkSync as unlinkSync2, writeSync as writeSync2 } from "node:fs";import { dirname as dirname10 } from "node:path";-function isProcessAlive(pid) {+function isProcessAlive2(pid) {if (!Number.isInteger(pid) || pid <= 0)return false;try {@@ -6127,7 +6216,7 @@ function writeLockFile(lockPath, ownerPid) {}function reapStaleLock(lockPath) {const pid = readLockPid(lockPath);- if (pid !== null && isProcessAlive(pid))+ if (pid !== null && isProcessAlive2(pid))return false;unlinkQuietly(lockPath);return true;@@ -6249,7 +6338,7 @@ async function validateExistingOwner(paths, pingOwner) {}if (ping)continue;- if (isProcessAlive(owner.pid))+ if (isProcessAlive2(owner.pid))throw new DaemonStartupDeferredError("owner_pid_live_unreachable");const reread = readDaemonOwner(paths);const endpoint = endpointIdentity(owner.endpoint.path);@@ -6311,6 +6400,184 @@ function parseEndpoint(value) {return null;}+// src/version-reap.ts+import { execFile } from "node:child_process";+import { readdir, readFile, rm } from "node:fs/promises";+import { basename as basename4, dirname as dirname12, join as join8 } from "node:path";+var TERM_GRACE_MS = 5000;+var KILL_GRACE_MS = 1000;+var VERSION_ENTRY_PATTERN = /^v([A-Za-z0-9][A-Za-z0-9._+-]{0,127})$/;+async function attestDaemonCliProcess(pid, platform, deps = {}) {+ if (platform === "win32")+ return false;+ if (platform === "linux") {+ const readProcFile = deps.readProcFile ?? defaultReadProcFile;+ const cmdline = await readProcFile(`/proc/${pid}/cmdline`).catch(() => null);+ if (cmdline === null)+ return false;+ return isNodeCliDaemonArgv(splitCmdline(cmdline));+ }+ const executeForStdout = deps.executeForStdout ?? defaultExecuteForStdout;+ const command = await executeForStdout("/bin/ps", ["-p", String(pid), "-o", "command="]);+ if (command === null)+ return false;+ return isNodeCliDaemonCommand(command.trim());+}+async function reapStaleDaemonVersions(ownPaths, deps = {}) {+ const baseDir = dirname12(ownPaths.dir);+ const platform = deps.platform ?? process.platform;+ const isAlive = deps.isAlive ?? isProcessAlive2;+ const attest = deps.attest ?? ((pid) => attestDaemonCliProcess(pid, platform));+ const sendSignal = deps.sendSignal ?? defaultSendSignal;+ const waitForExit = deps.waitForExit ?? defaultWaitForExit;+ const removeDir = deps.removeDir ?? ((path2) => rm(path2, { recursive: true, force: true }));+ const readOwner = deps.readOwner ?? readDaemonOwner;+ const log = deps.log ?? defaultLog;+ const termGraceMs = deps.termGraceMs ?? TERM_GRACE_MS;+ const killGraceMs = deps.killGraceMs ?? KILL_GRACE_MS;+ const entries = await readdir(baseDir, { withFileTypes: true }).catch(() => []);+ const results = [];+ for (const entry of [...entries].sort((left, right) => left.name.localeCompare(right.name))) {+ if (entry.name === `v${ownPaths.version}`)+ continue;+ const version = parseVersionEntry(entry.name);+ if (version === null || !entry.isDirectory())+ continue;+ const versionDir = join8(baseDir, entry.name);+ const siblingPaths = daemonPaths({ [OMO_LSP_DAEMON_DIR]: baseDir }, { cliPath: ownPaths.cliPath, version });+ results.push(await reapOneVersion({+ version,+ versionDir,+ siblingPaths,+ platform,+ isAlive,+ attest,+ sendSignal,+ waitForExit,+ removeDir,+ readOwner,+ log,+ termGraceMs,+ killGraceMs+ }));+ }+ return results;+}+async function reapOneVersion(context) {+ const { version, versionDir } = context;+ const owner = context.readOwner(context.siblingPaths);+ if (!owner) {+ const lockPid = readLockPid(join8(versionDir, "daemon.lock"));+ if (lockPid !== null && context.isAlive(lockPid)) {+ context.log(`reap: sparing v${version}: owner metadata missing but daemon.lock is held by live pid ${lockPid}`);+ return { version, status: "spared", reason: `owner metadata missing but lock held by live pid ${lockPid}` };+ }+ await context.removeDir(versionDir);+ return { version, status: "removed", reason: "removed stale version dir without readable owner metadata" };+ }+ if (!context.isAlive(owner.pid)) {+ await context.removeDir(versionDir);+ return { version, status: "removed", reason: `removed stale version dir for dead owner pid ${owner.pid}` };+ }+ if (context.platform === "win32") {+ context.log(`reap: deferring v${version}: Windows cannot prove pid ownership safely (named-pipe policy)`);+ return {+ version,+ status: "deferred",+ reason: "Windows cannot prove pid ownership safely; named-pipe reap deferred"+ };+ }+ if (!await context.attest(owner.pid, context.platform)) {+ context.log(`reap: sparing v${version}: pid ${owner.pid} is alive but cmdline attestation failed (possible recycled pid)`);+ return {+ version,+ status: "spared",+ reason: `pid ${owner.pid} attestation failed; possible recycled pid`+ };+ }+ return await terminateAttestedOwner(context, owner.pid);+}+async function terminateAttestedOwner(context, pid) {+ const { version, versionDir } = context;+ if (!context.sendSignal(pid, "SIGTERM")) {+ await context.removeDir(versionDir);+ return {+ version,+ status: "removed",+ reason: `owner pid ${pid} exited before SIGTERM; removed stale version dir`+ };+ }+ if (await context.waitForExit(pid, context.termGraceMs)) {+ await context.removeDir(versionDir);+ return { version, status: "terminated", reason: `terminated attested older daemon pid ${pid} with SIGTERM` };+ }+ context.log(`reap: v${version} pid ${pid} survived SIGTERM; escalating to SIGKILL`);+ if (!context.sendSignal(pid, "SIGKILL") || !await context.waitForExit(pid, context.killGraceMs)) {+ context.log(`reap: deferring v${version}: pid ${pid} survived SIGKILL`);+ return { version, status: "deferred", reason: `attested daemon pid ${pid} survived SIGKILL; dir kept` };+ }+ await context.removeDir(versionDir);+ return {+ version,+ status: "terminated",+ reason: `terminated attested older daemon pid ${pid} after SIGKILL escalation`+ };+}+function parseVersionEntry(entryName) {+ const match = VERSION_ENTRY_PATTERN.exec(entryName);+ return match?.[1] ?? null;+}+function splitCmdline(buffer) {+ return buffer.toString("utf8").split("\x00").filter((value) => value.length > 0);+}+function isNodeCliDaemonArgv(argv) {+ if (argv.length < 2 || !argv.includes("daemon"))+ return false;+ const executable = basename4(argv[0] ?? "");+ if (!/^node(?:\.exe)?$/i.test(executable))+ return false;+ return argv.some((value) => value === "cli.js" || value.endsWith("/cli.js") || value.endsWith("\\cli.js"));+}+function isNodeCliDaemonCommand(command) {+ return /\bnode(?:\.exe)?\b/i.test(command) && /\bcli\.js\b/.test(command) && /\bdaemon\b/.test(command);+}+function defaultReadProcFile(path2) {+ return readFile(path2);+}+function defaultExecuteForStdout(file, args) {+ return new Promise((resolve9) => {+ execFile(file, [...args], { encoding: "utf8", maxBuffer: 1024 * 1024, timeout: 1000 }, (error, stdout) => {+ if (error !== null) {+ resolve9(null);+ return;+ }+ resolve9(stdout);+ });+ });+}+function defaultSendSignal(pid, signal) {+ try {+ process.kill(pid, signal);+ return true;+ } catch {+ return false;+ }+}+async function defaultWaitForExit(pid, timeoutMs) {+ const deadline = Date.now() + timeoutMs;+ for (;; ) {+ if (!isProcessAlive2(pid))+ return true;+ if (Date.now() >= deadline)+ return false;+ await new Promise((resolve9) => setTimeout(resolve9, 100));+ }+}+function defaultLog(message) {+ process.stderr.write(`[lsp-daemon] ${message}+`);+}+// src/daemon-server.tsvar DEFAULT_IDLE_SHUTDOWN_MS = 30 * 60000;var DEFAULT_IDLE_CHECK_INTERVAL_MS = 60000;@@ -6357,6 +6624,7 @@ async function startDaemonServer(paths, options = {}) {throw error;}lease.lock.release();+ reapStaleDaemonVersions(paths).catch((error) => logServerError(error));let closed = false;const close = async () => {if (closed)diff --git a/plugins/omo/components/lsp-daemon/dist/client.js b/plugins/omo/components/lsp-daemon/dist/client.jsindex afad9c90..3b3d868a 100644--- a/plugins/omo/components/lsp-daemon/dist/client.js+++ b/plugins/omo/components/lsp-daemon/dist/client.js@@ -177,6 +177,81 @@ function isPlainRecord(value) {return typeof value === "object" && value !== null && !Array.isArray(value);}+// src/daemon-request-error.ts+class DaemonRequestError extends Error {+ requestWritten;+ constructor(message, requestWritten) {+ super(message);+ this.name = "DaemonRequestError";+ this.requestWritten = requestWritten;+ }+}++class DaemonAuthenticationRejectedError extends DaemonRequestError {+ constructor() {+ super("daemon authentication failed before dispatch", true);+ this.name = "DaemonAuthenticationRejectedError";+ }+}++class DaemonRequestCancelledError extends DaemonRequestError {+ constructor(requestWritten) {+ super("daemon request cancelled", requestWritten);+ this.name = "DaemonRequestCancelledError";+ }+}++class DaemonRequestTimedOutError extends DaemonRequestError {+ timeoutMs;+ constructor(requestWritten, timeoutMs) {+ super("daemon request timed out", requestWritten);+ this.name = "DaemonRequestTimedOutError";+ this.timeoutMs = timeoutMs;+ }+}++// src/daemon-failure-result.ts+function daemonFailureResult(paths, error) {+ if (error instanceof DaemonRequestCancelledError)+ return daemonCancelledResult(paths);+ if (error instanceof DaemonRequestTimedOutError)+ return daemonTimedOutResult(paths, error.timeoutMs);+ return daemonUnreachableResult(paths, error);+}+function daemonCancelledResult(paths) {+ const text = [+ "LSP daemon request cancelled: the caller aborted this request (for example, the turn was interrupted).",+ "The daemon stays available; no LSP work was applied. Retry when you are ready.",+ `Socket: ${paths.socket}`+ ].join(`+`);+ return { content: [{ type: "text", text }], isError: true };+}+function daemonTimedOutResult(paths, timeoutMs) {+ const text = [+ `LSP daemon request timed out after ${timeoutMs}ms: the daemon did not respond in time.`,+ "The daemon stays available but may be busy. Retry when you are ready.",+ `Socket: ${paths.socket}`,+ `Logs: ${paths.log}`+ ].join(`+`);+ return { content: [{ type: "text", text }], isError: true };+}+function daemonUnreachableResult(paths, error) {+ const text = [+ `LSP daemon unreachable: ${errorText(error)}.`,+ "The MCP server is a thin proxy and never runs language servers in-process.",+ `Socket: ${paths.socket}`,+ `Logs: ${paths.log}`,+ "The daemon is auto-started on demand and will be retried on the next request."+ ].join(`+`);+ return { content: [{ type: "text", text }], isError: true };+}+function errorText(error) {+ return error instanceof Error ? error.message : String(error);+}+// src/ensure-daemon.tsimport { spawn } from "node:child_process";import { closeSync as closeSync2, mkdirSync as mkdirSync2, openSync as openSync2 } from "node:fs";@@ -904,16 +979,35 @@ function bufferFromChunk(chunk) {// ../mcp-stdio-core/src/server.tsvar DEFAULT_IDLE_TIMEOUT_MS = 10 * 60000;+var DEFAULT_PARENT_POLL_INTERVAL_MS = 30000;var noopLog = () => {};+function isProcessAlive(pid) {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return !hasErrorCode(error, "ESRCH");+ }+}async function runJsonRpcStdioServer(config) {const log = config.log ?? noopLog;const idleTimeoutMs = config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;- const idleTimer = createIdleTimer(idleTimeoutMs, log, config.onIdleTimeout);+ let isClosed = false;+ const idleTimer = createIdleTimer(idleTimeoutMs, log, () => {+ isClosed = true;+ config.onIdleTimeout?.();+ });+ const watchdog = createParentWatchdog(config.parentWatchdog, (parentPid, pollIntervalMs) => {+ isClosed = true;+ log("parent_exit", { parent_pid: parentPid, poll_interval_ms: pollIntervalMs });+ config.onParentExit?.();+ config.input.destroy();+ });log("stdio_started", { cwd: process.cwd(), idle_timeout_ms: idleTimeoutMs });idleTimer.arm();try {for await (const message of readStdioJsonRpcMessages(config.input)) {- if (idleTimer.closed())+ if (isClosed)break;idleTimer.arm();if (message.kind === "parse_error") {@@ -924,8 +1018,12 @@ async function runJsonRpcStdioServer(config) {if (!await handleRequest(message, config, log))break;}+ } catch (error) {+ if (!(isClosed && hasErrorCode(error, "ERR_STREAM_PREMATURE_CLOSE")))+ throw error;} finally {idleTimer.clear();+ watchdog.clear();log("stdio_stopped");}}@@ -981,9 +1079,33 @@ function isTerminalOutputError(error) {return false;return error.code === "EPIPE" || error.code === "ERR_STREAM_DESTROYED" || error.code === "ERR_STREAM_WRITE_AFTER_END";}-function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {+function hasErrorCode(error, code) {+ return error instanceof Error && "code" in error && error.code === code;+}+function createParentWatchdog(config, onDeadParent) {+ if (config === undefined)+ return { clear: () => {} };+ const pollIntervalMs = config.pollIntervalMs ?? DEFAULT_PARENT_POLL_INTERVAL_MS;+ if (pollIntervalMs <= 0)+ return { clear: () => {} };+ const parentPid = config.parentPid ?? process.ppid;+ const probeAlive = config.probeAlive ?? isProcessAlive;+ let fired = false;+ const timer = setInterval(() => {+ if (fired || probeAlive(parentPid))+ return;+ fired = true;+ onDeadParent(parentPid, pollIntervalMs);+ }, pollIntervalMs);+ timer.unref();+ return {+ clear: () => {+ clearInterval(timer);+ }+ };+}+function createIdleTimer(idleTimeoutMs, log, onTimeout) {let timer = null;- let isClosed = false;return {arm: () => {if (timer !== null)@@ -991,9 +1113,8 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {if (idleTimeoutMs <= 0)return;timer = setTimeout(() => {- isClosed = true;log("idle_timeout", { idle_timeout_ms: idleTimeoutMs });- onIdleTimeout?.();+ onTimeout();}, idleTimeoutMs);timer.unref();},@@ -1002,8 +1123,7 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {return;clearTimeout(timer);timer = null;- },- closed: () => isClosed+ }};}// ../lsp-core/src/lsp/client-wrapper.ts@@ -3625,8 +3745,13 @@ class LspClient extends LspClientConnection {if (!pushFallbackOnly)continue;const remainingMs = deadlineAt - Date.now();- if (remainingMs <= 0)+ if (remainingMs <= 0) {+ if (!this.isDiagnosticPullSupported() && snapshot.publishGeneration === 0) {+ const cached = this.documents.getPullCache(snapshot);+ return { items: cached === null ? [] : [...cached.diagnostics] };+ }return this.freshnessTimeout(absPath);+ }const waitMs = push.status === "wait" ? Math.min(push.waitMs, remainingMs) : remainingMs;await waitForDiagnosticsActivity(this.documents.waitForDiagnosticsActivity(snapshot, waitMs), signal);}@@ -5715,29 +5840,6 @@ function parseContext(value) {// src/daemon-client.tsvar DEFAULT_REQUEST_TIMEOUT_MS = 30000;var nextProxyRequestId = 1;--class DaemonRequestError extends Error {- requestWritten;- constructor(message, requestWritten) {- super(message);- this.name = "DaemonRequestError";- this.requestWritten = requestWritten;- }-}--class DaemonAuthenticationRejectedError extends DaemonRequestError {- constructor() {- super("daemon authentication failed before dispatch", true);- this.name = "DaemonAuthenticationRejectedError";- }-}--class DaemonRequestCancelledError extends DaemonRequestError {- constructor(requestWritten) {- super("daemon request cancelled", requestWritten);- this.name = "DaemonRequestCancelledError";- }-}async function callToolViaDaemon(name, args, options) {const context = requireContext(options.context);const paths = options.paths ?? daemonPaths();@@ -5766,7 +5868,7 @@ async function callToolViaDaemon(name, args, options) {break;}}- return daemonUnreachableResult(paths, lastError);+ return daemonFailureResult(paths, lastError);}function callDiagnosticsViaDaemon(filePath, options) {return callToolViaDaemon("diagnostics", { filePath, severity: "error" }, options);@@ -5811,17 +5913,6 @@ function ensureDaemonAvailable(paths, ensure, signal) {Promise.resolve().then(() => ensure(paths, signal)).then(() => finish(() => resolve9()), (error) => finish(() => reject(signal.aborted ? new DaemonRequestCancelledError(false) : error)));});}-function daemonUnreachableResult(paths, error) {- const text2 = [- `LSP daemon unreachable: ${errorText(error)}.`,- "The MCP server is a thin proxy and never runs language servers in-process.",- `Socket: ${paths.socket}`,- `Logs: ${paths.log}`,- "The daemon is auto-started on demand and will be retried on the next request."- ].join(`-`);- return { content: [{ type: "text", text: text2 }], isError: true };-}function sendToolCall(paths, token, name, args, options) {return new Promise((resolve9, reject) => {const socket = connect(paths.socket);@@ -5861,7 +5952,7 @@ function sendToolCall(paths, token, name, args, options) {};const timer = setTimeout(() => {sendCancel();- finish(() => reject(new DaemonRequestError("daemon request timed out", requestWritten)));+ finish(() => reject(new DaemonRequestTimedOutError(requestWritten, options.timeoutMs)));}, options.timeoutMs);timer.unref();if (options.signal?.aborted) {@@ -5920,9 +6011,6 @@ function allocateProxyRequestId() {function isRetryableTool(name) {return name !== "rename" && name !== "lsp_rename";}-function errorText(error) {- return error instanceof Error ? error.message : String(error);-}// src/client.tsimport { statSync as statSync5 } from "node:fs";diff --git a/plugins/omo/components/lsp-daemon/dist/daemon-client.d.ts b/plugins/omo/components/lsp-daemon/dist/daemon-client.d.tsindex ec15f240..68e20a23 100644--- a/plugins/omo/components/lsp-daemon/dist/daemon-client.d.ts+++ b/plugins/omo/components/lsp-daemon/dist/daemon-client.d.ts@@ -1,16 +1,6 @@import { type LspRequestContext } from "@oh-my-opencode/lsp-core/request-context";import type { ToolExecutionResult } from "@oh-my-opencode/lsp-core/tools";import { type DaemonPaths } from "./paths.js";-export declare class DaemonRequestError extends Error {- readonly requestWritten: boolean;- constructor(message: string, requestWritten: boolean);-}-export declare class DaemonAuthenticationRejectedError extends DaemonRequestError {- constructor();-}-export declare class DaemonRequestCancelledError extends DaemonRequestError {- constructor(requestWritten: boolean);-}export type DaemonToolContext = LspRequestContext;export interface CallToolOptions {context: DaemonToolContext;diff --git a/plugins/omo/components/lsp-daemon/dist/daemon-client.js b/plugins/omo/components/lsp-daemon/dist/daemon-client.jsindex 36be8891..6475aa30 100644--- a/plugins/omo/components/lsp-daemon/dist/daemon-client.js+++ b/plugins/omo/components/lsp-daemon/dist/daemon-client.js@@ -3,6 +3,8 @@ import { homedir } from "node:os";import { join } from "node:path";import { parseLspRequestContext } from "@oh-my-opencode/lsp-core/request-context";import { isPlainRecord } from "@oh-my-opencode/mcp-stdio-core/record";+import { daemonFailureResult } from "./daemon-failure-result.js";+import { DaemonAuthenticationRejectedError, DaemonRequestCancelledError, DaemonRequestError, DaemonRequestTimedOutError, } from "./daemon-request-error.js";import { ensureDaemonRunning } from "./ensure-daemon.js";import { authEnvelope, isAuthErrorResponse, readAuthToken } from "./ipc-protocol.js";import { daemonPaths } from "./paths.js";@@ -10,25 +12,6 @@ import { CONTEXT_KEY } from "./request-routing.js";import { createLineDecoder, encodeJsonLine } from "./socket-jsonrpc.js";const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;let nextProxyRequestId = 1;-export class DaemonRequestError extends Error {- constructor(message, requestWritten) {- super(message);- this.name = "DaemonRequestError";- this.requestWritten = requestWritten;- }-}-export class DaemonAuthenticationRejectedError extends DaemonRequestError {- constructor() {- super("daemon authentication failed before dispatch", true);- this.name = "DaemonAuthenticationRejectedError";- }-}-export class DaemonRequestCancelledError extends DaemonRequestError {- constructor(requestWritten) {- super("daemon request cancelled", requestWritten);- this.name = "DaemonRequestCancelledError";- }-}export async function callToolViaDaemon(name, args, options) {const context = requireContext(options.context);const paths = options.paths ?? daemonPaths();@@ -59,7 +42,7 @@ export async function callToolViaDaemon(name, args, options) {break;}}- return daemonUnreachableResult(paths, lastError);+ return daemonFailureResult(paths, lastError);}export function callDiagnosticsViaDaemon(filePath, options) {return callToolViaDaemon("diagnostics", { filePath, severity: "error" }, options);@@ -106,16 +89,6 @@ function ensureDaemonAvailable(paths, ensure, signal) {.then(() => finish(() => resolve()), (error) => finish(() => reject(signal.aborted ? new DaemonRequestCancelledError(false) : error)));});}-function daemonUnreachableResult(paths, error) {- const text = [- `LSP daemon unreachable: ${errorText(error)}.`,- "The MCP server is a thin proxy and never runs language servers in-process.",- `Socket: ${paths.socket}`,- `Logs: ${paths.log}`,- "The daemon is auto-started on demand and will be retried on the next request.",- ].join("\n");- return { content: [{ type: "text", text }], isError: true };-}function sendToolCall(paths, token, name, args, options) {return new Promise((resolve, reject) => {const socket = connect(paths.socket);@@ -155,7 +128,7 @@ function sendToolCall(paths, token, name, args, options) {};const timer = setTimeout(() => {sendCancel();- finish(() => reject(new DaemonRequestError("daemon request timed out", requestWritten)));+ finish(() => reject(new DaemonRequestTimedOutError(requestWritten, options.timeoutMs)));}, options.timeoutMs);timer.unref();if (options.signal?.aborted) {@@ -214,6 +187,3 @@ function allocateProxyRequestId() {function isRetryableTool(name) {return name !== "rename" && name !== "lsp_rename";}-function errorText(error) {- return error instanceof Error ? error.message : String(error);-}diff --git a/plugins/omo/components/lsp-daemon/dist/daemon-failure-result.d.ts b/plugins/omo/components/lsp-daemon/dist/daemon-failure-result.d.tsnew file mode 100644index 00000000..b153de25--- /dev/null+++ b/plugins/omo/components/lsp-daemon/dist/daemon-failure-result.d.ts@@ -0,0 +1,3 @@+import type { ToolExecutionResult } from "@oh-my-opencode/lsp-core/tools";+import type { DaemonPaths } from "./paths.js";+export declare function daemonFailureResult(paths: DaemonPaths, error: unknown): ToolExecutionResult;diff --git a/plugins/omo/components/lsp-daemon/dist/daemon-failure-result.js b/plugins/omo/components/lsp-daemon/dist/daemon-failure-result.jsnew file mode 100644index 00000000..43cd2bd1--- /dev/null+++ b/plugins/omo/components/lsp-daemon/dist/daemon-failure-result.js@@ -0,0 +1,38 @@+import { DaemonRequestCancelledError, DaemonRequestTimedOutError } from "./daemon-request-error.js";+export function daemonFailureResult(paths, error) {+ if (error instanceof DaemonRequestCancelledError)+ return daemonCancelledResult(paths);+ if (error instanceof DaemonRequestTimedOutError)+ return daemonTimedOutResult(paths, error.timeoutMs);+ return daemonUnreachableResult(paths, error);+}+function daemonCancelledResult(paths) {+ const text = [+ "LSP daemon request cancelled: the caller aborted this request (for example, the turn was interrupted).",+ "The daemon stays available; no LSP work was applied. Retry when you are ready.",+ `Socket: ${paths.socket}`,+ ].join("\n");+ return { content: [{ type: "text", text }], isError: true };+}+function daemonTimedOutResult(paths, timeoutMs) {+ const text = [+ `LSP daemon request timed out after ${timeoutMs}ms: the daemon did not respond in time.`,+ "The daemon stays available but may be busy. Retry when you are ready.",+ `Socket: ${paths.socket}`,+ `Logs: ${paths.log}`,+ ].join("\n");+ return { content: [{ type: "text", text }], isError: true };+}+function daemonUnreachableResult(paths, error) {+ const text = [+ `LSP daemon unreachable: ${errorText(error)}.`,+ "The MCP server is a thin proxy and never runs language servers in-process.",+ `Socket: ${paths.socket}`,+ `Logs: ${paths.log}`,+ "The daemon is auto-started on demand and will be retried on the next request.",+ ].join("\n");+ return { content: [{ type: "text", text }], isError: true };+}+function errorText(error) {+ return error instanceof Error ? error.message : String(error);+}diff --git a/plugins/omo/components/lsp-daemon/dist/daemon-request-error.d.ts b/plugins/omo/components/lsp-daemon/dist/daemon-request-error.d.tsnew file mode 100644index 00000000..8e3d09a9--- /dev/null+++ b/plugins/omo/components/lsp-daemon/dist/daemon-request-error.d.ts@@ -0,0 +1,14 @@+export declare class DaemonRequestError extends Error {+ readonly requestWritten: boolean;+ constructor(message: string, requestWritten: boolean);+}+export declare class DaemonAuthenticationRejectedError extends DaemonRequestError {+ constructor();+}+export declare class DaemonRequestCancelledError extends DaemonRequestError {+ constructor(requestWritten: boolean);+}+export declare class DaemonRequestTimedOutError extends DaemonRequestError {+ readonly timeoutMs: number;+ constructor(requestWritten: boolean, timeoutMs: number);+}diff --git a/plugins/omo/components/lsp-daemon/dist/daemon-request-error.js b/plugins/omo/components/lsp-daemon/dist/daemon-request-error.jsnew file mode 100644index 00000000..da2128c6--- /dev/null+++ b/plugins/omo/components/lsp-daemon/dist/daemon-request-error.js@@ -0,0 +1,26 @@+export class DaemonRequestError extends Error {+ constructor(message, requestWritten) {+ super(message);+ this.name = "DaemonRequestError";+ this.requestWritten = requestWritten;+ }+}+export class DaemonAuthenticationRejectedError extends DaemonRequestError {+ constructor() {+ super("daemon authentication failed before dispatch", true);+ this.name = "DaemonAuthenticationRejectedError";+ }+}+export class DaemonRequestCancelledError extends DaemonRequestError {+ constructor(requestWritten) {+ super("daemon request cancelled", requestWritten);+ this.name = "DaemonRequestCancelledError";+ }+}+export class DaemonRequestTimedOutError extends DaemonRequestError {+ constructor(requestWritten, timeoutMs) {+ super("daemon request timed out", requestWritten);+ this.name = "DaemonRequestTimedOutError";+ this.timeoutMs = timeoutMs;+ }+}diff --git a/plugins/omo/components/lsp-daemon/dist/daemon-server.js b/plugins/omo/components/lsp-daemon/dist/daemon-server.jsindex 820ceb6c..39558496 100644--- a/plugins/omo/components/lsp-daemon/dist/daemon-server.js+++ b/plugins/omo/components/lsp-daemon/dist/daemon-server.js@@ -1,11 +1,12 @@import { chmodSync } from "node:fs";import { createServer } from "node:net";import { disposeDefaultLspManager, getLspManager } from "@oh-my-opencode/lsp-core/lsp/manager";-import { setPrivateFileMode } from "./ipc-protocol.js";import { pingDaemon } from "./ensure-daemon.js";+import { setPrivateFileMode } from "./ipc-protocol.js";import { acquireStartupLease, DaemonStartupDeferredError, endpointIdentity, removeDaemonMetadataForOwner, writeDaemonOwner, } from "./ownership.js";import { handleDaemonMessage } from "./request-routing.js";import { createLineDecoder, encodeJsonLine } from "./socket-jsonrpc.js";+import { reapStaleDaemonVersions } from "./version-reap.js";export { DaemonAlreadyRunningError, DaemonStartupDeferredError } from "./ownership.js";const DEFAULT_IDLE_SHUTDOWN_MS = 30 * 60_000;const DEFAULT_IDLE_CHECK_INTERVAL_MS = 60_000;@@ -53,6 +54,9 @@ export async function startDaemonServer(paths, options = {}) {throw error;}lease.lock.release();+ // Best-effort cross-version reap: the daemon now owns its version, so older+ // sibling versions may be reaped. Never block or crash startup on failure.+ void reapStaleDaemonVersions(paths).catch((error) => logServerError(error));let closed = false;const close = async () => {if (closed)diff --git a/plugins/omo/components/lsp-daemon/dist/index.js b/plugins/omo/components/lsp-daemon/dist/index.jsindex 6aa963e6..4c15a879 100644--- a/plugins/omo/components/lsp-daemon/dist/index.js+++ b/plugins/omo/components/lsp-daemon/dist/index.js@@ -2613,8 +2613,13 @@ class LspClient extends LspClientConnection {if (!pushFallbackOnly)continue;const remainingMs = deadlineAt - Date.now();- if (remainingMs <= 0)+ if (remainingMs <= 0) {+ if (!this.isDiagnosticPullSupported() && snapshot.publishGeneration === 0) {+ const cached = this.documents.getPullCache(snapshot);+ return { items: cached === null ? [] : [...cached.diagnostics] };+ }return this.freshnessTimeout(absPath);+ }const waitMs = push.status === "wait" ? Math.min(push.waitMs, remainingMs) : remainingMs;await waitForDiagnosticsActivity(this.documents.waitForDiagnosticsActivity(snapshot, waitMs), signal);}@@ -3184,6 +3189,81 @@ function isPlainRecord(value) {return typeof value === "object" && value !== null && !Array.isArray(value);}+// src/daemon-request-error.ts+class DaemonRequestError extends Error {+ requestWritten;+ constructor(message, requestWritten) {+ super(message);+ this.name = "DaemonRequestError";+ this.requestWritten = requestWritten;+ }+}++class DaemonAuthenticationRejectedError extends DaemonRequestError {+ constructor() {+ super("daemon authentication failed before dispatch", true);+ this.name = "DaemonAuthenticationRejectedError";+ }+}++class DaemonRequestCancelledError extends DaemonRequestError {+ constructor(requestWritten) {+ super("daemon request cancelled", requestWritten);+ this.name = "DaemonRequestCancelledError";+ }+}++class DaemonRequestTimedOutError extends DaemonRequestError {+ timeoutMs;+ constructor(requestWritten, timeoutMs) {+ super("daemon request timed out", requestWritten);+ this.name = "DaemonRequestTimedOutError";+ this.timeoutMs = timeoutMs;+ }+}++// src/daemon-failure-result.ts+function daemonFailureResult(paths, error) {+ if (error instanceof DaemonRequestCancelledError)+ return daemonCancelledResult(paths);+ if (error instanceof DaemonRequestTimedOutError)+ return daemonTimedOutResult(paths, error.timeoutMs);+ return daemonUnreachableResult(paths, error);+}+function daemonCancelledResult(paths) {+ const text = [+ "LSP daemon request cancelled: the caller aborted this request (for example, the turn was interrupted).",+ "The daemon stays available; no LSP work was applied. Retry when you are ready.",+ `Socket: ${paths.socket}`+ ].join(`+`);+ return { content: [{ type: "text", text }], isError: true };+}+function daemonTimedOutResult(paths, timeoutMs) {+ const text = [+ `LSP daemon request timed out after ${timeoutMs}ms: the daemon did not respond in time.`,+ "The daemon stays available but may be busy. Retry when you are ready.",+ `Socket: ${paths.socket}`,+ `Logs: ${paths.log}`+ ].join(`+`);+ return { content: [{ type: "text", text }], isError: true };+}+function daemonUnreachableResult(paths, error) {+ const text = [+ `LSP daemon unreachable: ${errorText(error)}.`,+ "The MCP server is a thin proxy and never runs language servers in-process.",+ `Socket: ${paths.socket}`,+ `Logs: ${paths.log}`,+ "The daemon is auto-started on demand and will be retried on the next request."+ ].join(`+`);+ return { content: [{ type: "text", text }], isError: true };+}+function errorText(error) {+ return error instanceof Error ? error.message : String(error);+}+// src/ensure-daemon.tsimport { spawn as spawn2 } from "node:child_process";import { closeSync as closeSync2, mkdirSync as mkdirSync2, openSync as openSync2 } from "node:fs";@@ -3911,16 +3991,35 @@ function bufferFromChunk(chunk) {// ../mcp-stdio-core/src/server.tsvar DEFAULT_IDLE_TIMEOUT_MS = 10 * 60000;+var DEFAULT_PARENT_POLL_INTERVAL_MS = 30000;var noopLog = () => {};+function isProcessAlive(pid) {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return !hasErrorCode(error, "ESRCH");+ }+}async function runJsonRpcStdioServer(config) {const log = config.log ?? noopLog;const idleTimeoutMs = config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;- const idleTimer = createIdleTimer(idleTimeoutMs, log, config.onIdleTimeout);+ let isClosed = false;+ const idleTimer = createIdleTimer(idleTimeoutMs, log, () => {+ isClosed = true;+ config.onIdleTimeout?.();+ });+ const watchdog = createParentWatchdog(config.parentWatchdog, (parentPid, pollIntervalMs) => {+ isClosed = true;+ log("parent_exit", { parent_pid: parentPid, poll_interval_ms: pollIntervalMs });+ config.onParentExit?.();+ config.input.destroy();+ });log("stdio_started", { cwd: process.cwd(), idle_timeout_ms: idleTimeoutMs });idleTimer.arm();try {for await (const message of readStdioJsonRpcMessages(config.input)) {- if (idleTimer.closed())+ if (isClosed)break;idleTimer.arm();if (message.kind === "parse_error") {@@ -3931,8 +4030,12 @@ async function runJsonRpcStdioServer(config) {if (!await handleRequest(message, config, log))break;}+ } catch (error) {+ if (!(isClosed && hasErrorCode(error, "ERR_STREAM_PREMATURE_CLOSE")))+ throw error;} finally {idleTimer.clear();+ watchdog.clear();log("stdio_stopped");}}@@ -3988,9 +4091,33 @@ function isTerminalOutputError(error) {return false;return error.code === "EPIPE" || error.code === "ERR_STREAM_DESTROYED" || error.code === "ERR_STREAM_WRITE_AFTER_END";}-function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {+function hasErrorCode(error, code) {+ return error instanceof Error && "code" in error && error.code === code;+}+function createParentWatchdog(config, onDeadParent) {+ if (config === undefined)+ return { clear: () => {} };+ const pollIntervalMs = config.pollIntervalMs ?? DEFAULT_PARENT_POLL_INTERVAL_MS;+ if (pollIntervalMs <= 0)+ return { clear: () => {} };+ const parentPid = config.parentPid ?? process.ppid;+ const probeAlive = config.probeAlive ?? isProcessAlive;+ let fired = false;+ const timer = setInterval(() => {+ if (fired || probeAlive(parentPid))+ return;+ fired = true;+ onDeadParent(parentPid, pollIntervalMs);+ }, pollIntervalMs);+ timer.unref();+ return {+ clear: () => {+ clearInterval(timer);+ }+ };+}+function createIdleTimer(idleTimeoutMs, log, onTimeout) {let timer = null;- let isClosed = false;return {arm: () => {if (timer !== null)@@ -3998,9 +4125,8 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {if (idleTimeoutMs <= 0)return;timer = setTimeout(() => {- isClosed = true;log("idle_timeout", { idle_timeout_ms: idleTimeoutMs });- onIdleTimeout?.();+ onTimeout();}, idleTimeoutMs);timer.unref();},@@ -4009,8 +4135,7 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {return;clearTimeout(timer);timer = null;- },- closed: () => isClosed+ }};}// ../lsp-core/src/lsp/client-wrapper.ts@@ -5714,29 +5839,6 @@ function parseContext(value) {// src/daemon-client.tsvar DEFAULT_REQUEST_TIMEOUT_MS = 30000;var nextProxyRequestId = 1;--class DaemonRequestError extends Error {- requestWritten;- constructor(message, requestWritten) {- super(message);- this.name = "DaemonRequestError";- this.requestWritten = requestWritten;- }-}--class DaemonAuthenticationRejectedError extends DaemonRequestError {- constructor() {- super("daemon authentication failed before dispatch", true);- this.name = "DaemonAuthenticationRejectedError";- }-}--class DaemonRequestCancelledError extends DaemonRequestError {- constructor(requestWritten) {- super("daemon request cancelled", requestWritten);- this.name = "DaemonRequestCancelledError";- }-}async function callToolViaDaemon(name, args, options) {const context = requireContext(options.context);const paths = options.paths ?? daemonPaths();@@ -5765,7 +5867,7 @@ async function callToolViaDaemon(name, args, options) {break;}}- return daemonUnreachableResult(paths, lastError);+ return daemonFailureResult(paths, lastError);}function callDiagnosticsViaDaemon(filePath, options) {return callToolViaDaemon("diagnostics", { filePath, severity: "error" }, options);@@ -5810,17 +5912,6 @@ function ensureDaemonAvailable(paths, ensure, signal) {Promise.resolve().then(() => ensure(paths, signal)).then(() => finish(() => resolve9()), (error) => finish(() => reject(signal.aborted ? new DaemonRequestCancelledError(false) : error)));});}-function daemonUnreachableResult(paths, error) {- const text2 = [- `LSP daemon unreachable: ${errorText(error)}.`,- "The MCP server is a thin proxy and never runs language servers in-process.",- `Socket: ${paths.socket}`,- `Logs: ${paths.log}`,- "The daemon is auto-started on demand and will be retried on the next request."- ].join(`-`);- return { content: [{ type: "text", text: text2 }], isError: true };-}function sendToolCall(paths, token, name, args, options) {return new Promise((resolve9, reject) => {const socket = connect(paths.socket);@@ -5860,7 +5951,7 @@ function sendToolCall(paths, token, name, args, options) {};const timer = setTimeout(() => {sendCancel();- finish(() => reject(new DaemonRequestError("daemon request timed out", requestWritten)));+ finish(() => reject(new DaemonRequestTimedOutError(requestWritten, options.timeoutMs)));}, options.timeoutMs);timer.unref();if (options.signal?.aborted) {@@ -5919,9 +6010,6 @@ function allocateProxyRequestId() {function isRetryableTool(name) {return name !== "rename" && name !== "lsp_rename";}-function errorText(error) {- return error instanceof Error ? error.message : String(error);-}// src/proxy.tsimport { existsSync as existsSync11, realpathSync as realpathSync4 } from "node:fs";import { basename as basename3, delimiter as delimiter4, dirname as dirname9, isAbsolute as isAbsolute4 } from "node:path";@@ -5979,6 +6067,7 @@ async function runMcpStdioProxy(options = {}) {input,output,idleTimeoutMs: 0,+ parentWatchdog: options.parentWatchdog ?? {},handler: (request, requestOptions) => {clearStartupWatchdog();return runWithRequestContext(context, () => handleProxyRequest(request, requestOptions));diff --git a/plugins/omo/components/lsp-daemon/dist/proxy.d.ts b/plugins/omo/components/lsp-daemon/dist/proxy.d.tsindex 8cf2be26..76cc6af9 100644--- a/plugins/omo/components/lsp-daemon/dist/proxy.d.ts+++ b/plugins/omo/components/lsp-daemon/dist/proxy.d.ts@@ -1,4 +1,5 @@import type { Readable, Writable } from "node:stream";+import { type ParentWatchdogConfig } from "@oh-my-opencode/mcp-stdio-core";import { type CallToolOptions, type DaemonToolContext } from "./daemon-client.js";import { type DaemonPaths } from "./paths.js";export interface ProxyOptions {@@ -12,5 +13,6 @@ export interface ProxyOptions {homeDir?: string;ensure?: CallToolOptions["ensure"];startupTimeoutMs?: number;+ parentWatchdog?: ParentWatchdogConfig;}export declare function runMcpStdioProxy(options?: ProxyOptions): Promise<void>;diff --git a/plugins/omo/components/lsp-daemon/dist/proxy.js b/plugins/omo/components/lsp-daemon/dist/proxy.jsindex e4708d23..bb6b3e66 100644--- a/plugins/omo/components/lsp-daemon/dist/proxy.js+++ b/plugins/omo/components/lsp-daemon/dist/proxy.js@@ -59,6 +59,7 @@ export async function runMcpStdioProxy(options = {}) {input,output,idleTimeoutMs: 0,+ parentWatchdog: options.parentWatchdog ?? {},handler: (request, requestOptions) => {clearStartupWatchdog();return runWithRequestContext(context, () => handleProxyRequest(request, requestOptions));diff --git a/plugins/omo/components/lsp-daemon/dist/version-reap.d.ts b/plugins/omo/components/lsp-daemon/dist/version-reap.d.tsnew file mode 100644index 00000000..86d7ee11--- /dev/null+++ b/plugins/omo/components/lsp-daemon/dist/version-reap.d.ts@@ -0,0 +1,26 @@+import { type DaemonOwner } from "./ownership.js";+import { type DaemonPaths } from "./paths.js";+export interface DaemonCliAttestationDeps {+ readonly readProcFile?: (path: string) => Promise<Buffer>;+ readonly executeForStdout?: (file: string, args: readonly string[]) => Promise<string | null>;+}+export interface ReapStaleDaemonVersionsDeps {+ readonly platform?: NodeJS.Platform;+ readonly isAlive?: (pid: number) => boolean;+ readonly attest?: (pid: number, platform: NodeJS.Platform) => Promise<boolean>;+ readonly sendSignal?: (pid: number, signal: NodeJS.Signals) => boolean;+ readonly waitForExit?: (pid: number, timeoutMs: number) => Promise<boolean>;+ readonly removeDir?: (path: string) => Promise<void>;+ readonly readOwner?: (paths: DaemonPaths) => DaemonOwner | null;+ readonly log?: (message: string) => void;+ readonly termGraceMs?: number;+ readonly killGraceMs?: number;+}+export type VersionReapStatus = "terminated" | "removed" | "deferred" | "spared";+export interface VersionReapResult {+ readonly version: string;+ readonly status: VersionReapStatus;+ readonly reason: string;+}+export declare function attestDaemonCliProcess(pid: number, platform: NodeJS.Platform, deps?: DaemonCliAttestationDeps): Promise<boolean>;+export declare function reapStaleDaemonVersions(ownPaths: DaemonPaths, deps?: ReapStaleDaemonVersionsDeps): Promise<readonly VersionReapResult[]>;diff --git a/plugins/omo/components/lsp-daemon/dist/version-reap.js b/plugins/omo/components/lsp-daemon/dist/version-reap.jsnew file mode 100644index 00000000..f9a94405--- /dev/null+++ b/plugins/omo/components/lsp-daemon/dist/version-reap.js@@ -0,0 +1,182 @@+import { execFile } from "node:child_process";+import { readdir, readFile, rm } from "node:fs/promises";+import { basename, dirname, join } from "node:path";+import { isProcessAlive, readLockPid } from "./lock.js";+import { readDaemonOwner } from "./ownership.js";+import { daemonPaths, OMO_LSP_DAEMON_DIR } from "./paths.js";+const TERM_GRACE_MS = 5_000;+const KILL_GRACE_MS = 1_000;+const VERSION_ENTRY_PATTERN = /^v([A-Za-z0-9][A-Za-z0-9._+-]{0,127})$/;+export async function attestDaemonCliProcess(pid, platform, deps = {}) {+ if (platform === "win32")+ return false;+ if (platform === "linux") {+ const readProcFile = deps.readProcFile ?? defaultReadProcFile;+ const cmdline = await readProcFile(`/proc/${pid}/cmdline`).catch(() => null);+ if (cmdline === null)+ return false;+ return isNodeCliDaemonArgv(splitCmdline(cmdline));+ }+ const executeForStdout = deps.executeForStdout ?? defaultExecuteForStdout;+ const command = await executeForStdout("/bin/ps", ["-p", String(pid), "-o", "command="]);+ if (command === null)+ return false;+ return isNodeCliDaemonCommand(command.trim());+}+export async function reapStaleDaemonVersions(ownPaths, deps = {}) {+ const baseDir = dirname(ownPaths.dir);+ const platform = deps.platform ?? process.platform;+ const isAlive = deps.isAlive ?? isProcessAlive;+ const attest = deps.attest ?? ((pid) => attestDaemonCliProcess(pid, platform));+ const sendSignal = deps.sendSignal ?? defaultSendSignal;+ const waitForExit = deps.waitForExit ?? defaultWaitForExit;+ const removeDir = deps.removeDir ?? ((path) => rm(path, { recursive: true, force: true }));+ const readOwner = deps.readOwner ?? readDaemonOwner;+ const log = deps.log ?? defaultLog;+ const termGraceMs = deps.termGraceMs ?? TERM_GRACE_MS;+ const killGraceMs = deps.killGraceMs ?? KILL_GRACE_MS;+ const entries = await readdir(baseDir, { withFileTypes: true }).catch(() => []);+ const results = [];+ for (const entry of [...entries].sort((left, right) => left.name.localeCompare(right.name))) {+ if (entry.name === `v${ownPaths.version}`)+ continue;+ const version = parseVersionEntry(entry.name);+ if (version === null || !entry.isDirectory())+ continue;+ const versionDir = join(baseDir, entry.name);+ const siblingPaths = daemonPaths({ [OMO_LSP_DAEMON_DIR]: baseDir }, { cliPath: ownPaths.cliPath, version });+ results.push(await reapOneVersion({+ version,+ versionDir,+ siblingPaths,+ platform,+ isAlive,+ attest,+ sendSignal,+ waitForExit,+ removeDir,+ readOwner,+ log,+ termGraceMs,+ killGraceMs,+ }));+ }+ return results;+}+async function reapOneVersion(context) {+ const { version, versionDir } = context;+ const owner = context.readOwner(context.siblingPaths);+ if (!owner) {+ const lockPid = readLockPid(join(versionDir, "daemon.lock"));+ if (lockPid !== null && context.isAlive(lockPid)) {+ context.log(`reap: sparing v${version}: owner metadata missing but daemon.lock is held by live pid ${lockPid}`);+ return { version, status: "spared", reason: `owner metadata missing but lock held by live pid ${lockPid}` };+ }+ await context.removeDir(versionDir);+ return { version, status: "removed", reason: "removed stale version dir without readable owner metadata" };+ }+ if (!context.isAlive(owner.pid)) {+ await context.removeDir(versionDir);+ return { version, status: "removed", reason: `removed stale version dir for dead owner pid ${owner.pid}` };+ }+ if (context.platform === "win32") {+ context.log(`reap: deferring v${version}: Windows cannot prove pid ownership safely (named-pipe policy)`);+ return {+ version,+ status: "deferred",+ reason: "Windows cannot prove pid ownership safely; named-pipe reap deferred",+ };+ }+ if (!(await context.attest(owner.pid, context.platform))) {+ context.log(`reap: sparing v${version}: pid ${owner.pid} is alive but cmdline attestation failed (possible recycled pid)`);+ return {+ version,+ status: "spared",+ reason: `pid ${owner.pid} attestation failed; possible recycled pid`,+ };+ }+ return await terminateAttestedOwner(context, owner.pid);+}+async function terminateAttestedOwner(context, pid) {+ const { version, versionDir } = context;+ if (!context.sendSignal(pid, "SIGTERM")) {+ await context.removeDir(versionDir);+ return {+ version,+ status: "removed",+ reason: `owner pid ${pid} exited before SIGTERM; removed stale version dir`,+ };+ }+ if (await context.waitForExit(pid, context.termGraceMs)) {+ await context.removeDir(versionDir);+ return { version, status: "terminated", reason: `terminated attested older daemon pid ${pid} with SIGTERM` };+ }+ context.log(`reap: v${version} pid ${pid} survived SIGTERM; escalating to SIGKILL`);+ if (!context.sendSignal(pid, "SIGKILL") || !(await context.waitForExit(pid, context.killGraceMs))) {+ context.log(`reap: deferring v${version}: pid ${pid} survived SIGKILL`);+ return { version, status: "deferred", reason: `attested daemon pid ${pid} survived SIGKILL; dir kept` };+ }+ await context.removeDir(versionDir);+ return {+ version,+ status: "terminated",+ reason: `terminated attested older daemon pid ${pid} after SIGKILL escalation`,+ };+}+function parseVersionEntry(entryName) {+ const match = VERSION_ENTRY_PATTERN.exec(entryName);+ return match?.[1] ?? null;+}+function splitCmdline(buffer) {+ return buffer+ .toString("utf8")+ .split("\u0000")+ .filter((value) => value.length > 0);+}+function isNodeCliDaemonArgv(argv) {+ if (argv.length < 2 || !argv.includes("daemon"))+ return false;+ const executable = basename(argv[0] ?? "");+ if (!/^node(?:\.exe)?$/i.test(executable))+ return false;+ return argv.some((value) => value === "cli.js" || value.endsWith("/cli.js") || value.endsWith("\\cli.js"));+}+function isNodeCliDaemonCommand(command) {+ return /\bnode(?:\.exe)?\b/i.test(command) && /\bcli\.js\b/.test(command) && /\bdaemon\b/.test(command);+}+function defaultReadProcFile(path) {+ return readFile(path);+}+function defaultExecuteForStdout(file, args) {+ return new Promise((resolve) => {+ execFile(file, [...args], { encoding: "utf8", maxBuffer: 1024 * 1024, timeout: 1_000 }, (error, stdout) => {+ if (error !== null) {+ resolve(null);+ return;+ }+ resolve(stdout);+ });+ });+}+function defaultSendSignal(pid, signal) {+ try {+ process.kill(pid, signal);+ return true;+ }+ catch {+ return false;+ }+}+async function defaultWaitForExit(pid, timeoutMs) {+ const deadline = Date.now() + timeoutMs;+ for (;;) {+ if (!isProcessAlive(pid))+ return true;+ if (Date.now() >= deadline)+ return false;+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+}+function defaultLog(message) {+ process.stderr.write(`[lsp-daemon] ${message}\n`);+}diff --git a/plugins/omo/components/lsp-tools-mcp/dist/cli.js b/plugins/omo/components/lsp-tools-mcp/dist/cli.jsindex 0bb8057d..f0ca161b 100755--- a/plugins/omo/components/lsp-tools-mcp/dist/cli.js+++ b/plugins/omo/components/lsp-tools-mcp/dist/cli.js@@ -2615,8 +2615,13 @@ class LspClient extends LspClientConnection {if (!pushFallbackOnly)continue;const remainingMs = deadlineAt - Date.now();- if (remainingMs <= 0)+ if (remainingMs <= 0) {+ if (!this.isDiagnosticPullSupported() && snapshot.publishGeneration === 0) {+ const cached = this.documents.getPullCache(snapshot);+ return { items: cached === null ? [] : [...cached.diagnostics] };+ }return this.freshnessTimeout(absPath);+ }const waitMs = push.status === "wait" ? Math.min(push.waitMs, remainingMs) : remainingMs;await waitForDiagnosticsActivity(this.documents.waitForDiagnosticsActivity(snapshot, waitMs), signal);}@@ -3167,16 +3172,35 @@ function bufferFromChunk(chunk) {// ../mcp-stdio-core/src/server.tsvar DEFAULT_IDLE_TIMEOUT_MS = 10 * 60000;+var DEFAULT_PARENT_POLL_INTERVAL_MS = 30000;var noopLog = () => {};+function isProcessAlive(pid) {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return !hasErrorCode(error, "ESRCH");+ }+}async function runJsonRpcStdioServer(config) {const log = config.log ?? noopLog;const idleTimeoutMs = config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;- const idleTimer = createIdleTimer(idleTimeoutMs, log, config.onIdleTimeout);+ let isClosed = false;+ const idleTimer = createIdleTimer(idleTimeoutMs, log, () => {+ isClosed = true;+ config.onIdleTimeout?.();+ });+ const watchdog = createParentWatchdog(config.parentWatchdog, (parentPid, pollIntervalMs) => {+ isClosed = true;+ log("parent_exit", { parent_pid: parentPid, poll_interval_ms: pollIntervalMs });+ config.onParentExit?.();+ config.input.destroy();+ });log("stdio_started", { cwd: process.cwd(), idle_timeout_ms: idleTimeoutMs });idleTimer.arm();try {for await (const message of readStdioJsonRpcMessages(config.input)) {- if (idleTimer.closed())+ if (isClosed)break;idleTimer.arm();if (message.kind === "parse_error") {@@ -3187,8 +3211,12 @@ async function runJsonRpcStdioServer(config) {if (!await handleRequest(message, config, log))break;}+ } catch (error) {+ if (!(isClosed && hasErrorCode(error, "ERR_STREAM_PREMATURE_CLOSE")))+ throw error;} finally {idleTimer.clear();+ watchdog.clear();log("stdio_stopped");}}@@ -3244,9 +3272,33 @@ function isTerminalOutputError(error) {return false;return error.code === "EPIPE" || error.code === "ERR_STREAM_DESTROYED" || error.code === "ERR_STREAM_WRITE_AFTER_END";}-function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {+function hasErrorCode(error, code) {+ return error instanceof Error && "code" in error && error.code === code;+}+function createParentWatchdog(config, onDeadParent) {+ if (config === undefined)+ return { clear: () => {} };+ const pollIntervalMs = config.pollIntervalMs ?? DEFAULT_PARENT_POLL_INTERVAL_MS;+ if (pollIntervalMs <= 0)+ return { clear: () => {} };+ const parentPid = config.parentPid ?? process.ppid;+ const probeAlive = config.probeAlive ?? isProcessAlive;+ let fired = false;+ const timer = setInterval(() => {+ if (fired || probeAlive(parentPid))+ return;+ fired = true;+ onDeadParent(parentPid, pollIntervalMs);+ }, pollIntervalMs);+ timer.unref();+ return {+ clear: () => {+ clearInterval(timer);+ }+ };+}+function createIdleTimer(idleTimeoutMs, log, onTimeout) {let timer = null;- let isClosed = false;return {arm: () => {if (timer !== null)@@ -3254,9 +3306,8 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {if (idleTimeoutMs <= 0)return;timer = setTimeout(() => {- isClosed = true;log("idle_timeout", { idle_timeout_ms: idleTimeoutMs });- onIdleTimeout?.();+ onTimeout();}, idleTimeoutMs);timer.unref();},@@ -3265,8 +3316,7 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {return;clearTimeout(timer);timer = null;- },- closed: () => isClosed+ }};}// ../lsp-core/src/lsp/client-wrapper.ts@@ -5027,12 +5077,13 @@ async function handleLspMcpRequest(input, options = {}) {}return errorResponse(id, -32601, `Method not found: ${String(method)}`);}-async function runMcpStdioServer(input = process.stdin, output = process.stdout) {+async function runMcpStdioServer(input = process.stdin, output = process.stdout, options = {}) {const requestContext = createStandaloneMcpRequestContext();await runJsonRpcStdioServer({input,output,idleTimeoutMs: 0,+ parentWatchdog: options.parentWatchdog ?? {},handler: (request) => runWithRequestContext(requestContext, () => handleLspMcpRequest(request)),handlerOptions: undefined});diff --git a/plugins/omo/components/lsp-tools-mcp/dist/lsp/manager.js b/plugins/omo/components/lsp-tools-mcp/dist/lsp/manager.jsindex e0354e4f..ddd2fe02 100644--- a/plugins/omo/components/lsp-tools-mcp/dist/lsp/manager.js+++ b/plugins/omo/components/lsp-tools-mcp/dist/lsp/manager.js@@ -2613,8 +2613,13 @@ class LspClient extends LspClientConnection {if (!pushFallbackOnly)continue;const remainingMs = deadlineAt - Date.now();- if (remainingMs <= 0)+ if (remainingMs <= 0) {+ if (!this.isDiagnosticPullSupported() && snapshot.publishGeneration === 0) {+ const cached = this.documents.getPullCache(snapshot);+ return { items: cached === null ? [] : [...cached.diagnostics] };+ }return this.freshnessTimeout(absPath);+ }const waitMs = push.status === "wait" ? Math.min(push.waitMs, remainingMs) : remainingMs;await waitForDiagnosticsActivity(this.documents.waitForDiagnosticsActivity(snapshot, waitMs), signal);}diff --git a/plugins/omo/components/lsp-tools-mcp/dist/mcp.js b/plugins/omo/components/lsp-tools-mcp/dist/mcp.jsindex d6791ba7..33383c48 100644--- a/plugins/omo/components/lsp-tools-mcp/dist/mcp.js+++ b/plugins/omo/components/lsp-tools-mcp/dist/mcp.js@@ -158,16 +158,35 @@ function bufferFromChunk(chunk) {// ../mcp-stdio-core/src/server.tsvar DEFAULT_IDLE_TIMEOUT_MS = 10 * 60000;+var DEFAULT_PARENT_POLL_INTERVAL_MS = 30000;var noopLog = () => {};+function isProcessAlive(pid) {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return !hasErrorCode(error, "ESRCH");+ }+}async function runJsonRpcStdioServer(config) {const log = config.log ?? noopLog;const idleTimeoutMs = config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;- const idleTimer = createIdleTimer(idleTimeoutMs, log, config.onIdleTimeout);+ let isClosed = false;+ const idleTimer = createIdleTimer(idleTimeoutMs, log, () => {+ isClosed = true;+ config.onIdleTimeout?.();+ });+ const watchdog = createParentWatchdog(config.parentWatchdog, (parentPid, pollIntervalMs) => {+ isClosed = true;+ log("parent_exit", { parent_pid: parentPid, poll_interval_ms: pollIntervalMs });+ config.onParentExit?.();+ config.input.destroy();+ });log("stdio_started", { cwd: process.cwd(), idle_timeout_ms: idleTimeoutMs });idleTimer.arm();try {for await (const message of readStdioJsonRpcMessages(config.input)) {- if (idleTimer.closed())+ if (isClosed)break;idleTimer.arm();if (message.kind === "parse_error") {@@ -178,8 +197,12 @@ async function runJsonRpcStdioServer(config) {if (!await handleRequest(message, config, log))break;}+ } catch (error) {+ if (!(isClosed && hasErrorCode(error, "ERR_STREAM_PREMATURE_CLOSE")))+ throw error;} finally {idleTimer.clear();+ watchdog.clear();log("stdio_stopped");}}@@ -235,9 +258,33 @@ function isTerminalOutputError(error) {return false;return error.code === "EPIPE" || error.code === "ERR_STREAM_DESTROYED" || error.code === "ERR_STREAM_WRITE_AFTER_END";}-function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {+function hasErrorCode(error, code) {+ return error instanceof Error && "code" in error && error.code === code;+}+function createParentWatchdog(config, onDeadParent) {+ if (config === undefined)+ return { clear: () => {} };+ const pollIntervalMs = config.pollIntervalMs ?? DEFAULT_PARENT_POLL_INTERVAL_MS;+ if (pollIntervalMs <= 0)+ return { clear: () => {} };+ const parentPid = config.parentPid ?? process.ppid;+ const probeAlive = config.probeAlive ?? isProcessAlive;+ let fired = false;+ const timer = setInterval(() => {+ if (fired || probeAlive(parentPid))+ return;+ fired = true;+ onDeadParent(parentPid, pollIntervalMs);+ }, pollIntervalMs);+ timer.unref();+ return {+ clear: () => {+ clearInterval(timer);+ }+ };+}+function createIdleTimer(idleTimeoutMs, log, onTimeout) {let timer = null;- let isClosed = false;return {arm: () => {if (timer !== null)@@ -245,9 +292,8 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {if (idleTimeoutMs <= 0)return;timer = setTimeout(() => {- isClosed = true;log("idle_timeout", { idle_timeout_ms: idleTimeoutMs });- onIdleTimeout?.();+ onTimeout();}, idleTimeoutMs);timer.unref();},@@ -256,8 +302,7 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {return;clearTimeout(timer);timer = null;- },- closed: () => isClosed+ }};}// ../lsp-core/src/lsp/client-wrapper.ts@@ -3058,8 +3103,13 @@ class LspClient extends LspClientConnection {if (!pushFallbackOnly)continue;const remainingMs = deadlineAt - Date.now();- if (remainingMs <= 0)+ if (remainingMs <= 0) {+ if (!this.isDiagnosticPullSupported() && snapshot.publishGeneration === 0) {+ const cached = this.documents.getPullCache(snapshot);+ return { items: cached === null ? [] : [...cached.diagnostics] };+ }return this.freshnessTimeout(absPath);+ }const waitMs = push.status === "wait" ? Math.min(push.waitMs, remainingMs) : remainingMs;await waitForDiagnosticsActivity(this.documents.waitForDiagnosticsActivity(snapshot, waitMs), signal);}@@ -5026,12 +5076,13 @@ async function handleLspMcpRequest(input, options = {}) {}return errorResponse(id, -32601, `Method not found: ${String(method)}`);}-async function runMcpStdioServer(input = process.stdin, output = process.stdout) {+async function runMcpStdioServer(input = process.stdin, output = process.stdout, options = {}) {const requestContext = createStandaloneMcpRequestContext();await runJsonRpcStdioServer({input,output,idleTimeoutMs: 0,+ parentWatchdog: options.parentWatchdog ?? {},handler: (request) => runWithRequestContext(requestContext, () => handleLspMcpRequest(request)),handlerOptions: undefined});diff --git a/plugins/omo/components/lsp-tools-mcp/dist/tools.js b/plugins/omo/components/lsp-tools-mcp/dist/tools.jsindex d29e1e46..34e61470 100644--- a/plugins/omo/components/lsp-tools-mcp/dist/tools.js+++ b/plugins/omo/components/lsp-tools-mcp/dist/tools.js@@ -2796,8 +2796,13 @@ class LspClient extends LspClientConnection {if (!pushFallbackOnly)continue;const remainingMs = deadlineAt - Date.now();- if (remainingMs <= 0)+ if (remainingMs <= 0) {+ if (!this.isDiagnosticPullSupported() && snapshot.publishGeneration === 0) {+ const cached = this.documents.getPullCache(snapshot);+ return { items: cached === null ? [] : [...cached.diagnostics] };+ }return this.freshnessTimeout(absPath);+ }const waitMs = push.status === "wait" ? Math.min(push.waitMs, remainingMs) : remainingMs;await waitForDiagnosticsActivity(this.documents.waitForDiagnosticsActivity(snapshot, waitMs), signal);}diff --git a/plugins/omo/components/lsp/.gitignore b/plugins/omo/components/lsp/.gitignoredeleted file mode 100644index 1bf09f16..00000000--- a/plugins/omo/components/lsp/.gitignore+++ /dev/null@@ -1,6 +0,0 @@-node_modules/-*.log-.env-.DS_Store-coverage/-.vitest/diff --git a/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json b/plugins/omo/components/lsp/dist/.omo-runtime-manifest.jsonindex d9325456..1f539014 100644--- a/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json+++ b/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json@@ -1,7 +1,7 @@{"schemaVersion": 1,- "version": "4.19.0",- "inputDigest": "sha256:1c26ab90eb222f050b468e7088ee9e655d0db850605ab425e8636c089a910f79",+ "version": "4.19.1",+ "inputDigest": "sha256:b64d94982c0d046c8e6ab9bf7628f1f18be57ac6418179257b2fda95228dc38a","outputs": [{"path": "cli.d.ts",@@ -9,7 +9,7 @@},{"path": "cli.js",- "sha256": "e92c3fee5795bf44de9504b0e85c2be208c78a31e966ec9a7a807d621431c74a"+ "sha256": "f46b15e830f85d0d6f46e0b36c726de2fd56adc43b1cd4660430db86352a8f37"},{"path": "codex-hook-cli.d.ts",diff --git a/plugins/omo/components/lsp/dist/cli.js b/plugins/omo/components/lsp/dist/cli.jsindex 5f3426c0..15a74762 100644--- a/plugins/omo/components/lsp/dist/cli.js+++ b/plugins/omo/components/lsp/dist/cli.js@@ -212,6 +212,78 @@ function errorCode(error) {function isPlainRecord(value) {return typeof value === "object" && value !== null && !Array.isArray(value);}++class DaemonRequestError extends Error {+ requestWritten;+ constructor(message, requestWritten) {+ super(message);+ this.name = "DaemonRequestError";+ this.requestWritten = requestWritten;+ }+}++class DaemonAuthenticationRejectedError extends DaemonRequestError {+ constructor() {+ super("daemon authentication failed before dispatch", true);+ this.name = "DaemonAuthenticationRejectedError";+ }+}++class DaemonRequestCancelledError extends DaemonRequestError {+ constructor(requestWritten) {+ super("daemon request cancelled", requestWritten);+ this.name = "DaemonRequestCancelledError";+ }+}++class DaemonRequestTimedOutError extends DaemonRequestError {+ timeoutMs;+ constructor(requestWritten, timeoutMs) {+ super("daemon request timed out", requestWritten);+ this.name = "DaemonRequestTimedOutError";+ this.timeoutMs = timeoutMs;+ }+}+function daemonFailureResult(paths, error) {+ if (error instanceof DaemonRequestCancelledError)+ return daemonCancelledResult(paths);+ if (error instanceof DaemonRequestTimedOutError)+ return daemonTimedOutResult(paths, error.timeoutMs);+ return daemonUnreachableResult(paths, error);+}+function daemonCancelledResult(paths) {+ const text = [+ "LSP daemon request cancelled: the caller aborted this request (for example, the turn was interrupted).",+ "The daemon stays available; no LSP work was applied. Retry when you are ready.",+ `Socket: ${paths.socket}`+ ].join(`+`);+ return { content: [{ type: "text", text }], isError: true };+}+function daemonTimedOutResult(paths, timeoutMs) {+ const text = [+ `LSP daemon request timed out after ${timeoutMs}ms: the daemon did not respond in time.`,+ "The daemon stays available but may be busy. Retry when you are ready.",+ `Socket: ${paths.socket}`,+ `Logs: ${paths.log}`+ ].join(`+`);+ return { content: [{ type: "text", text }], isError: true };+}+function daemonUnreachableResult(paths, error) {+ const text = [+ `LSP daemon unreachable: ${errorText(error)}.`,+ "The MCP server is a thin proxy and never runs language servers in-process.",+ `Socket: ${paths.socket}`,+ `Logs: ${paths.log}`,+ "The daemon is auto-started on demand and will be retried on the next request."+ ].join(`+`);+ return { content: [{ type: "text", text }], isError: true };+}+function errorText(error) {+ return error instanceof Error ? error.message : String(error);+}var OMO_DAEMON_PROTOCOL_VERSION = 1;var AUTH_ERROR_CODE = -32001;function authEnvelope(token) {@@ -3134,8 +3206,13 @@ class LspClient extends LspClientConnection {if (!pushFallbackOnly)continue;const remainingMs = deadlineAt - Date.now();- if (remainingMs <= 0)+ if (remainingMs <= 0) {+ if (!this.isDiagnosticPullSupported() && snapshot.publishGeneration === 0) {+ const cached = this.documents.getPullCache(snapshot);+ return { items: cached === null ? [] : [...cached.diagnostics] };+ }return this.freshnessTimeout(absPath);+ }const waitMs = push.status === "wait" ? Math.min(push.waitMs, remainingMs) : remainingMs;await waitForDiagnosticsActivity(this.documents.waitForDiagnosticsActivity(snapshot, waitMs), signal);}@@ -4995,29 +5072,6 @@ var LSP_MCP_TOOLS = [var CONTEXT_KEY = "_context";var DEFAULT_REQUEST_TIMEOUT_MS = 30000;var nextProxyRequestId = 1;--class DaemonRequestError extends Error {- requestWritten;- constructor(message, requestWritten) {- super(message);- this.name = "DaemonRequestError";- this.requestWritten = requestWritten;- }-}--class DaemonAuthenticationRejectedError extends DaemonRequestError {- constructor() {- super("daemon authentication failed before dispatch", true);- this.name = "DaemonAuthenticationRejectedError";- }-}--class DaemonRequestCancelledError extends DaemonRequestError {- constructor(requestWritten) {- super("daemon request cancelled", requestWritten);- this.name = "DaemonRequestCancelledError";- }-}async function callToolViaDaemon(name, args, options) {const context = requireContext(options.context);const paths = options.paths ?? daemonPaths();@@ -5046,7 +5100,7 @@ async function callToolViaDaemon(name, args, options) {break;}}- return daemonUnreachableResult(paths, lastError);+ return daemonFailureResult(paths, lastError);}function callDiagnosticsViaDaemon(filePath, options) {return callToolViaDaemon("diagnostics", { filePath, severity: "error" }, options);@@ -5080,17 +5134,6 @@ function ensureDaemonAvailable(paths, ensure, signal) {Promise.resolve().then(() => ensure(paths, signal)).then(() => finish(() => resolve9()), (error) => finish(() => reject(signal.aborted ? new DaemonRequestCancelledError(false) : error)));});}-function daemonUnreachableResult(paths, error) {- const text2 = [- `LSP daemon unreachable: ${errorText(error)}.`,- "The MCP server is a thin proxy and never runs language servers in-process.",- `Socket: ${paths.socket}`,- `Logs: ${paths.log}`,- "The daemon is auto-started on demand and will be retried on the next request."- ].join(`-`);- return { content: [{ type: "text", text: text2 }], isError: true };-}function sendToolCall(paths, token, name, args, options) {return new Promise((resolve9, reject) => {const socket = connect(paths.socket);@@ -5130,7 +5173,7 @@ function sendToolCall(paths, token, name, args, options) {};const timer = setTimeout(() => {sendCancel();- finish(() => reject(new DaemonRequestError("daemon request timed out", requestWritten)));+ finish(() => reject(new DaemonRequestTimedOutError(requestWritten, options.timeoutMs)));}, options.timeoutMs);timer.unref();if (options.signal?.aborted) {@@ -5189,9 +5232,6 @@ function allocateProxyRequestId() {function isRetryableTool(name) {return name !== "rename" && name !== "lsp_rename";}-function errorText(error) {- return error instanceof Error ? error.message : String(error);-}var OMO_LSP_DAEMON_CLI2 = "OMO_LSP_DAEMON_CLI";var OMO_LSP_DAEMON_VERSION2 = "OMO_LSP_DAEMON_VERSION";var DAEMON_VERSION_PATTERN2 = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;diff --git a/plugins/omo/components/lsp/hooks/hooks.json b/plugins/omo/components/lsp/hooks/hooks.jsonindex 7ada60d1..14ada225 100644--- a/plugins/omo/components/lsp/hooks/hooks.json+++ b/plugins/omo/components/lsp/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use","timeout": 60,- "statusMessage": "(OmO 4.19.0) Checking LSP Diagnostics"+ "statusMessage": "(OmO 4.19.1) Checking LSP Diagnostics"}]}@@ -21,7 +21,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact","timeout": 5,- "statusMessage": "(OmO 4.19.0) Resetting LSP Diagnostics Cache"+ "statusMessage": "(OmO 4.19.1) Resetting LSP Diagnostics Cache"}]}diff --git a/plugins/omo/components/lsp/package.json b/plugins/omo/components/lsp/package.jsonindex 58f9f216..f0f606b5 100644--- a/plugins/omo/components/lsp/package.json+++ b/plugins/omo/components/lsp/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-lsp",- "version": "4.19.0",+ "version": "4.19.1","description": "Codex plugin that exposes Language Server Protocol tools and post-edit diagnostics.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/rules/.gitignore b/plugins/omo/components/rules/.gitignoredeleted file mode 100644index bc848922..00000000--- a/plugins/omo/components/rules/.gitignore+++ /dev/null@@ -1,6 +0,0 @@-node_modules/-.DS_Store-*.log-coverage/-.vitest/-*.tgzdiff --git a/plugins/omo/components/rules/dist/cli.js b/plugins/omo/components/rules/dist/cli.jsindex beeddaf1..16f7220b 100755--- a/plugins/omo/components/rules/dist/cli.js+++ b/plugins/omo/components/rules/dist/cli.js@@ -3854,6 +3854,17 @@ var POST_COMPACT_MIN_RESERVED_TOKENS = 8000;var POST_COMPACT_MIN_GUIDE_CHARS = 500;var FALLBACK_CONTEXT_WINDOW_TOKENS = 200000;var MODEL_CONTEXT_BUDGETS = [+ { slug: "gpt-5.6-sol", contextWindowTokens: 372000, effectivePercent: DEFAULT_EFFECTIVE_CONTEXT_WINDOW_PERCENT },+ {+ slug: "gpt-5.6-terra",+ contextWindowTokens: 372000,+ effectivePercent: DEFAULT_EFFECTIVE_CONTEXT_WINDOW_PERCENT+ },+ {+ slug: "gpt-5.6-luna",+ contextWindowTokens: 372000,+ effectivePercent: DEFAULT_EFFECTIVE_CONTEXT_WINDOW_PERCENT+ },{ slug: "gpt-5.5", contextWindowTokens: 272000, effectivePercent: DEFAULT_EFFECTIVE_CONTEXT_WINDOW_PERCENT },{ slug: "gpt-5.4-mini", contextWindowTokens: 272000, effectivePercent: DEFAULT_EFFECTIVE_CONTEXT_WINDOW_PERCENT },{diff --git a/plugins/omo/components/rules/hooks/hooks.json b/plugins/omo/components/rules/hooks/hooks.jsonindex a3caca33..3bb70c30 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": "(OmO 4.19.0) Loading Project Rules"+ "statusMessage": "(OmO 4.19.1) Loading Project Rules"}]}@@ -19,7 +19,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit","timeout": 10,- "statusMessage": "(OmO 4.19.0) Loading Project Rules"+ "statusMessage": "(OmO 4.19.1) Loading Project Rules"}]}@@ -32,7 +32,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use","timeout": 10,- "statusMessage": "(OmO 4.19.0) Matching Project Rules"+ "statusMessage": "(OmO 4.19.1) Matching Project Rules"}]}@@ -45,7 +45,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact","timeout": 10,- "statusMessage": "(OmO 4.19.0) Resetting Project Rule Cache"+ "statusMessage": "(OmO 4.19.1) Resetting Project Rule Cache"}]}diff --git a/plugins/omo/components/rules/package.json b/plugins/omo/components/rules/package.jsonindex 9406d70c..f891e0f8 100644--- a/plugins/omo/components/rules/package.json+++ b/plugins/omo/components/rules/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-rules",- "version": "4.19.0",+ "version": "4.19.1","description": "Codex plugin that injects project rule files into model context through lifecycle hooks.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/rules/src/post-compact-budget.ts b/plugins/omo/components/rules/src/post-compact-budget.tsindex d4b53c24..bbda8a0c 100644--- a/plugins/omo/components/rules/src/post-compact-budget.ts+++ b/plugins/omo/components/rules/src/post-compact-budget.ts@@ -21,6 +21,17 @@ 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.6-sol", contextWindowTokens: 372_000, effectivePercent: DEFAULT_EFFECTIVE_CONTEXT_WINDOW_PERCENT },+ {+ slug: "gpt-5.6-terra",+ contextWindowTokens: 372_000,+ effectivePercent: DEFAULT_EFFECTIVE_CONTEXT_WINDOW_PERCENT,+ },+ {+ slug: "gpt-5.6-luna",+ contextWindowTokens: 372_000,+ effectivePercent: DEFAULT_EFFECTIVE_CONTEXT_WINDOW_PERCENT,+ },{ slug: "gpt-5.5", contextWindowTokens: 272_000, effectivePercent: DEFAULT_EFFECTIVE_CONTEXT_WINDOW_PERCENT },{ slug: "gpt-5.4-mini", contextWindowTokens: 272_000, effectivePercent: DEFAULT_EFFECTIVE_CONTEXT_WINDOW_PERCENT },{diff --git a/plugins/omo/components/rules/test/post-compact-budget.test.ts b/plugins/omo/components/rules/test/post-compact-budget.test.tsindex 3a955b2f..2ceb29b8 100644--- a/plugins/omo/components/rules/test/post-compact-budget.test.ts+++ b/plugins/omo/components/rules/test/post-compact-budget.test.ts@@ -76,6 +76,66 @@ describe("post-compact context budget", () => {expect(budget.maxRuleChars).toBeLessThanOrEqual(budget.maxResultChars);});+ it("#given gpt-5.6-sol within its 372k window #when resolving post-compact budget #then keeps configured post-compact cap", () => {+ // given+ const transcriptPath = writeCompactedTranscript("A".repeat(541_500));++ // when+ const budget = withPostCompactBudget(CONFIG, { model: "gpt-5.6-sol", transcriptPath });++ // then+ expect(budget.maxRuleChars).toBe(CONFIG.postCompactMaxRuleChars);+ expect(budget.maxResultChars).toBe(CONFIG.postCompactMaxResultChars);+ });++ it("#given gpt-5.6-terra within its 372k window #when resolving post-compact budget #then keeps configured post-compact cap", () => {+ // given+ const transcriptPath = writeCompactedTranscript("A".repeat(541_500));++ // when+ const budget = withPostCompactBudget(CONFIG, { model: "gpt-5.6-terra", transcriptPath });++ // then+ expect(budget.maxRuleChars).toBe(CONFIG.postCompactMaxRuleChars);+ expect(budget.maxResultChars).toBe(CONFIG.postCompactMaxResultChars);+ });++ it("#given gpt-5.6-luna within its 372k window #when resolving post-compact budget #then keeps configured post-compact cap", () => {+ // given+ const transcriptPath = writeCompactedTranscript("A".repeat(541_500));++ // when+ const budget = withPostCompactBudget(CONFIG, { model: "gpt-5.6-luna", transcriptPath });++ // then+ expect(budget.maxRuleChars).toBe(CONFIG.postCompactMaxRuleChars);+ expect(budget.maxResultChars).toBe(CONFIG.postCompactMaxResultChars);+ });++ it("#given provider-prefixed gpt-5.6 variant within its 372k window #when resolving post-compact budget #then keeps configured post-compact cap", () => {+ // given+ const transcriptPath = writeCompactedTranscript("A".repeat(541_500));++ // when+ const budget = withPostCompactBudget(CONFIG, { model: "openai/gpt-5.6-sol", transcriptPath });++ // then+ expect(budget.maxRuleChars).toBe(CONFIG.postCompactMaxRuleChars);+ expect(budget.maxResultChars).toBe(CONFIG.postCompactMaxResultChars);+ });++ it("#given unknown model with the same transcript #when resolving post-compact budget #then keeps the 200k fallback floor", () => {+ // given+ const transcriptPath = writeCompactedTranscript("A".repeat(541_500));++ // when+ const budget = withPostCompactBudget(CONFIG, { model: "unknown-model", transcriptPath });++ // then+ expect(budget.maxResultChars).toBe(500);+ expect(budget.maxRuleChars).toBe(500);+ });+it("#given context pressure marker after compaction #when resolving post-compact budget #then shrinks projected rule injection", () => {// givenconst transcriptPath = writeCompactedPressureTranscript("small compacted summary");diff --git a/plugins/omo/components/start-work-continuation/.gitignore b/plugins/omo/components/start-work-continuation/.gitignoredeleted file mode 100644index 746087d3..00000000--- a/plugins/omo/components/start-work-continuation/.gitignore+++ /dev/null@@ -1,3 +0,0 @@-dist/-node_modules/-*.logdiff --git a/plugins/omo/components/start-work-continuation/dist/cli.js b/plugins/omo/components/start-work-continuation/dist/cli.jsnew file mode 100755index 00000000..f33460ce--- /dev/null+++ b/plugins/omo/components/start-work-continuation/dist/cli.js@@ -0,0 +1,416 @@+#!/usr/bin/env node++// components/start-work-continuation/src/cli.ts+import { readFileSync as readFileSync4 } from "node:fs";+import { stdin as processStdin, stdout as processStdout } from "node:process";++// components/start-work-continuation/src/boulder-reader.ts+import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";+import { isAbsolute, join, relative, resolve } from "node:path";++// components/start-work-continuation/src/plan-checklist.ts+import { existsSync, readFileSync } from "node:fs";+var TODO_HEADING_PATTERN = /^##[ \t]+TODOs(?:[ \t]+#+)?[ \t]*$/i;+var FINAL_VERIFICATION_HEADING_PATTERN = /^##[ \t]+Final Verification Wave(?:[ \t]+#+)?[ \t]*$/i;+var SECTION_BOUNDARY_HEADING_PATTERN = /^#{1,2}(?:[ \t]+|$)/;+var FENCE_PATTERN = /^[ \t]{0,3}(`{3,}|~{3,})(.*)$/;+var SIMPLE_CHECKBOX_PATTERN = /^[-*][ \t]*\[[ \t]*([xX]?)[ \t]*\][ \t]+(.+)$/;+var TODO_CHECKBOX_PATTERN = /^- \[([ xX])\] ([1-9]\d*\. .+)$/;+var FINAL_WAVE_CHECKBOX_PATTERN = /^- \[([ xX])\] (F[1-9]\d*\. .+)$/i;+function getPlanChecklist(planPath) {+ if (!existsSync(planPath))+ return emptyChecklist();+ try {+ return parsePlanChecklist(readFileSync(planPath, "utf8"));+ } catch (error) {+ if (error instanceof Error)+ return emptyChecklist();+ throw error;+ }+}+function parsePlanChecklist(markdown) {+ const lines = markdown.split(/\r?\n/);+ if (!hasStructuredSection(lines))+ return parseSimpleChecklist(lines);+ let completed = 0;+ let remaining = 0;+ let nextTaskLabel = null;+ let section = "other";+ let fence = null;+ for (const line of lines) {+ if (fence !== null) {+ if (isClosingFence(line, fence))+ fence = null;+ continue;+ }+ const openingFence = parseOpeningFence(line);+ if (openingFence !== null) {+ fence = openingFence;+ continue;+ }+ if (SECTION_BOUNDARY_HEADING_PATTERN.test(line)) {+ section = parseStructuredSectionHeading(line);+ continue;+ }+ if (section === "other")+ continue;+ const checkbox = parseStructuredCheckbox(line, section);+ if (checkbox === null)+ continue;+ if (checkbox.checked)+ completed += 1;+ else {+ remaining += 1;+ nextTaskLabel = nextTaskLabel ?? checkbox.label;+ }+ }+ return { completed, remaining, total: completed + remaining, nextTaskLabel };+}+function hasStructuredSection(lines) {+ let fence = null;+ for (const line of lines) {+ if (fence !== null) {+ if (isClosingFence(line, fence))+ fence = null;+ continue;+ }+ const openingFence = parseOpeningFence(line);+ if (openingFence !== null) {+ fence = openingFence;+ continue;+ }+ if (parseStructuredSectionHeading(line) !== "other")+ return true;+ }+ return false;+}+function parseSimpleChecklist(lines) {+ let completed = 0;+ let remaining = 0;+ let nextTaskLabel = null;+ let fence = null;+ for (const line of lines) {+ if (fence !== null) {+ if (isClosingFence(line, fence))+ fence = null;+ continue;+ }+ const openingFence = parseOpeningFence(line);+ if (openingFence !== null) {+ fence = openingFence;+ continue;+ }+ const checkbox = parseSimpleTopLevelCheckbox(line);+ if (checkbox === null)+ continue;+ if (checkbox.checked)+ completed += 1;+ else {+ remaining += 1;+ nextTaskLabel = nextTaskLabel ?? checkbox.label;+ }+ }+ return { completed, remaining, total: completed + remaining, nextTaskLabel };+}+function parseStructuredSectionHeading(line) {+ if (TODO_HEADING_PATTERN.test(line))+ return "todo";+ if (FINAL_VERIFICATION_HEADING_PATTERN.test(line))+ return "final-wave";+ return "other";+}+function parseStructuredCheckbox(line, section) {+ const pattern = section === "todo" ? TODO_CHECKBOX_PATTERN : FINAL_WAVE_CHECKBOX_PATTERN;+ const match = line.match(pattern);+ const marker = match?.[1];+ const label = match?.[2];+ if (marker === undefined || label === undefined)+ return null;+ return { checked: marker.toLowerCase() === "x", label };+}+function parseSimpleTopLevelCheckbox(line) {+ const match = line.match(SIMPLE_CHECKBOX_PATTERN);+ const marker = match?.[1];+ const label = match?.[2];+ if (marker === undefined || label === undefined)+ return null;+ return { checked: marker.toLowerCase() === "x", label };+}+function parseOpeningFence(line) {+ const match = line.match(FENCE_PATTERN);+ const run = match?.[1];+ const info = match?.[2];+ const marker = run?.charAt(0);+ if (run === undefined || info === undefined || marker !== "`" && marker !== "~" || marker === "`" && info.includes("`"))+ return null;+ return { marker, length: run.length };+}+function isClosingFence(line, fence) {+ const run = line.match(/^[ \t]{0,3}(`{3,}|~{3,})[ \t]*$/)?.[1];+ return run?.charAt(0) === fence.marker && run.length >= fence.length;+}+function emptyChecklist() {+ return { completed: 0, remaining: 0, total: 0, nextTaskLabel: null };+}++// components/start-work-continuation/src/boulder-reader.ts+var SESSION_ID_PREFIX_PATTERN = /^(codex|opencode):/;+function readContinuationState(cwd, sessionId) {+ const boulderPath = getBoulderFilePath(cwd);+ const boulderState = readBoulderState(boulderPath);+ if (boulderState === null)+ return null;+ const work = getWorkForSession(boulderState, normalizeSessionId(sessionId, "codex"));+ if (work === null || !isContinuableStatus(work.status))+ return null;+ const planPath = resolveBoulderPlanPathForWork(cwd, work);+ const checklist = getPlanChecklist(planPath);+ if (checklist.total === 0)+ return null;+ return {+ planName: work.planName,+ planPath,+ boulderPath,+ ledgerPath: join(cwd, ".omo", "start-work", "ledger.jsonl"),+ worktreePath: work.worktreePath ?? null,+ checklist+ };+}+function readBoulderState(path) {+ try {+ const parsed = JSON.parse(readFileSync2(path, "utf8"));+ return parseBoulderState(parsed);+ } catch (error) {+ if (error instanceof Error)+ return null;+ throw error;+ }+}+function parseBoulderState(value) {+ if (!isRecord(value))+ return null;+ const works = [];+ const worksValue = value["works"];+ const hasWorksMap = isRecord(worksValue);+ if (hasWorksMap) {+ for (const workValue of Object.values(worksValue)) {+ const work = parseBoulderWork(workValue);+ if (work !== null)+ works.push(work);+ }+ }+ const mirrorWork = parseBoulderWork(value);+ if (works.length === 0 && mirrorWork === null)+ return null;+ return { works, mirrorWork, hasWorksMap };+}+function parseBoulderWork(value) {+ if (!isRecord(value))+ return null;+ const activePlan = value["active_plan"];+ const planName = value["plan_name"];+ if (typeof activePlan !== "string")+ return null;+ const status = parseBoulderWorkStatus(value["status"]);+ const sessionIds = parseSessionIds(value["session_ids"]);+ const worktreePath = value["worktree_path"];+ const startedAt = value["started_at"];+ const updatedAt = value["updated_at"];+ return {+ activePlan,+ planName: typeof planName === "string" ? planName : activePlan,+ sessionIds,+ ...status === undefined ? {} : { status },+ ...typeof startedAt === "string" ? { startedAt } : {},+ ...typeof updatedAt === "string" ? { updatedAt } : {},+ ...typeof worktreePath === "string" ? { worktreePath } : {}+ };+}+function getWorkForSession(state, normalizedSessionId) {+ let newestWork = null;+ let newestWorkMs = 0;+ for (const work of state.works) {+ if (!work.sessionIds.includes(normalizedSessionId))+ continue;+ const workMs = parseIsoToMs(work.updatedAt ?? work.startedAt) ?? 0;+ if (newestWork === null || workMs > newestWorkMs) {+ newestWork = work;+ newestWorkMs = workMs;+ }+ }+ if (newestWork !== null)+ return newestWork;+ if (state.hasWorksMap)+ return null;+ if (state.mirrorWork?.sessionIds.includes(normalizedSessionId) === true)+ return state.mirrorWork;+ return null;+}+function resolveBoulderPlanPathForWork(cwd, work) {+ const absolutePlanPath = resolveTrackedPath(cwd, work.activePlan);+ const worktreePath = work.worktreePath?.trim();+ if (worktreePath === undefined || worktreePath.length === 0)+ return absolutePlanPath;+ const relativePlanPath = relative(resolve(cwd), absolutePlanPath);+ if (relativePlanPath.length === 0 || relativePlanPath.startsWith("..") || isAbsolute(relativePlanPath)) {+ return absolutePlanPath;+ }+ const worktreePlanPath = resolve(resolveTrackedPath(cwd, worktreePath), relativePlanPath);+ return existsSync2(worktreePlanPath) ? worktreePlanPath : absolutePlanPath;+}+function resolveTrackedPath(baseDirectory, trackedPath) {+ return isAbsolute(trackedPath) ? resolve(trackedPath) : resolve(baseDirectory, trackedPath);+}+function parseBoulderWorkStatus(value) {+ if (value === "active" || value === "paused" || value === "completed" || value === "abandoned")+ return value;+ return;+}+function parseSessionIds(value) {+ if (!Array.isArray(value))+ return [];+ const sessionIds = [];+ for (const item of value) {+ if (typeof item === "string")+ sessionIds.push(normalizeSessionId(item));+ }+ return sessionIds;+}+function normalizeSessionId(sessionId, platform = "opencode") {+ if (SESSION_ID_PREFIX_PATTERN.test(sessionId))+ return sessionId;+ return `${platform}:${sessionId}`;+}+function parseIsoToMs(value) {+ if (value === undefined)+ return null;+ const parsed = Date.parse(value);+ return Number.isNaN(parsed) ? null : parsed;+}+function isContinuableStatus(status) {+ return status === "active" || status === "paused";+}+function getBoulderFilePath(cwd) {+ return join(cwd, ".omo", "boulder.json");+}+function isRecord(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++// components/start-work-continuation/src/directive.ts+import { readFileSync as readFileSync3 } from "node:fs";+var START_WORK_CONTINUATION_DIRECTIVE = readFileSync3(new URL("../directive.md", import.meta.url), "utf8");++// components/start-work-continuation/src/codex-hook.ts+function runStopHook(input, fs) {+ if (!isStopInput(input))+ return "";+ if (input.stop_hook_active)+ return "";+ if (transcriptHasContextPressureMarker(input.transcript_path, fs))+ return "";+ const state = readContinuationState(input.cwd, input.session_id);+ if (state === null)+ return "";+ return JSON.stringify({+ decision: "block",+ reason: renderDirective(state, input.session_id)+ });+}+function renderDirective(state, sessionId) {+ 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 ?? "none (final gate pending)",+ WORKTREE_BLOCK: worktreeBlock,+ LEDGER_PATH: state.ledgerPath,+ SESSION_ID: sessionId+ };+ let rendered = START_WORK_CONTINUATION_DIRECTIVE;+ for (const [placeholder, value] of Object.entries(replacements)) {+ rendered = rendered.replaceAll(`{{${placeholder}}}`, value);+ }+ return rendered;+}+var 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"+];+function transcriptHasContextPressureMarker(transcriptPath, fs) {+ try {+ const transcript = fs.readFileSync(transcriptPath, "utf8").toLowerCase();+ return CONTEXT_PRESSURE_MARKERS.some((marker) => transcript.includes(marker));+ } catch (error) {+ if (error instanceof Error)+ return false;+ throw error;+ }+}+function isStopInput(value) {+ return isRecord2(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) {+ return value === "Stop" || value === "SubagentStop";+}+function optionalString(value) {+ return value === undefined || typeof value === "string";+}+function isRecord2(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++// components/start-work-continuation/src/cli.ts+var nodeFileSystem = {+ readFileSync(path, encoding) {+ return readFileSync4(path, encoding);+ }+};+var command = process.argv[2];+var 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>+`);+ process.exitCode = 1;+}+async function runHookCli() {+ 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) {+ try {+ const parsed = JSON.parse(raw);+ return parsed;+ } catch (error) {+ if (error instanceof SyntaxError)+ return;+ throw error;+ }+}+function readStdin() {+ return new Promise((resolve2) => {+ let data = "";+ processStdin.setEncoding("utf8");+ processStdin.on("data", (chunk) => {+ data += chunk;+ });+ processStdin.once("error", () => resolve2(data));+ processStdin.once("end", () => resolve2(data));+ });+}diff --git a/plugins/omo/components/start-work-continuation/hooks/hooks.json b/plugins/omo/components/start-work-continuation/hooks/hooks.jsonindex ae985237..55334ff7 100644--- a/plugins/omo/components/start-work-continuation/hooks/hooks.json+++ b/plugins/omo/components/start-work-continuation/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js\" hook stop","timeout": 10,- "statusMessage": "(OmO 4.19.0) Checking Start-Work Continuation"+ "statusMessage": "(OmO 4.19.1) Checking Start-Work Continuation"}]}@@ -19,7 +19,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js\" hook subagent-stop","timeout": 10,- "statusMessage": "(OmO 4.19.0) Checking Start-Work Continuation"+ "statusMessage": "(OmO 4.19.1) Checking Start-Work Continuation"}]}diff --git a/plugins/omo/components/start-work-continuation/package.json b/plugins/omo/components/start-work-continuation/package.jsonindex d4fc1c14..8102dc5e 100644--- a/plugins/omo/components/start-work-continuation/package.json+++ b/plugins/omo/components/start-work-continuation/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-start-work-continuation",- "version": "4.19.0",+ "version": "4.19.1","description": "Codex Stop hook continuation injector for omo-codex start-work plans.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/teammode/hooks/hooks.json b/plugins/omo/components/teammode/hooks/hooks.jsonindex 815f8a41..86ddf5d9 100644--- a/plugins/omo/components/teammode/hooks/hooks.json+++ b/plugins/omo/components/teammode/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use","timeout": 10,- "statusMessage": "(OmO 4.19.0) Checking Thread Title Hygiene"+ "statusMessage": "(OmO 4.19.1) Checking Thread Title Hygiene"}]}diff --git a/plugins/omo/components/teammode/package.json b/plugins/omo/components/teammode/package.jsonindex 1de0a133..5a0ededa 100644--- a/plugins/omo/components/teammode/package.json+++ b/plugins/omo/components/teammode/package.json@@ -1,6 +1,6 @@{"name": "@sisyphuslabs/codex-teammode",- "version": "4.19.0",+ "version": "4.19.1","description": "Codex team-mode hook component that keeps background thread titles descriptive after create_thread.","type": "module","private": true,diff --git a/plugins/omo/components/telemetry/hooks/hooks.json b/plugins/omo/components/telemetry/hooks/hooks.jsonindex b80cfe53..9102d30d 100644--- a/plugins/omo/components/telemetry/hooks/hooks.json+++ b/plugins/omo/components/telemetry/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook session-start","timeout": 5,- "statusMessage": "(OmO 4.19.0) Recording Session Telemetry"+ "statusMessage": "(OmO 4.19.1) Recording Session Telemetry"}]}diff --git a/plugins/omo/components/telemetry/package.json b/plugins/omo/components/telemetry/package.jsonindex 8f2c1e39..71640d5c 100644--- a/plugins/omo/components/telemetry/package.json+++ b/plugins/omo/components/telemetry/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-telemetry",- "version": "4.19.0",+ "version": "4.19.1","description": "Codex plugin component that emits omo-codex anonymous daily-active telemetry on SessionStart.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/ultrawork/.gitignore b/plugins/omo/components/ultrawork/.gitignoredeleted file mode 100644index f3d1d95e..00000000--- a/plugins/omo/components/ultrawork/.gitignore+++ /dev/null@@ -1,5 +0,0 @@-__pycache__/-*.pyc-.DS_Store-.env-.env.*diff --git a/plugins/omo/components/ultrawork/agents/lazycodex-clone-fidelity-reviewer.toml b/plugins/omo/components/ultrawork/agents/lazycodex-clone-fidelity-reviewer.tomlindex 9dcd36f8..af8afb5b 100644--- a/plugins/omo/components/ultrawork/agents/lazycodex-clone-fidelity-reviewer.toml+++ b/plugins/omo/components/ultrawork/agents/lazycodex-clone-fidelity-reviewer.toml@@ -1,8 +1,8 @@name = "lazycodex-clone-fidelity-reviewer"description = "Read-only LazyCodex clone / design-system fidelity reviewer. Verifies clone and design-port work is a rigorous, token-driven design system, not a pasted screenshot or hardcoded fake."nickname_candidates = ["Clone Fidelity Reviewer"]-model = "gpt-5.6-sol"-model_reasoning_effort = "xhigh"+model = "gpt-5.6-terra"+model_reasoning_effort = "high"developer_instructions = """Role: clone / design-system fidelity reviewer. Read-only.diff --git a/plugins/omo/components/ultrawork/agents/lazycodex-code-reviewer.toml b/plugins/omo/components/ultrawork/agents/lazycodex-code-reviewer.tomlindex 0b22acb9..16e15ad1 100644--- a/plugins/omo/components/ultrawork/agents/lazycodex-code-reviewer.toml+++ b/plugins/omo/components/ultrawork/agents/lazycodex-code-reviewer.toml@@ -1,8 +1,8 @@name = "lazycodex-code-reviewer"description = "Read-only LazyCodex code-quality reviewer. Audits diffs, tests, and risk with strict artifact-backed findings."nickname_candidates = ["Code Reviewer"]-model = "gpt-5.6-sol"-model_reasoning_effort = "xhigh"+model = "gpt-5.6-terra"+model_reasoning_effort = "medium"developer_instructions = """Role: code quality reviewer. Read-only.diff --git a/plugins/omo/components/ultrawork/agents/lazycodex-gate-reviewer.toml b/plugins/omo/components/ultrawork/agents/lazycodex-gate-reviewer.tomlindex b124f013..be739e7c 100644--- a/plugins/omo/components/ultrawork/agents/lazycodex-gate-reviewer.toml+++ b/plugins/omo/components/ultrawork/agents/lazycodex-gate-reviewer.toml@@ -2,7 +2,7 @@ name = "lazycodex-gate-reviewer"description = "Read-only LazyCodex gate reviewer. Re-audits executor, code review, and QA artifacts before final approval."nickname_candidates = ["Gate Reviewer"]model = "gpt-5.6-sol"-model_reasoning_effort = "high"+model_reasoning_effort = "low"developer_instructions = """Role: final gate reviewer. Read-only.diff --git a/plugins/omo/components/ultrawork/agents/lazycodex-worker-high.toml b/plugins/omo/components/ultrawork/agents/lazycodex-worker-high.tomlindex f2d100a6..99dc8dda 100644--- a/plugins/omo/components/ultrawork/agents/lazycodex-worker-high.toml+++ b/plugins/omo/components/ultrawork/agents/lazycodex-worker-high.toml@@ -2,7 +2,7 @@ name = "lazycodex-worker-high"description = "LazyCodex high-difficulty implementation worker, sized for LARGE changes: a new module or abstraction, a cross-module refactor, concurrency/security/migration work, or any real, complex, big problem that has ONE clear goal. Owns the smallest correct change and records evidence before claiming completion."nickname_candidates = ["High Worker"]model = "gpt-5.6-sol"-model_reasoning_effort = "max"+model_reasoning_effort = "medium"developer_instructions = """Role: implementation executor. You own the task end to end.diff --git a/plugins/omo/components/ultrawork/agents/lazycodex-worker-medium.toml b/plugins/omo/components/ultrawork/agents/lazycodex-worker-medium.tomlindex 81c5c661..add0dbde 100644--- a/plugins/omo/components/ultrawork/agents/lazycodex-worker-medium.toml+++ b/plugins/omo/components/ultrawork/agents/lazycodex-worker-medium.toml@@ -1,8 +1,8 @@name = "lazycodex-worker-medium"description = "LazyCodex medium-difficulty implementation worker, sized for MID-SIZED changes: a standard feature inside existing layers, touching a few files along established patterns. Owns the smallest correct change and records evidence before claiming completion."nickname_candidates = ["Medium Worker"]-model = "gpt-5.6-luna"-model_reasoning_effort = "max"+model = "gpt-5.6-terra"+model_reasoning_effort = "high"developer_instructions = """Role: implementation executor. You own the task end to end.diff --git a/plugins/omo/components/ultrawork/agents/plan.toml b/plugins/omo/components/ultrawork/agents/plan.tomlindex d107583a..f6ac260c 100644--- a/plugins/omo/components/ultrawork/agents/plan.toml+++ b/plugins/omo/components/ultrawork/agents/plan.toml@@ -2,7 +2,7 @@ name = "plan"description = "Strategic planning consultant for work with unresolved design uncertainty after discovery. Produces one executable plan; never implements. Writes the plan to .omo/plans/<slug>.md."nickname_candidates = ["Planner"]model = "gpt-5.6-sol"-model_reasoning_effort = "max"+model_reasoning_effort = "high"developer_instructions = """Role: strategic planning consultant. You produce a single, bulletproof, executable work plan only when discovery leaves unresolved design uncertainty.diff --git a/plugins/omo/components/ultrawork/dist/cli.js b/plugins/omo/components/ultrawork/dist/cli.jsindex 3f71be50..bab1b0c6 100755--- a/plugins/omo/components/ultrawork/dist/cli.js+++ b/plugins/omo/components/ultrawork/dist/cli.js@@ -60,7 +60,7 @@ function buildUltraworkAdditionalContext(options = {}) {}// components/ultrawork/src/codex-hook.ts-var ULTRAWORK_CURRENT_PROMPT_PATTERN = /(?:ultrawork|ulw)/i;+var ULTRAWORK_CURRENT_PROMPT_PATTERN = /(?:ultrawork|ulw(?!-(?:plan|research)))/i;var ULTRAWORK_DIRECTIVE_MARKER = "<ultrawork-mode>";var TRANSCRIPT_SEARCH_BYTES = 512000;var CONTEXT_PRESSURE_MARKERS = [diff --git a/plugins/omo/components/ultrawork/hooks/hooks.json b/plugins/omo/components/ultrawork/hooks/hooks.jsonindex 3078a771..a2842a27 100644--- a/plugins/omo/components/ultrawork/hooks/hooks.json+++ b/plugins/omo/components/ultrawork/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit","timeout": 5,- "statusMessage": "(OmO 4.19.0) Checking Ultrawork Trigger"+ "statusMessage": "(OmO 4.19.1) Checking Ultrawork Trigger"}]}diff --git a/plugins/omo/components/ultrawork/package.json b/plugins/omo/components/ultrawork/package.jsonindex 23c1c81c..173ac109 100644--- a/plugins/omo/components/ultrawork/package.json+++ b/plugins/omo/components/ultrawork/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-ultrawork",- "version": "4.19.0",+ "version": "4.19.1","description": "Codex plugin that injects the ultrawork orchestration directive and ships LazyCodex planning, review, QA, and gate agent roles.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/ultrawork/skills/ulw-plan/SKILL.md b/plugins/omo/components/ultrawork/skills/ulw-plan/SKILL.mdindex 8dd26d48..17e3290a 100644--- a/plugins/omo/components/ultrawork/skills/ulw-plan/SKILL.md+++ b/plugins/omo/components/ultrawork/skills/ulw-plan/SKILL.md@@ -13,11 +13,30 @@ You are **Prometheus**, a planning consultant. You turn a vague or large requestOutcome-first: explore a lot, ask few sharp questions - or none, when the intent is fuzzy (see routing) - and stop the moment the plan is done.+## MANDATORY OPENING ANNOUNCEMENT++The FIRST user-visible line of the turn that activates this skill MUST be exactly:++`ULW-PLAN MODE ENABLED!`++If another active mode mandates its own first line (ultrawork does), print that line first and this marker on the next line - both contracts stay satisfied.++Directly under the marker, before any exploration, state the working contract once, in your own words, carrying ALL of these commitments:++1. **Persona + no-implementation pledge** - from now on you work as Prometheus, a planning consultant, and you will never start implementation - no product-code edits, no implementer subagents - until the user explicitly says okay; even then, approval authorizes writing the plan only, and execution starts in a separate worker session (e.g. `$start-work`).+2. **Workflow preview** - the order of what happens next: parallel read-only exploration (plus outside research when the repo cannot answer) until the open unknowns are resolved; the intent verdict from INTENT ROUTING, announced; questions to the user ONLY when a genuine owner-decision survives exploration - or when exploration and research both come back empty on a fork the plan cannot proceed without; then the approval brief, and the plan is written only after the explicit okay.++Example opening (adapt the wording, keep every commitment):++> ULW-PLAN MODE ENABLED!+> From now on I am working as Prometheus, a planning consultant. I will not start any implementation until you explicitly say okay - and approval authorizes writing the plan only; execution starts separately (e.g. `$start-work`).+> Next, in order: (1) parallel read-only exploration and research, (2) intent verdict announced (CLEAR or UNCLEAR, plus whether high-accuracy review is required), (3) questions only for the forks exploration cannot settle - or where research finds nothing on a blocking decision, (4) approval brief, then (5) the plan is written after your okay.+## INTENT ROUTING - pick ONE intent reference**Review modifiers are a gate trigger, not a style cue.** If the user says "high accuracy", "ultra high accuracy", "고정밀", "deep review", or equivalent - in ANY turn, even appended to a follow-up question and even after the plan already exists - set `review_required: true` in the draft: the dual high-accuracy review (native `momus` + the independent Codex CLI review) is now REQUIRED before handoff, and if the plan already exists you run it this same turn. Answering the current question more carefully does NOT satisfy it. This does NOT choose CLEAR/UNCLEAR and does NOT suppress interview.-After grounding, make ONE judgment, record `intent: clear|unclear` plus `review_required`, **ANNOUNCE both to the user in one line**, then load ONE intent reference (you ALSO read `references/full-workflow.md` for the shared mechanics - see below). The test keys on whether the desired **OUTCOME** is clear, NOT on request length. The announcement is the user's first signal of whether they will be interviewed and whether high-accuracy review is already requested - never skip it.+After grounding, make ONE judgment, record `intent: clear|unclear` plus `review_required`, **ANNOUNCE both to the user in one line**, then load ONE intent reference (you ALSO read `references/full-workflow.md` for the shared mechanics - see below). The test keys on whether the desired **OUTCOME** is clear, NOT on request length. This verdict line and the opening announcement above are the two mandatory user-visible signals of a planning session - it tells the user whether they will be interviewed and whether high-accuracy review is already requested; never skip either.> "Intent: **CLEAR**, review required - you specified the endpoint and asked for high accuracy. I will ask only the genuine forks, then run the high-accuracy review after approval."> "Intent: **UNCLEAR**, review required - 'make auth better' is open-ended and you asked for high accuracy. I will choose best-practice defaults, then run the high-accuracy review automatically."diff --git a/plugins/omo/components/ultrawork/src/codex-hook.ts b/plugins/omo/components/ultrawork/src/codex-hook.tsindex 008007d1..c96edd54 100644--- a/plugins/omo/components/ultrawork/src/codex-hook.ts+++ b/plugins/omo/components/ultrawork/src/codex-hook.ts@@ -2,7 +2,7 @@ import { readFileSync } from "node:fs";import { buildUltraworkAdditionalContext, type UltraworkAdditionalContextOptions } from "./skill-pointer.js";-const ULTRAWORK_CURRENT_PROMPT_PATTERN = /(?:ultrawork|ulw)/i;+const ULTRAWORK_CURRENT_PROMPT_PATTERN = /(?:ultrawork|ulw(?!-(?:plan|research)))/i;const ULTRAWORK_DIRECTIVE_MARKER = "<ultrawork-mode>";const TRANSCRIPT_SEARCH_BYTES = 512_000;const CONTEXT_PRESSURE_MARKERS = [diff --git a/plugins/omo/components/ultrawork/test/codex-hook-trigger-policy.test.ts b/plugins/omo/components/ultrawork/test/codex-hook-trigger-policy.test.tsindex 07c115c8..49d14b95 100644--- a/plugins/omo/components/ultrawork/test/codex-hook-trigger-policy.test.ts+++ b/plugins/omo/components/ultrawork/test/codex-hook-trigger-policy.test.ts@@ -88,6 +88,48 @@ describe("codex ultrawork trigger policy", () => {expect(isUltraworkPrompt(prompt)).toBe(true);});+ it("#given prompt invokes ulw-plan or ulw-research skills #when hook runs #then does not emit directive", () => {+ // given+ const prompts = [+ "$omo:ulw-plan refactor the auth module",+ "omo:ulw-plan",+ "/ulw-plan",+ "ulw-plan",+ "$omo:ulw-research how does the hook pipeline work",+ "ulw-research",+ "please run ULW-PLAN for this",+ ] as const;++ // when+ const outputs = prompts.map((prompt) => runUserPromptSubmitHook({ hook_event_name: "UserPromptSubmit", prompt }));++ // then+ expect(outputs).toEqual(["", "", "", "", "", "", ""]);+ expect(prompts.map((prompt) => isUltraworkPrompt(prompt))).toEqual([false, false, false, false, false, false, false]);+ });++ it("#given prompt contains ultrawork or standalone ulw #when hook runs #then emits directive", () => {+ // given+ const prompts = [+ "ultrawork this change",+ "ulw",+ "ulw ",+ "ulw fix this failing test",+ "ulw-loop keep iterating until green",+ ] as const;++ // when+ const outputs = prompts.map((prompt) => runUserPromptSubmitHook({ hook_event_name: "UserPromptSubmit", prompt }));++ // then+ for (const output of outputs) {+ const parsed = parseHookOutput(output);+ expect(parsed.hookSpecificOutput.hookEventName).toBe("UserPromptSubmit");+ expect(parsed.hookSpecificOutput.additionalContext).toMatch(/^<ultrawork-mode>/);+ }+ expect(prompts.map((prompt) => isUltraworkPrompt(prompt))).toEqual([true, true, true, true, true]);+ });+it("#given prior transcript contains triggers but current prompt does not #when hook runs #then does not emit directive", () => {// givenconst payload = {diff --git a/plugins/omo/components/ulw-loop/.gitignore b/plugins/omo/components/ulw-loop/.gitignoredeleted file mode 100644index e5f7145b..00000000--- a/plugins/omo/components/ulw-loop/.gitignore+++ /dev/null@@ -1,6 +0,0 @@-node_modules/-dist/-*.log-.DS_Store-coverage/-.vitest/diff --git a/plugins/omo/components/ulw-loop/README.md b/plugins/omo/components/ulw-loop/README.mdindex 815bba04..29a7a9a0 100644--- a/plugins/omo/components/ulw-loop/README.md+++ b/plugins/omo/components/ulw-loop/README.md@@ -11,11 +11,11 @@ Every subcommand below is implemented. Pass `--json` where supported for machine| Subcommand | Purpose ||------------|---------|| `omo ulw-loop help` | Print CLI usage. |-| `omo ulw-loop create-goals` | Create repo-native goals and seed success criteria from a brief. |+| `omo ulw-loop create-goals` | Create repo-native goals and seed success criteria from a brief; optionally define review-boundary validation batches with `--validation-batch-json`. || `omo ulw-loop status` | Report active goal, criteria, and evidence state. |-| `omo ulw-loop complete-goals` | Start or resume the next eligible goal, or report aggregate completion / blocked handoff. |-| `omo ulw-loop checkpoint` | Gate a goal transition with evidence; final completion requires a complete Codex goal snapshot and a passing quality gate. |-| `omo ulw-loop steer` | Apply a steering mutation proposal to the plan. |+| `omo ulw-loop complete-goals` | Manual fallback to start or resume the next eligible goal, or report aggregate completion / blocked handoff. |+| `omo ulw-loop checkpoint` | Gate a goal transition with evidence; complete checkpoints auto-start the next eligible goal by default, with `--no-advance` preserving the legacy two-call flow. |+| `omo ulw-loop steer` | Apply one steering mutation proposal or an atomic all-or-nothing batch with `--proposals-json`. || `omo ulw-loop add-goal` | Append a goal to the active plan. || `omo ulw-loop criteria` | Inspect one goal's success criteria. || `omo ulw-loop record-evidence` | Record observable evidence for one criterion. |@@ -23,6 +23,8 @@ Every subcommand below is implemented. Pass `--json` where supported for machineThe final quality gate parsed by `checkpoint` validates `codeReview`, `manualQa`, `gateReview`, `iteration`, and `criteriaCoverage`. `criteriaCoverage` records the original intent, desired outcome, user-facing outcome review, pass counts, and covered adversarial classes.+Validation batches are optional review boundaries declared at plan creation with `--validation-batch-json '[{"batchId":"VB001","memberIds":[...],"finalGoalId":"..."}]'`. The batch-final goal cannot complete until every other member is complete or superseded-resolved, every member criterion is pass, and a quality gate's coverage counts match the recomputed member criteria. Steering split/supersede mutations keep batch membership consistent and record `batch_updated`.+## Codex PluginThis directory is a component of the aggregate `@sisyphuslabs/omo-codex-plugin` root. Plugin discovery (`.codex-plugin/plugin.json`) is owned by that aggregate root, not by this component. The component ships:diff --git a/plugins/omo/components/ulw-loop/dist/checkpoint-continuation.d.ts b/plugins/omo/components/ulw-loop/dist/checkpoint-continuation.d.tsnew file mode 100644index 00000000..38b764d7--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/checkpoint-continuation.d.ts@@ -0,0 +1,21 @@+import { type CheckpointUlwLoopArgs, type CheckpointUlwLoopResult } from "./checkpoint.js";+import { type UlwLoopGoalInstruction } from "./codex-goal-instruction.js";+import type { UlwLoopScope } from "./paths.js";+import type { UlwLoopItem } from "./types.js";+type ContinuationNext = {+ readonly resumed: boolean;+ readonly goal: UlwLoopItem;+ readonly instruction: UlwLoopGoalInstruction;+} | {+ readonly done: true;+ readonly blocked: boolean;+ readonly handoff: string;+};+export type CheckpointAndContinueResult = CheckpointUlwLoopResult & {+ readonly next?: ContinuationNext;+};+export declare function checkpointAndContinue(repoRoot: string, args: CheckpointUlwLoopArgs & {+ readonly advance: boolean;+}, scope?: UlwLoopScope): Promise<CheckpointAndContinueResult>;+export declare function checkpoint(repoRoot: string, argv: readonly string[], json: boolean, scope?: UlwLoopScope): Promise<number>;+export {};diff --git a/plugins/omo/components/ulw-loop/dist/checkpoint-continuation.js b/plugins/omo/components/ulw-loop/dist/checkpoint-continuation.jsnew file mode 100644index 00000000..bb06c4bc--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/checkpoint-continuation.js@@ -0,0 +1,64 @@+import { checkpointUlwLoop } from "./checkpoint.js";+import { hasFlag, parseCodexGoalJson, readValue } from "./cli-arg-parser.js";+import { blockedDecisionHandoff, printJson } from "./cli-output.js";+import { buildCodexGoalInstruction } from "./codex-goal-instruction.js";+import { startNextUlwLoop, summarizeUlwLoopPlan } from "./plan-crud.js";+import { UlwLoopError } from "./types.js";+export async function checkpointAndContinue(repoRoot, args, scope) {+ const result = await checkpointUlwLoop(repoRoot, args, scope);+ if (args.status !== "complete" || result.aggregateCompletion !== undefined || !args.advance)+ return result;+ const next = await startNextUlwLoop(repoRoot, {}, scope);+ if ("done" in next)+ return { ...result, plan: next.plan, next: doneNext(next.plan) };+ const instruction = buildCodexGoalInstruction({ plan: next.plan, goal: next.goal });+ return { ...result, plan: next.plan, next: { resumed: next.resumed, goal: next.goal, instruction } };+}+export async function checkpoint(repoRoot, argv, json, scope) {+ 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 = {+ goalId,+ status: statusValue,+ evidence,+ advance: !hasFlag(argv, "--no-advance"),+ ...(codexGoalJson === undefined ? {} : { codexGoalJson }),+ ...(qualityGateJson === undefined ? {} : { qualityGateJson }),+ };+ const result = await checkpointAndContinue(repoRoot, args, scope);+ if (json)+ printJson({ ok: true, ...result, summary: summarizeUlwLoopPlan(result.plan) });+ else+ printCheckpointText(result);+ return 0;+}+function printCheckpointText(result) {+ process.stdout.write(`ulw-loop checkpoint: ${result.goal.id} -> ${result.goal.status}\n`);+ if (result.next === undefined)+ return;+ if ("instruction" in result.next)+ process.stdout.write(`${result.next.instruction.text}\n`);+ else+ process.stdout.write(`${result.next.handoff || "ulw-loop: all goals complete"}\n`);+}+function doneNext(plan) {+ const handoff = blockedDecisionHandoff(plan);+ return { done: true, blocked: handoff.length > 0, handoff };+}+function required(argv, flag) {+ const value = readValue(argv, flag)?.trim();+ if (value)+ return value;+ throw new UlwLoopError(`Missing ${flag}.`, "ULW_LOOP_ARGUMENT_MISSING", { details: { flag } });+}+function checkpointStatus(value) {+ 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 } });+}diff --git a/plugins/omo/components/ulw-loop/dist/checkpoint-reconciliation.d.ts b/plugins/omo/components/ulw-loop/dist/checkpoint-reconciliation.d.tsnew file mode 100644index 00000000..ab1937ec--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/checkpoint-reconciliation.d.ts@@ -0,0 +1,5 @@+import { type UlwLoopScope } from "./paths.js";+import type { UlwLoopItem, UlwLoopPlan } from "./types.js";+export declare function canReconcileCompletedTaskScopedAggregateSnapshot(repoRoot: string, plan: UlwLoopPlan, goal: UlwLoopItem, snapshotObjective: string, evidence: string, scope?: UlwLoopScope): Promise<boolean>;+export declare function canReconcileActiveFinalTaskScopedAggregateSnapshot(repoRoot: string, plan: UlwLoopPlan, goal: UlwLoopItem, snapshotObjective: string, evidence: string, scope?: UlwLoopScope): Promise<boolean>;+export declare function buildTaskScopedAggregateReconciliationHint(goal: UlwLoopItem, final: boolean): string;diff --git a/plugins/omo/components/ulw-loop/dist/checkpoint-reconciliation.js b/plugins/omo/components/ulw-loop/dist/checkpoint-reconciliation.jsnew file mode 100644index 00000000..6b9ede24--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/checkpoint-reconciliation.js@@ -0,0 +1,79 @@+import { existsSync } from "node:fs";+import { readFile } from "node:fs/promises";+import { codexGoalMode, isFinalRunCompletionCandidate } from "./goal-status.js";+import { ulwLoopBriefPath } from "./paths.js";+import { ULW_LOOP_DIR, ULW_LOOP_GOALS, ULW_LOOP_LEDGER } from "./types.js";+function normalizeObjective(value) {+ return value.replace(/\s+/g, " ").trim();+}+function textMentionsUlwLoopPlanArtifact(value) {+ const normalized = (value ?? "").toLowerCase();+ return (normalized.includes(ULW_LOOP_DIR.toLowerCase()) ||+ normalized.includes(ULW_LOOP_GOALS.toLowerCase()) ||+ normalized.includes(ULW_LOOP_LEDGER.toLowerCase()));+}+function textMentionsGoalId(value, goalId) {+ return (value ?? "").toLowerCase().includes(goalId.toLowerCase());+}+function textHasCompletionValidationEvidence(value) {+ const normalized = (value ?? "").toLowerCase();+ const done = /\b(?:planned work|implementation|deliverables?|scope|task|work)\b/.test(normalized) &&+ /\b(?:done|complete|completed|finished|shipped)\b/.test(normalized);+ const verified = /\b(?:validation|verification|tests?|build|lint|review|quality gate|code-review)\b/.test(normalized) &&+ /\b(?:passed|complete|completed|clean|green|approve|approved|clear)\b/.test(normalized);+ return done && verified;+}+async function snapshotObjectiveMapsToUlwLoopPlan(repoRoot, snapshotObjective, scope) {+ const actual = normalizeObjective(snapshotObjective).toLowerCase();+ if (textMentionsUlwLoopPlanArtifact(actual))+ return true;+ if (actual.length < 24 || !existsSync(ulwLoopBriefPath(repoRoot, scope)))+ return false;+ try {+ 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;+ throw error;+ }+}+export async function canReconcileCompletedTaskScopedAggregateSnapshot(repoRoot, plan, goal, snapshotObjective, evidence, scope) {+ if (codexGoalMode(plan) !== "aggregate")+ return false;+ if (goal.status !== "in_progress" || plan.activeGoalId !== 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 snapshotObjectiveMapsToUlwLoopPlan(repoRoot, snapshotObjective, scope);+}+export async function canReconcileActiveFinalTaskScopedAggregateSnapshot(repoRoot, plan, goal, snapshotObjective, evidence, scope) {+ 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) {+ 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 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(" ");+}+export function buildTaskScopedAggregateReconciliationHint(goal, final) {+ 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 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/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)}`;+}diff --git a/plugins/omo/components/ulw-loop/dist/checkpoint.d.ts b/plugins/omo/components/ulw-loop/dist/checkpoint.d.tsnew file mode 100644index 00000000..d71a180e--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/checkpoint.d.ts@@ -0,0 +1,16 @@+import type { UlwLoopScope } from "./paths.js";+import type { UlwLoopAggregateCompletion, UlwLoopItem, UlwLoopLedgerEntry, UlwLoopPlan } from "./types.js";+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;+}+export declare function checkpointUlwLoop(repoRoot: string, args: CheckpointUlwLoopArgs, scope?: UlwLoopScope): Promise<CheckpointUlwLoopResult>;diff --git a/plugins/omo/components/ulw-loop/dist/checkpoint.js b/plugins/omo/components/ulw-loop/dist/checkpoint.jsnew file mode 100644index 00000000..0a52903b--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/checkpoint.js@@ -0,0 +1,192 @@+// biome-ignore-all format: checkpoint stays under the pure LOC ceiling.+import { existsSync, statSync } from "node:fs";+import { readFile } from "node:fs/promises";+import { resolve } from "node:path";+import { buildTaskScopedAggregateReconciliationHint, canReconcileActiveFinalTaskScopedAggregateSnapshot, canReconcileCompletedTaskScopedAggregateSnapshot, } from "./checkpoint-reconciliation.js";+import { formatCodexGoalReconciliation, readCodexGoalSnapshotInput, reconcileCodexGoalSnapshot, } from "./codex-goal-snapshot.js";+import { requireAllCriteriaPass, requireAllPlanCriteriaPass, requireEssentialCriteriaPass } from "./evidence.js";+import { codexGoalMode, compatibleCodexObjectives, expectedCodexObjective, isFinalRunCompletionCandidate, } from "./goal-status.js";+import { ulwLoopAttemptEvidenceDir } from "./paths.js";+import { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";+import { classifyExternalAuthorizationBlocker, clearGoalBlockerFields, sameBlockerOccurrences, validateQualityGate, } from "./quality-gate.js";+import { iso, UlwLoopError } from "./types.js";+import { batchClosedBy, requireAllValidationBatchesClosed, requireBatchFinalReady, requireBatchGate } from "./validation-batch.js";+const QUALITY_GATE_FS = { existsSync, statSync };+function ulwLoopFail(message, code) {+ throw new UlwLoopError(message, code);+}+function normalizeObjective(value) {+ return value.replace(/\s+/g, " ").trim();+}+function nonEmptyEvidence(value) {+ const trimmed = value.trim();+ return trimmed || ulwLoopFail("Evidence must be a non-empty string.", "ulw_loop_evidence_required");+}+function findGoal(plan, goalId) {+ const goal = plan.goals.find((candidate) => candidate.id === goalId);+ return goal ?? ulwLoopFail(`Unknown ulw-loop id: ${goalId}.`, "ulw_loop_goal_not_found");+}+async function readJsonInput(raw, repoRoot) {+ if (raw === undefined || raw.trim() === "")+ return undefined;+ const trimmed = raw.trim();+ try {+ return JSON.parse(trimmed);+ }+ catch (error) {+ if (!(error instanceof SyntaxError))+ throw error;+ }+ const path = resolve(repoRoot, trimmed);+ if (!existsSync(path))+ return 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, evidence, codexGoal) {+ return { status: "complete", completedAt: now, evidence, codexGoal };+}+function applyBlockedOrFailed(goal, plan, status, evidence, now) {+ const signature = classifyExternalAuthorizationBlocker(evidence);+ const occurrences = signature === null ? 0 : sameBlockerOccurrences(plan, signature) + 1;+ const needsDecision = signature !== null && occurrences >= 3;+ goal.status = needsDecision ? "needs_user_decision" : status;+ goal.updatedAt = now;+ if (status === "failed" || needsDecision) {+ goal.failedAt = now;+ goal.failureReason = evidence;+ }+ if (status === "blocked" || needsDecision)+ goal.blockedReason = evidence;+ if (signature !== null) {+ goal.blockerSignature = signature;+ goal.blockerOccurrenceCount = occurrences;+ goal.requiredExternalDecision = `Resolve external authorization: ${signature}`;+ }+ if (needsDecision)+ goal.nonRetriable = true;+ if (plan.activeGoalId === goal.id)+ delete plan.activeGoalId;+}+function ledgerKind(status, goal, aggregateCompletion) {+ 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, args, goal, qualityGate, codexGoal, aggregateCompletion) {+ const watch = qualityGate?.codeReview.codeQualityStatus === "WATCH";+ const entry = {+ at: now,+ kind: ledgerKind(args.status, goal, aggregateCompletion),+ goalId: goal.id,+ status: goal.status,+ evidence: watch ? `${args.evidence} | codeQuality=WATCH: ${qualityGate.codeReview.evidence}` : args.evidence,+ };+ if (codexGoal !== undefined)+ entry.codexGoal = codexGoal;+ if (qualityGate !== undefined)+ entry.qualityGate = qualityGate;+ if (goal.blockerSignature !== undefined)+ entry.blockerSignature = goal.blockerSignature;+ if (goal.blockerOccurrenceCount !== undefined)+ entry.blockerOccurrenceCount = goal.blockerOccurrenceCount;+ if (goal.requiredExternalDecision !== undefined)+ entry.requiredExternalDecision = goal.requiredExternalDecision;+ return entry;+}+export async function checkpointUlwLoop(repoRoot, args, scope) {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ const plan = await readUlwLoopPlan(repoRoot, scope);+ const goal = findGoal(plan, args.goalId);+ const evidence = nonEmptyEvidence(args.evidence);+ const now = iso();+ let aggregateCompletion;+ let qualityGate;+ let codexGoal;+ if (args.status === "complete") {+ const aggregate = codexGoalMode(plan) === "aggregate";+ const final = isFinalRunCompletionCandidate(plan, goal);+ const closesBatch = batchClosedBy(plan, goal.id) !== undefined;+ if (final) {+ requireAllCriteriaPass(goal);+ requireAllPlanCriteriaPass(plan);+ requireAllValidationBatchesClosed(plan, goal.id);+ }+ else if (aggregate)+ requireEssentialCriteriaPass(goal);+ else+ requireAllCriteriaPass(goal);+ const snapshot = await readCodexGoalSnapshotInput(args.codexGoalJson, repoRoot);+ const reconciliation = reconcileCodexGoalSnapshot(snapshot, {+ expectedObjective: expectedCodexObjective(plan, goal),+ ...(aggregate ? { acceptedObjectives: compatibleCodexObjectives(plan) } : {}),+ allowedStatuses: aggregate ? (final ? ["complete"] : ["active"]) : ["complete"],+ requireSnapshot: true,+ requireComplete: !aggregate || final,+ });+ codexGoal = reconciliation.snapshot.raw;+ if (!reconciliation.ok) {+ const objective = snapshot?.objective;+ const 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");+ }+ if (closesBatch)+ requireBatchFinalReady(plan, goal);+ if (closesBatch && args.qualityGateJson === undefined)+ throw new UlwLoopError("Validation batch final checkpoint requires --quality-gate-json.", "ULW_LOOP_VALIDATION_BATCH_GATE_REQUIRED");+ if (final)+ aggregateCompletion = makeAggregateCompletion(now, evidence, codexGoal);+ if (final || aggregateCompletion !== undefined || closesBatch) {+ qualityGate = validateQualityGate(await readJsonInput(args.qualityGateJson, repoRoot), {+ repoRoot,+ fs: QUALITY_GATE_FS,+ ...(plan.evidenceLayoutVersion === 2+ ? { currentAttemptDir: ulwLoopAttemptEvidenceDir(goal.id, goal.attempt, scope) }+ : {}),+ });+ requireBatchGate(plan, goal, qualityGate);+ }+ goal.status = "complete";+ goal.completedAt = now;+ goal.evidence = evidence;+ delete goal.failedAt;+ delete goal.failureReason;+ clearGoalBlockerFields(goal);+ if (plan.activeGoalId === goal.id)+ delete plan.activeGoalId;+ }+ else+ applyBlockedOrFailed(goal, plan, args.status, evidence, now);+ goal.updatedAt = now;+ if (aggregateCompletion !== undefined)+ plan.aggregateCompletion = aggregateCompletion;+ plan.updatedAt = now;+ await writePlan(repoRoot, plan, scope);+ const ledgerEntry = buildLedger(now, args, goal, qualityGate, codexGoal, aggregateCompletion);+ await appendLedger(repoRoot, ledgerEntry, scope);+ const closedBatch = args.status === "complete" ? batchClosedBy(plan, goal.id) : undefined;+ if (closedBatch !== undefined)+ await appendLedger(repoRoot, { at: now, kind: "batch_closed", goalId: goal.id, message: closedBatch.batchId }, scope);+ return aggregateCompletion === undefined+ ? { plan, goal, ledgerEntry }+ : { plan, goal, ledgerEntry, aggregateCompletion };+ });+}diff --git a/plugins/omo/components/ulw-loop/dist/cli-arg-parser.d.ts b/plugins/omo/components/ulw-loop/dist/cli-arg-parser.d.tsnew file mode 100644index 00000000..ee898de3--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/cli-arg-parser.d.ts@@ -0,0 +1,17 @@+type RecordEvidenceCliArgs = {+ readonly goalId: string;+ readonly criterionId: string;+ readonly status: "pass" | "fail" | "blocked";+ readonly evidence: string;+ readonly notes?: string;+};+export declare function hasFlag(argv: readonly string[], flag: string): boolean;+export declare function readValue(argv: readonly string[], flag: string): string | undefined;+export declare function readRepeated(argv: readonly string[], flag: string): string[];+export declare function parseGoalArg(argv: readonly string[]): string | undefined;+export declare function readStdin(): Promise<string>;+export declare function positionalText(argv: readonly string[]): string;+export declare function readJsonInput(value: string | undefined): Promise<unknown | undefined>;+export declare function parseCodexGoalJson(value: string | undefined): Promise<string | undefined>;+export declare function parseRecordEvidenceArgs(argv: readonly string[]): RecordEvidenceCliArgs;+export {};diff --git a/plugins/omo/components/ulw-loop/dist/cli-arg-parser.js b/plugins/omo/components/ulw-loop/dist/cli-arg-parser.jsnew file mode 100644index 00000000..7c34abf9--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/cli-arg-parser.js@@ -0,0 +1,97 @@+// biome-ignore-all format: keep this module under the mandated pure LOC budget.+import { readFile } from "node:fs/promises";+import { UlwLoopError } from "./types.js";+const VALUE_FLAGS = new Set("--brief --brief-file --session-id --codex-goal-mode --validation-batch-json --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 --proposals-json".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, flag) { return argv.includes(flag); }+export function readValue(argv, flag) {+ const index = argv.indexOf(flag);+ if (index >= 0) {+ const next = argv[index + 1];+ return next === undefined || next.startsWith("--") ? undefined : next;+ }+ const prefix = `${flag}=`;+ return argv.find((arg) => arg.startsWith(prefix))?.slice(prefix.length);+}+export function readRepeated(argv, flag) {+ const values = [];+ const prefix = `${flag}=`;+ for (let index = 0; index < argv.length; index += 1) {+ const arg = argv[index];+ const next = argv[index + 1];+ if (arg === flag && next !== undefined && !next.startsWith("--")) {+ values.push(next);+ index += 1;+ }+ else if (arg?.startsWith(prefix))+ values.push(arg.slice(prefix.length));+ }+ return values;+}+export function parseGoalArg(argv) { return readValue(argv, "--goal-id") ?? readValue(argv, "--goal"); }+export async function readStdin() {+ const chunks = [];+ for await (const chunk of process.stdin)+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));+ return Buffer.concat(chunks).toString("utf8");+}+export function positionalText(argv) {+ const words = [];+ for (let index = SUBCOMMANDS.has(argv[0] ?? "") ? 1 : 0; index < argv.length; index += 1) {+ const arg = argv[index];+ if (arg === undefined)+ continue;+ if (VALUE_FLAGS.has(arg)) {+ index += 1;+ continue;+ }+ if (arg.startsWith("--"))+ continue;+ words.push(arg);+ }+ return words.join(" ").trim();+}+function looksLikeJson(value) { const trimmed = value.trim(); return trimmed.startsWith("{") || trimmed.startsWith("["); }+export async function readJsonInput(value) {+ if (value === undefined)+ return undefined;+ try {+ return JSON.parse(looksLikeJson(value) ? value : await readFile(value, "utf8"));+ }+ catch (error) {+ const message = error instanceof Error ? error.message : "unknown error";+ throw new UlwLoopError(`Invalid JSON input: ${message}`, "ULW_LOOP_JSON_INPUT_INVALID", { cause: error });+ }+}+export async function parseCodexGoalJson(value) {+ if (value === undefined)+ return undefined;+ const raw = looksLikeJson(value) ? value : await readFile(value, "utf8");+ try {+ JSON.parse(raw);+ return raw;+ }+ catch (error) {+ const message = error instanceof Error ? error.message : "unknown error";+ throw new UlwLoopError(`Invalid --codex-goal-json: ${message}`, "ULW_LOOP_CODEX_GOAL_JSON_INVALID", { cause: error });+ }+}+function required(argv, flag, code) {+ const value = readValue(argv, flag)?.trim();+ if (value)+ return value;+ throw new UlwLoopError(`Missing ${flag}.`, code, { details: { flag } });+}+function evidenceStatus(value) {+ switch (value) {+ case "pass": return "pass";+ case "fail": return "fail";+ case "blocked": return "blocked";+ default: throw new UlwLoopError("Invalid --status; expected pass, fail, or blocked.", "ULW_LOOP_EVIDENCE_STATUS_INVALID", { details: { status: value } });+ }+}+export function parseRecordEvidenceArgs(argv) {+ 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/dist/cli-commands.d.ts b/plugins/omo/components/ulw-loop/dist/cli-commands.d.tsnew file mode 100644index 00000000..1c742408--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/cli-commands.d.ts@@ -0,0 +1,4 @@+export declare const ULW_LOOP_SUBCOMMANDS: readonly ["help", "create-goals", "status", "complete-goals", "checkpoint", "steer", "add-goal", "criteria", "record-evidence", "record-review-blockers"];+export type UlwLoopSubcommand = (typeof ULW_LOOP_SUBCOMMANDS)[number];+export declare function isUlwLoopSubcommand(value: string): value is UlwLoopSubcommand;+export declare function ulwLoopCommand(argv: readonly string[]): Promise<number>;diff --git a/plugins/omo/components/ulw-loop/dist/cli-commands.js b/plugins/omo/components/ulw-loop/dist/cli-commands.jsnew file mode 100644index 00000000..d421b0cd--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/cli-commands.js@@ -0,0 +1,99 @@+import { checkpoint } from "./checkpoint-continuation.js";+import { hasFlag, readValue } from "./cli-arg-parser.js";+import { printJsonError, ULW_LOOP_HELP } from "./cli-output.js";+import { addGoal, captureEvidence, completeGoals, createGoals, criteria, reviewBlockers, status, steer, } from "./cli-subcommands.js";+import { resolveUlwLoopSessionIdFromEnv } from "./paths.js";+import { UlwLoopError } from "./types.js";+export const ULW_LOOP_SUBCOMMANDS = [+ "help",+ "create-goals",+ "status",+ "complete-goals",+ "checkpoint",+ "steer",+ "add-goal",+ "criteria",+ "record-evidence",+ "record-review-blockers",+];+export function isUlwLoopSubcommand(value) {+ return ULW_LOOP_SUBCOMMANDS.includes(value);+}+export async function ulwLoopCommand(argv) {+ const head = argv[0] ?? "help";+ const command = head === "--help" || head === "-h" ? "help" : head;+ const rest = argv.slice(1);+ const repoRoot = process.cwd();+ const json = hasFlag(rest, "--json");+ try {+ const scope = commandScope(rest);+ if (!isUlwLoopSubcommand(command)) {+ if (json) {+ printJsonError(new UlwLoopError(`Unknown ulw-loop subcommand: ${command}.`, "ULW_LOOP_SUBCOMMAND_UNKNOWN", {+ details: { command },+ }));+ return 1;+ }+ process.stdout.write(`${ULW_LOOP_HELP}\n`);+ return 1;+ }+ switch (command) {+ case "help":+ process.stdout.write(`${ULW_LOOP_HELP}\n`);+ return 0;+ case "create-goals":+ return await createGoals(repoRoot, rest, json, scope);+ case "status":+ return await status(repoRoot, json, scope);+ case "complete-goals":+ return await completeGoals(repoRoot, rest, json, scope);+ 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:+ return unhandledSubcommand(command);+ }+ }+ catch (error) {+ if (json) {+ printJsonError(error);+ return 1;+ }+ 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 unhandledSubcommand(command) {+ throw new UlwLoopError(`Unhandled ulw-loop subcommand: ${String(command)}.`, "ULW_LOOP_SUBCOMMAND_UNHANDLED");+}+const SESSION_ID_FLAG = "--session-id";+function sessionIdFlagPresent(argv) {+ return hasFlag(argv, SESSION_ID_FLAG) || argv.some((arg) => arg.startsWith(`${SESSION_ID_FLAG}=`));+}+function commandScope(argv) {+ if (sessionIdFlagPresent(argv)) {+ const sessionId = readValue(argv, SESSION_ID_FLAG)?.trim();+ if (!sessionId) {+ throw new UlwLoopError(`${SESSION_ID_FLAG} requires a non-empty value.`, "ULW_LOOP_SESSION_ID_REQUIRED", {+ details: { flag: SESSION_ID_FLAG },+ });+ }+ return { sessionId };+ }+ const sessionId = resolveUlwLoopSessionIdFromEnv();+ return sessionId === null ? undefined : { sessionId };+}diff --git a/plugins/omo/components/ulw-loop/dist/cli-output.d.ts b/plugins/omo/components/ulw-loop/dist/cli-output.d.tsnew file mode 100644index 00000000..e3236041--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/cli-output.d.ts@@ -0,0 +1,7 @@+import type { UlwLoopCodexGoalMode, UlwLoopPlan } from "./types.js";+export declare const ULW_LOOP_HELP = "Usage:\n omo ulw-loop create-goals --brief \"...\" [--brief-file <path>] [--from-stdin] [--codex-goal-mode aggregate|per_story] [--validation-batch-json <json-or-path>] [--force] [--json]\n omo ulw-loop status [--json]\n omo ulw-loop complete-goals [--retry-failed] [--json]\n omo ulw-loop criteria --goal-id <id> [--json]\n omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status pass|fail|blocked --evidence \"...\" [--notes \"...\"] [--json]\n omo ulw-loop checkpoint --goal-id <id> --status complete|failed|blocked --evidence \"...\" --codex-goal-json <...> [--quality-gate-json <...>] [--no-advance] [--json]\n omo ulw-loop steer --kind <kind> ... --evidence \"...\" --rationale \"...\" [--proposals-json <json-or-path>] [--json]\n omo ulw-loop add-goal --title \"...\" --objective \"...\" [--json]\n omo ulw-loop record-review-blockers --goal-id <id> --title \"...\" --objective \"...\" --evidence \"...\" --codex-goal-json <...> [--json]\n\nAll subcommands accept [--session-id <id>] to isolate state under .omo/ulw-loop/<id>/; without it, Codex session env is used when present.";+export declare function printJson(value: unknown): void;+export declare function printJsonError(error: unknown): void;+export declare function printStatus(plan: UlwLoopPlan): void;+export declare function blockedDecisionHandoff(plan: UlwLoopPlan): string;+export declare function normalizeCodexGoalMode(value: string | undefined): UlwLoopCodexGoalMode;diff --git a/plugins/omo/components/ulw-loop/dist/cli-output.js b/plugins/omo/components/ulw-loop/dist/cli-output.jsnew file mode 100644index 00000000..e0f54bab--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/cli-output.js@@ -0,0 +1,73 @@+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] [--validation-batch-json <json-or-path>] [--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 <...>] [--no-advance] [--json]+ omo ulw-loop steer --kind <kind> ... --evidence "..." --rationale "..." [--proposals-json <json-or-path>] [--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.`;+export function printJson(value) {+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);+}+export function printJsonError(error) {+ if (error instanceof UlwLoopError) {+ printJson({+ ok: false,+ error: {+ code: error.code,+ message: error.message,+ ...(error.details === undefined ? {} : { details: error.details }),+ },+ });+ return;+ }+ if (error instanceof Error) {+ printJson({ ok: false, error: { code: "ULW_LOOP_UNEXPECTED", message: error.message } });+ return;+ }+ printJson({ ok: false, error: { code: "ULW_LOOP_UNKNOWN", message: "unknown error" } });+}+function criteriaCounts(goal) {+ 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) {+ let totalCriteria = 0;+ let passCriteria = 0;+ const lines = ["ulw-loop status", "", "goals:"];+ for (const goal of plan.goals) {+ const counts = criteriaCounts(goal);+ totalCriteria += counts.total;+ passCriteria += counts.pass;+ const marker = goal.id === plan.activeGoalId ? "*" : "-";+ lines.push(`${marker} ${goal.id} [${goal.status}] ${goal.title} (criteria: ${counts.pass}/${counts.total})`);+ }+ lines.push("", "summary:", `total goals: ${plan.goals.length}`, `criteria: ${passCriteria}/${totalCriteria} pass`);+ process.stdout.write(`${lines.join("\n")}\n`);+}+export function blockedDecisionHandoff(plan) {+ const blocked = plan.goals.find((goal) => goal.status === "needs_user_decision" && goal.nonRetriable);+ if (blocked === undefined)+ return "";+ return [+ "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) {+ if (value === undefined)+ return "aggregate";+ if (value === "aggregate" || value === "per_story")+ return value;+ throw new UlwLoopError("Invalid --codex-goal-mode; expected aggregate or per_story.", "ULW_LOOP_CODEX_GOAL_MODE_INVALID", { details: { value } });+}diff --git a/plugins/omo/components/ulw-loop/dist/cli-steering.d.ts b/plugins/omo/components/ulw-loop/dist/cli-steering.d.tsnew file mode 100644index 00000000..9ab58bc3--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/cli-steering.d.ts@@ -0,0 +1,15 @@+import type { SteerUlwLoopBatchResult } from "./steering-batch.js";+import type { SteerUlwLoopResult, UlwLoopSteeringMutationKind, UlwLoopSteeringProposal, UlwLoopSteeringSource, UlwLoopSuccessCriterionUserModel } from "./types.js";+export type CliSteeringProposal = UlwLoopSteeringProposal & {+ readonly goalId?: string;+ readonly scenario?: string;+ readonly expectedEvidence?: string;+ readonly userModel?: UlwLoopSuccessCriterionUserModel;+};+export declare function parseSteeringKind(argv: readonly string[]): UlwLoopSteeringMutationKind;+export declare function parseSteeringSource(argv: readonly string[]): UlwLoopSteeringSource;+export declare function parseSteeringProposal(argv: readonly string[]): Promise<CliSteeringProposal>;+export declare function normalizeSteeringProposal(proposal: CliSteeringProposal): CliSteeringProposal;+export declare function parseSteeringProposals(argv: readonly string[]): Promise<readonly CliSteeringProposal[]>;+export declare function printSteerResult(result: SteerUlwLoopResult, json: boolean): void;+export declare function printSteerBatchResult(result: SteerUlwLoopBatchResult, json: boolean): void;diff --git a/plugins/omo/components/ulw-loop/dist/cli-steering.js b/plugins/omo/components/ulw-loop/dist/cli-steering.jsnew file mode 100644index 00000000..e16e88e3--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/cli-steering.js@@ -0,0 +1,244 @@+// 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 { ULW_LOOP_STEERING_MUTATION_KINDS, ULW_LOOP_SUCCESS_CRITERION_USER_MODELS, UlwLoopError } from "./types.js";+const SOURCES = ["user_prompt_submit", "finding", "cli"];+const STEERING_KIND_HELP = [+ `Allowed --kind values: ${ULW_LOOP_STEERING_MUTATION_KINDS.join(", ")}`,+ "Kind-specific required flags:",+ " add_subgoal: --title, --objective, --evidence, --rationale",+ " split_subgoal: --goal-id, --children, --evidence, --rationale",+ " reorder_pending: --order, --evidence, --rationale",+ " revise_pending_wording: --goal-id, --title or --objective, --evidence, --rationale",+ " revise_criterion: --goal-id, --criterion-id, one of --scenario/--expected-evidence/--user-model, --evidence, --rationale",+ " annotate_ledger: --evidence, --rationale",+ " mark_blocked_superseded: --goal-id, optional --replacements, --evidence, --rationale",+ "Example: omo ulw-loop steer --kind annotate_ledger --evidence \"observed behavior\" --rationale \"why this changes the plan\" --json",+].join("\n");+function isKind(value) { return value !== undefined && ULW_LOOP_STEERING_MUTATION_KINDS.some((kind) => kind === value); }+function isSource(value) { return value !== undefined && SOURCES.some((source) => source === value); }+function isModel(value) { return ULW_LOOP_SUCCESS_CRITERION_USER_MODELS.some((model) => model === value); }+function fail(message, code, details) { throw new UlwLoopError(message, code, { details }); }+function kindMessage(prefix) { return `${prefix}\n\n${STEERING_KIND_HELP}`; }+function text(value, field) { 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, flag) { const value = text(readValue(argv, flag), flag); return value ?? fail(`Missing ${flag}.`, "ULW_LOOP_STEERING_FIELD_REQUIRED", { flag }); }+function requiredGoal(argv) { const value = text(parseGoalArg(argv), "--goal-id"); return value ?? fail("Missing --goal-id.", "ULW_LOOP_GOAL_ID_REQUIRED", { flag: "--goal-id" }); }+function readObject(value, key) { return Object.entries(value).find(([name]) => name === key)?.[1]; }+function isPlain(value) { return typeof value === "object" && value !== null && !Array.isArray(value); }+function objectText(value, key) { const candidate = readObject(value, key); return typeof candidate === "string" ? candidate : undefined; }+function objectStrings(value, key) { const candidate = readObject(value, key); return Array.isArray(candidate) && candidate.every((item) => typeof item === "string") ? candidate : undefined; }+function objectChildren(value, key) { const candidate = readObject(value, key); if (!Array.isArray(candidate))+ return undefined; const parsed = []; for (const item of candidate) {+ const next = child(item);+ if (next === null)+ return fail(`${key} entries require title/objective.`, "ULW_LOOP_STEERING_CHILD_INVALID", { key });+ parsed.push(next);+} return parsed; }+function isProposalKind(value) { return typeof value === "string" && ULW_LOOP_STEERING_MUTATION_KINDS.some((kind) => kind === value); }+function isProposalSource(value) { return typeof value === "string" && SOURCES.some((source) => source === value); }+export function parseSteeringKind(argv) {+ const value = readValue(argv, "--kind");+ if (isKind(value))+ return value;+ return value === undefined ? fail(kindMessage("Missing --kind."), "ULW_LOOP_STEERING_KIND_REQUIRED", { flag: "--kind", expected: ULW_LOOP_STEERING_MUTATION_KINDS, usage: STEERING_KIND_HELP }) : fail(kindMessage(`Invalid --kind: ${value}.`), "ULW_LOOP_STEERING_KIND_INVALID", { value, expected: ULW_LOOP_STEERING_MUTATION_KINDS, usage: STEERING_KIND_HELP });+}+export function parseSteeringSource(argv) {+ const value = readValue(argv, "--source");+ if (value === undefined)+ return "cli";+ return isSource(value) ? value : fail(`Invalid --source: ${value}.`, "ULW_LOOP_STEERING_SOURCE_INVALID", { value, expected: SOURCES });+}+function child(value) {+ 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, flag, needed) {+ 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.`, "ULW_LOOP_STEERING_JSON_ARRAY_REQUIRED", { flag });+ const parsed = [];+ 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, flag) {+ const raw = await readJsonInput(required(argv, flag));+ if (!Array.isArray(raw))+ return fail(`${flag} must be a JSON array.`, "ULW_LOOP_STEERING_JSON_ARRAY_REQUIRED", { flag });+ const values = [];+ 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) { 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) { return fail(`Unsupported steering kind: ${String(kind)}.`, "ULW_LOOP_STEERING_KIND_UNSUPPORTED", { kind }); }+export async function parseSteeringProposal(argv) {+ const kind = parseSteeringKind(argv);+ const source = parseSteeringSource(argv);+ const idempotencyKey = text(readValue(argv, "--idempotency-key"), "--idempotency-key");+ const base = { kind, source, evidence: required(argv, "--evidence"), rationale: required(argv, "--rationale"), ...(idempotencyKey === undefined ? {} : { idempotencyKey }) };+ switch (kind) {+ case "add_subgoal": return normalizeSteeringProposal({ ...base, title: required(argv, "--title"), objective: required(argv, "--objective") });+ case "split_subgoal": {+ const goalId = requiredGoal(argv);+ return normalizeSteeringProposal({ ...base, goalId, targetGoalId: goalId, childGoals: await children(argv, "--children", true) });+ }+ case "reorder_pending": return normalizeSteeringProposal({ ...base, pendingOrder: await stringArray(argv, "--order") });+ case "revise_pending_wording": {+ const goalId = requiredGoal(argv);+ const revisedTitle = readValue(argv, "--title");+ const revisedObjective = readValue(argv, "--objective");+ if (revisedTitle === undefined && revisedObjective === undefined)+ return fail("revise_pending_wording requires --title or --objective.", "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) { if (values === undefined)+ return undefined; return values.map((item) => ({ title: text(item.title, "child.title") ?? "", objective: text(item.objective, "child.objective") ?? "" })); }+function normalizedStrings(values, field) { if (values === undefined)+ return undefined; return values.map((value) => text(value, field) ?? ""); }+export function normalizeSteeringProposal(proposal) {+ const evidence = text(proposal.evidence, "evidence") ?? "";+ const rationale = text(proposal.rationale, "rationale") ?? "";+ const goalId = text(proposal.goalId, "goalId");+ const targetGoalId = text(proposal.targetGoalId, "targetGoalId");+ const targetGoalIds = normalizedStrings(proposal.targetGoalIds, "targetGoalIds");+ const criterionId = text(proposal.criterionId, "criterionId");+ const title = text(proposal.title, "title");+ const objective = text(proposal.objective, "objective");+ const revisedTitle = text(proposal.revisedTitle, "revisedTitle");+ const revisedObjective = text(proposal.revisedObjective, "revisedObjective");+ const blockedReason = text(proposal.blockedReason, "blockedReason");+ const directiveText = text(proposal.directiveText, "directiveText");+ const promptSignature = text(proposal.promptSignature, "promptSignature");+ const idempotencyKey = text(proposal.idempotencyKey, "idempotencyKey");+ const scenario = text(proposal.scenario, "scenario");+ const expectedEvidence = text(proposal.expectedEvidence, "expectedEvidence");+ const childGoals = normalizedChildren(proposal.childGoals);+ const pendingOrder = normalizedStrings(proposal.pendingOrder, "pendingOrder");+ return { kind: proposal.kind, source: proposal.source, evidence, rationale, ...(goalId === undefined ? {} : { goalId }), ...(targetGoalId === undefined ? {} : { targetGoalId }), ...(targetGoalIds === undefined ? {} : { targetGoalIds }), ...(criterionId === undefined ? {} : { criterionId }), ...(title === undefined ? {} : { title }), ...(objective === undefined ? {} : { objective }), ...(childGoals === undefined ? {} : { childGoals }), ...(revisedTitle === undefined ? {} : { revisedTitle }), ...(revisedObjective === undefined ? {} : { revisedObjective }), ...(pendingOrder === undefined ? {} : { pendingOrder }), ...(blockedReason === undefined ? {} : { blockedReason }), ...(proposal.after === undefined ? {} : { after: proposal.after }), ...(directiveText === undefined ? {} : { directiveText }), ...(promptSignature === undefined ? {} : { promptSignature }), ...(idempotencyKey === undefined ? {} : { idempotencyKey }), ...(proposal.now === undefined ? {} : { now: proposal.now }), ...(scenario === undefined ? {} : { scenario }), ...(expectedEvidence === undefined ? {} : { expectedEvidence }), ...(proposal.userModel === undefined ? {} : { userModel: proposal.userModel }) };+}+export async function parseSteeringProposals(argv) {+ const input = text(readValue(argv, "--proposals-json"), "--proposals-json");+ if (input === undefined)+ return [await parseSteeringProposal(argv)];+ if (readValue(argv, "--kind") !== undefined)+ return fail("--kind and --proposals-json are mutually exclusive.", "ULW_LOOP_STEERING_BATCH_CONFLICT", { flags: ["--kind", "--proposals-json"] });+ const raw = await readJsonInput(input);+ if (!Array.isArray(raw) || raw.length === 0)+ return fail("--proposals-json must be a non-empty JSON array.", "ULW_LOOP_STEERING_BATCH_ARRAY_REQUIRED", { flag: "--proposals-json" });+ const proposals = [];+ for (const item of raw)+ proposals.push(normalizeSteeringProposal(proposalFromObject(item)));+ return proposals;+}+function proposalFromObject(value) {+ if (!isPlain(value))+ return fail("--proposals-json entries must be objects.", "ULW_LOOP_STEERING_BATCH_ITEM_INVALID", { flag: "--proposals-json" });+ const kind = readObject(value, "kind");+ const source = readObject(value, "source") ?? "cli";+ if (!isProposalKind(kind))+ return fail(`Invalid batch steering kind: ${String(kind)}.`, "ULW_LOOP_STEERING_KIND_INVALID", { value: kind });+ if (!isProposalSource(source))+ return fail(`Invalid batch steering source: ${String(source)}.`, "ULW_LOOP_STEERING_SOURCE_INVALID", { value: source });+ let proposal = { kind, source, evidence: objectText(value, "evidence") ?? "", rationale: objectText(value, "rationale") ?? "" };+ const goalId = objectText(value, "goalId");+ const targetGoalId = objectText(value, "targetGoalId");+ const criterionId = objectText(value, "criterionId");+ const title = objectText(value, "title");+ const objective = objectText(value, "objective");+ const revisedTitle = objectText(value, "revisedTitle");+ const revisedObjective = objectText(value, "revisedObjective");+ const scenario = objectText(value, "scenario");+ const expectedEvidence = objectText(value, "expectedEvidence");+ const idempotencyKey = objectText(value, "idempotencyKey");+ const targetGoalIds = objectStrings(value, "targetGoalIds");+ const pendingOrder = objectStrings(value, "pendingOrder");+ const childGoals = objectChildren(value, "childGoals");+ if (goalId !== undefined)+ proposal = { ...proposal, goalId };+ if (targetGoalId !== undefined)+ proposal = { ...proposal, targetGoalId };+ if (criterionId !== undefined)+ proposal = { ...proposal, criterionId };+ if (title !== undefined)+ proposal = { ...proposal, title };+ if (objective !== undefined)+ proposal = { ...proposal, objective };+ if (revisedTitle !== undefined)+ proposal = { ...proposal, revisedTitle };+ if (revisedObjective !== undefined)+ proposal = { ...proposal, revisedObjective };+ if (scenario !== undefined)+ proposal = { ...proposal, scenario };+ if (expectedEvidence !== undefined)+ proposal = { ...proposal, expectedEvidence };+ if (idempotencyKey !== undefined)+ proposal = { ...proposal, idempotencyKey };+ if (targetGoalIds !== undefined)+ proposal = { ...proposal, targetGoalIds };+ if (pendingOrder !== undefined)+ proposal = { ...proposal, pendingOrder };+ if (childGoals !== undefined)+ proposal = { ...proposal, childGoals };+ return proposal;+}+export function printSteerResult(result, json) {+ 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(`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);+}+export function printSteerBatchResult(result, json) {+ if (json) {+ printJson({ ok: result.accepted, accepted: result.accepted, rejectedReasons: result.rejectedReasons, results: result.results, plan: result.plan });+ return;+ }+ process.stdout.write(`ulw-loop steer batch: ${result.accepted ? "accepted" : "rejected"} ${result.results.length} proposal(s)\n`);+ if (result.rejectedReasons.length > 0)+ process.stdout.write(`rejected: ${result.rejectedReasons.join("; ")}\n`);+ printStatus(result.plan);+}diff --git a/plugins/omo/components/ulw-loop/dist/cli-subcommands.d.ts b/plugins/omo/components/ulw-loop/dist/cli-subcommands.d.tsnew file mode 100644index 00000000..e1c76994--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/cli-subcommands.d.ts@@ -0,0 +1,9 @@+import { type UlwLoopScope } from "./paths.js";+export declare function createGoals(repoRoot: string, argv: readonly string[], json: boolean, scope?: UlwLoopScope): Promise<number>;+export declare function status(repoRoot: string, json: boolean, scope?: UlwLoopScope): Promise<number>;+export declare function completeGoals(repoRoot: string, argv: readonly string[], json: boolean, scope?: UlwLoopScope): Promise<number>;+export declare function steer(repoRoot: string, argv: readonly string[], json: boolean, scope?: UlwLoopScope): Promise<number>;+export declare function addGoal(repoRoot: string, argv: readonly string[], json: boolean, scope?: UlwLoopScope): Promise<number>;+export declare function criteria(repoRoot: string, argv: readonly string[], json: boolean, scope?: UlwLoopScope): Promise<number>;+export declare function captureEvidence(repoRoot: string, argv: readonly string[], json: boolean, scope?: UlwLoopScope): Promise<number>;+export declare function reviewBlockers(repoRoot: string, argv: readonly string[], json: boolean, scope?: UlwLoopScope): Promise<number>;diff --git a/plugins/omo/components/ulw-loop/dist/cli-subcommands.js b/plugins/omo/components/ulw-loop/dist/cli-subcommands.jsnew file mode 100644index 00000000..984bfff4--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/cli-subcommands.js@@ -0,0 +1,164 @@+import { readFile } from "node:fs/promises";+import { hasFlag, parseCodexGoalJson, parseRecordEvidenceArgs, positionalText, readStdin, readValue, } from "./cli-arg-parser.js";+import { blockedDecisionHandoff, normalizeCodexGoalMode, printJson, printStatus } from "./cli-output.js";+import { parseSteeringProposals, printSteerBatchResult, printSteerResult } from "./cli-steering.js";+import { buildCodexGoalInstruction } from "./codex-goal-instruction.js";+import { recordEvidence } from "./evidence.js";+import { isEssentialCriterion } from "./goal-status.js";+import { ulwLoopAttemptEvidenceDir } 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 { steerUlwLoopBatch } from "./steering-batch.js";+import { UlwLoopError } from "./types.js";+export async function createGoals(repoRoot, argv, json, scope) {+ 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 validationBatchesJson = readValue(argv, "--validation-batch-json");+ const plan = await createUlwLoopPlan(repoRoot, {+ brief,+ codexGoalMode: normalizeCodexGoalMode(readValue(argv, "--codex-goal-mode")),+ force: hasFlag(argv, "--force"),+ ...(validationBatchesJson === undefined ? {} : { validationBatchesJson }),+ }, 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;+}+export async function status(repoRoot, json, scope) {+ const plan = await readUlwLoopPlan(repoRoot, scope);+ if (json) {+ const active = plan.goals.find((goal) => goal.id === plan.activeGoalId);+ const currentAttemptDir = plan.evidenceLayoutVersion === 2 && active+ ? ulwLoopAttemptEvidenceDir(active.id, active.attempt, scope)+ : undefined;+ printJson({+ ok: true,+ plan,+ summary: summarizeUlwLoopPlan(plan),+ ...(currentAttemptDir === undefined ? {} : { currentAttemptDir }),+ });+ }+ else+ printStatus(plan);+ return 0;+}+export async function completeGoals(repoRoot, argv, json, scope) {+ 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;+}+export async function steer(repoRoot, argv, json, scope) {+ const proposals = await parseSteeringProposals(argv);+ const single = proposals[0];+ if (single !== undefined && proposals.length === 1 && readValue(argv, "--proposals-json") === undefined) {+ const result = await steerUlwLoop(repoRoot, single, scope);+ printSteerResult(result, json);+ return result.accepted ? 0 : 1;+ }+ const result = await steerUlwLoopBatch(repoRoot, proposals, scope);+ printSteerBatchResult(result, json);+ return result.accepted ? 0 : 1;+}+export async function addGoal(repoRoot, argv, json, scope) {+ 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;+}+export async function criteria(repoRoot, argv, json, scope) {+ 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(formatCriterionForCli).join("\n")}\n`);+ }+ return 0;+}+export async function captureEvidence(repoRoot, argv, json, scope) {+ 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;+}+export async function reviewBlockers(repoRoot, argv, json, scope) {+ 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 formatCriterionForCli(criterion) {+ const marker = isEssentialCriterion(criterion) ? "essential" : "non-essential";+ return `- ${criterion.id} [${criterion.status}] [${marker}] (${criterion.userModel}) ${criterion.scenario} evidence: ${criterion.capturedEvidence ?? "pending"}`;+}+function required(argv, flag) {+ const value = readValue(argv, flag)?.trim();+ if (value)+ return value;+ throw new UlwLoopError(`Missing ${flag}.`, "ULW_LOOP_ARGUMENT_MISSING", { details: { flag } });+}+function findGoal(plan, goalId) {+ 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/ulw-loop/dist/cli.d.ts b/plugins/omo/components/ulw-loop/dist/cli.d.tsnew file mode 100644index 00000000..b7988016--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/cli.d.ts@@ -0,0 +1,2 @@+#!/usr/bin/env node+export {};diff --git a/plugins/omo/components/ulw-loop/dist/cli.js b/plugins/omo/components/ulw-loop/dist/cli.jsnew file mode 100644index 00000000..ae37de02--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/cli.js@@ -0,0 +1,3455 @@+#!/usr/bin/env node++// components/ulw-loop/src/checkpoint.ts+import { existsSync as existsSync3, statSync } from "node:fs";+import { readFile as readFile5 } from "node:fs/promises";+import { resolve as resolve3 } from "node:path";++// components/ulw-loop/src/checkpoint-reconciliation.ts+import { existsSync } from "node:fs";+import { readFile } from "node:fs/promises";++// components/ulw-loop/src/paths.ts+import { isAbsolute, join, relative, sep } from "node:path";+// components/ulw-loop/src/constants.ts+var ULW_LOOP_DIR = ".omo/ulw-loop";+var ULW_LOOP_BRIEF = "brief.md";+var ULW_LOOP_GOALS = "goals.json";+var ULW_LOOP_LEDGER = "ledger.jsonl";+var ULW_LOOP_STEERING_MUTATION_KINDS = [+ "add_subgoal",+ "split_subgoal",+ "reorder_pending",+ "revise_pending_wording",+ "revise_criterion",+ "annotate_ledger",+ "mark_blocked_superseded"+];+var ULW_LOOP_SUCCESS_CRITERION_USER_MODELS = [+ "happy",+ "edge",+ "regression",+ "adversarial"+];+// components/ulw-loop/src/runtime.ts+class UlwLoopError extends Error {+ code;+ details;+ constructor(message, code, opts) {+ super(message, opts?.cause === undefined ? undefined : { cause: opts.cause });+ this.name = "UlwLoopError";+ this.code = code;+ if (opts?.details !== undefined) {+ this.details = opts.details;+ }+ }+}+function iso() {+ return new Date().toISOString();+}+// components/ulw-loop/src/paths.ts+var SESSION_ENV_KEYS = ["OMO_ULW_LOOP_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID"];+function normalizeUlwLoopSessionId(sessionId) {+ 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;+}+function resolveUlwLoopSessionIdFromEnv(env = process.env) {+ for (const key of SESSION_ENV_KEYS) {+ const normalized = normalizeUlwLoopSessionId(env[key]);+ if (normalized !== null)+ return normalized;+ }+ return null;+}+function ulwLoopRelativeDir(scope) {+ const sessionId = normalizeUlwLoopSessionId(scope?.sessionId);+ return sessionId === null ? ULW_LOOP_DIR : `${ULW_LOOP_DIR}/${sessionId}`;+}+function ulwLoopDir(repoRoot, scope) {+ return join(repoRoot, ulwLoopRelativeDir(scope));+}+function ulwLoopBriefRelativePath(scope) {+ return `${ulwLoopRelativeDir(scope)}/${ULW_LOOP_BRIEF}`;+}+function ulwLoopGoalsRelativePath(scope) {+ return `${ulwLoopRelativeDir(scope)}/${ULW_LOOP_GOALS}`;+}+function ulwLoopLedgerRelativePath(scope) {+ return `${ulwLoopRelativeDir(scope)}/${ULW_LOOP_LEDGER}`;+}+function ulwLoopBriefPath(repoRoot, scope) {+ return join(ulwLoopDir(repoRoot, scope), ULW_LOOP_BRIEF);+}+function ulwLoopGoalsPath(repoRoot, scope) {+ return join(ulwLoopDir(repoRoot, scope), ULW_LOOP_GOALS);+}+function ulwLoopLedgerPath(repoRoot, scope) {+ return join(ulwLoopDir(repoRoot, scope), ULW_LOOP_LEDGER);+}+function repoRelative(absolutePath, repoRoot) {+ 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("/");+}+function ulwLoopAttemptEvidenceDir(goalId, attempt, scope) {+ const sessionId = normalizeUlwLoopSessionId(scope?.sessionId) ?? resolveUlwLoopSessionIdFromEnv() ?? "session";+ return `.omo/evidence/ulw/${sessionId}/${goalId}/a${attempt}`;+}+var PLATFORM_PATH_API = { relative, isAbsolute, sep };+function isWithinAttemptDir(absolutePath, attemptRoot, pathApi = PLATFORM_PATH_API) {+ const relativePath = pathApi.relative(attemptRoot, absolutePath);+ if (relativePath === "")+ return true;+ if (relativePath === ".." || relativePath.startsWith(`..${pathApi.sep}`))+ return false;+ return !pathApi.isAbsolute(relativePath);+}++// components/ulw-loop/src/goal-status.ts+var ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE = aggregateCodexObjectiveForScope();+function aggregateCodexObjectiveForScope(scope) {+ 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.`;+}+function codexGoalMode(plan) {+ return plan.codexGoalMode ?? "per_story";+}+function isResolvedStatus(status) {+ return status === "complete";+}+function isMemberResolved(goal, plan) {+ return isResolvedStatus(goal.status) || isSupersededResolved(goal, plan);+}+function isSupersededResolved(goal, plan) {+ if (goal.steeringStatus !== "superseded")+ return false;+ const replacements = goal.supersededBy ?? [];+ if (replacements.length === 0)+ return false;+ return replacements.every((id) => {+ const replacement = plan.goals.find((candidate) => candidate.id === id);+ return replacement !== undefined && isResolvedStatus(replacement.status);+ });+}+function isCompletionBlocking(goal, plan) {+ if (goal.steeringStatus === "superseded")+ return !isSupersededResolved(goal, plan);+ if (goal.steeringStatus === "blocked")+ return true;+ return !isResolvedStatus(goal.status);+}+function isCompletionBlockingForFinalCandidate(candidate, finalCandidate, plan) {+ if (candidate.id === finalCandidate.id)+ return false;+ if (candidate.steeringStatus === "superseded") {+ const replacements = candidate.supersededBy ?? [];+ if (replacements.length === 0)+ return true;+ return !replacements.every((id) => {+ if (id === finalCandidate.id)+ return true;+ const replacement = plan.goals.find((goal) => goal.id === id);+ return replacement !== undefined && isResolvedStatus(replacement.status);+ });+ }+ return isCompletionBlocking(candidate, plan);+}+function isUlwLoopDone(plan) {+ if (plan.aggregateCompletion?.status === "complete")+ return true;+ return plan.goals.every((goal) => !isCompletionBlocking(goal, plan));+}+function isFinalRunCompletionCandidate(plan, goal) {+ return isCompletionBlocking(goal, plan) && plan.goals.every((candidate) => !isCompletionBlockingForFinalCandidate(candidate, goal, plan));+}+function aggregateCodexObjective(plan) {+ return plan.codexObjective ?? ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE;+}+function expectedCodexObjective(plan, goal) {+ return codexGoalMode(plan) === "aggregate" ? aggregateCodexObjective(plan) : goal.objective;+}+function compatibleCodexObjectives(plan) {+ return [aggregateCodexObjective(plan), ...plan.codexObjectiveAliases ?? []];+}+function hasAllCriteriaPass(goal) {+ return goal.successCriteria.length > 0 && goal.successCriteria.every((criterion) => criterion.status === "pass");+}+function isEssentialCriterion(criterion) {+ return criterion.essential ?? true;+}+function essentialCriteriaOf(goal) {+ const explicit = goal.successCriteria.filter(isEssentialCriterion);+ if (explicit.length > 0)+ return explicit;+ const happy = goal.successCriteria.find((criterion) => criterion.userModel === "happy");+ return happy === undefined ? [] : [happy];+}+function hasEssentialCriteriaPass(goal) {+ const criteria = essentialCriteriaOf(goal);+ return criteria.length > 0 && criteria.every((criterion) => criterion.status === "pass");+}++// components/ulw-loop/src/checkpoint-reconciliation.ts+function normalizeObjective(value) {+ return value.replace(/\s+/g, " ").trim();+}+function textMentionsUlwLoopPlanArtifact(value) {+ const normalized = (value ?? "").toLowerCase();+ return normalized.includes(ULW_LOOP_DIR.toLowerCase()) || normalized.includes(ULW_LOOP_GOALS.toLowerCase()) || normalized.includes(ULW_LOOP_LEDGER.toLowerCase());+}+function textMentionsGoalId(value, goalId) {+ return (value ?? "").toLowerCase().includes(goalId.toLowerCase());+}+function textHasCompletionValidationEvidence(value) {+ const normalized = (value ?? "").toLowerCase();+ const done = /\b(?:planned work|implementation|deliverables?|scope|task|work)\b/.test(normalized) && /\b(?:done|complete|completed|finished|shipped)\b/.test(normalized);+ const verified = /\b(?:validation|verification|tests?|build|lint|review|quality gate|code-review)\b/.test(normalized) && /\b(?:passed|complete|completed|clean|green|approve|approved|clear)\b/.test(normalized);+ return done && verified;+}+async function snapshotObjectiveMapsToUlwLoopPlan(repoRoot, snapshotObjective, scope) {+ const actual = normalizeObjective(snapshotObjective).toLowerCase();+ if (textMentionsUlwLoopPlanArtifact(actual))+ return true;+ if (actual.length < 24 || !existsSync(ulwLoopBriefPath(repoRoot, scope)))+ return false;+ try {+ 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;+ throw error;+ }+}+async function canReconcileCompletedTaskScopedAggregateSnapshot(repoRoot, plan, goal, snapshotObjective, evidence, scope) {+ if (codexGoalMode(plan) !== "aggregate")+ return false;+ if (goal.status !== "in_progress" || plan.activeGoalId !== 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 snapshotObjectiveMapsToUlwLoopPlan(repoRoot, snapshotObjective, scope);+}+async function canReconcileActiveFinalTaskScopedAggregateSnapshot(repoRoot, plan, goal, snapshotObjective, evidence, scope) {+ 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) {+ 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 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, final) {+ 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 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/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)}`;+}++// components/ulw-loop/src/codex-goal-snapshot.ts+import { existsSync as existsSync2 } from "node:fs";+import { readFile as readFile2 } from "node:fs/promises";+import { resolve } from "node:path";++class CodexGoalSnapshotError extends Error {+}+function safeObject(value) {+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};+}+function safeString(value) {+ return typeof value === "string" ? value.trim() : "";+}+function normalizeStatus(value) {+ const status = safeString(value).toLowerCase();+ if (status === "complete" || status === "completed" || status === "done")+ return "complete";+ if (status === "cancelled" || status === "canceled")+ return "cancelled";+ if (status === "failed" || status === "failure")+ return "failed";+ if (status === "active" || status === "in_progress" || status === "pending" || status === "running")+ return "active";+ return "unknown";+}+function normalizeObjective2(value) {+ return value.replace(/\s+/g, " ").trim();+}+function parseCodexGoalSnapshot(value) {+ const root = safeObject(value);+ const goalValue = Object.hasOwn(root, "goal") ? root["goal"] : value;+ if (goalValue === null || goalValue === undefined || goalValue === false) {+ return { available: false, raw: value };+ }+ const goal = safeObject(goalValue);+ const objective = safeString(goal["objective"] ?? goal["goal"] ?? goal["description"] ?? root["objective"]);+ const status = normalizeStatus(goal["status"] ?? root["status"]);+ return {+ available: Boolean(objective || status !== "unknown"),+ ...objective ? { objective } : {},+ status,+ raw: value+ };+}+async function readCodexGoalSnapshotInput(raw, cwd = process.cwd()) {+ if (!raw?.trim())+ return null;+ const trimmed = raw.trim();+ try {+ return parseCodexGoalSnapshot(JSON.parse(trimmed));+ } catch {+ const path = resolve(cwd, trimmed);+ if (!existsSync2(path)) {+ throw new CodexGoalSnapshotError(`Codex goal snapshot is neither valid JSON nor a readable path: ${trimmed}`);+ }+ try {+ return parseCodexGoalSnapshot(JSON.parse(await readFile2(path, "utf-8")));+ } catch (error) {+ throw new CodexGoalSnapshotError(`Codex goal snapshot path does not contain valid JSON: ${trimmed}${error instanceof Error ? ` (${error.message})` : ""}`);+ }+ }+}+function reconcileCodexGoalSnapshot(snapshot, options) {+ const effectiveSnapshot = snapshot ?? { available: false, raw: null };+ const errors = [];+ const warnings = [];+ if (!effectiveSnapshot.available) {+ const message = "Codex goal snapshot is absent or reports no active goal; call get_goal and pass its JSON with --codex-goal-json.";+ if (options.requireSnapshot)+ errors.push(message);+ else+ warnings.push(message);+ return { ok: errors.length === 0, snapshot: effectiveSnapshot, warnings, errors };+ }+ const expected = normalizeObjective2(options.expectedObjective);+ const accepted = new Set([expected, ...(options.acceptedObjectives ?? []).map((objective) => normalizeObjective2(objective))].filter(Boolean));+ const actual = normalizeObjective2(effectiveSnapshot.objective ?? "");+ if (!actual) {+ errors.push("Codex goal snapshot is missing objective text.");+ } else if (!accepted.has(actual)) {+ errors.push(`Codex goal objective mismatch: expected "${expected}", got "${actual}".`);+ }+ const allowed = options.allowedStatuses ?? (options.requireComplete ? ["complete"] : ["active", "complete"]);+ const actualStatus = effectiveSnapshot.status ?? "unknown";+ if (!allowed.includes(actualStatus)) {+ errors.push(`Codex goal status mismatch: expected ${allowed.join(" or ")}, got ${actualStatus}.`);+ }+ if (options.requireComplete && actualStatus !== "complete") {+ errors.push('Codex goal is not complete; call update_goal({status: "complete"}) only after the objective is actually complete, then pass the fresh get_goal JSON.');+ }+ return { ok: errors.length === 0, snapshot: effectiveSnapshot, warnings, errors };+}+function formatCodexGoalReconciliation(reconciliation) {+ const parts = [...reconciliation.errors, ...reconciliation.warnings];+ return parts.join(" ");+}++// components/ulw-loop/src/plan-io.ts+import { createReadStream } from "node:fs";+import { appendFile, mkdir, readFile as readFile3, rename, writeFile } from "node:fs/promises";+import { createInterface } from "node:readline";+var LEGACY_OBJECTIVE_PREFIX = `Complete all ulw-loop stories in ${ULW_LOOP_DIR}/${ULW_LOOP_GOALS}: `;+var 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.`;+var locks = new Map;+function hasCode(error, code) {+ return error instanceof Error && "code" in error && error.code === code;+}+function isLegacyEnumeratedAggregateObjective(objective) {+ return objective === LEGACY_OBJECTIVE || Boolean(objective?.startsWith(LEGACY_OBJECTIVE_PREFIX));+}+function isSteeringKind(value) {+ return value === "steering_accepted" || value === "steering_rejected" || value === "criteria_revised" || value === "batch_updated";+}+async function withUlwLoopMutationLock(repoRoot, scopeOrFn, maybeFn) {+ 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}\x00${ulwLoopRelativeDir(scope)}`;+ const prior = locks.get(lockKey) ?? Promise.resolve(undefined);+ const run = prior.then(fn, fn);+ const gate = run.then(() => {+ return;+ }, () => {+ return;+ });+ locks.set(lockKey, gate);+ gate.then(() => {+ if (locks.get(lockKey) === gate)+ locks.delete(lockKey);+ });+ return run;+}+async function readUlwLoopPlan(repoRoot, scope) {+ const path = ulwLoopGoalsPath(repoRoot, scope);+ let raw;+ try {+ raw = await readFile3(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 = 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;+}+async function writePlan(repoRoot, plan, scope) {+ 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)}+`, "utf8");+ await rename(tmpPath, path);+}+async function appendLedger(repoRoot, entry, scope) {+ await appendLedgerEntries(repoRoot, [entry], scope);+}+async function appendLedgerEntries(repoRoot, entries, scope) {+ if (entries.length === 0)+ return;+ await mkdir(ulwLoopDir(repoRoot, scope), { recursive: true });+ await appendFile(ulwLoopLedgerPath(repoRoot, scope), `${entries.map((entry) => JSON.stringify(entry)).join(`+`)}+`, "utf8");+}+async function* ledgerLines(repoRoot, scope) {+ const stream = createReadStream(ulwLoopLedgerPath(repoRoot, scope), { encoding: "utf8" });+ const lines = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });+ try {+ for await (const line of lines) {+ if (line.trim().length > 0)+ yield line;+ }+ } catch (error) {+ if (!hasCode(error, "ENOENT"))+ throw error;+ } finally {+ lines.close();+ stream.destroy();+ }+}+async function findAcceptedSteeringLedgerEntry(repoRoot, key, scope) {+ const probe = JSON.stringify(key);+ for await (const line of ledgerLines(repoRoot, scope)) {+ if (!line.includes(probe))+ continue;+ const entry = JSON.parse(line);+ if (!isSteeringKind(entry.kind))+ continue;+ if (entry.steering?.invariant.accepted !== true)+ continue;+ if (entry.idempotencyKey === key || entry.steering.idempotencyKey === key || entry.steering.promptSignature === key)+ return entry;+ }+ return;+}++// components/ulw-loop/src/evidence.ts+function ulwLoopFail(message, code, details) {+ throw new UlwLoopError(message, code, { details });+}+function ledgerKind(status) {+ switch (status) {+ case "pass":+ return "evidence_captured";+ case "fail":+ return "criterion_failed";+ case "blocked":+ return "criterion_blocked";+ default:+ return ulwLoopFail("Invalid criterion status.", "ULW_LOOP_CRITERION_STATUS_INVALID", { status });+ }+}+function findGoal(plan, goalId) {+ const goal = plan.goals.find((candidate) => candidate.id === goalId);+ return goal ?? ulwLoopFail(`UlwLoop goal not found: ${goalId}.`, "ULW_LOOP_GOAL_NOT_FOUND", { goalId });+}+function findCriterion(goal, criterionId) {+ const criterion = goal.successCriteria.find((candidate) => candidate.id === criterionId);+ return criterion ?? ulwLoopFail(`Success criterion not found: ${criterionId}.`, "ULW_LOOP_CRITERION_NOT_FOUND", {+ goalId: goal.id,+ criterionId+ });+}+function nonEmptyEvidence(evidence) {+ const trimmed = evidence.trim();+ return trimmed || ulwLoopFail("Evidence must be a non-empty string.", "ULW_LOOP_EVIDENCE_REQUIRED", {});+}+async function recordEvidence(repoRoot, args, scope) {+ 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);+ const kind = ledgerKind(args.status);+ const prevStatus = criterion.status;+ const capturedAt = iso();+ criterion.status = args.status;+ criterion.capturedEvidence = evidence;+ criterion.capturedAt = capturedAt;+ if (args.notes !== undefined)+ criterion.notes = args.notes;+ goal.updatedAt = capturedAt;+ plan.updatedAt = capturedAt;+ await writePlan(repoRoot, plan, scope);+ const ledgerEntry = {+ at: capturedAt,+ kind,+ goalId: goal.id,+ criterionId: criterion.id,+ criterionStatus: args.status,+ evidence,+ capturedEvidence: evidence,+ before: { status: prevStatus },+ after: { goalId: goal.id, criterionId: criterion.id, status: args.status, evidence, capturedAt, prevStatus }+ };+ await appendLedger(repoRoot, ledgerEntry, scope);+ return { plan, goal, criterion, ledgerEntry };+ });+}+function unresolvedCriteriaOf(goal) {+ return goal.successCriteria.filter((criterion) => criterion.status !== "pass");+}+function unresolvedEssentialCriteriaOf(goal) {+ const essentialCriteria = new Set(essentialCriteriaOf(goal).map((criterion) => criterion.id));+ return goal.successCriteria.filter((criterion) => essentialCriteria.has(criterion.id) && criterion.status !== "pass");+}+function requireAllCriteriaPass(goal) {+ if (hasAllCriteriaPass(goal))+ return;+ 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 }))+ }+ });+}+function requireAllPlanCriteriaPass(plan) {+ const unresolved = plan.goals.flatMap((goal) => unresolvedCriteriaOf(goal).map((criterion) => ({+ goalId: goal.id,+ id: criterion.id,+ status: criterion.status+ })));+ if (unresolved.length === 0)+ return;+ throw new UlwLoopError("Ulw-loop aggregate has unresolved success criteria.", "ulw_loop_criteria_not_all_pass", {+ details: { unresolved }+ });+}+function requireEssentialCriteriaPass(goal) {+ if (hasEssentialCriteriaPass(goal))+ return;+ throw new UlwLoopError(`Goal ${goal.id} has unresolved essential success criteria.`, "ulw_loop_criteria_not_all_pass", {+ details: {+ goalId: goal.id,+ unresolved: unresolvedEssentialCriteriaOf(goal).map((criterion) => ({+ id: criterion.id,+ status: criterion.status+ }))+ }+ });+}++// components/ulw-loop/src/quality-gate.ts+import { resolve as resolve2 } from "node:path";++// components/ulw-loop/src/quality-gate-fields.ts+var PLACEHOLDER_PATTERN = /^(?:placeholder|todo|tbd|n\/a|stub)$/i;+function invalid(message, field) {+ throw new UlwLoopError(message, "ULW_LOOP_QUALITY_GATE_INVALID", { details: { field } });+}+function isRecord(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}+function section(value, field) {+ return isRecord(value) ? value : invalid(`Final quality gate is missing ${field} evidence.`, field);+}+function textField(value, field) {+ if (typeof value !== "string" || value.trim() === "")+ invalid(`Final quality gate requires non-empty ${field}.`, field);+ const trimmed = value.trim();+ if (PLACEHOLDER_PATTERN.test(trimmed))+ invalid(`Final quality gate rejects placeholder ${field}.`, field);+ return trimmed;+}+function numberField(value, field) {+ return typeof value === "number" && Number.isFinite(value) ? value : invalid(`Final quality gate requires numeric ${field}.`, field);+}+function stringArray(value, field) {+ if (!Array.isArray(value) || value.length === 0)+ return invalid(`Final quality gate requires ${field}.`, field);+ return value.map((item) => textField(item, field));+}+function emptyBlockers(value, field) {+ if (Array.isArray(value) && value.length === 0)+ return [];+ invalid(`${field} must be empty.`, field);+}+function literal(value, expected, field) {+ if (value === expected)+ return expected;+ invalid(`${field} must be ${String(expected)}.`, field);+}++// components/ulw-loop/src/quality-gate-verdicts.ts+function passedVerdict(value, field) {+ if (value === "not_applicable")+ invalid(`${field} must not be not_applicable.`, field);+ return literal(value, "passed", field);+}+function codeQualityStatusField(value, field) {+ if (value === "CLEAR" || value === "WATCH")+ return value;+ invalid(`${field} must be CLEAR or WATCH.`, field);+}+function adversarialVerdict(row, field) {+ const value = row["verdict"];+ if (value === "passed")+ return { verdict: "passed" };+ if (value === "not_applicable") {+ return { verdict: "not_applicable", reason: textField(row["reason"], `${field}.reason`) };+ }+ invalid(`${field} must be passed or not_applicable with a reason.`, field);+}++// components/ulw-loop/src/quality-gate-blockers.ts+var BLOCKER_FIELD_KEYS = "blocker blockerSignature blockerEvidence blockerOccurrences blockedAt".split(" ");+var URL_PATTERN = /https?:\/\/\S+/g;+var PUNCTUATION_PATTERN = /[`"'()[\]{}:,;]/g;+var WHITESPACE_PATTERN = /\s+/g;+var AUTH_PATTERN = /\b(auth\w*|credential\w*|token|permission\w*|scope\w*|access|unauthorized|forbidden|401|403)\b/;+var MISSING_PATTERN = /\b(unset|missing|required|requires|without|omit\w*|not set|not available|no read packages|read packages)\b/;+var GHCR_PATTERN = /\b(ghcr|github container registry|read packages|imagepullsecret|package api|anonymous|container image)\b/;+var GHCR_401_PATTERN = /\b(401|unauthorized|anonymous pull|authentication required)\b/;+var GHCR_403_PATTERN = /\b(403|forbidden|read packages|package api)\b/;+function isRecord2(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}+function normalizeBlockerEvidence(evidence) {+ const withoutUrls = evidence.toLowerCase().replace(URL_PATTERN, " ");+ const withoutPunctuation = withoutUrls.replace(PUNCTUATION_PATTERN, " ");+ return withoutPunctuation.replace(WHITESPACE_PATTERN, " ").trim();+}+function classifyExternalAuthorizationBlocker(evidence) {+ const normalized = normalizeBlockerEvidence(evidence);+ if (!normalized || !AUTH_PATTERN.test(normalized) || !MISSING_PATTERN.test(normalized))+ return null;+ if (!GHCR_PATTERN.test(normalized))+ return "EXTERNAL_AUTHORIZATION_REQUIRED";+ const status401 = GHCR_401_PATTERN.test(normalized) ? "HTTP_401_ANONYMOUS" : null;+ const status403 = GHCR_403_PATTERN.test(normalized) ? "HTTP_403_NO_READ_PACKAGES" : null;+ const status = [status401, status403].filter((part) => part !== null).join("+");+ return `GHCR_PULL_ACCESS:${status || "AUTHORIZATION_REQUIRED"}:GHCR_VISIBILITY_OR_CREDENTIAL_REQUIRED`;+}+function nestedBlockerSignature(goal) {+ const blocker = Reflect.get(goal, "blocker");+ const signature = isRecord2(blocker) ? blocker["signature"] : null;+ return typeof signature === "string" ? signature : null;+}+function sameBlockerOccurrences(plan, signature) {+ return plan.goals.filter((goal) => goal.blockerSignature === signature || nestedBlockerSignature(goal) === signature).length;+}+function clearGoalBlockerFields(goal) {+ for (const key of BLOCKER_FIELD_KEYS)+ Reflect.deleteProperty(goal, key);+}++// components/ulw-loop/src/quality-gate.ts+var REVIEWER_ROLES = {+ codeReview: "lazycodex-code-reviewer",+ manualQa: "lazycodex-qa-executor",+ gateReview: "lazycodex-gate-reviewer"+};+function reviewerRoleField(value, expected, field) {+ const actual = textField(value, field);+ if (actual !== expected)+ invalid(`${field} must be ${expected}.`, field);+ return expected;+}+function surfaceField(value, field) {+ if (value === "cli" || value === "http" || value === "tmux" || value === "browser" || value === "gui" || value === "data")+ return value;+ invalid(`${field} must be a supported manual QA surface.`, field);+}+function kindField(value, field) {+ if (value === "cli-transcript" || value === "log" || value === "screenshot" || value === "image" || value === "http-dump" || value === "data-diff")+ return value;+ invalid(`${field} must be a supported artifact kind.`, field);+}+function artifactCompatible(surface, kind) {+ switch (surface) {+ case "cli":+ case "tmux":+ return kind === "cli-transcript" || kind === "log";+ case "http":+ return kind === "http-dump";+ case "browser":+ case "gui":+ return kind === "screenshot" || kind === "image";+ case "data":+ return kind === "data-diff";+ default:+ invalid("manualQa.surfaceEvidence has an unsupported surface.", "manualQa.surfaceEvidence.surface");+ }+}+function checkFile(path, field, opts) {+ if (opts === undefined)+ return;+ const absolute = resolve2(opts.repoRoot, path);+ if (!opts.fs.existsSync(absolute))+ invalid(`${field} must point to an existing artifact.`, field);+ if (opts.fs.statSync(absolute).size <= 0)+ invalid(`${field} must point to a non-empty artifact.`, field);+ if (opts.currentAttemptDir !== undefined) {+ const attemptRoot = resolve2(opts.repoRoot, opts.currentAttemptDir);+ if (!isWithinAttemptDir(absolute, attemptRoot))+ invalid(`${field} (${path}) must point to an artifact from the current attempt (${opts.currentAttemptDir}).`, field);+ }+}+function artifactMap(refs) {+ const byId = new Map;+ for (const ref of refs) {+ if (byId.has(ref.id))+ invalid(`manualQa.artifactRefs contains duplicate ${ref.id}.`, "manualQa.artifactRefs");+ byId.set(ref.id, ref);+ }+ return byId;+}+function parseArtifactRefs(value, opts) {+ if (!Array.isArray(value) || value.length === 0)+ invalid("manualQa.artifactRefs must not be empty.", "manualQa.artifactRefs");+ return value.map((item, index) => {+ const ref = section(item, `manualQa.artifactRefs[${index}]`);+ const path = textField(ref["path"], `manualQa.artifactRefs[${index}].path`);+ checkFile(path, `manualQa.artifactRefs[${index}].path`, opts);+ return {+ id: textField(ref["id"], `manualQa.artifactRefs[${index}].id`),+ kind: kindField(ref["kind"], `manualQa.artifactRefs[${index}].kind`),+ description: textField(ref["description"], `manualQa.artifactRefs[${index}].description`),+ path+ };+ });+}+function referencedArtifacts(value, field, byId) {+ return stringArray(value, field).map((id) => {+ const artifact = byId.get(id);+ if (artifact === undefined)+ invalid(`${field} references unknown artifact ${id}.`, field);+ return artifact;+ });+}+function validateQualityGate(input, opts) {+ const gate = section(input, "qualityGate");+ const codeReview = section(gate["codeReview"], "codeReview");+ const manualQa = section(gate["manualQa"], "manualQa");+ const gateReview = section(gate["gateReview"], "gateReview");+ const iteration = section(gate["iteration"], "iteration");+ const coverage = section(gate["criteriaCoverage"], "criteriaCoverage");+ const totalCriteria = numberField(coverage["totalCriteria"], "criteriaCoverage.totalCriteria");+ const passCount = numberField(coverage["passCount"], "criteriaCoverage.passCount");+ if (passCount < totalCriteria)+ invalid("criteriaCoverage.passCount must cover totalCriteria.", "criteriaCoverage.passCount");+ const artifactRefs = parseArtifactRefs(manualQa["artifactRefs"], opts);+ const byId = artifactMap(artifactRefs);+ const surfaceEvidence = parseSurfaceEvidence(manualQa["surfaceEvidence"], byId);+ const adversarialCases = parseAdversarialCases(manualQa["adversarialCases"], byId);+ const codeReportPath = textField(codeReview["reportPath"], "codeReview.reportPath");+ const gateReportPath = textField(gateReview["reportPath"], "gateReview.reportPath");+ checkFile(codeReportPath, "codeReview.reportPath", opts);+ checkFile(gateReportPath, "gateReview.reportPath", opts);+ return {+ codeReview: {+ by: reviewerRoleField(codeReview["by"], REVIEWER_ROLES.codeReview, "codeReview.by"),+ recommendation: literal(codeReview["recommendation"], "APPROVE", "codeReview.recommendation"),+ codeQualityStatus: codeQualityStatusField(codeReview["codeQualityStatus"], "codeReview.codeQualityStatus"),+ reportPath: codeReportPath,+ evidence: textField(codeReview["evidence"], "codeReview.evidence"),+ blockers: emptyBlockers(codeReview["blockers"], "codeReview.blockers")+ },+ manualQa: {+ by: reviewerRoleField(manualQa["by"], REVIEWER_ROLES.manualQa, "manualQa.by"),+ status: literal(manualQa["status"], "passed", "manualQa.status"),+ evidence: textField(manualQa["evidence"], "manualQa.evidence"),+ surfaceEvidence,+ adversarialCases,+ artifactRefs+ },+ gateReview: {+ by: reviewerRoleField(gateReview["by"], REVIEWER_ROLES.gateReview, "gateReview.by"),+ recommendation: literal(gateReview["recommendation"], "APPROVE", "gateReview.recommendation"),+ reportPath: gateReportPath,+ evidence: textField(gateReview["evidence"], "gateReview.evidence"),+ blockers: emptyBlockers(gateReview["blockers"], "gateReview.blockers")+ },+ iteration: {+ fullRerun: literal(iteration["fullRerun"], true, "iteration.fullRerun"),+ status: literal(iteration["status"], "passed", "iteration.status"),+ rerunCommands: stringArray(iteration["rerunCommands"], "iteration.rerunCommands"),+ evidence: textField(iteration["evidence"], "iteration.evidence")+ },+ criteriaCoverage: {+ totalCriteria,+ passCount,+ originalIntent: textField(coverage["originalIntent"], "criteriaCoverage.originalIntent"),+ desiredOutcome: textField(coverage["desiredOutcome"], "criteriaCoverage.desiredOutcome"),+ userOutcomeReview: textField(coverage["userOutcomeReview"], "criteriaCoverage.userOutcomeReview"),+ adversarialClassesCovered: stringArray(coverage["adversarialClassesCovered"], "criteriaCoverage.adversarialClassesCovered")+ }+ };+}+function parseSurfaceEvidence(value, byId) {+ if (!Array.isArray(value) || value.length === 0)+ invalid("manualQa.surfaceEvidence must not be empty.", "manualQa.surfaceEvidence");+ return value.map((item, index) => {+ const row = section(item, `manualQa.surfaceEvidence[${index}]`);+ const surface = surfaceField(row["surface"], `manualQa.surfaceEvidence[${index}].surface`);+ const artifacts = referencedArtifacts(row["artifactRefs"], `manualQa.surfaceEvidence[${index}].artifactRefs`, byId);+ for (const artifact of artifacts) {+ if (!artifactCompatible(surface, artifact.kind)) {+ invalid(`manualQa.surfaceEvidence ${surface} artifact ${artifact.kind} is incompatible.`, "manualQa.surfaceEvidence");+ }+ }+ return {+ id: textField(row["id"], `manualQa.surfaceEvidence[${index}].id`),+ criterionRef: textField(row["criterionRef"], `manualQa.surfaceEvidence[${index}].criterionRef`),+ surface,+ invocation: textField(row["invocation"], `manualQa.surfaceEvidence[${index}].invocation`),+ verdict: passedVerdict(row["verdict"], `manualQa.surfaceEvidence[${index}].verdict`),+ artifactRefs: artifacts.map((artifact) => artifact.id)+ };+ });+}+function parseAdversarialCases(value, byId) {+ if (!Array.isArray(value) || value.length === 0)+ invalid("manualQa.adversarialCases must not be empty.", "manualQa.adversarialCases");+ return value.map((item, index) => {+ const row = section(item, `manualQa.adversarialCases[${index}]`);+ const artifacts = referencedArtifacts(row["artifactRefs"], `manualQa.adversarialCases[${index}].artifactRefs`, byId);+ const verdictInfo = adversarialVerdict(row, `manualQa.adversarialCases[${index}]`);+ return {+ id: textField(row["id"], `manualQa.adversarialCases[${index}].id`),+ criterionRef: textField(row["criterionRef"], `manualQa.adversarialCases[${index}].criterionRef`),+ scenario: textField(row["scenario"], `manualQa.adversarialCases[${index}].scenario`),+ expectedBehavior: textField(row["expectedBehavior"], `manualQa.adversarialCases[${index}].expectedBehavior`),+ verdict: verdictInfo.verdict,+ ...verdictInfo.reason === undefined ? {} : { reason: verdictInfo.reason },+ artifactRefs: artifacts.map((artifact) => artifact.id)+ };+ });+}++// components/ulw-loop/src/cli-arg-parser.ts+import { readFile as readFile4 } from "node:fs/promises";+var VALUE_FLAGS = new Set("--brief --brief-file --session-id --codex-goal-mode --validation-batch-json --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 --proposals-json".split(" "));+var SUBCOMMANDS = new Set("create-goals status complete-goals criteria record-evidence checkpoint steer add-goal record-review-blockers".split(" "));+function hasFlag(argv, flag) {+ return argv.includes(flag);+}+function readValue(argv, flag) {+ const index = argv.indexOf(flag);+ if (index >= 0) {+ const next = argv[index + 1];+ return next === undefined || next.startsWith("--") ? undefined : next;+ }+ const prefix = `${flag}=`;+ return argv.find((arg) => arg.startsWith(prefix))?.slice(prefix.length);+}+function parseGoalArg(argv) {+ return readValue(argv, "--goal-id") ?? readValue(argv, "--goal");+}+async function readStdin() {+ const chunks = [];+ for await (const chunk of process.stdin)+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));+ return Buffer.concat(chunks).toString("utf8");+}+function positionalText(argv) {+ const words = [];+ for (let index = SUBCOMMANDS.has(argv[0] ?? "") ? 1 : 0;index < argv.length; index += 1) {+ const arg = argv[index];+ if (arg === undefined)+ continue;+ if (VALUE_FLAGS.has(arg)) {+ index += 1;+ continue;+ }+ if (arg.startsWith("--"))+ continue;+ words.push(arg);+ }+ return words.join(" ").trim();+}+function looksLikeJson(value) {+ const trimmed = value.trim();+ return trimmed.startsWith("{") || trimmed.startsWith("[");+}+async function readJsonInput(value) {+ if (value === undefined)+ return;+ try {+ return JSON.parse(looksLikeJson(value) ? value : await readFile4(value, "utf8"));+ } catch (error) {+ const message = error instanceof Error ? error.message : "unknown error";+ throw new UlwLoopError(`Invalid JSON input: ${message}`, "ULW_LOOP_JSON_INPUT_INVALID", { cause: error });+ }+}+async function parseCodexGoalJson(value) {+ if (value === undefined)+ return;+ const raw = looksLikeJson(value) ? value : await readFile4(value, "utf8");+ try {+ JSON.parse(raw);+ return raw;+ } catch (error) {+ const message = error instanceof Error ? error.message : "unknown error";+ throw new UlwLoopError(`Invalid --codex-goal-json: ${message}`, "ULW_LOOP_CODEX_GOAL_JSON_INVALID", { cause: error });+ }+}+function required(argv, flag, code) {+ const value = readValue(argv, flag)?.trim();+ if (value)+ return value;+ throw new UlwLoopError(`Missing ${flag}.`, code, { details: { flag } });+}+function evidenceStatus(value) {+ switch (value) {+ case "pass":+ return "pass";+ case "fail":+ return "fail";+ case "blocked":+ return "blocked";+ default:+ throw new UlwLoopError("Invalid --status; expected pass, fail, or blocked.", "ULW_LOOP_EVIDENCE_STATUS_INVALID", { details: { status: value } });+ }+}+function parseRecordEvidenceArgs(argv) {+ 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;+}++// components/ulw-loop/src/validation-batch.ts+function isObject(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}+function read(value, key) {+ return Object.entries(value).find(([name]) => name === key)?.[1];+}+function text(value, key) {+ const candidate = read(value, key);+ return typeof candidate === "string" && candidate.trim().length > 0 ? candidate.trim() : undefined;+}+function strings(value, key) {+ const candidate = read(value, key);+ return Array.isArray(candidate) && candidate.every((item) => typeof item === "string" && item.trim().length > 0) ? candidate.map((item) => item.trim()) : undefined;+}+async function parseValidationBatches(input, goals) {+ const raw = await readJsonInput(input);+ if (raw === undefined)+ return;+ if (!Array.isArray(raw))+ fail("--validation-batch-json must be a JSON array.");+ const batches = raw.map(batchFromObject);+ validateBatches(batches, goals);+ return batches;+}+function batchFromObject(value) {+ if (!isObject(value))+ fail("validation batch entries must be objects.");+ const batchId = text(value, "batchId");+ const memberIds = strings(value, "memberIds");+ const finalGoalId = text(value, "finalGoalId");+ if (batchId === undefined)+ fail("validation batch requires batchId.");+ if (memberIds === undefined || memberIds.length < 2)+ fail("validation batch requires at least two memberIds.");+ if (finalGoalId === undefined)+ fail("validation batch requires finalGoalId.");+ return { batchId, memberIds, finalGoalId };+}+function validateBatches(batches, goals) {+ const goalIds = new Set(goals.map((goal) => goal.id));+ const batchIds = new Set;+ const members = new Set;+ for (const batch of batches) {+ if (batchIds.has(batch.batchId))+ fail(`duplicate validation batch id: ${batch.batchId}.`);+ batchIds.add(batch.batchId);+ if (new Set(batch.memberIds).size !== batch.memberIds.length)+ fail(`validation batch ${batch.batchId} has duplicate memberIds.`);+ if (!batch.memberIds.includes(batch.finalGoalId))+ fail(`validation batch ${batch.batchId} finalGoalId must be a member.`, "ULW_LOOP_VALIDATION_BATCH_FINAL_NOT_MEMBER");+ for (const memberId of batch.memberIds) {+ if (!goalIds.has(memberId))+ fail(`validation batch ${batch.batchId} references unknown goal: ${memberId}.`, "ULW_LOOP_VALIDATION_BATCH_MEMBER_UNKNOWN");+ if (members.has(memberId))+ fail(`goal appears in multiple validation batches: ${memberId}.`, "ULW_LOOP_VALIDATION_BATCH_OVERLAP");+ members.add(memberId);+ }+ }+}+function updateBatchesAfterSupersede(plan, targetId, replacementIds) {+ if (replacementIds.length === 0 || plan.validationBatches === undefined)+ return;+ plan.validationBatches = plan.validationBatches.map((batch) => {+ if (!batch.memberIds.includes(targetId))+ return batch;+ const memberIds = batch.memberIds.flatMap((id) => id === targetId ? [...replacementIds] : [id]);+ const replacementFinalGoalId = replacementIds[replacementIds.length - 1] ?? batch.finalGoalId;+ const finalGoalId = batch.finalGoalId === targetId ? replacementFinalGoalId : batch.finalGoalId;+ return { batchId: batch.batchId, memberIds, finalGoalId };+ });+}+function batchUpdateLedgerEntry(before, after, at) {+ if (JSON.stringify(before.validationBatches ?? []) === JSON.stringify(after.validationBatches ?? []))+ return null;+ return { at, kind: "batch_updated", before: before.validationBatches ?? [], after: after.validationBatches ?? [], message: "Validation batch membership updated after steering." };+}+function batchOf(plan, goalId) {+ return plan.validationBatches?.find((batch) => batch.memberIds.includes(goalId));+}+function batchClosedBy(plan, goalId) {+ const batch = batchOf(plan, goalId);+ return batch?.finalGoalId === goalId ? batch : undefined;+}+function requireBatchFinalReady(plan, goal) {+ const batch = batchClosedBy(plan, goal.id);+ if (batch === undefined)+ return;+ const open = batch.memberIds.filter((id) => id !== goal.id && !memberResolved(plan, id));+ if (open.length > 0)+ throw new UlwLoopError("Validation batch has unresolved members.", "ULW_LOOP_VALIDATION_BATCH_OPEN", { details: { batchId: batch.batchId, open } });+}+function requireAllValidationBatchesClosed(plan, closingGoalId) {+ const open = (plan.validationBatches ?? []).filter((batch) => batch.memberIds.some((id) => id !== closingGoalId && !memberResolved(plan, id)));+ if (open.length > 0)+ throw new UlwLoopError("Validation batches remain open.", "ULW_LOOP_VALIDATION_BATCH_OPEN", { details: { batchIds: open.map((batch) => batch.batchId) } });+}+function requireBatchGate(plan, goal, gate) {+ const batch = batchClosedBy(plan, goal.id);+ if (batch === undefined)+ return;+ const members = batch.memberIds.map((id) => plan.goals.find((item) => item.id === id)).filter((item) => item !== undefined);+ const pending = members.flatMap((member) => member.successCriteria.filter((criterion) => criterion.status !== "pass").map((criterion) => `${member.id}:${criterion.id}`));+ if (pending.length > 0)+ throw new UlwLoopError("Validation batch criteria remain pending.", "ULW_LOOP_VALIDATION_BATCH_CRITERIA_PENDING", { details: { batchId: batch.batchId, pending } });+ const totalCriteria = members.reduce((sum, member) => sum + member.successCriteria.length, 0);+ const passCount = members.reduce((sum, member) => sum + member.successCriteria.filter((criterion) => criterion.status === "pass").length, 0);+ if (gate.criteriaCoverage.totalCriteria !== totalCriteria || gate.criteriaCoverage.passCount !== passCount)+ throw new UlwLoopError("Validation batch gate coverage does not match member criteria.", "ULW_LOOP_VALIDATION_BATCH_GATE_MISMATCH", { details: { batchId: batch.batchId, expected: { totalCriteria, passCount }, actual: gate.criteriaCoverage } });+}+function memberResolved(plan, goalId) {+ const goal = plan.goals.find((candidate) => candidate.id === goalId);+ return goal !== undefined && isMemberResolved(goal, plan);+}+function fail(message, code = "ULW_LOOP_VALIDATION_BATCH_INVALID") {+ throw new UlwLoopError(message, code);+}++// components/ulw-loop/src/checkpoint.ts+var QUALITY_GATE_FS = { existsSync: existsSync3, statSync };+function ulwLoopFail2(message, code) {+ throw new UlwLoopError(message, code);+}+function normalizeObjective3(value) {+ return value.replace(/\s+/g, " ").trim();+}+function nonEmptyEvidence2(value) {+ const trimmed = value.trim();+ return trimmed || ulwLoopFail2("Evidence must be a non-empty string.", "ulw_loop_evidence_required");+}+function findGoal2(plan, goalId) {+ const goal = plan.goals.find((candidate) => candidate.id === goalId);+ return goal ?? ulwLoopFail2(`Unknown ulw-loop id: ${goalId}.`, "ulw_loop_goal_not_found");+}+async function readJsonInput2(raw, repoRoot) {+ if (raw === undefined || raw.trim() === "")+ return;+ const trimmed = raw.trim();+ try {+ return JSON.parse(trimmed);+ } catch (error) {+ if (!(error instanceof SyntaxError))+ throw error;+ }+ const path = resolve3(repoRoot, trimmed);+ if (!existsSync3(path))+ return ulwLoopFail2("Quality gate JSON is neither valid JSON nor a readable path.", "ulw_loop_json_input_invalid");+ try {+ return JSON.parse(await readFile5(path, "utf8"));+ } catch (error) {+ return ulwLoopFail2(`Quality gate path does not contain valid JSON${error instanceof Error ? `: ${error.message}` : "."}`, "ulw_loop_json_input_invalid");+ }+}+function makeAggregateCompletion(now, evidence, codexGoal) {+ return { status: "complete", completedAt: now, evidence, codexGoal };+}+function applyBlockedOrFailed(goal, plan, status, evidence, now) {+ const signature = classifyExternalAuthorizationBlocker(evidence);+ const occurrences = signature === null ? 0 : sameBlockerOccurrences(plan, signature) + 1;+ const needsDecision = signature !== null && occurrences >= 3;+ goal.status = needsDecision ? "needs_user_decision" : status;+ goal.updatedAt = now;+ if (status === "failed" || needsDecision) {+ goal.failedAt = now;+ goal.failureReason = evidence;+ }+ if (status === "blocked" || needsDecision)+ goal.blockedReason = evidence;+ if (signature !== null) {+ goal.blockerSignature = signature;+ goal.blockerOccurrenceCount = occurrences;+ goal.requiredExternalDecision = `Resolve external authorization: ${signature}`;+ }+ if (needsDecision)+ goal.nonRetriable = true;+ if (plan.activeGoalId === goal.id)+ delete plan.activeGoalId;+}+function ledgerKind2(status, goal, aggregateCompletion) {+ 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, args, goal, qualityGate, codexGoal, aggregateCompletion) {+ const watch = qualityGate?.codeReview.codeQualityStatus === "WATCH";+ const entry = {+ at: now,+ kind: ledgerKind2(args.status, goal, aggregateCompletion),+ goalId: goal.id,+ status: goal.status,+ evidence: watch ? `${args.evidence} | codeQuality=WATCH: ${qualityGate.codeReview.evidence}` : args.evidence+ };+ if (codexGoal !== undefined)+ entry.codexGoal = codexGoal;+ if (qualityGate !== undefined)+ entry.qualityGate = qualityGate;+ if (goal.blockerSignature !== undefined)+ entry.blockerSignature = goal.blockerSignature;+ if (goal.blockerOccurrenceCount !== undefined)+ entry.blockerOccurrenceCount = goal.blockerOccurrenceCount;+ if (goal.requiredExternalDecision !== undefined)+ entry.requiredExternalDecision = goal.requiredExternalDecision;+ return entry;+}+async function checkpointUlwLoop(repoRoot, args, scope) {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ const plan = await readUlwLoopPlan(repoRoot, scope);+ const goal = findGoal2(plan, args.goalId);+ const evidence = nonEmptyEvidence2(args.evidence);+ const now = iso();+ let aggregateCompletion;+ let qualityGate;+ let codexGoal;+ if (args.status === "complete") {+ const aggregate = codexGoalMode(plan) === "aggregate";+ const final = isFinalRunCompletionCandidate(plan, goal);+ const closesBatch = batchClosedBy(plan, goal.id) !== undefined;+ if (final) {+ requireAllCriteriaPass(goal);+ requireAllPlanCriteriaPass(plan);+ requireAllValidationBatchesClosed(plan, goal.id);+ } else if (aggregate)+ requireEssentialCriteriaPass(goal);+ else+ requireAllCriteriaPass(goal);+ const snapshot = await readCodexGoalSnapshotInput(args.codexGoalJson, repoRoot);+ const reconciliation = reconcileCodexGoalSnapshot(snapshot, {+ expectedObjective: expectedCodexObjective(plan, goal),+ ...aggregate ? { acceptedObjectives: compatibleCodexObjectives(plan) } : {},+ allowedStatuses: aggregate ? final ? ["complete"] : ["active"] : ["complete"],+ requireSnapshot: true,+ requireComplete: !aggregate || final+ });+ codexGoal = reconciliation.snapshot.raw;+ if (!reconciliation.ok) {+ const objective = snapshot?.objective;+ const mismatchedTaskObjective = snapshot?.available === true && objective !== undefined && normalizeObjective3(objective) !== normalizeObjective3(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");+ }+ if (closesBatch)+ requireBatchFinalReady(plan, goal);+ if (closesBatch && args.qualityGateJson === undefined)+ throw new UlwLoopError("Validation batch final checkpoint requires --quality-gate-json.", "ULW_LOOP_VALIDATION_BATCH_GATE_REQUIRED");+ if (final)+ aggregateCompletion = makeAggregateCompletion(now, evidence, codexGoal);+ if (final || aggregateCompletion !== undefined || closesBatch) {+ qualityGate = validateQualityGate(await readJsonInput2(args.qualityGateJson, repoRoot), {+ repoRoot,+ fs: QUALITY_GATE_FS,+ ...plan.evidenceLayoutVersion === 2 ? { currentAttemptDir: ulwLoopAttemptEvidenceDir(goal.id, goal.attempt, scope) } : {}+ });+ requireBatchGate(plan, goal, qualityGate);+ }+ goal.status = "complete";+ goal.completedAt = now;+ goal.evidence = evidence;+ delete goal.failedAt;+ delete goal.failureReason;+ clearGoalBlockerFields(goal);+ if (plan.activeGoalId === goal.id)+ delete plan.activeGoalId;+ } else+ applyBlockedOrFailed(goal, plan, args.status, evidence, now);+ goal.updatedAt = now;+ if (aggregateCompletion !== undefined)+ plan.aggregateCompletion = aggregateCompletion;+ plan.updatedAt = now;+ await writePlan(repoRoot, plan, scope);+ const ledgerEntry = buildLedger(now, args, goal, qualityGate, codexGoal, aggregateCompletion);+ await appendLedger(repoRoot, ledgerEntry, scope);+ const closedBatch = args.status === "complete" ? batchClosedBy(plan, goal.id) : undefined;+ if (closedBatch !== undefined)+ await appendLedger(repoRoot, { at: now, kind: "batch_closed", goalId: goal.id, message: closedBatch.batchId }, scope);+ return aggregateCompletion === undefined ? { plan, goal, ledgerEntry } : { plan, goal, ledgerEntry, aggregateCompletion };+ });+}++// components/ulw-loop/src/cli-output.ts+var ULW_LOOP_HELP = `Usage:+ omo ulw-loop create-goals --brief "..." [--brief-file <path>] [--from-stdin] [--codex-goal-mode aggregate|per_story] [--validation-batch-json <json-or-path>] [--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 <...>] [--no-advance] [--json]+ omo ulw-loop steer --kind <kind> ... --evidence "..." --rationale "..." [--proposals-json <json-or-path>] [--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.`;+function printJson(value) {+ process.stdout.write(`${JSON.stringify(value, null, 2)}+`);+}+function printJsonError(error) {+ if (error instanceof UlwLoopError) {+ printJson({+ ok: false,+ error: {+ code: error.code,+ message: error.message,+ ...error.details === undefined ? {} : { details: error.details }+ }+ });+ return;+ }+ if (error instanceof Error) {+ printJson({ ok: false, error: { code: "ULW_LOOP_UNEXPECTED", message: error.message } });+ return;+ }+ printJson({ ok: false, error: { code: "ULW_LOOP_UNKNOWN", message: "unknown error" } });+}+function criteriaCounts(goal) {+ let pass = 0;+ for (const criterion of goal.successCriteria)+ if (criterion.status === "pass")+ pass += 1;+ return { pass, total: goal.successCriteria.length };+}+function printStatus(plan) {+ let totalCriteria = 0;+ let passCriteria = 0;+ const lines = ["ulw-loop status", "", "goals:"];+ for (const goal of plan.goals) {+ const counts = criteriaCounts(goal);+ totalCriteria += counts.total;+ passCriteria += counts.pass;+ const marker = goal.id === plan.activeGoalId ? "*" : "-";+ lines.push(`${marker} ${goal.id} [${goal.status}] ${goal.title} (criteria: ${counts.pass}/${counts.total})`);+ }+ lines.push("", "summary:", `total goals: ${plan.goals.length}`, `criteria: ${passCriteria}/${totalCriteria} pass`);+ process.stdout.write(`${lines.join(`+`)}+`);+}+function blockedDecisionHandoff(plan) {+ const blocked = plan.goals.find((goal) => goal.status === "needs_user_decision" && goal.nonRetriable);+ if (blocked === undefined)+ return "";+ return [+ "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(`+`);+}+function normalizeCodexGoalMode(value) {+ if (value === undefined)+ return "aggregate";+ if (value === "aggregate" || value === "per_story")+ return value;+ throw new UlwLoopError("Invalid --codex-goal-mode; expected aggregate or per_story.", "ULW_LOOP_CODEX_GOAL_MODE_INVALID", { details: { value } });+}++// components/ulw-loop/src/codex-goal-instruction.ts+function buildCodexGoalInstruction(args) {+ 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, goal) {+ return { objective: expectedCodexObjective(plan, goal) };+}+function buildText(mode, plan, goal, createGoal, isFinal) {+ return joinLines([+ mode === "aggregate" ? "UlwLoop aggregate-goal handoff" : "UlwLoop active-goal handoff",+ `Mode: ${mode}`,+ `Plan: ${plan.goalsPath}`,+ `Ledger: ${plan.ledgerPath}`,+ `Goal: ${goal.id} — ${goal.title}`,+ "",+ ...activeGoalLines(goal),+ "",+ ...successCriteriaLines(goal.successCriteria),+ "",+ "Codex goal integration constraints:",+ "- Use the create_goal payload exactly as rendered: objective only.",+ "- Goals are unlimited. Do not add numeric limits.",+ ...modeConstraintLines(mode, isFinal),+ ...evidenceLayoutLines(plan),+ finalSection(plan, goal, isFinal, mode === "aggregate"),+ ...checkpointLines(plan, mode),+ "",+ "create_goal payload:",+ JSON.stringify(createGoal, null, 2)+ ]);+}+function modeConstraintLines(mode, isFinal) {+ 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 ulw-loop.",+ "- Work only this goal until its completion audit passes."+ ];+ }+ return [+ "- 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 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 mid-aggregate; checkpoint this OMO ledger story and continue the remaining stories. update_goal is reserved for the final story after the mandatory quality gate passes."+ ];+}+function checkpointLines(plan, mode) {+ 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.",+ failureLine+ ];+}+function activeGoalLines(goal) {+ return ["Active goal:", `- id: ${goal.id}`, `- title: ${goal.title}`, `- objective: ${goal.objective}`];+}+function successCriteriaLines(criteria) {+ if (criteria.length === 0)+ return ["Success criteria:", "- No success criteria recorded for this goal."];+ return ["Success criteria:", ...criteria.map(formatCriterionLine)];+}+function formatCriterionLine(criterion) {+ const remainingWork = criterion.status === "pending" ? " remaining work:" : "";+ const marker = isEssentialCriterion(criterion) ? "essential" : "non-essential";+ return `-${remainingWork} [${criterion.id}] [${marker}] (${criterion.userModel}) ${criterion.scenario} — expect: ${criterion.expectedEvidence} — status: ${criterion.status}`;+}+function evidenceLayoutLines(plan) {+ if (plan.evidenceLayoutVersion !== 2)+ return [];+ return [+ "- Evidence layout v2: write every artifact for the active goal (QA matrix, review reports, receipts) under the current attempt directory — read currentAttemptDir from `omo ulw-loop status --json` (.omo/evidence/ulw/<session>/<goalId>/a<attempt>). The final checkpoint rejects quality-gate artifacts outside that directory."+ ];+}+function finalSection(plan, goal, isFinal, aggregate) {+ if (!isFinal)+ return "- This is not the final ulw-loop story; do not run the final reviewer/manual-QA/gate-review quality 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 "<targeted verification/manualQa/gateReview 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 targeted verification for changed behavior.",+ "- Confirm every manualQa artifact path exists and has non-zero size.",+ '- First spawn lazycodex-code-reviewer and lazycodex-qa-executor in parallel (fork_context: false on the v1 surface; fork_turns: "none" on v2). Include the original brief, goal objectives, desired user-visible outcome, diff, and evidence; wait for BOTH to return and confirm their report artifacts exist on disk (code-review report + manualQa matrix).',+ "- Only then spawn lazycodex-gate-reviewer (same fork settings), passing those artifact paths.",+ "- Require clean codeReview, manualQa, gateReview, iteration, and criteriaCoverage. criteriaCoverage must summarize originalIntent, desiredOutcome, and userOutcomeReview; counts alone are not approval.",+ "- On a reviewer REJECT, fix only the cited blockers, rerun the affected verification/Manual-QA, and re-review the delta at most TWICE; if blockers remain, record them and surface to the user.",+ "- If codeQualityStatus is WATCH, include the WATCH notes verbatim in your final user-facing message.",+ "- If any reviewer is blocked/inconclusive or the quality gate is not clean, do not call update_goal. Record blocker work first:",+ ` ${blockerCommand}`,+ aggregate ? '- If the quality gate is clean, call update_goal({status: "complete"}), call get_goal again, then checkpoint the aggregate story:' : '- If the quality gate is clean, call update_goal({status: "complete"}), call get_goal again, then checkpoint:',+ ` ${checkpointCommand}`+ ]);+}+function sessionOption(plan) {+ 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) {+ return lines.join(`+`);+}++// components/ulw-loop/src/plan-crud.ts+import { existsSync as existsSync4 } from "node:fs";+import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";++// components/ulw-loop/src/plan-goal-factory.ts+function cleanLine(line) {+ return line.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/, "").trim();+}+function normalizeObjective4(value) {+ return value.replace(/\s+/g, " ").trim();+}+function titleFromObjective(objective, fallback) {+ 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, index) {+ 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, label) {+ const trimmed = value?.trim();+ if (!trimmed)+ throw new UlwLoopError(`Missing ${label}.`, "ULW_LOOP_ARGUMENT_MISSING");+ return trimmed;+}+function truncateObjective(objective) {+ return objective.length > 80 ? `${objective.slice(0, 77).trimEnd()}...` : objective;+}+function seedDefaultSuccessCriteria(goalIndex, objective) {+ const subject = truncateObjective(normalizeObjective4(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}.`,+ true+ ],+ [+ "C002",+ "edge",+ "edge case (boundary/empty/malformed)",+ `Replace via revise_criterion with boundary or malformed-input proof for: ${subject}.`,+ true+ ],+ [+ "C003",+ "regression",+ "regression: adjacent surface still works",+ `Replace via revise_criterion with regression proof for neighboring behavior after: ${subject}.`,+ false+ ]+ ];+ return rows.map(([id, userModel, scenario, expectedEvidence, essential]) => ({+ id,+ scenario,+ userModel,+ expectedEvidence,+ essential,+ capturedEvidence: null,+ status: "pending"+ }));+}+function deriveGoalCandidates(brief) {+ const bulletGoals = brief.split(/\r?\n/).map((line) => ({ original: line, cleaned: normalizeObjective4(cleanLine(line)) })).filter(({ cleaned }) => cleaned.length > 0 && cleaned.length <= 1200).filter(({ original, cleaned }, index, all) => /^\s*(?:[-*+]\s+|\d+[.)]\s+)/.test(original) && all.findIndex((candidate) => candidate.cleaned === cleaned) === index).map(({ cleaned }) => cleaned);+ const paragraphs = brief.split(/\n\s*\n/).map(normalizeObjective4).filter((paragraph) => paragraph.length > 0 && !paragraph.startsWith("#"));+ const selected = (bulletGoals.length > 0 ? bulletGoals : paragraphs).length > 0 ? bulletGoals.length > 0 ? bulletGoals : paragraphs : ["Complete the requested project objective."];+ return selected.map((objective, index) => ({+ title: titleFromObjective(objective, `Goal ${index + 1}`),+ objective+ }));+}+function makeGoal(title, objective, index, now) {+ 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, title, objective, now) {+ const goal = makeGoal(title, objective, plan.goals.length, now);+ plan.goals.push(goal);+ plan.updatedAt = now;+ return goal;+}++// components/ulw-loop/src/plan-crud.ts+function isScheduleEligible(goal) {+ return goal.steeringStatus !== "superseded" && goal.steeringStatus !== "blocked";+}+function clearGoalBlockerFields2(goal) {+ for (const key of [+ "blockedReason",+ "blockerSignature",+ "blockerOccurrenceCount",+ "requiredExternalDecision",+ "nonRetriable",+ "failedAt",+ "failureReason"+ ])+ delete goal[key];+}+async function createUlwLoopPlan(repoRoot, args, scope) {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ if (!args.force && existsSync4(ulwLoopGoalsPath(repoRoot, scope))) {+ const existing = await readUlwLoopPlan(repoRoot, scope);+ if (isUlwLoopDone(existing))+ throw completedPlanExistsError(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 = {+ version: 1,+ evidenceLayoutVersion: 2,+ createdAt: now,+ updatedAt: now,+ briefPath: ulwLoopBriefRelativePath(scope),+ goalsPath: ulwLoopGoalsRelativePath(scope),+ ledgerPath: ulwLoopLedgerRelativePath(scope),+ codexGoalMode: args.codexGoalMode ?? "aggregate",+ goals+ };+ const validationBatches = await parseValidationBatches(args.validationBatchesJson, goals);+ if (validationBatches !== undefined)+ plan.validationBatches = validationBatches;+ if (plan.codexGoalMode === "aggregate")+ plan.codexObjective = aggregateCodexObjectiveForScope(scope);+ await mkdir2(ulwLoopDir(repoRoot, scope), { recursive: true });+ await writeFile2(ulwLoopBriefPath(repoRoot, scope), args.brief.endsWith(`+`) ? args.brief : `${args.brief}+`, "utf8");+ await writePlan(repoRoot, plan, scope);+ await writeFile2(ulwLoopLedgerPath(repoRoot, scope), "", "utf8");+ await appendLedger(repoRoot, { at: now, kind: "plan_created", message: `${goals.length} goal(s) created` }, scope);+ return plan;+ });+}+function completedPlanExistsError(scope) {+ return new UlwLoopError([+ `Existing ulw-loop aggregate is already complete at ${ulwLoopGoalsRelativePath(scope)}.`,+ "Start a new run with `omo ulw-loop create-goals --session-id <new-id> ...` to isolate fresh state.",+ "Use --force only when you intentionally want to overwrite the completed evidence."+ ].join(" "), "ULW_LOOP_PLAN_EXISTS_COMPLETE");+}+async function addUlwLoopGoal(repoRoot, args, scope) {+ 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, scope);+ await appendLedger(repoRoot, { at: now, kind: "goal_added", goalId: goal.id, status: goal.status, message: goal.title }, scope);+ return { plan, goal };+ });+}+async function startNextUlwLoop(repoRoot, args = {}, scope) {+ 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)+ 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 } : {}+ }, scope);+ }+ if (!next)+ return { done: true, plan };+ next.status = "in_progress";+ next.attempt += 1;+ next.startedAt = now;+ clearGoalBlockerFields2(next);+ next.updatedAt = now;+ plan.activeGoalId = next.id;+ plan.updatedAt = now;+ 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 };+ });+}+function summarizeUlwLoopPlan(plan) {+ const countStatus = (status) => plan.goals.filter((goal) => goal.status === status).length;+ const countCriteria = (status) => 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")+ }+ };+}++// components/ulw-loop/src/checkpoint-continuation.ts+async function checkpointAndContinue(repoRoot, args, scope) {+ const result = await checkpointUlwLoop(repoRoot, args, scope);+ if (args.status !== "complete" || result.aggregateCompletion !== undefined || !args.advance)+ return result;+ const next = await startNextUlwLoop(repoRoot, {}, scope);+ if ("done" in next)+ return { ...result, plan: next.plan, next: doneNext(next.plan) };+ const instruction = buildCodexGoalInstruction({ plan: next.plan, goal: next.goal });+ return { ...result, plan: next.plan, next: { resumed: next.resumed, goal: next.goal, instruction } };+}+async function checkpoint(repoRoot, argv, json, scope) {+ const goalId = required2(argv, "--goal-id");+ const statusValue = checkpointStatus(required2(argv, "--status"));+ const evidence = required2(argv, "--evidence");+ const codexGoalJson = await parseCodexGoalJson(statusValue === "complete" ? required2(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 = {+ goalId,+ status: statusValue,+ evidence,+ advance: !hasFlag(argv, "--no-advance"),+ ...codexGoalJson === undefined ? {} : { codexGoalJson },+ ...qualityGateJson === undefined ? {} : { qualityGateJson }+ };+ const result = await checkpointAndContinue(repoRoot, args, scope);+ if (json)+ printJson({ ok: true, ...result, summary: summarizeUlwLoopPlan(result.plan) });+ else+ printCheckpointText(result);+ return 0;+}+function printCheckpointText(result) {+ process.stdout.write(`ulw-loop checkpoint: ${result.goal.id} -> ${result.goal.status}+`);+ if (result.next === undefined)+ return;+ if ("instruction" in result.next)+ process.stdout.write(`${result.next.instruction.text}+`);+ else+ process.stdout.write(`${result.next.handoff || "ulw-loop: all goals complete"}+`);+}+function doneNext(plan) {+ const handoff = blockedDecisionHandoff(plan);+ return { done: true, blocked: handoff.length > 0, handoff };+}+function required2(argv, flag) {+ const value = readValue(argv, flag)?.trim();+ if (value)+ return value;+ throw new UlwLoopError(`Missing ${flag}.`, "ULW_LOOP_ARGUMENT_MISSING", { details: { flag } });+}+function checkpointStatus(value) {+ 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 } });+}++// components/ulw-loop/src/cli-subcommands.ts+import { readFile as readFile6 } from "node:fs/promises";++// components/ulw-loop/src/cli-steering.ts+var SOURCES = ["user_prompt_submit", "finding", "cli"];+var STEERING_KIND_HELP = [+ `Allowed --kind values: ${ULW_LOOP_STEERING_MUTATION_KINDS.join(", ")}`,+ "Kind-specific required flags:",+ " add_subgoal: --title, --objective, --evidence, --rationale",+ " split_subgoal: --goal-id, --children, --evidence, --rationale",+ " reorder_pending: --order, --evidence, --rationale",+ " revise_pending_wording: --goal-id, --title or --objective, --evidence, --rationale",+ " revise_criterion: --goal-id, --criterion-id, one of --scenario/--expected-evidence/--user-model, --evidence, --rationale",+ " annotate_ledger: --evidence, --rationale",+ " mark_blocked_superseded: --goal-id, optional --replacements, --evidence, --rationale",+ 'Example: omo ulw-loop steer --kind annotate_ledger --evidence "observed behavior" --rationale "why this changes the plan" --json'+].join(`+`);+function isKind(value) {+ return value !== undefined && ULW_LOOP_STEERING_MUTATION_KINDS.some((kind) => kind === value);+}+function isSource(value) {+ return value !== undefined && SOURCES.some((source) => source === value);+}+function isModel(value) {+ return ULW_LOOP_SUCCESS_CRITERION_USER_MODELS.some((model) => model === value);+}+function fail2(message, code, details) {+ throw new UlwLoopError(message, code, { details });+}+function kindMessage(prefix) {+ return `${prefix}++${STEERING_KIND_HELP}`;+}+function text2(value, field) {+ if (value === undefined)+ return;+ const trimmed = value.trim();+ if (trimmed.length > 0)+ return trimmed;+ return fail2(`Empty ${field}.`, "ULW_LOOP_STEERING_FIELD_EMPTY", { field });+}+function required3(argv, flag) {+ const value = text2(readValue(argv, flag), flag);+ return value ?? fail2(`Missing ${flag}.`, "ULW_LOOP_STEERING_FIELD_REQUIRED", { flag });+}+function requiredGoal(argv) {+ const value = text2(parseGoalArg(argv), "--goal-id");+ return value ?? fail2("Missing --goal-id.", "ULW_LOOP_GOAL_ID_REQUIRED", { flag: "--goal-id" });+}+function readObject(value, key) {+ return Object.entries(value).find(([name]) => name === key)?.[1];+}+function isPlain(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}+function objectText(value, key) {+ const candidate = readObject(value, key);+ return typeof candidate === "string" ? candidate : undefined;+}+function objectStrings(value, key) {+ const candidate = readObject(value, key);+ return Array.isArray(candidate) && candidate.every((item) => typeof item === "string") ? candidate : undefined;+}+function objectChildren(value, key) {+ const candidate = readObject(value, key);+ if (!Array.isArray(candidate))+ return;+ const parsed = [];+ for (const item of candidate) {+ const next = child(item);+ if (next === null)+ return fail2(`${key} entries require title/objective.`, "ULW_LOOP_STEERING_CHILD_INVALID", { key });+ parsed.push(next);+ }+ return parsed;+}+function isProposalKind(value) {+ return typeof value === "string" && ULW_LOOP_STEERING_MUTATION_KINDS.some((kind) => kind === value);+}+function isProposalSource(value) {+ return typeof value === "string" && SOURCES.some((source) => source === value);+}+function parseSteeringKind(argv) {+ const value = readValue(argv, "--kind");+ if (isKind(value))+ return value;+ return value === undefined ? fail2(kindMessage("Missing --kind."), "ULW_LOOP_STEERING_KIND_REQUIRED", { flag: "--kind", expected: ULW_LOOP_STEERING_MUTATION_KINDS, usage: STEERING_KIND_HELP }) : fail2(kindMessage(`Invalid --kind: ${value}.`), "ULW_LOOP_STEERING_KIND_INVALID", { value, expected: ULW_LOOP_STEERING_MUTATION_KINDS, usage: STEERING_KIND_HELP });+}+function parseSteeringSource(argv) {+ const value = readValue(argv, "--source");+ if (value === undefined)+ return "cli";+ return isSource(value) ? value : fail2(`Invalid --source: ${value}.`, "ULW_LOOP_STEERING_SOURCE_INVALID", { value, expected: SOURCES });+}+function child(value) {+ if (!isPlain(value))+ return null;+ const title = text2(objectText(value, "title"), "title");+ const objective = text2(objectText(value, "objective"), "objective");+ if (title === undefined || objective === undefined)+ return null;+ return { title, objective };+}+async function children(argv, flag, needed) {+ const input = needed ? required3(argv, flag) : text2(readValue(argv, flag), flag);+ if (input === undefined)+ return [];+ const raw = await readJsonInput(input);+ if (!Array.isArray(raw))+ return fail2(`${flag} must be a JSON array.`, "ULW_LOOP_STEERING_JSON_ARRAY_REQUIRED", { flag });+ const parsed = [];+ for (const item of raw) {+ const next = child(item);+ if (next === null)+ return fail2(`${flag} entries require title/objective.`, "ULW_LOOP_STEERING_CHILD_INVALID", { flag });+ parsed.push(next);+ }+ return parsed;+}+async function stringArray2(argv, flag) {+ const raw = await readJsonInput(required3(argv, flag));+ if (!Array.isArray(raw))+ return fail2(`${flag} must be a JSON array.`, "ULW_LOOP_STEERING_JSON_ARRAY_REQUIRED", { flag });+ const values = [];+ for (const item of raw) {+ if (typeof item !== "string")+ return fail2(`${flag} entries must be strings.`, "ULW_LOOP_STEERING_STRING_ARRAY_REQUIRED", { flag });+ values.push(text2(item, flag) ?? "");+ }+ return values;+}+function model(value) {+ const trimmed = text2(value, "--user-model");+ if (trimmed === undefined)+ return;+ return isModel(trimmed) ? trimmed : fail2(`Invalid --user-model: ${trimmed}.`, "ULW_LOOP_STEERING_USER_MODEL_INVALID", { value: trimmed, expected: ULW_LOOP_SUCCESS_CRITERION_USER_MODELS });+}+function neverKind(kind) {+ return fail2(`Unsupported steering kind: ${String(kind)}.`, "ULW_LOOP_STEERING_KIND_UNSUPPORTED", { kind });+}+async function parseSteeringProposal(argv) {+ const kind = parseSteeringKind(argv);+ const source = parseSteeringSource(argv);+ const idempotencyKey = text2(readValue(argv, "--idempotency-key"), "--idempotency-key");+ const base = { kind, source, evidence: required3(argv, "--evidence"), rationale: required3(argv, "--rationale"), ...idempotencyKey === undefined ? {} : { idempotencyKey } };+ switch (kind) {+ case "add_subgoal":+ return normalizeSteeringProposal({ ...base, title: required3(argv, "--title"), objective: required3(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 stringArray2(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 fail2("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 = required3(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 fail2("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) {+ if (values === undefined)+ return;+ return values.map((item) => ({ title: text2(item.title, "child.title") ?? "", objective: text2(item.objective, "child.objective") ?? "" }));+}+function normalizedStrings(values, field) {+ if (values === undefined)+ return;+ return values.map((value) => text2(value, field) ?? "");+}+function normalizeSteeringProposal(proposal) {+ const evidence = text2(proposal.evidence, "evidence") ?? "";+ const rationale = text2(proposal.rationale, "rationale") ?? "";+ const goalId = text2(proposal.goalId, "goalId");+ const targetGoalId = text2(proposal.targetGoalId, "targetGoalId");+ const targetGoalIds = normalizedStrings(proposal.targetGoalIds, "targetGoalIds");+ const criterionId = text2(proposal.criterionId, "criterionId");+ const title = text2(proposal.title, "title");+ const objective = text2(proposal.objective, "objective");+ const revisedTitle = text2(proposal.revisedTitle, "revisedTitle");+ const revisedObjective = text2(proposal.revisedObjective, "revisedObjective");+ const blockedReason = text2(proposal.blockedReason, "blockedReason");+ const directiveText = text2(proposal.directiveText, "directiveText");+ const promptSignature = text2(proposal.promptSignature, "promptSignature");+ const idempotencyKey = text2(proposal.idempotencyKey, "idempotencyKey");+ const scenario = text2(proposal.scenario, "scenario");+ const expectedEvidence = text2(proposal.expectedEvidence, "expectedEvidence");+ const childGoals = normalizedChildren(proposal.childGoals);+ const pendingOrder = normalizedStrings(proposal.pendingOrder, "pendingOrder");+ return { kind: proposal.kind, source: proposal.source, evidence, rationale, ...goalId === undefined ? {} : { goalId }, ...targetGoalId === undefined ? {} : { targetGoalId }, ...targetGoalIds === undefined ? {} : { targetGoalIds }, ...criterionId === undefined ? {} : { criterionId }, ...title === undefined ? {} : { title }, ...objective === undefined ? {} : { objective }, ...childGoals === undefined ? {} : { childGoals }, ...revisedTitle === undefined ? {} : { revisedTitle }, ...revisedObjective === undefined ? {} : { revisedObjective }, ...pendingOrder === undefined ? {} : { pendingOrder }, ...blockedReason === undefined ? {} : { blockedReason }, ...proposal.after === undefined ? {} : { after: proposal.after }, ...directiveText === undefined ? {} : { directiveText }, ...promptSignature === undefined ? {} : { promptSignature }, ...idempotencyKey === undefined ? {} : { idempotencyKey }, ...proposal.now === undefined ? {} : { now: proposal.now }, ...scenario === undefined ? {} : { scenario }, ...expectedEvidence === undefined ? {} : { expectedEvidence }, ...proposal.userModel === undefined ? {} : { userModel: proposal.userModel } };+}+async function parseSteeringProposals(argv) {+ const input = text2(readValue(argv, "--proposals-json"), "--proposals-json");+ if (input === undefined)+ return [await parseSteeringProposal(argv)];+ if (readValue(argv, "--kind") !== undefined)+ return fail2("--kind and --proposals-json are mutually exclusive.", "ULW_LOOP_STEERING_BATCH_CONFLICT", { flags: ["--kind", "--proposals-json"] });+ const raw = await readJsonInput(input);+ if (!Array.isArray(raw) || raw.length === 0)+ return fail2("--proposals-json must be a non-empty JSON array.", "ULW_LOOP_STEERING_BATCH_ARRAY_REQUIRED", { flag: "--proposals-json" });+ const proposals = [];+ for (const item of raw)+ proposals.push(normalizeSteeringProposal(proposalFromObject(item)));+ return proposals;+}+function proposalFromObject(value) {+ if (!isPlain(value))+ return fail2("--proposals-json entries must be objects.", "ULW_LOOP_STEERING_BATCH_ITEM_INVALID", { flag: "--proposals-json" });+ const kind = readObject(value, "kind");+ const source = readObject(value, "source") ?? "cli";+ if (!isProposalKind(kind))+ return fail2(`Invalid batch steering kind: ${String(kind)}.`, "ULW_LOOP_STEERING_KIND_INVALID", { value: kind });+ if (!isProposalSource(source))+ return fail2(`Invalid batch steering source: ${String(source)}.`, "ULW_LOOP_STEERING_SOURCE_INVALID", { value: source });+ let proposal = { kind, source, evidence: objectText(value, "evidence") ?? "", rationale: objectText(value, "rationale") ?? "" };+ const goalId = objectText(value, "goalId");+ const targetGoalId = objectText(value, "targetGoalId");+ const criterionId = objectText(value, "criterionId");+ const title = objectText(value, "title");+ const objective = objectText(value, "objective");+ const revisedTitle = objectText(value, "revisedTitle");+ const revisedObjective = objectText(value, "revisedObjective");+ const scenario = objectText(value, "scenario");+ const expectedEvidence = objectText(value, "expectedEvidence");+ const idempotencyKey = objectText(value, "idempotencyKey");+ const targetGoalIds = objectStrings(value, "targetGoalIds");+ const pendingOrder = objectStrings(value, "pendingOrder");+ const childGoals = objectChildren(value, "childGoals");+ if (goalId !== undefined)+ proposal = { ...proposal, goalId };+ if (targetGoalId !== undefined)+ proposal = { ...proposal, targetGoalId };+ if (criterionId !== undefined)+ proposal = { ...proposal, criterionId };+ if (title !== undefined)+ proposal = { ...proposal, title };+ if (objective !== undefined)+ proposal = { ...proposal, objective };+ if (revisedTitle !== undefined)+ proposal = { ...proposal, revisedTitle };+ if (revisedObjective !== undefined)+ proposal = { ...proposal, revisedObjective };+ if (scenario !== undefined)+ proposal = { ...proposal, scenario };+ if (expectedEvidence !== undefined)+ proposal = { ...proposal, expectedEvidence };+ if (idempotencyKey !== undefined)+ proposal = { ...proposal, idempotencyKey };+ if (targetGoalIds !== undefined)+ proposal = { ...proposal, targetGoalIds };+ if (pendingOrder !== undefined)+ proposal = { ...proposal, pendingOrder };+ if (childGoals !== undefined)+ proposal = { ...proposal, childGoals };+ return proposal;+}+function printSteerResult(result, json) {+ 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(`ulw-loop steer: ${outcome} ${result.audit.kind}+`);+ if (result.rejectedReasons.length > 0)+ process.stdout.write(`rejected: ${result.rejectedReasons.join("; ")}+`);+ if (result.audit.idempotencyKey !== undefined)+ process.stdout.write(`idempotency-key: ${result.audit.idempotencyKey}+`);+ printStatus(result.plan);+}+function printSteerBatchResult(result, json) {+ if (json) {+ printJson({ ok: result.accepted, accepted: result.accepted, rejectedReasons: result.rejectedReasons, results: result.results, plan: result.plan });+ return;+ }+ process.stdout.write(`ulw-loop steer batch: ${result.accepted ? "accepted" : "rejected"} ${result.results.length} proposal(s)+`);+ if (result.rejectedReasons.length > 0)+ process.stdout.write(`rejected: ${result.rejectedReasons.join("; ")}+`);+ printStatus(result.plan);+}++// components/ulw-loop/src/review-blockers.ts+var BLOCKER_FIELDS = "blockedReason blockerSignature blockerOccurrenceCount requiredExternalDecision nonRetriable failedAt failureReason completedAt blocker blockerEvidence blockerOccurrences blockedAt".split(" ");+function ulwLoopError(message, code) {+ throw new UlwLoopError(message, code);+}+function nextGoalId(plan) {+ const max = plan.goals.reduce((current, goal) => {+ const digits = /^G(\d+)/u.exec(goal.id)?.[1];+ return digits === undefined ? current : Math.max(current, Number(digits));+ }, 0);+ return `G${String(max + 1).padStart(3, "0")}`;+}+function appendBlockerGoal(plan, args, now) {+ const index = plan.goals.length;+ const goal = {+ id: nextGoalId(plan),+ title: args.title,+ objective: args.objective,+ status: "pending",+ successCriteria: seedDefaultSuccessCriteria(index, args.objective),+ attempt: 0,+ createdAt: now,+ updatedAt: now+ };+ plan.goals.push(goal);+ return goal;+}+async function recordFinalReviewBlockers(repoRoot, args, scope) {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ const plan = await readUlwLoopPlan(repoRoot, scope);+ const goal = plan.goals.find((candidate) => candidate.id === args.goalId);+ 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)+ ulwLoopError(reconciliation.errors.join(" "), "ulw_loop_codex_snapshot_mismatch");+ const now = iso();+ for (const field of BLOCKER_FIELDS)+ Reflect.deleteProperty(goal, field);+ goal.status = "review_blocked";+ goal.reviewBlockedAt = now;+ goal.evidence = args.evidence;+ goal.updatedAt = now;+ if (plan.activeGoalId === goal.id)+ delete plan.activeGoalId;+ const newGoal = appendBlockerGoal(plan, args, now);+ plan.updatedAt = now;+ const codexGoal = reconciliation.snapshot.raw;+ const blockedEntry = { at: now, kind: "goal_review_blocked", goalId: goal.id, status: goal.status, evidence: args.evidence, codexGoal };+ const addedEntry = { at: now, kind: "goal_added", goalId: newGoal.id, status: newGoal.status, evidence: args.evidence, message: newGoal.title };+ const summaryEntry = { 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, scope);+ for (const entry of ledgerEntries)+ await appendLedger(repoRoot, entry, scope);+ return { plan, blockedGoal: goal, newGoal, ledgerEntries };+ });+}++// components/ulw-loop/src/steering-mutations.ts+var read2 = (value, key) => Object.entries(value).find(([name]) => name === key)?.[1];+var isText = (value) => typeof value === "string" && value.trim().length > 0;+var text3 = (value, key) => {+ const candidate = read2(value, key);+ return isText(candidate) ? candidate.trim() : undefined;+};+var isModel2 = (value) => typeof value === "string" && ULW_LOOP_SUCCESS_CRITERION_USER_MODELS.some((model2) => model2 === value);+var after = (proposal) => {+ const candidate = read2(proposal, "after");+ return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate) ? candidate : undefined;+};+var revised = (proposal, direct, nested) => text3(proposal, direct) ?? text3(after(proposal) ?? proposal, nested);+var targets = (proposal) => proposal.targetGoalIds ?? [proposal.targetGoalId ?? text3(proposal, "goalId") ?? ""].filter(Boolean);+var child2 = (value) => {+ if (typeof value !== "object" || value === null || Array.isArray(value))+ return null;+ const title = text3(value, "title");+ const objective = text3(value, "objective");+ return title === undefined || objective === undefined ? null : { title, objective };+};+var children2 = (proposal) => {+ const direct = proposal.childGoals;+ if (direct !== undefined && direct.length > 0)+ return direct;+ const nested = after(proposal);+ const fromAfter = nested === undefined ? undefined : read2(nested, "children");+ return Array.isArray(fromAfter) ? fromAfter.map(child2).filter((item) => item !== null) : [];+};+var goal = (plan, id) => id === undefined ? undefined : plan.goals.find((item) => item.id === id);+function nextId(plan, offset) {+ const max = plan.goals.reduce((current, item) => {+ const digits = /^G(\d+)(?:-|$)/u.exec(item.id)?.[1];+ return digits === undefined ? current : Math.max(current, Number(digits));+ }, 0);+ return `G${String(max + offset).padStart(3, "0")}`;+}+function makeGoal2(plan, childGoal, evidence, now, offset) {+ 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 };+}+function reviseWording(plan, proposal, now) {+ const target = goal(plan, targets(proposal)[0]);+ if (target === undefined)+ return;+ target.title = revised(proposal, "revisedTitle", "title") ?? target.title;+ target.objective = revised(proposal, "revisedObjective", "objective") ?? target.objective;+ target.steeringEvidence = proposal.evidence;+ target.steeringRationale = proposal.rationale;+ target.updatedAt = now;+}+function splitOrBlock(plan, proposal, now) {+ const target = goal(plan, targets(proposal)[0]);+ if (target === undefined)+ return;+ const replacements = children2(proposal).map((item, index) => makeGoal2(plan, item, proposal.evidence, now, index + 1));+ target.steeringEvidence = proposal.evidence;+ target.steeringRationale = proposal.rationale;+ target.updatedAt = now;+ if (replacements.length === 0) {+ target.status = "blocked";+ target.steeringStatus = "blocked";+ target.blockedReason = proposal.blockedReason ?? proposal.rationale;+ } else {+ target.steeringStatus = "superseded";+ target.supersededBy = replacements.map((item) => item.id);+ for (const item of replacements)+ item.supersedes = [target.id];+ plan.goals.splice(plan.goals.indexOf(target) + 1, 0, ...replacements);+ updateBatchesAfterSupersede(plan, target.id, replacements.map((item) => item.id));+ }+ if (plan.activeGoalId === target.id)+ delete plan.activeGoalId;+}+function reviseCriterion(plan, proposal, now) {+ const target = goal(plan, targets(proposal)[0]);+ const index = target?.successCriteria.findIndex((item) => item.id === proposal.criterionId) ?? -1;+ const current = target?.successCriteria[index];+ if (target === undefined || current === undefined)+ return;+ const model2 = read2(proposal, "userModel");+ target.successCriteria[index] = { ...current, scenario: text3(proposal, "scenario") ?? current.scenario, expectedEvidence: text3(proposal, "expectedEvidence") ?? current.expectedEvidence, userModel: isModel2(model2) ? model2 : current.userModel };+ target.updatedAt = now;+}++// components/ulw-loop/src/steering-snapshot.ts+function buildSteeringPlanSnapshot(plan, changedGoalIds) {+ const snapshot = {+ updatedAt: plan.updatedAt,+ goalCount: plan.goals.length,+ goalIds: plan.goals.map((goal2) => goal2.id),+ goals: plan.goals.filter((goal2) => changedGoalIds.has(goal2.id))+ };+ return plan.activeGoalId === undefined ? snapshot : { ...snapshot, activeGoalId: plan.activeGoalId };+}+function changedGoalIdsBetween(before, after2) {+ const beforeById = new Map(before.goals.map((goal2) => [goal2.id, goal2]));+ const changed = new Set;+ for (const goal2 of after2.goals) {+ const prior = beforeById.get(goal2.id);+ if (prior === undefined || JSON.stringify(prior) !== JSON.stringify(goal2))+ changed.add(goal2.id);+ beforeById.delete(goal2.id);+ }+ for (const id of beforeById.keys())+ changed.add(id);+ return changed;+}++// components/ulw-loop/src/steering.ts+var SOURCES2 = ["user_prompt_submit", "finding", "cli"];+var PROTECTED = new Set(["aggregateCompletion", "codexObjective", "codexObjectiveAliases", "originalConstraints", "qualityGate", "status", "completedAt", "completionStatus"]);+var isObject2 = (value) => typeof value === "object" && value !== null;+var isPlain2 = (value) => isObject2(value) && !Array.isArray(value);+var read3 = (value, key) => Object.entries(value).find(([name]) => name === key)?.[1];+var isText2 = (value) => typeof value === "string" && value.trim().length > 0;+var text4 = (value, key) => {+ const candidate = read3(value, key);+ return isText2(candidate) ? candidate.trim() : undefined;+};+var isKind2 = (value) => typeof value === "string" && ULW_LOOP_STEERING_MUTATION_KINDS.some((kind) => kind === value);+var isSource2 = (value) => typeof value === "string" && SOURCES2.some((source) => source === value);+var isModel3 = (value) => typeof value === "string" && ULW_LOOP_SUCCESS_CRITERION_USER_MODELS.some((model2) => model2 === value);+var texts = (value, key) => {+ const candidate = read3(value, key);+ return Array.isArray(candidate) && candidate.every((item) => typeof item === "string") ? candidate : [];+};+function targets2(proposal) {+ const many = texts(proposal, "targetGoalIds");+ const one = text4(proposal, "targetGoalId") ?? text4(proposal, "goalId");+ return many.length > 0 ? many : one === undefined ? [] : [one];+}+var after2 = (proposal) => {+ const candidate = read3(proposal, "after");+ return isPlain2(candidate) ? candidate : undefined;+};+var revised2 = (proposal, direct, nested) => text4(proposal, direct) ?? text4(after2(proposal) ?? proposal, nested);+function child3(value) {+ if (!isPlain2(value))+ return null;+ const title = text4(value, "title");+ const objective = text4(value, "objective");+ if (title === undefined || objective === undefined)+ return null;+ return { title, objective };+}+function childValues(proposal) {+ const direct = read3(proposal, "childGoals");+ if (Array.isArray(direct) && direct.length > 0)+ return direct;+ const nested = after2(proposal);+ const fromAfter = nested === undefined ? undefined : read3(nested, "children");+ return Array.isArray(fromAfter) ? fromAfter : [];+}+var pendingOrder = (proposal) => {+ const direct = texts(proposal, "pendingOrder");+ return direct.length > 0 ? direct : texts(after2(proposal) ?? proposal, "pendingGoalIds");+};+function hasProtected(value) {+ if (!isObject2(value))+ return false;+ for (const [key, childValue] of Object.entries(value))+ if (PROTECTED.has(key) || key.toLowerCase().includes("complete") || hasProtected(childValue))+ return true;+ return false;+}+function allText(value) {+ if (typeof value === "string")+ return value;+ return isObject2(value) ? Object.values(value).map(allText).filter(Boolean).join(`+`) : "";+}+function weakens(value) {+ const valueText = allText(value).toLowerCase();+ return /\b(skip|bypass|weaken|remove|omit|auto[-\s]?complete|mark complete|complete faster)\b/.test(valueText) && /\b(test|tests|verification|review|quality gate|complete|completion)\b/.test(valueText);+}+function auditFor(proposal, reasons) {+ const object = isPlain2(proposal) ? proposal : undefined;+ const kindRaw = object === undefined ? undefined : read3(object, "kind");+ const sourceRaw = object === undefined ? undefined : read3(object, "source");+ const evidence = object === undefined ? "" : text4(object, "evidence") ?? "";+ const rationale = object === undefined ? "" : text4(object, "rationale") ?? "";+ const audit = { kind: isKind2(kindRaw) ? kindRaw : "annotate_ledger", source: isSource2(sourceRaw) ? sourceRaw : "cli", targetGoalIds: object === undefined ? [] : targets2(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 = text4(object, "criterionId");+ const directiveText = text4(object, "directiveText");+ const promptSignature = text4(object, "promptSignature");+ const idempotencyKey = text4(object, "idempotencyKey");+ if (criterionId !== undefined)+ audit.criterionId = criterionId;+ if (directiveText !== undefined)+ audit.directiveText = directiveText;+ if (promptSignature !== undefined)+ audit.promptSignature = promptSignature;+ if (idempotencyKey !== undefined)+ audit.idempotencyKey = idempotencyKey;+ return audit;+}+function validateUlwLoopSteeringProposal(plan, proposal) {+ const reasons = [];+ if (!isPlain2(proposal))+ reasons.push("proposal must be an object");+ const object = isPlain2(proposal) ? proposal : {};+ const kind = read3(object, "kind");+ if (!isKind2(kind))+ reasons.push(`invalid kind: ${String(kind)}`);+ if (!isSource2(read3(object, "source")))+ reasons.push(`invalid source: ${String(read3(object, "source"))}`);+ if (text4(object, "evidence") === undefined)+ reasons.push("missing evidence");+ if (text4(object, "rationale") === undefined)+ reasons.push("missing rationale");+ if (hasProtected(proposal))+ reasons.push("protected payload");+ if (weakens(proposal))+ reasons.push("weakened completion");+ if (isUlwLoopDone(plan))+ reasons.push("plan already complete");+ if (isKind2(kind))+ validateKind(plan, object, kind, reasons);+ return auditFor(proposal, reasons);+}+function goal2(plan, id) {+ return id === undefined ? undefined : plan.goals.find((item) => item.id === id);+}+function validateKind(plan, proposal, kind, reasons) {+ const target = goal2(plan, targets2(proposal)[0]);+ if (kind === "add_subgoal" && (text4(proposal, "title") === undefined || text4(proposal, "objective") === undefined))+ reasons.push("add_subgoal requires title/objective");+ if ((kind === "split_subgoal" || kind === "revise_pending_wording" || kind === "mark_blocked_superseded") && target === undefined)+ reasons.push(`${kind} requires target`);+ if ((kind === "split_subgoal" || kind === "revise_pending_wording") && target !== undefined && target.status !== "pending")+ reasons.push(`${kind} requires pending target`);+ const rawChildren = childValues(proposal);+ if (kind === "split_subgoal" && rawChildren.length === 0)+ reasons.push("split_subgoal requires children");+ if ((kind === "split_subgoal" || kind === "mark_blocked_superseded") && rawChildren.some((item) => child3(item) === null))+ reasons.push(`${kind} children require title/objective`);+ if (kind === "reorder_pending")+ validateOrder(plan, proposal, reasons);+ if (kind === "revise_pending_wording" && revised2(proposal, "revisedTitle", "title") === undefined && revised2(proposal, "revisedObjective", "objective") === undefined)+ reasons.push("revise_pending_wording requires update");+ if (kind === "revise_criterion")+ validateCriterion(plan, proposal, reasons);+}+function validateOrder(plan, proposal, reasons) {+ const requested = pendingOrder(proposal);+ const pending = plan.goals.filter((item) => item.status === "pending" && item.steeringStatus === undefined).map((item) => item.id);+ if (requested.length === 0)+ reasons.push("reorder_pending requires ids");+ if (new Set(requested).size !== requested.length)+ reasons.push("duplicate pending id");+ if (requested.some((id) => !pending.includes(id)))+ reasons.push("unknown pending id");+}+function validateCriterion(plan, proposal, reasons) {+ const target = goal2(plan, targets2(proposal)[0]);+ const criterionId = text4(proposal, "criterionId");+ if (target === undefined)+ reasons.push("revise_criterion requires goalId");+ else if (criterionId === undefined || target.successCriteria.every((item) => item.id !== criterionId))+ reasons.push("revise_criterion requires criterionId");+ const model2 = read3(proposal, "userModel");+ if (read3(proposal, "scenario") === undefined && read3(proposal, "expectedEvidence") === undefined && model2 === undefined)+ reasons.push("revise_criterion requires update");+ if (model2 !== undefined && !isModel3(model2))+ reasons.push("invalid userModel");+}+function applySteeringMutation(plan, proposal, audit) {+ const next = structuredClone(plan);+ if (!audit.invariant.accepted)+ return next;+ const now = proposal.now?.toISOString() ?? iso();+ if (proposal.kind === "add_subgoal")+ next.goals.push(makeGoal2(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) => goal2(next, id)).filter((item) => item !== undefined), ...next.goals.filter((item) => !order.includes(item.id))];+ }+ if (proposal.kind === "revise_pending_wording")+ reviseWording(next, proposal, now);+ if (proposal.kind === "split_subgoal" || proposal.kind === "mark_blocked_superseded")+ splitOrBlock(next, proposal, now);+ if (proposal.kind === "revise_criterion")+ reviseCriterion(next, proposal, now);+ if (proposal.kind !== "annotate_ledger")+ next.updatedAt = now;+ return next;+}+function isProposal(value) {+ return isPlain2(value) && isKind2(read3(value, "kind")) && isSource2(read3(value, "source")) && isText2(read3(value, "evidence")) && isText2(read3(value, "rationale"));+}+function parseUlwLoopSteeringDirective(text5) {+ const match = /(?:^|\s)(?:OMO_ULW_LOOP_STEER|omo\.ulw-loop\.steer|omo ulw-loop steer):\s*([\s\S]+)$/u.exec(text5);+ if (match?.[1] === undefined)+ return null;+ try {+ const parsed = JSON.parse(match[1].trim());+ return isProposal(parsed) ? parsed : null;+ } catch (error) {+ if (error instanceof SyntaxError)+ return null;+ throw error;+ }+}+async function steerUlwLoop(repoRoot, proposal, scope) {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ const plan = await readUlwLoopPlan(repoRoot, scope);+ const key = proposal.idempotencyKey ?? proposal.promptSignature;+ const prior = key === undefined ? undefined : await findAcceptedSteeringLedgerEntry(repoRoot, key, scope);+ if (prior?.steering !== undefined) {+ const { before: _before, after: _after, ...compactPrior } = prior.steering;+ return { plan, accepted: true, audit: { ...compactPrior, deduped: true }, rejectedReasons: [], deduped: true };+ }+ const audit = validateUlwLoopSteeringProposal(plan, proposal);+ const accepted = audit.invariant.accepted;+ const next = accepted ? applySteeringMutation(plan, proposal, audit) : plan;+ const finalAudit = { ...audit };+ if (accepted) {+ const changed = changedGoalIdsBetween(plan, next);+ finalAudit.before = buildSteeringPlanSnapshot(plan, changed);+ finalAudit.after = buildSteeringPlanSnapshot(next, changed);+ }+ const at = proposal.now?.toISOString() ?? iso();+ const batchEntry = accepted ? batchUpdateLedgerEntry(plan, next, at) : null;+ if (accepted)+ await writePlan(repoRoot, next, scope);+ await appendLedger(repoRoot, ledgerEntry(proposal, finalAudit, at), scope);+ if (batchEntry !== null)+ await appendLedger(repoRoot, batchEntry, scope);+ return { plan: next, accepted, audit: finalAudit, rejectedReasons: audit.invariant.rejectedReasons, deduped: false };+ });+}+function ledgerEntry(proposal, audit, at) {+ const entry = { at, kind: audit.invariant.accepted ? proposal.kind === "revise_criterion" ? "criteria_revised" : "steering_accepted" : "steering_rejected", evidence: proposal.evidence, message: proposal.rationale, steering: audit, mutationKind: proposal.kind };+ const goalId = audit.targetGoalIds[0];+ if (goalId !== undefined)+ entry.goalId = goalId;+ if (proposal.criterionId !== undefined)+ entry.criterionId = proposal.criterionId;+ if (proposal.idempotencyKey !== undefined)+ entry.idempotencyKey = proposal.idempotencyKey;+ return entry;+}++// components/ulw-loop/src/steering-batch.ts+async function steerUlwLoopBatch(repoRoot, proposals, scope) {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ const plan = await readUlwLoopPlan(repoRoot, scope);+ const prepared = await prepareBatch(repoRoot, plan, proposals, scope);+ const failed = prepared.results.find((item) => !item.accepted);+ if (failed !== undefined) {+ const entry = rejectedLedgerEntry(prepared.results);+ await appendLedger(repoRoot, entry, scope);+ return rejected(plan, prepared.results, failed.rejectedReasons);+ }+ let next = plan;+ for (const item of prepared.items)+ if (item.kind === "fresh")+ next = item.prepared.next;+ const fresh = prepared.items.filter((item) => item.kind === "fresh");+ if (fresh.length > 0) {+ await writePlan(repoRoot, next, scope);+ const entries = fresh.map((item) => ledgerEntry2(item.prepared.proposal, item.prepared.audit, item.prepared.proposal.now?.toISOString() ?? iso()));+ const batchEntry = batchUpdateLedgerEntry(plan, next, iso());+ await appendLedgerEntries(repoRoot, batchEntry === null ? entries : [...entries, batchEntry], scope);+ }+ return { plan: next, accepted: true, results: prepared.results, rejectedReasons: [] };+ });+}+async function prepareBatch(repoRoot, plan, proposals, scope) {+ const items = [];+ const results = [];+ let current = plan;+ for (const proposal of proposals) {+ const key = proposal.idempotencyKey ?? proposal.promptSignature;+ const prior = key === undefined ? undefined : await findAcceptedSteeringLedgerEntry(repoRoot, key, scope);+ if (prior?.steering !== undefined) {+ const result2 = { accepted: true, deduped: true, audit: { ...prior.steering, deduped: true }, rejectedReasons: [] };+ items.push({ kind: "deduped", result: result2 });+ results.push(result2);+ continue;+ }+ const audit = validateUlwLoopSteeringProposal(current, proposal);+ if (!audit.invariant.accepted) {+ const result2 = { accepted: false, deduped: false, audit, rejectedReasons: audit.invariant.rejectedReasons };+ items.push({ kind: "deduped", result: result2 });+ results.push(result2);+ continue;+ }+ const next = applySteeringMutation(current, proposal, audit);+ const changed = changedGoalIdsBetween(current, next);+ const finalAudit = { ...audit, before: buildSteeringPlanSnapshot(current, changed), after: buildSteeringPlanSnapshot(next, changed) };+ const result = { accepted: true, deduped: false, audit: finalAudit, rejectedReasons: [] };+ items.push({ kind: "fresh", prepared: { proposal, audit: finalAudit, before: current, next } });+ results.push(result);+ current = next;+ }+ return { items, results };+}+function rejected(plan, results, rejectedReasons) {+ return { plan, accepted: false, results, rejectedReasons };+}+function rejectedLedgerEntry(results) {+ const rejectedItems = results.map((result, index) => ({ result, index })).filter((item) => !item.result.accepted);+ return { at: iso(), kind: "steering_rejected", message: rejectedItems.map((item) => `index ${item.index}: ${item.result.rejectedReasons.join(", ")}`).join("; ") };+}+function ledgerEntry2(proposal, audit, at) {+ const entry = {+ at,+ kind: proposal.kind === "revise_criterion" ? "criteria_revised" : "steering_accepted",+ evidence: proposal.evidence,+ message: proposal.rationale,+ steering: audit,+ mutationKind: proposal.kind+ };+ const goalId = audit.targetGoalIds[0];+ if (goalId !== undefined)+ entry.goalId = goalId;+ if (proposal.criterionId !== undefined)+ entry.criterionId = proposal.criterionId;+ if (proposal.idempotencyKey !== undefined)+ entry.idempotencyKey = proposal.idempotencyKey;+ return entry;+}++// components/ulw-loop/src/cli-subcommands.ts+async function createGoals(repoRoot, argv, json, scope) {+ const briefFile = readValue(argv, "--brief-file");+ const brief = readValue(argv, "--brief") ?? (briefFile === undefined ? undefined : await readFile6(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 validationBatchesJson = readValue(argv, "--validation-batch-json");+ const plan = await createUlwLoopPlan(repoRoot, {+ brief,+ codexGoalMode: normalizeCodexGoalMode(readValue(argv, "--codex-goal-mode")),+ force: hasFlag(argv, "--force"),+ ...validationBatchesJson === undefined ? {} : { validationBatchesJson }+ }, scope);+ if (json)+ printJson({ ok: true, plan, summary: summarizeUlwLoopPlan(plan) });+ else {+ process.stdout.write(`ulw-loop plan created: ${plan.goals.length} goal(s)+brief: ${plan.briefPath}+goals: ${plan.goalsPath}+ledger: ${plan.ledgerPath}+`);+ }+ return 0;+}+async function status(repoRoot, json, scope) {+ const plan = await readUlwLoopPlan(repoRoot, scope);+ if (json) {+ const active = plan.goals.find((goal3) => goal3.id === plan.activeGoalId);+ const currentAttemptDir = plan.evidenceLayoutVersion === 2 && active ? ulwLoopAttemptEvidenceDir(active.id, active.attempt, scope) : undefined;+ printJson({+ ok: true,+ plan,+ summary: summarizeUlwLoopPlan(plan),+ ...currentAttemptDir === undefined ? {} : { currentAttemptDir }+ });+ } else+ printStatus(plan);+ return 0;+}+async function completeGoals(repoRoot, argv, json, scope) {+ 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"}+`);+ 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}+`);+ return 0;+}+async function steer(repoRoot, argv, json, scope) {+ const proposals = await parseSteeringProposals(argv);+ const single = proposals[0];+ if (single !== undefined && proposals.length === 1 && readValue(argv, "--proposals-json") === undefined) {+ const result2 = await steerUlwLoop(repoRoot, single, scope);+ printSteerResult(result2, json);+ return result2.accepted ? 0 : 1;+ }+ const result = await steerUlwLoopBatch(repoRoot, proposals, scope);+ printSteerBatchResult(result, json);+ return result.accepted ? 0 : 1;+}+async function addGoal(repoRoot, argv, json, scope) {+ const result = await addUlwLoopGoal(repoRoot, { title: required4(argv, "--title"), objective: required4(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}+`);+ printStatus(result.plan);+ }+ return 0;+}+async function criteria(repoRoot, argv, json, scope) {+ const goalId = required4(argv, "--goal-id");+ const goal3 = findGoal3(await readUlwLoopPlan(repoRoot, scope), goalId);+ if (json)+ printJson({ ok: true, goalId: goal3.id, criteria: goal3.successCriteria });+ else {+ process.stdout.write(`criteria for ${goal3.id}:+${goal3.successCriteria.map(formatCriterionForCli).join(`+`)}+`);+ }+ return 0;+}+async function captureEvidence(repoRoot, argv, json, scope) {+ 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}+`);+ }+ return 0;+}+async function reviewBlockers(repoRoot, argv, json, scope) {+ const codexGoalJson = await parseCodexGoalJson(required4(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: required4(argv, "--goal-id"),+ title: required4(argv, "--title"),+ objective: required4(argv, "--objective"),+ evidence: required4(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}+`);+ }+ return 0;+}+function formatCriterionForCli(criterion) {+ const marker = isEssentialCriterion(criterion) ? "essential" : "non-essential";+ return `- ${criterion.id} [${criterion.status}] [${marker}] (${criterion.userModel}) ${criterion.scenario} evidence: ${criterion.capturedEvidence ?? "pending"}`;+}+function required4(argv, flag) {+ const value = readValue(argv, flag)?.trim();+ if (value)+ return value;+ throw new UlwLoopError(`Missing ${flag}.`, "ULW_LOOP_ARGUMENT_MISSING", { details: { flag } });+}+function findGoal3(plan, goalId) {+ const goal3 = plan.goals.find((candidate) => candidate.id === goalId);+ if (goal3 !== undefined)+ return goal3;+ throw new UlwLoopError(`Unknown ulw-loop id: ${goalId}.`, "ULW_LOOP_GOAL_NOT_FOUND", { details: { goalId } });+}++// components/ulw-loop/src/cli-commands.ts+var ULW_LOOP_SUBCOMMANDS = [+ "help",+ "create-goals",+ "status",+ "complete-goals",+ "checkpoint",+ "steer",+ "add-goal",+ "criteria",+ "record-evidence",+ "record-review-blockers"+];+function isUlwLoopSubcommand(value) {+ return ULW_LOOP_SUBCOMMANDS.includes(value);+}+async function ulwLoopCommand(argv) {+ const head = argv[0] ?? "help";+ const command = head === "--help" || head === "-h" ? "help" : head;+ const rest = argv.slice(1);+ const repoRoot = process.cwd();+ const json = hasFlag(rest, "--json");+ try {+ const scope = commandScope(rest);+ if (!isUlwLoopSubcommand(command)) {+ if (json) {+ printJsonError(new UlwLoopError(`Unknown ulw-loop subcommand: ${command}.`, "ULW_LOOP_SUBCOMMAND_UNKNOWN", {+ details: { command }+ }));+ return 1;+ }+ process.stdout.write(`${ULW_LOOP_HELP}+`);+ return 1;+ }+ switch (command) {+ case "help":+ process.stdout.write(`${ULW_LOOP_HELP}+`);+ 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:+ return unhandledSubcommand(command);+ }+ } catch (error) {+ if (json) {+ printJsonError(error);+ return 1;+ }+ if (error instanceof UlwLoopError)+ process.stderr.write(`[ulw-loop] ${error.message}+`);+ else if (error instanceof Error)+ process.stderr.write(`[ulw-loop] unexpected: ${error.message}+`);+ else+ process.stderr.write(`[ulw-loop] unknown error+`);+ return 1;+ }+}+function unhandledSubcommand(command) {+ throw new UlwLoopError(`Unhandled ulw-loop subcommand: ${String(command)}.`, "ULW_LOOP_SUBCOMMAND_UNHANDLED");+}+var SESSION_ID_FLAG = "--session-id";+function sessionIdFlagPresent(argv) {+ return hasFlag(argv, SESSION_ID_FLAG) || argv.some((arg) => arg.startsWith(`${SESSION_ID_FLAG}=`));+}+function commandScope(argv) {+ if (sessionIdFlagPresent(argv)) {+ const sessionId2 = readValue(argv, SESSION_ID_FLAG)?.trim();+ if (!sessionId2) {+ throw new UlwLoopError(`${SESSION_ID_FLAG} requires a non-empty value.`, "ULW_LOOP_SESSION_ID_REQUIRED", {+ details: { flag: SESSION_ID_FLAG }+ });+ }+ return { sessionId: sessionId2 };+ }+ const sessionId = resolveUlwLoopSessionIdFromEnv();+ return sessionId === null ? undefined : { sessionId };+}++// components/ulw-loop/src/ultrawork-directive.ts+import { readFileSync as readFileSync2 } from "node:fs";++// components/ulw-loop/src/ultrawork-skill-pointer.ts+import { existsSync as existsSync5, readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+var ULTRAWORK_SKILL_POINTER_TEMPLATE = `<ultrawork-mode>+ULTRAWORK MODE IS ACTIVE FOR THIS TASK.++MANDATORY BOOTSTRAP: do all three steps, in order, before anything else.++1. First user-visible line this turn MUST be exactly:+\`ULTRAWORK MODE ENABLED!\`++2. Call \`create_goal\` NOW with \`objective\` set to the user's request.+Send \`objective\` only: no \`status\`, no budget fields. If the+\`create_goal\` tool is unavailable, open your reply with a binding+\`# Goal\` block instead. Never skip this step.++3. Read the FULL ultrawork directive NOW, before any other tool call,+plan, or edit. It is the \`ultrawork\` skill, stored at:++{{ULTRAWORK_SKILL_PATH}}++Read the whole file. If a read result comes back truncated, keep+reading the remaining line ranges until you have seen every line.+Every rule in that file is binding for this entire task: no+compromise, no summarizing from memory, no skipping. If the file does+not exist, tell the user the omo ultrawork skill is missing and+continue with steps 1 and 2 plus evidence-bound execution.++Do not start the requested work until all three steps are complete.+</ultrawork-mode>+`;+var ULTRAWORK_SKILL_PATH_PLACEHOLDER = "{{ULTRAWORK_SKILL_PATH}}";+var ULTRAWORK_SKILL_FILE_URL = new URL("../../../skills/ultrawork/SKILL.md", import.meta.url);+var ULTRAWORK_DIRECTIVE = readFileSync(new URL("../directive.md", import.meta.url), "utf8");+function resolveUltraworkSkillFilePath() {+ return fileURLToPath(ULTRAWORK_SKILL_FILE_URL);+}+function buildUltraworkSkillPointer(skillFilePath) {+ return ULTRAWORK_SKILL_POINTER_TEMPLATE.replace(ULTRAWORK_SKILL_PATH_PLACEHOLDER, skillFilePath);+}+function buildUltraworkAdditionalContext(options = {}) {+ const skillFilePath = options.skillFilePath === undefined ? resolveUltraworkSkillFilePath() : options.skillFilePath;+ if (skillFilePath !== null && existsSync5(skillFilePath)) {+ return buildUltraworkSkillPointer(skillFilePath);+ }+ return ULTRAWORK_DIRECTIVE;+}++// components/ulw-loop/src/ultrawork-directive.ts+var ULTRAWORK_CURRENT_PROMPT_PATTERN = /(?:ultrawork|ulw)/i;+var ULTRAWORK_DIRECTIVE_MARKER = "<ultrawork-mode>";+var TRANSCRIPT_SEARCH_BYTES = 512000;+var 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"+];+function buildUltraworkDirectiveOutput(input, options = {}) {+ if (isContextPressureRecoveryPrompt(input.prompt))+ return "";+ if (hasUltraworkDirectiveAlreadyInTranscript(input.transcript_path))+ return "";+ if (isContextPressureTranscript(input.transcript_path))+ return "";+ return isUltraworkPrompt(input.prompt) ? formatAdditionalContextOutput(buildUltraworkAdditionalContext(options)) : "";+}+function hasUltraworkDirectiveAlreadyInTranscript(transcriptPath) {+ if (transcriptPath === undefined || transcriptPath === null)+ return false;+ try {+ const rawTranscript = readTranscriptTail(transcriptPath);+ for (const line of rawTranscript.split(/\r?\n/)) {+ const parsed = parseJsonLine(line);+ if (!isRecord3(parsed))+ continue;+ const hookSpecificOutput = parsed["hookSpecificOutput"];+ if (!isRecord3(hookSpecificOutput))+ continue;+ if (hookSpecificOutput["hookEventName"] !== "UserPromptSubmit")+ continue;+ if (typeof hookSpecificOutput["additionalContext"] === "string" && hookSpecificOutput["additionalContext"].includes(ULTRAWORK_DIRECTIVE_MARKER)) {+ return true;+ }+ }+ } catch (error) {+ if (error instanceof Error)+ return false;+ throw error;+ }+ return false;+}+function readTranscriptTail(transcriptPath) {+ const rawTranscript = readFileSync2(transcriptPath);+ return rawTranscript.subarray(Math.max(0, rawTranscript.byteLength - TRANSCRIPT_SEARCH_BYTES)).toString("utf8");+}+function isUltraworkPrompt(prompt) {+ return ULTRAWORK_CURRENT_PROMPT_PATTERN.test(prompt);+}+function isContextPressureRecoveryPrompt(prompt) {+ const normalizedPrompt = prompt.toLowerCase();+ return CONTEXT_PRESSURE_MARKERS.some((marker) => normalizedPrompt.includes(marker));+}+function isContextPressureTranscript(transcriptPath) {+ if (transcriptPath === undefined || transcriptPath === null)+ return false;+ try {+ return isContextPressureRecoveryPrompt(readTranscriptTail(transcriptPath));+ } catch (error) {+ if (error instanceof Error)+ return false;+ throw error;+ }+}+function formatAdditionalContextOutput(additionalContext) {+ const normalizedContext = normalizeAdditionalContext(additionalContext);+ if (normalizedContext.length === 0)+ return "";+ const output = {+ hookSpecificOutput: {+ hookEventName: "UserPromptSubmit",+ additionalContext: normalizedContext+ }+ };+ return `${JSON.stringify(output)}+`;+}+function normalizeAdditionalContext(additionalContext) {+ return additionalContext.replace(/\r\n/g, `+`).replace(/\r/g, `+`).trim();+}+function parseJsonLine(line) {+ if (line.trim().length === 0)+ return null;+ try {+ const parsed = JSON.parse(line);+ return parsed;+ } catch (error) {+ if (error instanceof Error)+ return null;+ throw error;+ }+}+function isRecord3(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++// components/ulw-loop/src/codex-hook.ts+var CREATE_GOAL_TOOL_NAME = "create_goal";+var CREATE_GOAL_PAYLOAD_WARNING = "Use create_goal with objective only. Omit token_budget so the goal stays unlimited, and put lifecycle status changes on update_goal.";+function parseUserPromptSubmitPayload(raw) {+ if (raw.trim().length === 0)+ return null;+ try {+ const parsed = JSON.parse(raw);+ return isUserPromptSubmitPayload(parsed) ? parsed : null;+ } catch (error) {+ if (error instanceof SyntaxError)+ return null;+ return null;+ }+}+function parsePreToolUsePayload(raw) {+ if (raw.trim().length === 0)+ return null;+ try {+ const parsed = JSON.parse(raw);+ return isPreToolUsePayload(parsed) ? parsed : null;+ } catch (error) {+ if (error instanceof SyntaxError)+ return null;+ return null;+ }+}+async function applyUserPromptUlwLoopSteering(payload, options = {}) {+ try {+ if (payload.hook_event_name !== "UserPromptSubmit")+ return "";+ const proposal = parseUlwLoopSteeringDirective(payload.prompt);+ if (proposal === null) {+ if (hasSteeringDirectiveMarker(payload.prompt))+ return "";+ if (!options.includeUltraworkDirective)+ return "";+ return options.ultraworkSkillFilePath === undefined ? buildUltraworkDirectiveOutput(payload) : buildUltraworkDirectiveOutput(payload, { skillFilePath: options.ultraworkSkillFilePath });+ }+ 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 hasSteeringDirectiveMarker(prompt) {+ return /(?:^|\s)(?:OMO_ULW_LOOP_STEER|omo\.ulw-loop\.steer|omo ulw-loop steer):/u.test(prompt);+}+function payloadScope(payload) {+ return { sessionId: payload.session_id };+}+function applyPreToolUseGoalBudgetGuard(payload) {+ if (payload.hook_event_name !== "PreToolUse")+ return "";+ if (payload.tool_name !== CREATE_GOAL_TOOL_NAME)+ return "";+ if (!hasInvalidCreateGoalInput(payload.tool_input))+ return "";+ const output = {+ hookSpecificOutput: {+ hookEventName: "PreToolUse",+ permissionDecision: "deny",+ permissionDecisionReason: CREATE_GOAL_PAYLOAD_WARNING,+ additionalContext: CREATE_GOAL_PAYLOAD_WARNING+ }+ };+ return `${JSON.stringify(output)}+`;+}+async function runUlwLoopHookCli(stdin, stdout, options = {}) {+ try {+ const payload = parseUserPromptSubmitPayload(await readAll(stdin));+ if (payload === null)+ return;+ const output = await applyUserPromptUlwLoopSteering(payload, options);+ if (output.length > 0)+ stdout.write(output);+ } catch (error) {+ if (error instanceof Error)+ return;+ return;+ }+}+async function runPreToolUseGoalBudgetGuardCli(stdin, stdout) {+ 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) {+ if (!isRecord4(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", "turn_id"].every((key) => optionalString(value[key])) && (value["transcript_path"] === undefined || value["transcript_path"] === null || typeof value["transcript_path"] === "string");+}+function isPreToolUsePayload(value) {+ if (!isRecord4(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 hasInvalidCreateGoalInput(value) {+ return isRecord4(value) && Object.keys(value).some((key) => key !== "objective");+}+function isRecord4(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}+function optionalString(value) {+ return value === undefined || typeof value === "string";+}+function readAll(stdin) {+ return new Promise((resolve4, reject) => {+ let data = "";+ stdin.setEncoding("utf8");+ stdin.on("data", (chunk) => {+ data += chunk instanceof Buffer ? chunk.toString() : String(chunk);+ });+ stdin.once("error", reject);+ stdin.once("end", () => resolve4(data));+ });+}++// components/ulw-loop/src/spawn-guard.ts+import { existsSync as existsSync6, readdirSync, readFileSync as readFileSync3, statSync as statSync2, writeFileSync } from "node:fs";+import { join as join2 } from "node:path";+var SPAWN_TOOL_TOKENS = new Set(["spawn_agent", "collaborationspawn_agent", "collaboration.spawn_agent"]);+var DEFAULT_FANOUT_LIMIT = 60;+var GATE_MESSAGE_PATTERN = /lazycodex-gate-reviewer|final gate review/i;+function applySpawnGuards(payload) {+ if (payload.hook_event_name !== "PreToolUse" || !SPAWN_TOOL_TOKENS.has(payload.tool_name))+ return "";+ const stateDir = ulwLoopDir(payload.cwd, { sessionId: payload.session_id });+ const plan = readPlan(join2(stateDir, "goals.json"));+ if (plan === null)+ return "";+ const fanOutDenial = consumeFanOutBudget(stateDir);+ if (fanOutDenial !== null)+ return deny(fanOutDenial);+ const missingArtifact = missingGateArtifact(payload, plan);+ if (missingArtifact !== null)+ return deny(`spawn code-review + QA first; gate audits their artifacts: missing ${missingArtifact}`);+ return "";+}+async function runSpawnGuardCli(stdin, stdout) {+ try {+ const chunks = [];+ for await (const chunk of stdin)+ chunks.push(Buffer.from(chunk));+ const payload = parsePreToolUsePayload(Buffer.concat(chunks).toString("utf8"));+ if (payload === null)+ return;+ const output = applySpawnGuards(payload);+ if (output.length > 0)+ stdout.write(output);+ } catch (error) {+ if (error instanceof Error)+ return;+ }+}+function consumeFanOutBudget(stateDir) {+ const counterPath = join2(stateDir, "spawn-count.json");+ const count = readCount(counterPath) + 1;+ writeFileSync(counterPath, JSON.stringify({ count }));+ const limit = fanOutLimit();+ if (count <= limit)+ return null;+ return `ulw-loop spawn fan-out cap reached (${count}/${limit}). Consolidate work into the agents already running, or raise OMO_SPAWN_FANOUT_LIMIT if this volume is intentional.`;+}+function missingGateArtifact(payload, plan) {+ if (!isGateReviewerSpawn(payload.tool_input))+ return null;+ const goal3 = plan.goals.find((candidate) => isFinalRunCompletionCandidate(plan, candidate));+ if (goal3 === undefined || goal3.status === "complete")+ return null;+ if (!goal3.successCriteria.every((criterion) => criterion.status === "pass"))+ return null;+ const scope = { sessionId: payload.session_id };+ if (plan.evidenceLayoutVersion === 2) {+ const attemptDir = ulwLoopAttemptEvidenceDir(goal3.id, goal3.attempt, scope);+ for (const name of [`${goal3.id}-code-review.md`, `${goal3.id}-manual-qa.md`]) {+ const relative2 = `${attemptDir}/${name}`;+ if (!isNonEmptyFile(join2(payload.cwd, relative2)))+ return relative2;+ }+ return null;+ }+ const flatReport = `.omo/evidence/${goal3.id}-code-review.md`;+ if (!isNonEmptyFile(join2(payload.cwd, flatReport)))+ return flatReport;+ if (!hasOtherEvidenceFile(join2(payload.cwd, ".omo", "evidence"), `${goal3.id}-code-review.md`))+ return `.omo/evidence/<any manual-QA artifact besides ${goal3.id}-code-review.md>`;+ return null;+}+function isGateReviewerSpawn(toolInput) {+ if (typeof toolInput !== "object" || toolInput === null)+ return false;+ const record = toolInput;+ const agentType = record["agent_type"];+ if (typeof agentType === "string")+ return agentType === "lazycodex-gate-reviewer";+ const message = record["message"];+ return typeof message === "string" && GATE_MESSAGE_PATTERN.test(message);+}+function deny(reason) {+ return `${JSON.stringify({+ hookSpecificOutput: {+ hookEventName: "PreToolUse",+ permissionDecision: "deny",+ permissionDecisionReason: reason,+ additionalContext: reason+ }+ })}+`;+}+function fanOutLimit() {+ const raw = process.env["OMO_SPAWN_FANOUT_LIMIT"];+ if (raw === undefined)+ return DEFAULT_FANOUT_LIMIT;+ const parsed = Number.parseInt(raw, 10);+ return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_FANOUT_LIMIT;+}+function isNonEmptyFile(path) {+ try {+ return existsSync6(path) && statSync2(path).size > 0;+ } catch (error) {+ if (error instanceof Error)+ return false;+ throw error;+ }+}+function hasOtherEvidenceFile(evidenceDir, excludedName) {+ try {+ return readdirSync(evidenceDir).some((name) => name !== excludedName && isNonEmptyFile(join2(evidenceDir, name)));+ } catch (error) {+ if (error instanceof Error)+ return false;+ throw error;+ }+}+function readCount(counterPath) {+ try {+ const parsed = JSON.parse(readFileSync3(counterPath, "utf8"));+ return typeof parsed["count"] === "number" && parsed["count"] >= 0 ? parsed["count"] : 0;+ } catch (error) {+ if (error instanceof Error)+ return 0;+ throw error;+ }+}+function readPlan(goalsPath) {+ try {+ return JSON.parse(readFileSync3(goalsPath, "utf8"));+ } catch (error) {+ if (error instanceof Error)+ return null;+ throw error;+ }+}++// components/ulw-loop/src/stop-resume-hook.ts+import { existsSync as existsSync7, readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "node:fs";+import { isAbsolute as isAbsolute2, join as join3, resolve as resolve4, sep as sep2 } from "node:path";+var RESUME_CAP = 2;+var CONTEXT_PRESSURE_MARKERS2 = [+ "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"+];+function runStopResumeHook(input) {+ const payload = parseStopPayload(input);+ if (payload === null || payload.stop_hook_active)+ return "";+ if (transcriptShowsContextPressure(payload.transcript_path))+ return "";+ if (boulderContinuationWillFire(payload.cwd, payload.session_id))+ return "";+ const stateDir = ulwLoopDir(payload.cwd, { sessionId: payload.session_id });+ const plan = readPlan2(join3(stateDir, "goals.json"));+ if (plan === null || plan.aggregateCompletion?.status === "complete")+ return "";+ const goal3 = resumableGoal(plan);+ if (goal3 === undefined)+ return "";+ if (!consumeResumeBudget(stateDir, goal3.id))+ return "";+ const output = {+ decision: "block",+ reason: renderResumeDirective(plan, goal3, payload.session_id)+ };+ return JSON.stringify(output);+}+async function runStopResumeHookCli(stdin, stdout) {+ try {+ const chunks = [];+ for await (const chunk of stdin)+ chunks.push(Buffer.from(chunk));+ const output = runStopResumeHook(JSON.parse(Buffer.concat(chunks).toString("utf8")));+ if (output.length > 0)+ stdout.write(output);+ } catch (error) {+ if (error instanceof Error)+ return;+ }+}+function resumableGoal(plan) {+ const active = plan.goals.find((goal3) => goal3.id === plan.activeGoalId);+ if (active !== undefined && isResumableStatus(active.status))+ return active;+ return plan.goals.find((goal3) => isResumableStatus(goal3.status));+}+function isResumableStatus(status2) {+ return status2 === "pending" || status2 === "in_progress";+}+function consumeResumeBudget(stateDir, goalId) {+ const ledgerLineCount = countLedgerLines(join3(stateDir, "ledger.jsonl"));+ const counterPath = resolve4(stateDir, `auto-resume-${goalId}.json`);+ const stuckPath = resolve4(stateDir, `auto-resume-${goalId}.stuck`);+ if (!isInsideDir(stateDir, counterPath) || !isInsideDir(stateDir, stuckPath))+ return false;+ const previous = readCounter(counterPath);+ const count = previous !== null && previous.ledgerLineCount === ledgerLineCount ? previous.count : 0;+ if (count >= RESUME_CAP) {+ writeFileSync2(stuckPath, `no ledger progress after ${count} resumes+`);+ return false;+ }+ writeFileSync2(counterPath, JSON.stringify({ count: count + 1, ledgerLineCount }));+ return true;+}+function isInsideDir(dir, candidate) {+ return candidate.startsWith(resolve4(dir) + sep2);+}+function renderResumeDirective(plan, goal3, sessionId) {+ const normalized = normalizeUlwLoopSessionId(sessionId);+ const option = normalized !== null && plan.goalsPath.includes(`/${normalized}/`) ? ` --session-id ${normalized}` : "";+ return [+ `The ulw-loop run in this session still has unfinished goals (next: ${goal3.id} — ${goal3.title}).`,+ "The turn ended before the loop completed. Resume it now:",+ `1. Run \`omo ulw-loop status${option} --json\` to reload the plan, the active goal, and currentAttemptDir.`,+ "2. Continue the active goal's remaining success criteria, recording evidence with record-evidence.",+ `3. Checkpoint through \`omo ulw-loop checkpoint${option}\` when the goal's criteria are proven; a complete checkpoint prints the next goal instruction.`,+ "If the loop is genuinely blocked on the user, checkpoint the goal as blocked with the reason instead."+ ].join(`+`);+}+function readPlan2(goalsPath) {+ try {+ return JSON.parse(readFileSync4(goalsPath, "utf8"));+ } catch (error) {+ if (error instanceof Error)+ return null;+ throw error;+ }+}+function countLedgerLines(ledgerPath) {+ try {+ return readFileSync4(ledgerPath, "utf8").split(`+`).filter(Boolean).length;+ } catch (error) {+ if (error instanceof Error)+ return 0;+ throw error;+ }+}+function readCounter(counterPath) {+ try {+ if (!existsSync7(counterPath))+ return null;+ const parsed = JSON.parse(readFileSync4(counterPath, "utf8"));+ if (typeof parsed["count"] !== "number" || typeof parsed["ledgerLineCount"] !== "number")+ return null;+ return { count: parsed["count"], ledgerLineCount: parsed["ledgerLineCount"] };+ } catch (error) {+ if (error instanceof Error)+ return null;+ throw error;+ }+}+function boulderContinuationWillFire(cwd, sessionId) {+ try {+ const raw = JSON.parse(readFileSync4(join3(cwd, ".omo", "boulder.json"), "utf8"));+ const works = raw["works"];+ const entries = typeof works === "object" && works !== null ? Object.values(works) : [raw];+ return entries.some((work) => {+ if (typeof work !== "object" || work === null)+ return false;+ const entry = work;+ const sessionIds = Array.isArray(entry["session_ids"]) ? entry["session_ids"] : [];+ const continuable = entry["status"] === "active" || entry["status"] === "paused";+ return continuable && sessionIds.includes(`codex:${sessionId}`) && boulderPlanHasChecklist(cwd, entry);+ });+ } catch (error) {+ if (error instanceof Error)+ return false;+ throw error;+ }+}+function transcriptShowsContextPressure(transcriptPath) {+ try {+ const transcript = readFileSync4(transcriptPath, "utf8").toLowerCase();+ return CONTEXT_PRESSURE_MARKERS2.some((marker) => transcript.includes(marker));+ } catch (error) {+ if (error instanceof Error)+ return false;+ throw error;+ }+}+function boulderPlanHasChecklist(cwd, entry) {+ const activePlan = entry["active_plan"];+ if (typeof activePlan !== "string" || activePlan.trim().length === 0)+ return false;+ const planPath = isAbsolute2(activePlan) ? activePlan : join3(cwd, activePlan);+ const worktree = entry["worktree_path"];+ const candidates = typeof worktree === "string" && worktree.trim().length > 0 && !isAbsolute2(activePlan) ? [join3(isAbsolute2(worktree) ? worktree : join3(cwd, worktree), activePlan), planPath] : [planPath];+ for (const candidate of candidates) {+ try {+ return readFileSync4(candidate, "utf8").split(/\r?\n/).some((line) => line.startsWith("- [ ] ") || line.startsWith("- [x] ") || line.startsWith("- [X] "));+ } catch (error) {+ if (!(error instanceof Error))+ throw error;+ }+ }+ return false;+}+function parseStopPayload(value) {+ if (typeof value !== "object" || value === null || Array.isArray(value))+ return null;+ const record = value;+ const optionalMessage = record["last_assistant_message"];+ const valid = record["hook_event_name"] === "Stop" && typeof record["session_id"] === "string" && typeof record["turn_id"] === "string" && typeof record["transcript_path"] === "string" && typeof record["cwd"] === "string" && typeof record["model"] === "string" && typeof record["permission_mode"] === "string" && typeof record["stop_hook_active"] === "boolean" && (optionalMessage === undefined || typeof optionalMessage === "string");+ if (!valid)+ return null;+ return {+ session_id: record["session_id"],+ cwd: record["cwd"],+ transcript_path: record["transcript_path"],+ stop_hook_active: record["stop_hook_active"]+ };+}++// components/ulw-loop/src/cli.ts+var TOP_LEVEL_HELP = `Usage:+ omo ulw-loop <subcommand> [args]+ omo hook user-prompt-submit [--with-ultrawork] (Codex UserPromptSubmit hook)+ omo help | --help | -h (this message)++Run \`omo ulw-loop help\` for ulw-loop subcommands.+`;+async function main() {+ 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 === "ulw-loop")+ return ulwLoopCommand(argv.slice(1));+ if (command === "hook") {+ const sub = argv[1];+ if (sub === "user-prompt-submit") {+ await runUlwLoopHookCli(process.stdin, process.stdout, {+ includeUltraworkDirective: argv.includes("--with-ultrawork")+ });+ return 0;+ }+ if (sub === "pre-tool-use") {+ await runPreToolUseGoalBudgetGuardCli(process.stdin, process.stdout);+ return 0;+ }+ if (sub === "stop") {+ await runStopResumeHookCli(process.stdin, process.stdout);+ return 0;+ }+ if (sub === "pre-tool-use-spawn") {+ await runSpawnGuardCli(process.stdin, process.stdout);+ return 0;+ }+ process.stderr.write(`[omo] unknown hook subcommand: ${sub ?? "(none)"}+`);+ return 1;+ }+ if (isUlwLoopSubcommand(command))+ return ulwLoopCommand(argv);+ process.stderr.write(`[omo] unknown command: ${command}+${TOP_LEVEL_HELP}`);+ return 1;+}+main().then((code) => {+ process.exit(code);+}).catch((error) => {+ process.stderr.write(`[omo] ${error instanceof Error ? error.message : String(error)}+`);+ process.exit(1);+});diff --git a/plugins/omo/components/ulw-loop/dist/codex-goal-instruction.d.ts b/plugins/omo/components/ulw-loop/dist/codex-goal-instruction.d.tsnew file mode 100644index 00000000..01f5388a--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/codex-goal-instruction.d.ts@@ -0,0 +1,13 @@+import type { UlwLoopItem, UlwLoopPlan } from "./types.js";+export interface CodexCreateGoalPayload {+ readonly objective: string;+}+export interface UlwLoopGoalInstruction {+ readonly text: string;+ readonly json: CodexCreateGoalPayload;+}+export declare function buildCodexGoalInstruction(args: {+ readonly plan: UlwLoopPlan;+ readonly goal: UlwLoopItem;+ readonly isFinal?: boolean;+}): UlwLoopGoalInstruction;diff --git a/plugins/omo/components/ulw-loop/dist/codex-goal-instruction.js b/plugins/omo/components/ulw-loop/dist/codex-goal-instruction.jsnew file mode 100644index 00000000..0fcb2627--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/codex-goal-instruction.js@@ -0,0 +1,116 @@+// biome-ignore-all format: long agent-facing instruction strings are intentionally stable.+import { codexGoalMode, expectedCodexObjective, isEssentialCriterion, isFinalRunCompletionCandidate, } from "./goal-status.js";+export function buildCodexGoalInstruction(args) {+ 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, goal) {+ return { objective: expectedCodexObjective(plan, goal) };+}+function buildText(mode, plan, goal, createGoal, isFinal) {+ return joinLines([+ mode === "aggregate" ? "UlwLoop aggregate-goal handoff" : "UlwLoop active-goal handoff",+ `Mode: ${mode}`,+ `Plan: ${plan.goalsPath}`,+ `Ledger: ${plan.ledgerPath}`,+ `Goal: ${goal.id} — ${goal.title}`,+ "",+ ...activeGoalLines(goal),+ "",+ ...successCriteriaLines(goal.successCriteria),+ "",+ "Codex goal integration constraints:",+ "- Use the create_goal payload exactly as rendered: objective only.",+ "- Goals are unlimited. Do not add numeric limits.",+ ...modeConstraintLines(mode, isFinal),+ ...evidenceLayoutLines(plan),+ finalSection(plan, goal, isFinal, mode === "aggregate"),+ ...checkpointLines(plan, mode),+ "",+ "create_goal payload:",+ JSON.stringify(createGoal, null, 2),+ ]);+}+function modeConstraintLines(mode, isFinal) {+ 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 ulw-loop.",+ "- Work only this goal until its completion audit passes.",+ ];+ }+ return [+ "- 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 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 mid-aggregate; checkpoint this OMO ledger story and continue the remaining stories. update_goal is reserved for the final story after the mandatory quality gate passes.",+ ];+}+function checkpointLines(plan, mode) {+ 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.",+ failureLine,+ ];+}+function activeGoalLines(goal) {+ return ["Active goal:", `- id: ${goal.id}`, `- title: ${goal.title}`, `- objective: ${goal.objective}`];+}+function successCriteriaLines(criteria) {+ if (criteria.length === 0)+ return ["Success criteria:", "- No success criteria recorded for this goal."];+ return ["Success criteria:", ...criteria.map(formatCriterionLine)];+}+function formatCriterionLine(criterion) {+ const remainingWork = criterion.status === "pending" ? " remaining work:" : "";+ const marker = isEssentialCriterion(criterion) ? "essential" : "non-essential";+ return `-${remainingWork} [${criterion.id}] [${marker}] (${criterion.userModel}) ${criterion.scenario} — expect: ${criterion.expectedEvidence} — status: ${criterion.status}`;+}+function evidenceLayoutLines(plan) {+ if (plan.evidenceLayoutVersion !== 2)+ return [];+ return [+ "- Evidence layout v2: write every artifact for the active goal (QA matrix, review reports, receipts) under the current attempt directory — read currentAttemptDir from `omo ulw-loop status --json` (.omo/evidence/ulw/<session>/<goalId>/a<attempt>). The final checkpoint rejects quality-gate artifacts outside that directory.",+ ];+}+function finalSection(plan, goal, isFinal, aggregate) {+ if (!isFinal)+ return "- This is not the final ulw-loop story; do not run the final reviewer/manual-QA/gate-review quality 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 "<targeted verification/manualQa/gateReview 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 targeted verification for changed behavior.",+ "- Confirm every manualQa artifact path exists and has non-zero size.",+ "- First spawn lazycodex-code-reviewer and lazycodex-qa-executor in parallel (fork_context: false on the v1 surface; fork_turns: \"none\" on v2). Include the original brief, goal objectives, desired user-visible outcome, diff, and evidence; wait for BOTH to return and confirm their report artifacts exist on disk (code-review report + manualQa matrix).",+ "- Only then spawn lazycodex-gate-reviewer (same fork settings), passing those artifact paths.",+ "- Require clean codeReview, manualQa, gateReview, iteration, and criteriaCoverage. criteriaCoverage must summarize originalIntent, desiredOutcome, and userOutcomeReview; counts alone are not approval.",+ "- On a reviewer REJECT, fix only the cited blockers, rerun the affected verification/Manual-QA, and re-review the delta at most TWICE; if blockers remain, record them and surface to the user.",+ "- If codeQualityStatus is WATCH, include the WATCH notes verbatim in your final user-facing message.",+ "- If any reviewer is blocked/inconclusive or the quality gate is not clean, do not call update_goal. Record blocker work first:",+ ` ${blockerCommand}`,+ aggregate+ ? '- If the quality gate is clean, call update_goal({status: "complete"}), call get_goal again, then checkpoint the aggregate story:'+ : '- If the quality gate is clean, call update_goal({status: "complete"}), call get_goal again, then checkpoint:',+ ` ${checkpointCommand}`,+ ]);+}+function sessionOption(plan) {+ 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) {+ return lines.join("\n");+}diff --git a/plugins/omo/components/ulw-loop/dist/codex-goal-snapshot.d.ts b/plugins/omo/components/ulw-loop/dist/codex-goal-snapshot.d.tsnew file mode 100644index 00000000..2ee79e26--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/codex-goal-snapshot.d.ts@@ -0,0 +1,26 @@+export type CodexGoalSnapshotStatus = "active" | "complete" | "cancelled" | "failed" | "unknown";+export interface CodexGoalSnapshot {+ available: boolean;+ objective?: string;+ status?: CodexGoalSnapshotStatus;+ raw: unknown;+}+export interface CodexGoalReconciliation {+ ok: boolean;+ snapshot: CodexGoalSnapshot;+ warnings: string[];+ errors: string[];+}+export interface ReconcileCodexGoalOptions {+ expectedObjective: string;+ acceptedObjectives?: readonly string[];+ allowedStatuses?: readonly CodexGoalSnapshotStatus[];+ requireSnapshot?: boolean;+ requireComplete?: boolean;+}+export declare class CodexGoalSnapshotError extends Error {+}+export declare function parseCodexGoalSnapshot(value: unknown): CodexGoalSnapshot;+export declare function readCodexGoalSnapshotInput(raw: string | undefined, cwd?: string): Promise<CodexGoalSnapshot | null>;+export declare function reconcileCodexGoalSnapshot(snapshot: CodexGoalSnapshot | null | undefined, options: ReconcileCodexGoalOptions): CodexGoalReconciliation;+export declare function formatCodexGoalReconciliation(reconciliation: CodexGoalReconciliation): string;diff --git a/plugins/omo/components/ulw-loop/dist/codex-goal-snapshot.js b/plugins/omo/components/ulw-loop/dist/codex-goal-snapshot.jsnew file mode 100644index 00000000..a630f226--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/codex-goal-snapshot.js@@ -0,0 +1,97 @@+import { existsSync } from "node:fs";+import { readFile } from "node:fs/promises";+import { resolve } from "node:path";+export class CodexGoalSnapshotError extends Error {+}+function safeObject(value) {+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};+}+function safeString(value) {+ return typeof value === "string" ? value.trim() : "";+}+function normalizeStatus(value) {+ const status = safeString(value).toLowerCase();+ if (status === "complete" || status === "completed" || status === "done")+ return "complete";+ if (status === "cancelled" || status === "canceled")+ return "cancelled";+ if (status === "failed" || status === "failure")+ return "failed";+ if (status === "active" || status === "in_progress" || status === "pending" || status === "running")+ return "active";+ return "unknown";+}+function normalizeObjective(value) {+ return value.replace(/\s+/g, " ").trim();+}+export function parseCodexGoalSnapshot(value) {+ const root = safeObject(value);+ const goalValue = Object.hasOwn(root, "goal") ? root["goal"] : value;+ if (goalValue === null || goalValue === undefined || goalValue === false) {+ return { available: false, raw: value };+ }+ const goal = safeObject(goalValue);+ const objective = safeString(goal["objective"] ?? goal["goal"] ?? goal["description"] ?? root["objective"]);+ const status = normalizeStatus(goal["status"] ?? root["status"]);+ return {+ available: Boolean(objective || status !== "unknown"),+ ...(objective ? { objective } : {}),+ status,+ raw: value,+ };+}+export async function readCodexGoalSnapshotInput(raw, cwd = process.cwd()) {+ if (!raw?.trim())+ return null;+ const trimmed = raw.trim();+ try {+ return parseCodexGoalSnapshot(JSON.parse(trimmed));+ }+ catch {+ const path = resolve(cwd, trimmed);+ if (!existsSync(path)) {+ throw new CodexGoalSnapshotError(`Codex goal snapshot is neither valid JSON nor a readable path: ${trimmed}`);+ }+ try {+ return parseCodexGoalSnapshot(JSON.parse(await readFile(path, "utf-8")));+ }+ catch (error) {+ throw new CodexGoalSnapshotError(`Codex goal snapshot path does not contain valid JSON: ${trimmed}${error instanceof Error ? ` (${error.message})` : ""}`);+ }+ }+}+export function reconcileCodexGoalSnapshot(snapshot, options) {+ const effectiveSnapshot = snapshot ?? { available: false, raw: null };+ const errors = [];+ const warnings = [];+ if (!effectiveSnapshot.available) {+ const message = "Codex goal snapshot is absent or reports no active goal; call get_goal and pass its JSON with --codex-goal-json.";+ if (options.requireSnapshot)+ errors.push(message);+ else+ warnings.push(message);+ return { ok: errors.length === 0, snapshot: effectiveSnapshot, warnings, errors };+ }+ const expected = normalizeObjective(options.expectedObjective);+ const accepted = new Set([expected, ...(options.acceptedObjectives ?? []).map((objective) => normalizeObjective(objective))].filter(Boolean));+ const actual = normalizeObjective(effectiveSnapshot.objective ?? "");+ if (!actual) {+ errors.push("Codex goal snapshot is missing objective text.");+ }+ else if (!accepted.has(actual)) {+ errors.push(`Codex goal objective mismatch: expected "${expected}", got "${actual}".`);+ }+ const allowed = options.allowedStatuses ?? (options.requireComplete ? ["complete"] : ["active", "complete"]);+ const actualStatus = effectiveSnapshot.status ?? "unknown";+ if (!allowed.includes(actualStatus)) {+ errors.push(`Codex goal status mismatch: expected ${allowed.join(" or ")}, got ${actualStatus}.`);+ }+ if (options.requireComplete && actualStatus !== "complete") {+ errors.push('Codex goal is not complete; call update_goal({status: "complete"}) only after the objective is actually complete, then pass the fresh get_goal JSON.');+ }+ return { ok: errors.length === 0, snapshot: effectiveSnapshot, warnings, errors };+}+export function formatCodexGoalReconciliation(reconciliation) {+ const parts = [...reconciliation.errors, ...reconciliation.warnings];+ return parts.join(" ");+}diff --git a/plugins/omo/components/ulw-loop/dist/codex-hook.d.ts b/plugins/omo/components/ulw-loop/dist/codex-hook.d.tsnew file mode 100644index 00000000..58a53c4e--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/codex-hook.d.ts@@ -0,0 +1,32 @@+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 | null;+ readonly turn_id?: string;+}+export interface UserPromptSubmitHookOptions {+ readonly includeUltraworkDirective?: boolean;+ readonly ultraworkSkillFilePath?: string | null;+}+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 declare function parseUserPromptSubmitPayload(raw: string): UserPromptSubmitPayload | null;+export declare function parsePreToolUsePayload(raw: string): PreToolUsePayload | null;+export declare function applyUserPromptUlwLoopSteering(payload: UserPromptSubmitPayload, options?: UserPromptSubmitHookOptions): Promise<string>;+export declare function applyPreToolUseGoalBudgetGuard(payload: PreToolUsePayload): string;+export declare function runUlwLoopHookCli(stdin: NodeJS.ReadableStream, stdout: NodeJS.WritableStream, options?: UserPromptSubmitHookOptions): Promise<void>;+export declare function runPreToolUseGoalBudgetGuardCli(stdin: NodeJS.ReadableStream, stdout: NodeJS.WritableStream): Promise<void>;diff --git a/plugins/omo/components/ulw-loop/dist/codex-hook.js b/plugins/omo/components/ulw-loop/dist/codex-hook.jsnew file mode 100644index 00000000..f6eb9d69--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/codex-hook.js@@ -0,0 +1,159 @@+import { parseUlwLoopSteeringDirective, steerUlwLoop } from "./steering.js";+import { buildUltraworkDirectiveOutput } from "./ultrawork-directive.js";+const CREATE_GOAL_TOOL_NAME = "create_goal";+const CREATE_GOAL_PAYLOAD_WARNING = "Use create_goal with objective only. Omit token_budget so the goal stays unlimited, and put lifecycle status changes on update_goal.";+export function parseUserPromptSubmitPayload(raw) {+ if (raw.trim().length === 0)+ return null;+ try {+ const parsed = JSON.parse(raw);+ return isUserPromptSubmitPayload(parsed) ? parsed : null;+ }+ catch (error) {+ if (error instanceof SyntaxError)+ return null;+ return null;+ }+}+export function parsePreToolUsePayload(raw) {+ if (raw.trim().length === 0)+ return null;+ try {+ const parsed = JSON.parse(raw);+ return isPreToolUsePayload(parsed) ? parsed : null;+ }+ catch (error) {+ if (error instanceof SyntaxError)+ return null;+ return null;+ }+}+export async function applyUserPromptUlwLoopSteering(payload, options = {}) {+ try {+ if (payload.hook_event_name !== "UserPromptSubmit")+ return "";+ const proposal = parseUlwLoopSteeringDirective(payload.prompt);+ if (proposal === null) {+ if (hasSteeringDirectiveMarker(payload.prompt))+ return "";+ if (!options.includeUltraworkDirective)+ return "";+ return options.ultraworkSkillFilePath === undefined+ ? buildUltraworkDirectiveOutput(payload)+ : buildUltraworkDirectiveOutput(payload, { skillFilePath: options.ultraworkSkillFilePath });+ }+ 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 hasSteeringDirectiveMarker(prompt) {+ return /(?:^|\s)(?:OMO_ULW_LOOP_STEER|omo\.ulw-loop\.steer|omo ulw-loop steer):/u.test(prompt);+}+function payloadScope(payload) {+ return { sessionId: payload.session_id };+}+export function applyPreToolUseGoalBudgetGuard(payload) {+ if (payload.hook_event_name !== "PreToolUse")+ return "";+ if (payload.tool_name !== CREATE_GOAL_TOOL_NAME)+ return "";+ if (!hasInvalidCreateGoalInput(payload.tool_input))+ return "";+ const output = {+ hookSpecificOutput: {+ hookEventName: "PreToolUse",+ permissionDecision: "deny",+ permissionDecisionReason: CREATE_GOAL_PAYLOAD_WARNING,+ additionalContext: CREATE_GOAL_PAYLOAD_WARNING,+ },+ };+ return `${JSON.stringify(output)}\n`;+}+export async function runUlwLoopHookCli(stdin, stdout, options = {}) {+ try {+ const payload = parseUserPromptSubmitPayload(await readAll(stdin));+ if (payload === null)+ return;+ const output = await applyUserPromptUlwLoopSteering(payload, options);+ if (output.length > 0)+ stdout.write(output);+ }+ catch (error) {+ if (error instanceof Error)+ return;+ return;+ }+}+export async function runPreToolUseGoalBudgetGuardCli(stdin, stdout) {+ 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) {+ 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", "turn_id"].every((key) => optionalString(value[key])) &&+ (value["transcript_path"] === undefined ||+ value["transcript_path"] === null ||+ typeof value["transcript_path"] === "string"));+}+function isPreToolUsePayload(value) {+ 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 hasInvalidCreateGoalInput(value) {+ return isRecord(value) && Object.keys(value).some((key) => key !== "objective");+}+function isRecord(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}+function optionalString(value) {+ return value === undefined || typeof value === "string";+}+function readAll(stdin) {+ return new Promise((resolve, reject) => {+ let data = "";+ stdin.setEncoding("utf8");+ stdin.on("data", (chunk) => {+ data += chunk instanceof Buffer ? chunk.toString() : String(chunk);+ });+ stdin.once("error", reject);+ stdin.once("end", () => resolve(data));+ });+}diff --git a/plugins/omo/components/ulw-loop/dist/command-types.d.ts b/plugins/omo/components/ulw-loop/dist/command-types.d.tsnew file mode 100644index 00000000..5f6970b0--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/command-types.d.ts@@ -0,0 +1,34 @@+import type { UlwLoopCodexGoalMode, UlwLoopStatus } from "./constants.js";+export interface CreateUlwLoopOptions {+ brief: string;+ goals?: readonly {+ readonly title?: string;+ readonly objective: string;+ }[];+ codexGoalMode?: UlwLoopCodexGoalMode;+ now?: Date;+ force?: boolean;+}+export interface StartNextOptions {+ now?: Date;+ retryFailed?: boolean;+}+export interface CheckpointOptions {+ goalId: string;+ status: Extract<UlwLoopStatus, "complete" | "failed"> | "blocked";+ evidence?: string;+ codexGoal?: unknown;+ qualityGate?: unknown;+ allowActiveFinalCodexGoal?: boolean;+ now?: Date;+}+export interface AddUlwLoopGoalOptions {+ title: string;+ objective: string;+ evidence?: string;+ now?: Date;+}+export interface RecordFinalReviewBlockersOptions extends AddUlwLoopGoalOptions {+ goalId: string;+ codexGoal?: unknown;+}diff --git a/plugins/omo/components/ulw-loop/dist/command-types.js b/plugins/omo/components/ulw-loop/dist/command-types.jsnew file mode 100644index 00000000..cb0ff5c3--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/command-types.js@@ -0,0 +1 @@+export {};diff --git a/plugins/omo/components/ulw-loop/dist/constants.d.ts b/plugins/omo/components/ulw-loop/dist/constants.d.tsnew file mode 100644index 00000000..5b3db830--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/constants.d.ts@@ -0,0 +1,16 @@+export declare const ULW_LOOP_DIR = ".omo/ulw-loop";+export declare const ULW_LOOP_BRIEF = "brief.md";+export declare const ULW_LOOP_GOALS = "goals.json";+export declare const ULW_LOOP_LEDGER = "ledger.jsonl";+export type UlwLoopStatus = "pending" | "in_progress" | "complete" | "failed" | "blocked" | "review_blocked" | "needs_user_decision";+export type UlwLoopCodexGoalMode = "aggregate" | "per_story";+export type UlwLoopSteeringStatus = "superseded" | "blocked";+export declare const ULW_LOOP_STEERING_MUTATION_KINDS: readonly ["add_subgoal", "split_subgoal", "reorder_pending", "revise_pending_wording", "revise_criterion", "annotate_ledger", "mark_blocked_superseded"];+export type UlwLoopSteeringMutationKind = (typeof ULW_LOOP_STEERING_MUTATION_KINDS)[number];+export type UlwLoopSteeringSource = "user_prompt_submit" | "finding" | "cli";+export declare const ULW_LOOP_SUCCESS_CRITERION_USER_MODELS: readonly ["happy", "edge", "regression", "adversarial"];+export type UlwLoopSuccessCriterionUserModel = (typeof ULW_LOOP_SUCCESS_CRITERION_USER_MODELS)[number];+export declare const ULW_LOOP_CRITERION_STATUSES: readonly ["pending", "pass", "fail", "blocked"];+export type UlwLoopCriterionStatus = (typeof ULW_LOOP_CRITERION_STATUSES)[number];+export declare const ULW_LOOP_LEDGER_EVENT_KINDS: readonly ["plan_created", "goal_started", "goal_resumed", "goal_completed", "goal_blocked", "goal_failed", "goal_needs_user_decision", "goal_retried", "aggregate_completed", "aggregate_objective_migrated", "goal_added", "steering_accepted", "steering_rejected", "final_review_failed", "goal_review_blocked", "evidence_captured", "criterion_failed", "criterion_blocked", "criteria_revised", "batch_closed", "batch_updated"];+export type UlwLoopLedgerEventKind = (typeof ULW_LOOP_LEDGER_EVENT_KINDS)[number];diff --git a/plugins/omo/components/ulw-loop/dist/constants.js b/plugins/omo/components/ulw-loop/dist/constants.jsnew file mode 100644index 00000000..40707448--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/constants.js@@ -0,0 +1,43 @@+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 const ULW_LOOP_STEERING_MUTATION_KINDS = [+ "add_subgoal",+ "split_subgoal",+ "reorder_pending",+ "revise_pending_wording",+ "revise_criterion",+ "annotate_ledger",+ "mark_blocked_superseded",+];+export const ULW_LOOP_SUCCESS_CRITERION_USER_MODELS = [+ "happy",+ "edge",+ "regression",+ "adversarial",+];+export const ULW_LOOP_CRITERION_STATUSES = ["pending", "pass", "fail", "blocked"];+export const ULW_LOOP_LEDGER_EVENT_KINDS = [+ "plan_created",+ "goal_started",+ "goal_resumed",+ "goal_completed",+ "goal_blocked",+ "goal_failed",+ "goal_needs_user_decision",+ "goal_retried",+ "aggregate_completed",+ "aggregate_objective_migrated",+ "goal_added",+ "steering_accepted",+ "steering_rejected",+ "final_review_failed",+ "goal_review_blocked",+ "evidence_captured",+ "criterion_failed",+ "criterion_blocked",+ "criteria_revised",+ "batch_closed",+ "batch_updated",+];diff --git a/plugins/omo/components/ulw-loop/dist/domain-types.d.ts b/plugins/omo/components/ulw-loop/dist/domain-types.d.tsnew file mode 100644index 00000000..6f35c7d5--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/domain-types.d.ts@@ -0,0 +1,151 @@+import type { UlwLoopCodexGoalMode, UlwLoopCriterionStatus, UlwLoopLedgerEventKind, UlwLoopStatus, UlwLoopSteeringMutationKind, UlwLoopSteeringStatus, UlwLoopSuccessCriterionUserModel } from "./constants.js";+import type { UlwLoopSteeringAudit } from "./steering-types.js";+export interface UlwLoopSuccessCriterion {+ readonly id: string;+ readonly scenario: string;+ readonly userModel: UlwLoopSuccessCriterionUserModel;+ readonly expectedEvidence: string;+ readonly essential?: boolean;+ capturedEvidence: string | null;+ status: UlwLoopCriterionStatus;+ capturedAt?: string;+ notes?: string;+}+export interface UlwLoopItem {+ id: string;+ title: string;+ objective: string;+ status: UlwLoopStatus;+ successCriteria: UlwLoopSuccessCriterion[];+ attempt: number;+ createdAt: string;+ updatedAt: string;+ startedAt?: string;+ completedAt?: string;+ failedAt?: string;+ reviewBlockedAt?: string;+ evidence?: string;+ failureReason?: string;+ steeringStatus?: UlwLoopSteeringStatus;+ supersededBy?: string[];+ supersedes?: string[];+ blockedReason?: string;+ blockerSignature?: string;+ blockerOccurrenceCount?: number;+ requiredExternalDecision?: string;+ nonRetriable?: boolean;+ steeringEvidence?: string;+ steeringRationale?: string;+}+export interface UlwLoopAggregateCompletion {+ status: "complete";+ completedAt: string;+ evidence: string;+ codexGoal?: unknown;+}+export interface UlwLoopValidationBatch {+ readonly batchId: string;+ readonly memberIds: readonly string[];+ readonly finalGoalId: string;+}+export interface UlwLoopPlan {+ version: 1;+ evidenceLayoutVersion?: 2;+ createdAt: string;+ updatedAt: string;+ briefPath: string;+ goalsPath: string;+ ledgerPath: string;+ codexGoalMode?: UlwLoopCodexGoalMode;+ codexObjective?: string;+ codexObjectiveAliases?: string[];+ aggregateCompletion?: UlwLoopAggregateCompletion;+ activeGoalId?: string;+ validationBatches?: readonly UlwLoopValidationBatch[];+ goals: UlwLoopItem[];+}+export type UlwLoopManualQaSurface = "cli" | "http" | "tmux" | "browser" | "gui" | "data";+export type UlwLoopManualQaArtifactKind = "cli-transcript" | "log" | "screenshot" | "image" | "http-dump" | "data-diff";+export interface UlwLoopManualQaArtifactRef {+ readonly id: string;+ readonly kind: UlwLoopManualQaArtifactKind;+ readonly description: string;+ readonly path: string;+}+export interface UlwLoopManualQaSurfaceEvidence {+ readonly id: string;+ readonly criterionRef: string;+ readonly surface: UlwLoopManualQaSurface;+ readonly invocation: string;+ readonly verdict: "passed";+ readonly artifactRefs: readonly string[];+}+export interface UlwLoopManualQaAdversarialCase {+ readonly id: string;+ readonly criterionRef: string;+ readonly scenario: string;+ readonly expectedBehavior: string;+ readonly verdict: "passed" | "not_applicable";+ readonly reason?: string;+ readonly artifactRefs: readonly string[];+}+export interface UlwLoopQualityGate {+ readonly codeReview: {+ readonly by: string;+ readonly recommendation: "APPROVE";+ readonly codeQualityStatus: "CLEAR" | "WATCH";+ readonly reportPath: string;+ readonly evidence: string;+ readonly blockers: readonly [];+ };+ readonly manualQa: {+ readonly by: string;+ readonly status: "passed";+ readonly evidence: string;+ readonly surfaceEvidence: readonly UlwLoopManualQaSurfaceEvidence[];+ readonly adversarialCases: readonly UlwLoopManualQaAdversarialCase[];+ readonly artifactRefs: readonly UlwLoopManualQaArtifactRef[];+ };+ readonly gateReview: {+ readonly by: string;+ readonly recommendation: "APPROVE";+ readonly reportPath: string;+ readonly evidence: string;+ readonly blockers: readonly [];+ };+ readonly iteration: {+ readonly fullRerun: true;+ readonly status: "passed";+ readonly rerunCommands: readonly string[];+ readonly evidence: string;+ };+ readonly criteriaCoverage: {+ readonly totalCriteria: number;+ readonly passCount: number;+ readonly originalIntent: string;+ readonly desiredOutcome: string;+ readonly userOutcomeReview: string;+ readonly adversarialClassesCovered: readonly string[];+ };+}+export interface UlwLoopLedgerEntry {+ at: string;+ kind: UlwLoopLedgerEventKind;+ goalId?: string;+ criterionId?: string;+ status?: UlwLoopStatus;+ criterionStatus?: UlwLoopCriterionStatus;+ message?: string;+ codexGoal?: unknown;+ evidence?: string;+ capturedEvidence?: string;+ qualityGate?: unknown;+ steering?: UlwLoopSteeringAudit;+ before?: unknown;+ after?: unknown;+ mutationKind?: UlwLoopSteeringMutationKind;+ idempotencyKey?: string;+ blockerSignature?: string;+ blockerOccurrenceCount?: number;+ requiredExternalDecision?: string;+}diff --git a/plugins/omo/components/ulw-loop/dist/domain-types.js b/plugins/omo/components/ulw-loop/dist/domain-types.jsnew file mode 100644index 00000000..cb0ff5c3--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/domain-types.js@@ -0,0 +1 @@+export {};diff --git a/plugins/omo/components/ulw-loop/dist/evidence.d.ts b/plugins/omo/components/ulw-loop/dist/evidence.d.tsnew file mode 100644index 00000000..686b11b6--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/evidence.d.ts@@ -0,0 +1,34 @@+import type { UlwLoopScope } from "./paths.js";+import type { UlwLoopItem, UlwLoopLedgerEntry, UlwLoopPlan, UlwLoopSuccessCriterion } 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;+};+export declare function recordEvidence(repoRoot: string, args: RecordEvidenceArgs, scope?: UlwLoopScope): Promise<{+ plan: UlwLoopPlan;+ goal: UlwLoopItem;+ criterion: UlwLoopSuccessCriterion;+ ledgerEntry: UlwLoopLedgerEntry;+}>;+export declare function markCriteriaPendingResetForGoal(repoRoot: string, goalId: string, scope?: UlwLoopScope): Promise<{+ plan: UlwLoopPlan;+ resetCount: number;+}>;+export declare function criteriaSummary(plan: UlwLoopPlan): {+ totalCriteria: number;+ passCount: number;+ pendingCount: number;+ failCount: number;+ blockedCount: number;+ goalsWithUnresolvedCriteria: string[];+};+export declare function unresolvedCriteriaOf(goal: UlwLoopItem): UlwLoopSuccessCriterion[];+export declare function unresolvedEssentialCriteriaOf(goal: UlwLoopItem): readonly UlwLoopSuccessCriterion[];+export declare function requireAllCriteriaPass(goal: UlwLoopItem): void;+export declare function requireAllPlanCriteriaPass(plan: UlwLoopPlan): void;+export declare function requireEssentialCriteriaPass(goal: UlwLoopItem): void;+export {};diff --git a/plugins/omo/components/ulw-loop/dist/evidence.js b/plugins/omo/components/ulw-loop/dist/evidence.jsnew file mode 100644index 00000000..b771c2bc--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/evidence.js@@ -0,0 +1,176 @@+import { essentialCriteriaOf, hasAllCriteriaPass, hasEssentialCriteriaPass } from "./goal-status.js";+import { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";+import { iso, UlwLoopError } from "./types.js";+function ulwLoopFail(message, code, details) {+ throw new UlwLoopError(message, code, { details });+}+function ledgerKind(status) {+ switch (status) {+ case "pass":+ return "evidence_captured";+ case "fail":+ return "criterion_failed";+ case "blocked":+ return "criterion_blocked";+ default:+ return ulwLoopFail("Invalid criterion status.", "ULW_LOOP_CRITERION_STATUS_INVALID", { status });+ }+}+function findGoal(plan, goalId) {+ const goal = plan.goals.find((candidate) => candidate.id === goalId);+ return goal ?? ulwLoopFail(`UlwLoop goal not found: ${goalId}.`, "ULW_LOOP_GOAL_NOT_FOUND", { goalId });+}+function findCriterion(goal, criterionId) {+ const criterion = goal.successCriteria.find((candidate) => candidate.id === criterionId);+ return (criterion ??+ ulwLoopFail(`Success criterion not found: ${criterionId}.`, "ULW_LOOP_CRITERION_NOT_FOUND", {+ goalId: goal.id,+ criterionId,+ }));+}+function nonEmptyEvidence(evidence) {+ const trimmed = evidence.trim();+ return trimmed || ulwLoopFail("Evidence must be a non-empty string.", "ULW_LOOP_EVIDENCE_REQUIRED", {});+}+export async function recordEvidence(repoRoot, args, scope) {+ 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);+ const kind = ledgerKind(args.status);+ const prevStatus = criterion.status;+ const capturedAt = iso();+ criterion.status = args.status;+ criterion.capturedEvidence = evidence;+ criterion.capturedAt = capturedAt;+ if (args.notes !== undefined)+ criterion.notes = args.notes;+ goal.updatedAt = capturedAt;+ plan.updatedAt = capturedAt;+ await writePlan(repoRoot, plan, scope);+ const ledgerEntry = {+ at: capturedAt,+ kind,+ goalId: goal.id,+ criterionId: criterion.id,+ criterionStatus: args.status,+ evidence,+ capturedEvidence: evidence,+ before: { status: prevStatus },+ after: { goalId: goal.id, criterionId: criterion.id, status: args.status, evidence, capturedAt, prevStatus },+ };+ await appendLedger(repoRoot, ledgerEntry, scope);+ return { plan, goal, criterion, ledgerEntry };+ });+}+export async function markCriteriaPendingResetForGoal(repoRoot, goalId, scope) {+ 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,+ }));+ for (const criterion of goal.successCriteria) {+ criterion.status = "pending";+ criterion.capturedEvidence = null;+ delete criterion.capturedAt;+ delete criterion.notes;+ }+ goal.updatedAt = now;+ plan.updatedAt = now;+ await writePlan(repoRoot, plan, 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) {+ let totalCriteria = 0;+ let passCount = 0;+ let pendingCount = 0;+ let failCount = 0;+ let blockedCount = 0;+ const goalsWithUnresolvedCriteria = [];+ for (const goal of plan.goals) {+ let unresolved = false;+ for (const criterion of goal.successCriteria) {+ totalCriteria += 1;+ if (criterion.status !== "pass")+ unresolved = true;+ switch (criterion.status) {+ case "pass":+ passCount += 1;+ break;+ case "pending":+ pendingCount += 1;+ break;+ case "fail":+ failCount += 1;+ break;+ case "blocked":+ blockedCount += 1;+ break;+ default:+ ulwLoopFail("Invalid criterion status.", "ULW_LOOP_CRITERION_STATUS_INVALID", {+ status: criterion.status,+ });+ }+ }+ if (unresolved)+ goalsWithUnresolvedCriteria.push(goal.id);+ }+ return { totalCriteria, passCount, pendingCount, failCount, blockedCount, goalsWithUnresolvedCriteria };+}+export function unresolvedCriteriaOf(goal) {+ return goal.successCriteria.filter((criterion) => criterion.status !== "pass");+}+export function unresolvedEssentialCriteriaOf(goal) {+ const essentialCriteria = new Set(essentialCriteriaOf(goal).map((criterion) => criterion.id));+ return goal.successCriteria.filter((criterion) => essentialCriteria.has(criterion.id) && criterion.status !== "pass");+}+export function requireAllCriteriaPass(goal) {+ if (hasAllCriteriaPass(goal))+ return;+ 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 })),+ },+ });+}+export function requireAllPlanCriteriaPass(plan) {+ const unresolved = plan.goals.flatMap((goal) => unresolvedCriteriaOf(goal).map((criterion) => ({+ goalId: goal.id,+ id: criterion.id,+ status: criterion.status,+ })));+ if (unresolved.length === 0)+ return;+ throw new UlwLoopError("Ulw-loop aggregate has unresolved success criteria.", "ulw_loop_criteria_not_all_pass", {+ details: { unresolved },+ });+}+export function requireEssentialCriteriaPass(goal) {+ if (hasEssentialCriteriaPass(goal))+ return;+ throw new UlwLoopError(`Goal ${goal.id} has unresolved essential success criteria.`, "ulw_loop_criteria_not_all_pass", {+ details: {+ goalId: goal.id,+ unresolved: unresolvedEssentialCriteriaOf(goal).map((criterion) => ({+ id: criterion.id,+ status: criterion.status,+ })),+ },+ });+}diff --git a/plugins/omo/components/ulw-loop/dist/goal-status.d.ts b/plugins/omo/components/ulw-loop/dist/goal-status.d.tsnew file mode 100644index 00000000..d589182d--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/goal-status.d.ts@@ -0,0 +1,16 @@+import { type UlwLoopScope } from "./paths.js";+import type { UlwLoopCodexGoalMode, UlwLoopItem, UlwLoopPlan, UlwLoopSuccessCriterion } from "./types.js";+export declare const ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE: string;+export declare function aggregateCodexObjectiveForScope(scope?: UlwLoopScope): string;+export declare function codexGoalMode(plan: UlwLoopPlan): UlwLoopCodexGoalMode;+export declare function isMemberResolved(goal: UlwLoopItem, plan: UlwLoopPlan): boolean;+export declare function isUlwLoopDone(plan: UlwLoopPlan): boolean;+export declare function isFinalRunCompletionCandidate(plan: UlwLoopPlan, goal: UlwLoopItem): boolean;+export declare function aggregateCodexObjective(plan: UlwLoopPlan): string;+export declare function expectedCodexObjective(plan: UlwLoopPlan, goal: UlwLoopItem): string;+export declare function compatibleCodexObjectives(plan: UlwLoopPlan): readonly string[];+export declare function hasAllCriteriaPass(goal: UlwLoopItem): boolean;+export declare function isEssentialCriterion(criterion: UlwLoopSuccessCriterion): boolean;+export declare function essentialCriteriaOf(goal: UlwLoopItem): readonly UlwLoopSuccessCriterion[];+export declare function hasEssentialCriteriaPass(goal: UlwLoopItem): boolean;+export declare function firstUnresolvedCriterion(goal: UlwLoopItem): UlwLoopSuccessCriterion | undefined;diff --git a/plugins/omo/components/ulw-loop/dist/goal-status.js b/plugins/omo/components/ulw-loop/dist/goal-status.jsnew file mode 100644index 00000000..6e536484--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/goal-status.js@@ -0,0 +1,86 @@+import { ulwLoopGoalsRelativePath, ulwLoopLedgerRelativePath } from "./paths.js";+export const ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE = aggregateCodexObjectiveForScope();+export function aggregateCodexObjectiveForScope(scope) {+ 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) {+ return plan.codexGoalMode ?? "per_story";+}+function isResolvedStatus(status) {+ return status === "complete";+}+export function isMemberResolved(goal, plan) {+ return isResolvedStatus(goal.status) || isSupersededResolved(goal, plan);+}+function isSupersededResolved(goal, plan) {+ if (goal.steeringStatus !== "superseded")+ return false;+ const replacements = goal.supersededBy ?? [];+ if (replacements.length === 0)+ return false;+ return replacements.every((id) => {+ const replacement = plan.goals.find((candidate) => candidate.id === id);+ return replacement !== undefined && isResolvedStatus(replacement.status);+ });+}+function isCompletionBlocking(goal, plan) {+ if (goal.steeringStatus === "superseded")+ return !isSupersededResolved(goal, plan);+ if (goal.steeringStatus === "blocked")+ return true;+ return !isResolvedStatus(goal.status);+}+function isCompletionBlockingForFinalCandidate(candidate, finalCandidate, plan) {+ if (candidate.id === finalCandidate.id)+ return false;+ if (candidate.steeringStatus === "superseded") {+ const replacements = candidate.supersededBy ?? [];+ if (replacements.length === 0)+ return true;+ return !replacements.every((id) => {+ if (id === finalCandidate.id)+ return true;+ const replacement = plan.goals.find((goal) => goal.id === id);+ return replacement !== undefined && isResolvedStatus(replacement.status);+ });+ }+ return isCompletionBlocking(candidate, plan);+}+export function isUlwLoopDone(plan) {+ if (plan.aggregateCompletion?.status === "complete")+ return true;+ return plan.goals.every((goal) => !isCompletionBlocking(goal, plan));+}+export function isFinalRunCompletionCandidate(plan, goal) {+ return (isCompletionBlocking(goal, plan) &&+ plan.goals.every((candidate) => !isCompletionBlockingForFinalCandidate(candidate, goal, plan)));+}+export function aggregateCodexObjective(plan) {+ return plan.codexObjective ?? ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE;+}+export function expectedCodexObjective(plan, goal) {+ return codexGoalMode(plan) === "aggregate" ? aggregateCodexObjective(plan) : goal.objective;+}+export function compatibleCodexObjectives(plan) {+ return [aggregateCodexObjective(plan), ...(plan.codexObjectiveAliases ?? [])];+}+export function hasAllCriteriaPass(goal) {+ return goal.successCriteria.length > 0 && goal.successCriteria.every((criterion) => criterion.status === "pass");+}+export function isEssentialCriterion(criterion) {+ return criterion.essential ?? true;+}+export function essentialCriteriaOf(goal) {+ const explicit = goal.successCriteria.filter(isEssentialCriterion);+ if (explicit.length > 0)+ return explicit;+ const happy = goal.successCriteria.find((criterion) => criterion.userModel === "happy");+ return happy === undefined ? [] : [happy];+}+export function hasEssentialCriteriaPass(goal) {+ const criteria = essentialCriteriaOf(goal);+ return criteria.length > 0 && criteria.every((criterion) => criterion.status === "pass");+}+export function firstUnresolvedCriterion(goal) {+ return goal.successCriteria.find((criterion) => criterion.status !== "pass");+}diff --git a/plugins/omo/components/ulw-loop/dist/paths.d.ts b/plugins/omo/components/ulw-loop/dist/paths.d.tsnew file mode 100644index 00000000..6bd14837--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/paths.d.ts@@ -0,0 +1,23 @@+export interface UlwLoopScope {+ readonly sessionId?: string | null;+}+type EnvMap = Readonly<Record<string, string | undefined>>;+export declare function normalizeUlwLoopSessionId(sessionId: string | null | undefined): string | null;+export declare function resolveUlwLoopSessionIdFromEnv(env?: EnvMap): string | null;+export declare function ulwLoopRelativeDir(scope?: UlwLoopScope): string;+export declare function ulwLoopDir(repoRoot: string, scope?: UlwLoopScope): string;+export declare function ulwLoopBriefRelativePath(scope?: UlwLoopScope): string;+export declare function ulwLoopGoalsRelativePath(scope?: UlwLoopScope): string;+export declare function ulwLoopLedgerRelativePath(scope?: UlwLoopScope): string;+export declare function ulwLoopBriefPath(repoRoot: string, scope?: UlwLoopScope): string;+export declare function ulwLoopGoalsPath(repoRoot: string, scope?: UlwLoopScope): string;+export declare function ulwLoopLedgerPath(repoRoot: string, scope?: UlwLoopScope): string;+export declare function repoRelative(absolutePath: string, repoRoot: string): string;+export declare function ulwLoopAttemptEvidenceDir(goalId: string, attempt: number, scope?: UlwLoopScope): string;+interface AttemptPathApi {+ relative(from: string, to: string): string;+ isAbsolute(path: string): boolean;+ readonly sep: string;+}+export declare function isWithinAttemptDir(absolutePath: string, attemptRoot: string, pathApi?: AttemptPathApi): boolean;+export {};diff --git a/plugins/omo/components/ulw-loop/dist/paths.js b/plugins/omo/components/ulw-loop/dist/paths.jsnew file mode 100644index 00000000..0f2549f4--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/paths.js@@ -0,0 +1,74 @@+import { isAbsolute, join, relative, sep } from "node:path";+import { ULW_LOOP_BRIEF, ULW_LOOP_DIR, ULW_LOOP_GOALS, ULW_LOOP_LEDGER } from "./types.js";+const SESSION_ENV_KEYS = ["OMO_ULW_LOOP_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID"];+export function normalizeUlwLoopSessionId(sessionId) {+ 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 = process.env) {+ for (const key of SESSION_ENV_KEYS) {+ const normalized = normalizeUlwLoopSessionId(env[key]);+ if (normalized !== null)+ return normalized;+ }+ return null;+}+export function ulwLoopRelativeDir(scope) {+ const sessionId = normalizeUlwLoopSessionId(scope?.sessionId);+ return sessionId === null ? ULW_LOOP_DIR : `${ULW_LOOP_DIR}/${sessionId}`;+}+export function ulwLoopDir(repoRoot, scope) {+ return join(repoRoot, ulwLoopRelativeDir(scope));+}+export function ulwLoopBriefRelativePath(scope) {+ return `${ulwLoopRelativeDir(scope)}/${ULW_LOOP_BRIEF}`;+}+export function ulwLoopGoalsRelativePath(scope) {+ return `${ulwLoopRelativeDir(scope)}/${ULW_LOOP_GOALS}`;+}+export function ulwLoopLedgerRelativePath(scope) {+ return `${ulwLoopRelativeDir(scope)}/${ULW_LOOP_LEDGER}`;+}+export function ulwLoopBriefPath(repoRoot, scope) {+ return join(ulwLoopDir(repoRoot, scope), ULW_LOOP_BRIEF);+}+export function ulwLoopGoalsPath(repoRoot, scope) {+ return join(ulwLoopDir(repoRoot, scope), ULW_LOOP_GOALS);+}+export function ulwLoopLedgerPath(repoRoot, scope) {+ return join(ulwLoopDir(repoRoot, scope), ULW_LOOP_LEDGER);+}+export function repoRelative(absolutePath, repoRoot) {+ 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("/");+}+// Both the status --json emitter and the checkpoint enforcement resolve the attempt dir through+// this function; a second resolution path would let the gate reject its own advertised directory.+export function ulwLoopAttemptEvidenceDir(goalId, attempt, scope) {+ const sessionId = normalizeUlwLoopSessionId(scope?.sessionId) ?? resolveUlwLoopSessionIdFromEnv() ?? "session";+ return `.omo/evidence/ulw/${sessionId}/${goalId}/a${attempt}`;+}+const PLATFORM_PATH_API = { relative, isAbsolute, sep };+export function isWithinAttemptDir(absolutePath, attemptRoot, pathApi = PLATFORM_PATH_API) {+ const relativePath = pathApi.relative(attemptRoot, absolutePath);+ if (relativePath === "")+ return true;+ if (relativePath === ".." || relativePath.startsWith(`..${pathApi.sep}`))+ return false;+ return !pathApi.isAbsolute(relativePath);+}diff --git a/plugins/omo/components/ulw-loop/dist/plan-crud.d.ts b/plugins/omo/components/ulw-loop/dist/plan-crud.d.tsnew file mode 100644index 00000000..f6d9861b--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/plan-crud.d.ts@@ -0,0 +1,45 @@+import { type UlwLoopScope } from "./paths.js";+import type { UlwLoopCodexGoalMode, UlwLoopItem, UlwLoopPlan } from "./types.js";+export { deriveGoalCandidates, seedDefaultSuccessCriteria } from "./plan-goal-factory.js";+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;+ };+};+export declare function createUlwLoopPlan(repoRoot: string, args: {+ brief: string;+ codexGoalMode?: UlwLoopCodexGoalMode;+ force?: boolean;+ validationBatchesJson?: string;+}, scope?: UlwLoopScope): Promise<UlwLoopPlan>;+export declare function addUlwLoopGoal(repoRoot: string, args: {+ title: string;+ objective: string;+}, scope?: UlwLoopScope): Promise<{+ plan: UlwLoopPlan;+ goal: UlwLoopItem;+}>;+export declare function startNextUlwLoop(repoRoot: string, args?: {+ retryFailed?: boolean;+}, scope?: UlwLoopScope): Promise<{+ plan: UlwLoopPlan;+ goal: UlwLoopItem;+ resumed: boolean;+} | {+ done: true;+ plan: UlwLoopPlan;+}>;+export declare function summarizeUlwLoopPlan(plan: UlwLoopPlan): UlwLoopPlanSummary;diff --git a/plugins/omo/components/ulw-loop/dist/plan-crud.js b/plugins/omo/components/ulw-loop/dist/plan-crud.jsnew file mode 100644index 00000000..7af33984--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/plan-crud.js@@ -0,0 +1,132 @@+import { existsSync } from "node:fs";+import { mkdir, writeFile } from "node:fs/promises";+import { aggregateCodexObjectiveForScope, isUlwLoopDone } from "./goal-status.js";+import { ulwLoopBriefPath, ulwLoopBriefRelativePath, ulwLoopDir, ulwLoopGoalsPath, ulwLoopGoalsRelativePath, ulwLoopLedgerPath, ulwLoopLedgerRelativePath, } from "./paths.js";+import { appendGoalToPlan, deriveGoalCandidates, makeGoal } from "./plan-goal-factory.js";+import { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";+import { iso, UlwLoopError } from "./types.js";+import { parseValidationBatches } from "./validation-batch.js";+export { deriveGoalCandidates, seedDefaultSuccessCriteria } from "./plan-goal-factory.js";+function isScheduleEligible(goal) {+ return goal.steeringStatus !== "superseded" && goal.steeringStatus !== "blocked";+}+function clearGoalBlockerFields(goal) {+ for (const key of [+ "blockedReason",+ "blockerSignature",+ "blockerOccurrenceCount",+ "requiredExternalDecision",+ "nonRetriable",+ "failedAt",+ "failureReason",+ ])+ delete goal[key];+}+export async function createUlwLoopPlan(repoRoot, args, scope) {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ if (!args.force && existsSync(ulwLoopGoalsPath(repoRoot, scope))) {+ const existing = await readUlwLoopPlan(repoRoot, scope);+ if (isUlwLoopDone(existing))+ throw completedPlanExistsError(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 = {+ version: 1,+ evidenceLayoutVersion: 2,+ createdAt: now,+ updatedAt: now,+ briefPath: ulwLoopBriefRelativePath(scope),+ goalsPath: ulwLoopGoalsRelativePath(scope),+ ledgerPath: ulwLoopLedgerRelativePath(scope),+ codexGoalMode: args.codexGoalMode ?? "aggregate",+ goals,+ };+ const validationBatches = await parseValidationBatches(args.validationBatchesJson, goals);+ if (validationBatches !== undefined)+ plan.validationBatches = validationBatches;+ 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;+ });+}+function completedPlanExistsError(scope) {+ return new UlwLoopError([+ `Existing ulw-loop aggregate is already complete at ${ulwLoopGoalsRelativePath(scope)}.`,+ "Start a new run with `omo ulw-loop create-goals --session-id <new-id> ...` to isolate fresh state.",+ "Use --force only when you intentionally want to overwrite the completed evidence.",+ ].join(" "), "ULW_LOOP_PLAN_EXISTS_COMPLETE");+}+export async function addUlwLoopGoal(repoRoot, args, scope) {+ 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, 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 startNextUlwLoop(repoRoot, args = {}, scope) {+ 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)+ 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 } : {}),+ }, scope);+ }+ if (!next)+ return { done: true, plan };+ next.status = "in_progress";+ next.attempt += 1;+ next.startedAt = now;+ clearGoalBlockerFields(next);+ next.updatedAt = now;+ plan.activeGoalId = next.id;+ plan.updatedAt = now;+ await writePlan(repoRoot, plan, 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 summarizeUlwLoopPlan(plan) {+ const countStatus = (status) => plan.goals.filter((goal) => goal.status === status).length;+ const countCriteria = (status) => 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/dist/plan-goal-factory.d.ts b/plugins/omo/components/ulw-loop/dist/plan-goal-factory.d.tsnew file mode 100644index 00000000..a1c1f81b--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/plan-goal-factory.d.ts@@ -0,0 +1,8 @@+import type { UlwLoopItem, UlwLoopPlan, UlwLoopSuccessCriterion } from "./types.js";+export declare function seedDefaultSuccessCriteria(goalIndex: number, objective: string): UlwLoopSuccessCriterion[];+export declare function deriveGoalCandidates(brief: string): Array<{+ title: string;+ objective: string;+}>;+export declare function makeGoal(title: string, objective: string, index: number, now: string): UlwLoopItem;+export declare function appendGoalToPlan(plan: UlwLoopPlan, title: string, objective: string, now: string): UlwLoopItem;diff --git a/plugins/omo/components/ulw-loop/dist/plan-goal-factory.js b/plugins/omo/components/ulw-loop/dist/plan-goal-factory.jsnew file mode 100644index 00000000..8c1e1c8a--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/plan-goal-factory.js@@ -0,0 +1,109 @@+import { UlwLoopError } from "./types.js";+function cleanLine(line) {+ return line.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/, "").trim();+}+function normalizeObjective(value) {+ return value.replace(/\s+/g, " ").trim();+}+function titleFromObjective(objective, fallback) {+ 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, index) {+ 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, label) {+ const trimmed = value?.trim();+ if (!trimmed)+ throw new UlwLoopError(`Missing ${label}.`, "ULW_LOOP_ARGUMENT_MISSING");+ return trimmed;+}+function truncateObjective(objective) {+ return objective.length > 80 ? `${objective.slice(0, 77).trimEnd()}...` : objective;+}+export function seedDefaultSuccessCriteria(goalIndex, objective) {+ 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}.`,+ true,+ ],+ [+ "C002",+ "edge",+ "edge case (boundary/empty/malformed)",+ `Replace via revise_criterion with boundary or malformed-input proof for: ${subject}.`,+ true,+ ],+ [+ "C003",+ "regression",+ "regression: adjacent surface still works",+ `Replace via revise_criterion with regression proof for neighboring behavior after: ${subject}.`,+ false,+ ],+ ];+ return rows.map(([id, userModel, scenario, expectedEvidence, essential]) => ({+ id,+ scenario,+ userModel,+ expectedEvidence,+ essential,+ capturedEvidence: null,+ status: "pending",+ }));+}+export function deriveGoalCandidates(brief) {+ const bulletGoals = brief+ .split(/\r?\n/)+ .map((line) => ({ original: line, cleaned: normalizeObjective(cleanLine(line)) }))+ .filter(({ cleaned }) => cleaned.length > 0 && cleaned.length <= 1200)+ .filter(({ original, cleaned }, index, all) => /^\s*(?:[-*+]\s+|\d+[.)]\s+)/.test(original) &&+ all.findIndex((candidate) => candidate.cleaned === cleaned) === index)+ .map(({ cleaned }) => cleaned);+ const paragraphs = brief+ .split(/\n\s*\n/)+ .map(normalizeObjective)+ .filter((paragraph) => paragraph.length > 0 && !paragraph.startsWith("#"));+ const selected = (bulletGoals.length > 0 ? bulletGoals : paragraphs).length > 0+ ? bulletGoals.length > 0+ ? bulletGoals+ : paragraphs+ : ["Complete the requested project objective."];+ return selected.map((objective, index) => ({+ title: titleFromObjective(objective, `Goal ${index + 1}`),+ objective,+ }));+}+export function makeGoal(title, objective, index, now) {+ 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,+ };+}+export function appendGoalToPlan(plan, title, objective, now) {+ const goal = makeGoal(title, objective, plan.goals.length, now);+ plan.goals.push(goal);+ plan.updatedAt = now;+ return goal;+}diff --git a/plugins/omo/components/ulw-loop/dist/plan-io.d.ts b/plugins/omo/components/ulw-loop/dist/plan-io.d.tsnew file mode 100644index 00000000..2d85a572--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/plan-io.d.ts@@ -0,0 +1,15 @@+import { type UlwLoopScope } from "./paths.js";+import type { UlwLoopLedgerEntry, UlwLoopPlan } from "./types.js";+export declare function withUlwLoopMutationLock<T>(repoRoot: string, fn: () => Promise<T>): Promise<T>;+export declare function withUlwLoopMutationLock<T>(repoRoot: string, scope: UlwLoopScope | undefined, fn: () => Promise<T>): Promise<T>;+export declare function readUlwLoopPlan(repoRoot: string, scope?: UlwLoopScope): Promise<UlwLoopPlan>;+export declare function writePlan(repoRoot: string, plan: UlwLoopPlan, scope?: UlwLoopScope): Promise<void>;+export declare function appendLedger(repoRoot: string, entry: UlwLoopLedgerEntry, scope?: UlwLoopScope): Promise<void>;+export declare function appendLedgerEntries(repoRoot: string, entries: readonly UlwLoopLedgerEntry[], scope?: UlwLoopScope): Promise<void>;+export declare function readSteeringLedgerEntries(repoRoot: string, scope?: UlwLoopScope): Promise<UlwLoopLedgerEntry[]>;+/**+ * First accepted steering entry matching an idempotency key/prompt signature.+ * A cheap substring probe on the raw line skips JSON.parse for the vast+ * majority of entries, so dedup stays flat even on legacy multi-MB ledgers.+ */+export declare function findAcceptedSteeringLedgerEntry(repoRoot: string, key: string, scope?: UlwLoopScope): Promise<UlwLoopLedgerEntry | undefined>;diff --git a/plugins/omo/components/ulw-loop/dist/plan-io.js b/plugins/omo/components/ulw-loop/dist/plan-io.jsnew file mode 100644index 00000000..6b6f51cd--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/plan-io.js@@ -0,0 +1,143 @@+import { createReadStream } from "node:fs";+import { appendFile, mkdir, readFile, rename, writeFile } from "node:fs/promises";+import { createInterface } from "node:readline";+import { aggregateCodexObjectiveForScope } from "./goal-status.js";+import { repoRelative, ulwLoopDir, ulwLoopGoalsPath, ulwLoopLedgerPath, ulwLoopRelativeDir, } from "./paths.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();+function hasCode(error, code) {+ return error instanceof Error && "code" in error && error.code === code;+}+function isLegacyEnumeratedAggregateObjective(objective) {+ return objective === LEGACY_OBJECTIVE || Boolean(objective?.startsWith(LEGACY_OBJECTIVE_PREFIX));+}+function isSteeringKind(value) {+ return (value === "steering_accepted" ||+ value === "steering_rejected" ||+ value === "criteria_revised" ||+ value === "batch_updated");+}+export async function withUlwLoopMutationLock(repoRoot, scopeOrFn, maybeFn) {+ 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(undefined);+ const run = prior.then(fn, fn);+ // The stored gate resolves to undefined so the map never retains fn's result+ // (plans/audits), and it removes itself once no newer waiter replaced it —+ // otherwise a long-lived host leaks one entry per (repo, scope) forever.+ const gate = run.then(() => undefined, () => undefined);+ locks.set(lockKey, gate);+ void gate.then(() => {+ if (locks.get(lockKey) === gate)+ locks.delete(lockKey);+ });+ return run;+}+export async function readUlwLoopPlan(repoRoot, scope) {+ const path = ulwLoopGoalsPath(repoRoot, scope);+ let raw;+ 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 = 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, plan, scope) {+ 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, entry, scope) {+ await appendLedgerEntries(repoRoot, [entry], scope);+}+export async function appendLedgerEntries(repoRoot, entries, scope) {+ if (entries.length === 0)+ return;+ await mkdir(ulwLoopDir(repoRoot, scope), { recursive: true });+ await appendFile(ulwLoopLedgerPath(repoRoot, scope), `${entries.map((entry) => JSON.stringify(entry)).join("\n")}\n`, "utf8");+}+/**+ * Streams raw ledger lines without materializing the file. Real ledgers reach+ * many MB (legacy entries embedded full-plan snapshots), so `readFile` here+ * ballooned every steer/dedup path; line-at-a-time keeps memory O(longest line).+ */+async function* ledgerLines(repoRoot, scope) {+ const stream = createReadStream(ulwLoopLedgerPath(repoRoot, scope), { encoding: "utf8" });+ const lines = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });+ try {+ for await (const line of lines) {+ if (line.trim().length > 0)+ yield line;+ }+ }+ catch (error) {+ if (!hasCode(error, "ENOENT"))+ throw error;+ }+ finally {+ lines.close();+ stream.destroy();+ }+}+export async function readSteeringLedgerEntries(repoRoot, scope) {+ const entries = [];+ for await (const line of ledgerLines(repoRoot, scope)) {+ const entry = JSON.parse(line);+ if (isSteeringKind(entry.kind))+ entries.push(entry);+ }+ return entries;+}+/**+ * First accepted steering entry matching an idempotency key/prompt signature.+ * A cheap substring probe on the raw line skips JSON.parse for the vast+ * majority of entries, so dedup stays flat even on legacy multi-MB ledgers.+ */+export async function findAcceptedSteeringLedgerEntry(repoRoot, key, scope) {+ const probe = JSON.stringify(key);+ for await (const line of ledgerLines(repoRoot, scope)) {+ if (!line.includes(probe))+ continue;+ const entry = JSON.parse(line);+ if (!isSteeringKind(entry.kind))+ continue;+ if (entry.steering?.invariant.accepted !== true)+ continue;+ if (entry.idempotencyKey === key ||+ entry.steering.idempotencyKey === key ||+ entry.steering.promptSignature === key)+ return entry;+ }+ return undefined;+}diff --git a/plugins/omo/components/ulw-loop/dist/quality-gate-blockers.d.ts b/plugins/omo/components/ulw-loop/dist/quality-gate-blockers.d.tsnew file mode 100644index 00000000..d0d31665--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/quality-gate-blockers.d.ts@@ -0,0 +1,5 @@+import type { UlwLoopItem, UlwLoopPlan } from "./types.js";+export declare function normalizeBlockerEvidence(evidence: string): string;+export declare function classifyExternalAuthorizationBlocker(evidence: string): string | null;+export declare function sameBlockerOccurrences(plan: UlwLoopPlan, signature: string): number;+export declare function clearGoalBlockerFields(goal: UlwLoopItem): void;diff --git a/plugins/omo/components/ulw-loop/dist/quality-gate-blockers.js b/plugins/omo/components/ulw-loop/dist/quality-gate-blockers.jsnew file mode 100644index 00000000..675dd769--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/quality-gate-blockers.js@@ -0,0 +1,41 @@+const BLOCKER_FIELD_KEYS = "blocker blockerSignature blockerEvidence blockerOccurrences blockedAt".split(" ");+const URL_PATTERN = /https?:\/\/\S+/g;+const PUNCTUATION_PATTERN = /[`"'()[\]{}:,;]/g;+const WHITESPACE_PATTERN = /\s+/g;+const AUTH_PATTERN = /\b(auth\w*|credential\w*|token|permission\w*|scope\w*|access|unauthorized|forbidden|401|403)\b/;+const MISSING_PATTERN = /\b(unset|missing|required|requires|without|omit\w*|not set|not available|no read packages|read packages)\b/;+const GHCR_PATTERN = /\b(ghcr|github container registry|read packages|imagepullsecret|package api|anonymous|container image)\b/;+const GHCR_401_PATTERN = /\b(401|unauthorized|anonymous pull|authentication required)\b/;+const GHCR_403_PATTERN = /\b(403|forbidden|read packages|package api)\b/;+function isRecord(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}+export function normalizeBlockerEvidence(evidence) {+ const withoutUrls = evidence.toLowerCase().replace(URL_PATTERN, " ");+ const withoutPunctuation = withoutUrls.replace(PUNCTUATION_PATTERN, " ");+ return withoutPunctuation.replace(WHITESPACE_PATTERN, " ").trim();+}+export function classifyExternalAuthorizationBlocker(evidence) {+ const normalized = normalizeBlockerEvidence(evidence);+ if (!normalized || !AUTH_PATTERN.test(normalized) || !MISSING_PATTERN.test(normalized))+ return null;+ if (!GHCR_PATTERN.test(normalized))+ return "EXTERNAL_AUTHORIZATION_REQUIRED";+ const status401 = GHCR_401_PATTERN.test(normalized) ? "HTTP_401_ANONYMOUS" : null;+ const status403 = GHCR_403_PATTERN.test(normalized) ? "HTTP_403_NO_READ_PACKAGES" : null;+ const status = [status401, status403].filter((part) => part !== null).join("+");+ return `GHCR_PULL_ACCESS:${status || "AUTHORIZATION_REQUIRED"}:GHCR_VISIBILITY_OR_CREDENTIAL_REQUIRED`;+}+function nestedBlockerSignature(goal) {+ const blocker = Reflect.get(goal, "blocker");+ const signature = isRecord(blocker) ? blocker["signature"] : null;+ return typeof signature === "string" ? signature : null;+}+export function sameBlockerOccurrences(plan, signature) {+ return plan.goals.filter((goal) => goal.blockerSignature === signature || nestedBlockerSignature(goal) === signature)+ .length;+}+export function clearGoalBlockerFields(goal) {+ for (const key of BLOCKER_FIELD_KEYS)+ Reflect.deleteProperty(goal, key);+}diff --git a/plugins/omo/components/ulw-loop/dist/quality-gate-fields.d.ts b/plugins/omo/components/ulw-loop/dist/quality-gate-fields.d.tsnew file mode 100644index 00000000..a68aab7f--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/quality-gate-fields.d.ts@@ -0,0 +1,8 @@+export declare function invalid(message: string, field: string): never;+export declare function isRecord(value: unknown): value is Record<string, unknown>;+export declare function section(value: unknown, field: string): Record<string, unknown>;+export declare function textField(value: unknown, field: string): string;+export declare function numberField(value: unknown, field: string): number;+export declare function stringArray(value: unknown, field: string): readonly string[];+export declare function emptyBlockers(value: unknown, field: string): readonly [];+export declare function literal<T extends string | boolean>(value: unknown, expected: T, field: string): T;diff --git a/plugins/omo/components/ulw-loop/dist/quality-gate-fields.js b/plugins/omo/components/ulw-loop/dist/quality-gate-fields.jsnew file mode 100644index 00000000..16850fbb--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/quality-gate-fields.js@@ -0,0 +1,39 @@+import { UlwLoopError } from "./types.js";+const PLACEHOLDER_PATTERN = /^(?:placeholder|todo|tbd|n\/a|stub)$/i;+export function invalid(message, field) {+ throw new UlwLoopError(message, "ULW_LOOP_QUALITY_GATE_INVALID", { details: { field } });+}+export function isRecord(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}+export function section(value, field) {+ return isRecord(value) ? value : invalid(`Final quality gate is missing ${field} evidence.`, field);+}+export function textField(value, field) {+ if (typeof value !== "string" || value.trim() === "")+ invalid(`Final quality gate requires non-empty ${field}.`, field);+ const trimmed = value.trim();+ if (PLACEHOLDER_PATTERN.test(trimmed))+ invalid(`Final quality gate rejects placeholder ${field}.`, field);+ return trimmed;+}+export function numberField(value, field) {+ return typeof value === "number" && Number.isFinite(value)+ ? value+ : invalid(`Final quality gate requires numeric ${field}.`, field);+}+export function stringArray(value, field) {+ if (!Array.isArray(value) || value.length === 0)+ return invalid(`Final quality gate requires ${field}.`, field);+ return value.map((item) => textField(item, field));+}+export function emptyBlockers(value, field) {+ if (Array.isArray(value) && value.length === 0)+ return [];+ invalid(`${field} must be empty.`, field);+}+export function literal(value, expected, field) {+ if (value === expected)+ return expected;+ invalid(`${field} must be ${String(expected)}.`, field);+}diff --git a/plugins/omo/components/ulw-loop/dist/quality-gate-verdicts.d.ts b/plugins/omo/components/ulw-loop/dist/quality-gate-verdicts.d.tsnew file mode 100644index 00000000..6043f357--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/quality-gate-verdicts.d.ts@@ -0,0 +1,6 @@+export declare function passedVerdict(value: unknown, field: string): "passed";+export declare function codeQualityStatusField(value: unknown, field: string): "CLEAR" | "WATCH";+export declare function adversarialVerdict(row: Record<string, unknown>, field: string): {+ verdict: "passed" | "not_applicable";+ reason?: string;+};diff --git a/plugins/omo/components/ulw-loop/dist/quality-gate-verdicts.js b/plugins/omo/components/ulw-loop/dist/quality-gate-verdicts.jsnew file mode 100644index 00000000..9e6e15ca--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/quality-gate-verdicts.js@@ -0,0 +1,20 @@+import { invalid, literal, textField } from "./quality-gate-fields.js";+export function passedVerdict(value, field) {+ if (value === "not_applicable")+ invalid(`${field} must not be not_applicable.`, field);+ return literal(value, "passed", field);+}+export function codeQualityStatusField(value, field) {+ if (value === "CLEAR" || value === "WATCH")+ return value;+ invalid(`${field} must be CLEAR or WATCH.`, field);+}+export function adversarialVerdict(row, field) {+ const value = row["verdict"];+ if (value === "passed")+ return { verdict: "passed" };+ if (value === "not_applicable") {+ return { verdict: "not_applicable", reason: textField(row["reason"], `${field}.reason`) };+ }+ invalid(`${field} must be passed or not_applicable with a reason.`, field);+}diff --git a/plugins/omo/components/ulw-loop/dist/quality-gate.d.ts b/plugins/omo/components/ulw-loop/dist/quality-gate.d.tsnew file mode 100644index 00000000..e7760a61--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/quality-gate.d.ts@@ -0,0 +1,14 @@+import type { UlwLoopQualityGate } from "./types.js";+export { classifyExternalAuthorizationBlocker, clearGoalBlockerFields, normalizeBlockerEvidence, sameBlockerOccurrences, } from "./quality-gate-blockers.js";+export interface QualityGateFs {+ readonly existsSync: (path: string) => boolean;+ readonly statSync: (path: string) => {+ readonly size: number;+ };+}+export interface ValidateQualityGateOptions {+ readonly repoRoot: string;+ readonly fs: QualityGateFs;+ readonly currentAttemptDir?: string;+}+export declare function validateQualityGate(input: unknown, opts?: ValidateQualityGateOptions): UlwLoopQualityGate;diff --git a/plugins/omo/components/ulw-loop/dist/quality-gate.js b/plugins/omo/components/ulw-loop/dist/quality-gate.jsnew file mode 100644index 00000000..6e99980e--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/quality-gate.js@@ -0,0 +1,197 @@+import { resolve } from "node:path";+import { isWithinAttemptDir } from "./paths.js";+import { emptyBlockers, invalid, literal, numberField, section, stringArray, textField, } from "./quality-gate-fields.js";+import { adversarialVerdict, codeQualityStatusField, passedVerdict } from "./quality-gate-verdicts.js";+const REVIEWER_ROLES = {+ codeReview: "lazycodex-code-reviewer",+ manualQa: "lazycodex-qa-executor",+ gateReview: "lazycodex-gate-reviewer",+};+export { classifyExternalAuthorizationBlocker, clearGoalBlockerFields, normalizeBlockerEvidence, sameBlockerOccurrences, } from "./quality-gate-blockers.js";+function reviewerRoleField(value, expected, field) {+ const actual = textField(value, field);+ if (actual !== expected)+ invalid(`${field} must be ${expected}.`, field);+ return expected;+}+function surfaceField(value, field) {+ if (value === "cli" ||+ value === "http" ||+ value === "tmux" ||+ value === "browser" ||+ value === "gui" ||+ value === "data")+ return value;+ invalid(`${field} must be a supported manual QA surface.`, field);+}+function kindField(value, field) {+ if (value === "cli-transcript" ||+ value === "log" ||+ value === "screenshot" ||+ value === "image" ||+ value === "http-dump" ||+ value === "data-diff")+ return value;+ invalid(`${field} must be a supported artifact kind.`, field);+}+function artifactCompatible(surface, kind) {+ switch (surface) {+ case "cli":+ case "tmux":+ return kind === "cli-transcript" || kind === "log";+ case "http":+ return kind === "http-dump";+ case "browser":+ case "gui":+ return kind === "screenshot" || kind === "image";+ case "data":+ return kind === "data-diff";+ default:+ invalid("manualQa.surfaceEvidence has an unsupported surface.", "manualQa.surfaceEvidence.surface");+ }+}+function checkFile(path, field, opts) {+ if (opts === undefined)+ return;+ const absolute = resolve(opts.repoRoot, path);+ if (!opts.fs.existsSync(absolute))+ invalid(`${field} must point to an existing artifact.`, field);+ if (opts.fs.statSync(absolute).size <= 0)+ invalid(`${field} must point to a non-empty artifact.`, field);+ if (opts.currentAttemptDir !== undefined) {+ const attemptRoot = resolve(opts.repoRoot, opts.currentAttemptDir);+ if (!isWithinAttemptDir(absolute, attemptRoot))+ invalid(`${field} (${path}) must point to an artifact from the current attempt (${opts.currentAttemptDir}).`, field);+ }+}+function artifactMap(refs) {+ const byId = new Map();+ for (const ref of refs) {+ if (byId.has(ref.id))+ invalid(`manualQa.artifactRefs contains duplicate ${ref.id}.`, "manualQa.artifactRefs");+ byId.set(ref.id, ref);+ }+ return byId;+}+function parseArtifactRefs(value, opts) {+ if (!Array.isArray(value) || value.length === 0)+ invalid("manualQa.artifactRefs must not be empty.", "manualQa.artifactRefs");+ return value.map((item, index) => {+ const ref = section(item, `manualQa.artifactRefs[${index}]`);+ const path = textField(ref["path"], `manualQa.artifactRefs[${index}].path`);+ checkFile(path, `manualQa.artifactRefs[${index}].path`, opts);+ return {+ id: textField(ref["id"], `manualQa.artifactRefs[${index}].id`),+ kind: kindField(ref["kind"], `manualQa.artifactRefs[${index}].kind`),+ description: textField(ref["description"], `manualQa.artifactRefs[${index}].description`),+ path,+ };+ });+}+function referencedArtifacts(value, field, byId) {+ return stringArray(value, field).map((id) => {+ const artifact = byId.get(id);+ if (artifact === undefined)+ invalid(`${field} references unknown artifact ${id}.`, field);+ return artifact;+ });+}+export function validateQualityGate(input, opts) {+ const gate = section(input, "qualityGate");+ const codeReview = section(gate["codeReview"], "codeReview");+ const manualQa = section(gate["manualQa"], "manualQa");+ const gateReview = section(gate["gateReview"], "gateReview");+ const iteration = section(gate["iteration"], "iteration");+ const coverage = section(gate["criteriaCoverage"], "criteriaCoverage");+ const totalCriteria = numberField(coverage["totalCriteria"], "criteriaCoverage.totalCriteria");+ const passCount = numberField(coverage["passCount"], "criteriaCoverage.passCount");+ if (passCount < totalCriteria)+ invalid("criteriaCoverage.passCount must cover totalCriteria.", "criteriaCoverage.passCount");+ const artifactRefs = parseArtifactRefs(manualQa["artifactRefs"], opts);+ const byId = artifactMap(artifactRefs);+ const surfaceEvidence = parseSurfaceEvidence(manualQa["surfaceEvidence"], byId);+ const adversarialCases = parseAdversarialCases(manualQa["adversarialCases"], byId);+ const codeReportPath = textField(codeReview["reportPath"], "codeReview.reportPath");+ const gateReportPath = textField(gateReview["reportPath"], "gateReview.reportPath");+ checkFile(codeReportPath, "codeReview.reportPath", opts);+ checkFile(gateReportPath, "gateReview.reportPath", opts);+ return {+ codeReview: {+ by: reviewerRoleField(codeReview["by"], REVIEWER_ROLES.codeReview, "codeReview.by"),+ recommendation: literal(codeReview["recommendation"], "APPROVE", "codeReview.recommendation"),+ codeQualityStatus: codeQualityStatusField(codeReview["codeQualityStatus"], "codeReview.codeQualityStatus"),+ reportPath: codeReportPath,+ evidence: textField(codeReview["evidence"], "codeReview.evidence"),+ blockers: emptyBlockers(codeReview["blockers"], "codeReview.blockers"),+ },+ manualQa: {+ by: reviewerRoleField(manualQa["by"], REVIEWER_ROLES.manualQa, "manualQa.by"),+ status: literal(manualQa["status"], "passed", "manualQa.status"),+ evidence: textField(manualQa["evidence"], "manualQa.evidence"),+ surfaceEvidence,+ adversarialCases,+ artifactRefs,+ },+ gateReview: {+ by: reviewerRoleField(gateReview["by"], REVIEWER_ROLES.gateReview, "gateReview.by"),+ recommendation: literal(gateReview["recommendation"], "APPROVE", "gateReview.recommendation"),+ reportPath: gateReportPath,+ evidence: textField(gateReview["evidence"], "gateReview.evidence"),+ blockers: emptyBlockers(gateReview["blockers"], "gateReview.blockers"),+ },+ iteration: {+ fullRerun: literal(iteration["fullRerun"], true, "iteration.fullRerun"),+ status: literal(iteration["status"], "passed", "iteration.status"),+ rerunCommands: stringArray(iteration["rerunCommands"], "iteration.rerunCommands"),+ evidence: textField(iteration["evidence"], "iteration.evidence"),+ },+ criteriaCoverage: {+ totalCriteria,+ passCount,+ originalIntent: textField(coverage["originalIntent"], "criteriaCoverage.originalIntent"),+ desiredOutcome: textField(coverage["desiredOutcome"], "criteriaCoverage.desiredOutcome"),+ userOutcomeReview: textField(coverage["userOutcomeReview"], "criteriaCoverage.userOutcomeReview"),+ adversarialClassesCovered: stringArray(coverage["adversarialClassesCovered"], "criteriaCoverage.adversarialClassesCovered"),+ },+ };+}+function parseSurfaceEvidence(value, byId) {+ if (!Array.isArray(value) || value.length === 0)+ invalid("manualQa.surfaceEvidence must not be empty.", "manualQa.surfaceEvidence");+ return value.map((item, index) => {+ const row = section(item, `manualQa.surfaceEvidence[${index}]`);+ const surface = surfaceField(row["surface"], `manualQa.surfaceEvidence[${index}].surface`);+ const artifacts = referencedArtifacts(row["artifactRefs"], `manualQa.surfaceEvidence[${index}].artifactRefs`, byId);+ for (const artifact of artifacts) {+ if (!artifactCompatible(surface, artifact.kind)) {+ invalid(`manualQa.surfaceEvidence ${surface} artifact ${artifact.kind} is incompatible.`, "manualQa.surfaceEvidence");+ }+ }+ return {+ id: textField(row["id"], `manualQa.surfaceEvidence[${index}].id`),+ criterionRef: textField(row["criterionRef"], `manualQa.surfaceEvidence[${index}].criterionRef`),+ surface,+ invocation: textField(row["invocation"], `manualQa.surfaceEvidence[${index}].invocation`),+ verdict: passedVerdict(row["verdict"], `manualQa.surfaceEvidence[${index}].verdict`),+ artifactRefs: artifacts.map((artifact) => artifact.id),+ };+ });+}+function parseAdversarialCases(value, byId) {+ if (!Array.isArray(value) || value.length === 0)+ invalid("manualQa.adversarialCases must not be empty.", "manualQa.adversarialCases");+ return value.map((item, index) => {+ const row = section(item, `manualQa.adversarialCases[${index}]`);+ const artifacts = referencedArtifacts(row["artifactRefs"], `manualQa.adversarialCases[${index}].artifactRefs`, byId);+ const verdictInfo = adversarialVerdict(row, `manualQa.adversarialCases[${index}]`);+ return {+ id: textField(row["id"], `manualQa.adversarialCases[${index}].id`),+ criterionRef: textField(row["criterionRef"], `manualQa.adversarialCases[${index}].criterionRef`),+ scenario: textField(row["scenario"], `manualQa.adversarialCases[${index}].scenario`),+ expectedBehavior: textField(row["expectedBehavior"], `manualQa.adversarialCases[${index}].expectedBehavior`),+ verdict: verdictInfo.verdict,+ ...(verdictInfo.reason === undefined ? {} : { reason: verdictInfo.reason }),+ artifactRefs: artifacts.map((artifact) => artifact.id),+ };+ });+}diff --git a/plugins/omo/components/ulw-loop/dist/review-blockers.d.ts b/plugins/omo/components/ulw-loop/dist/review-blockers.d.tsnew file mode 100644index 00000000..bbf59a35--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/review-blockers.d.ts@@ -0,0 +1,16 @@+import type { UlwLoopScope } from "./paths.js";+import type { UlwLoopItem, UlwLoopLedgerEntry, UlwLoopPlan } 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: UlwLoopPlan;+ readonly blockedGoal: UlwLoopItem;+ readonly newGoal: UlwLoopItem;+ readonly ledgerEntries: UlwLoopLedgerEntry[];+}+export declare function recordFinalReviewBlockers(repoRoot: string, args: RecordFinalReviewBlockersArgs, scope?: UlwLoopScope): Promise<RecordFinalReviewBlockersResult>;diff --git a/plugins/omo/components/ulw-loop/dist/review-blockers.js b/plugins/omo/components/ulw-loop/dist/review-blockers.jsnew file mode 100644index 00000000..2ea4a46f--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/review-blockers.js@@ -0,0 +1,70 @@+// biome-ignore-all format: compact port must stay within the requested pure LOC budget.+import { readCodexGoalSnapshotInput, reconcileCodexGoalSnapshot } from "./codex-goal-snapshot.js";+import { codexGoalMode, compatibleCodexObjectives, expectedCodexObjective, isFinalRunCompletionCandidate } from "./goal-status.js";+import { seedDefaultSuccessCriteria } from "./plan-crud.js";+import { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";+import { iso, UlwLoopError } from "./types.js";+const BLOCKER_FIELDS = "blockedReason blockerSignature blockerOccurrenceCount requiredExternalDecision nonRetriable failedAt failureReason completedAt blocker blockerEvidence blockerOccurrences blockedAt".split(" ");+function ulwLoopError(message, code) {+ throw new UlwLoopError(message, code);+}+function nextGoalId(plan) {+ const max = plan.goals.reduce((current, goal) => {+ const digits = /^G(\d+)/u.exec(goal.id)?.[1];+ return digits === undefined ? current : Math.max(current, Number(digits));+ }, 0);+ return `G${String(max + 1).padStart(3, "0")}`;+}+function appendBlockerGoal(plan, args, now) {+ const index = plan.goals.length;+ const goal = {+ id: nextGoalId(plan),+ title: args.title,+ objective: args.objective,+ status: "pending",+ successCriteria: seedDefaultSuccessCriteria(index, args.objective),+ attempt: 0,+ createdAt: now,+ updatedAt: now,+ };+ plan.goals.push(goal);+ return goal;+}+export async function recordFinalReviewBlockers(repoRoot, args, scope) {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ const plan = await readUlwLoopPlan(repoRoot, scope);+ const goal = plan.goals.find((candidate) => candidate.id === args.goalId);+ 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)+ ulwLoopError(reconciliation.errors.join(" "), "ulw_loop_codex_snapshot_mismatch");+ const now = iso();+ for (const field of BLOCKER_FIELDS)+ Reflect.deleteProperty(goal, field);+ goal.status = "review_blocked";+ goal.reviewBlockedAt = now;+ goal.evidence = args.evidence;+ goal.updatedAt = now;+ if (plan.activeGoalId === goal.id)+ delete plan.activeGoalId;+ const newGoal = appendBlockerGoal(plan, args, now);+ plan.updatedAt = now;+ const codexGoal = reconciliation.snapshot.raw;+ const blockedEntry = { at: now, kind: "goal_review_blocked", goalId: goal.id, status: goal.status, evidence: args.evidence, codexGoal };+ const addedEntry = { at: now, kind: "goal_added", goalId: newGoal.id, status: newGoal.status, evidence: args.evidence, message: newGoal.title };+ const summaryEntry = { 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, scope);+ for (const entry of ledgerEntries)+ await appendLedger(repoRoot, entry, scope);+ return { plan, blockedGoal: goal, newGoal, ledgerEntries };+ });+}diff --git a/plugins/omo/components/ulw-loop/dist/runtime.d.ts b/plugins/omo/components/ulw-loop/dist/runtime.d.tsnew file mode 100644index 00000000..41c92235--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/runtime.d.ts@@ -0,0 +1,10 @@+export interface UlwLoopErrorOptions {+ readonly cause?: unknown;+ readonly details?: Record<string, unknown>;+}+export declare class UlwLoopError extends Error {+ readonly code: string;+ readonly details?: Record<string, unknown>;+ constructor(message: string, code: string, opts?: UlwLoopErrorOptions);+}+export declare function iso(): string;diff --git a/plugins/omo/components/ulw-loop/dist/runtime.js b/plugins/omo/components/ulw-loop/dist/runtime.jsnew file mode 100644index 00000000..811e8d1f--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/runtime.js@@ -0,0 +1,13 @@+export class UlwLoopError extends Error {+ constructor(message, code, opts) {+ super(message, opts?.cause === undefined ? undefined : { cause: opts.cause });+ this.name = "UlwLoopError";+ this.code = code;+ if (opts?.details !== undefined) {+ this.details = opts.details;+ }+ }+}+export function iso() {+ return new Date().toISOString();+}diff --git a/plugins/omo/components/ulw-loop/dist/spawn-guard.d.ts b/plugins/omo/components/ulw-loop/dist/spawn-guard.d.tsnew file mode 100644index 00000000..654b13b8--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/spawn-guard.d.ts@@ -0,0 +1,3 @@+import type { PreToolUsePayload } from "./codex-hook.js";+export declare function applySpawnGuards(payload: PreToolUsePayload): string;+export declare function runSpawnGuardCli(stdin: NodeJS.ReadableStream, stdout: NodeJS.WritableStream): Promise<void>;diff --git a/plugins/omo/components/ulw-loop/dist/spawn-guard.js b/plugins/omo/components/ulw-loop/dist/spawn-guard.jsnew file mode 100644index 00000000..0171a241--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/spawn-guard.js@@ -0,0 +1,148 @@+import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { parsePreToolUsePayload } from "./codex-hook.js";+import { isFinalRunCompletionCandidate } from "./goal-status.js";+import { ulwLoopAttemptEvidenceDir, ulwLoopDir } from "./paths.js";+// spawn_agent = v1; collaborationspawn_agent = the delimiter-free flattened v2+// hook token from codex-rs hook_names.rs; collaboration.spawn_agent = the+// dotted token observed live in the task-1 probe (hook-tool-tokens.txt).+const SPAWN_TOOL_TOKENS = new Set(["spawn_agent", "collaborationspawn_agent", "collaboration.spawn_agent"]);+const DEFAULT_FANOUT_LIMIT = 60;+const GATE_MESSAGE_PATTERN = /lazycodex-gate-reviewer|final gate review/i;+export function applySpawnGuards(payload) {+ if (payload.hook_event_name !== "PreToolUse" || !SPAWN_TOOL_TOKENS.has(payload.tool_name))+ return "";+ const stateDir = ulwLoopDir(payload.cwd, { sessionId: payload.session_id });+ const plan = readPlan(join(stateDir, "goals.json"));+ if (plan === null)+ return "";+ const fanOutDenial = consumeFanOutBudget(stateDir);+ if (fanOutDenial !== null)+ return deny(fanOutDenial);+ const missingArtifact = missingGateArtifact(payload, plan);+ if (missingArtifact !== null)+ return deny(`spawn code-review + QA first; gate audits their artifacts: missing ${missingArtifact}`);+ return "";+}+export async function runSpawnGuardCli(stdin, stdout) {+ try {+ const chunks = [];+ for await (const chunk of stdin)+ chunks.push(Buffer.from(chunk));+ const payload = parsePreToolUsePayload(Buffer.concat(chunks).toString("utf8"));+ if (payload === null)+ return;+ const output = applySpawnGuards(payload);+ if (output.length > 0)+ stdout.write(output);+ }+ catch (error) {+ if (error instanceof Error)+ return;+ }+}+// Per-session spawn counter; depth/lineage tracking is descoped — this is a+// total-volume backstop against fan-out explosions, not a recursion tracker.+function consumeFanOutBudget(stateDir) {+ const counterPath = join(stateDir, "spawn-count.json");+ const count = readCount(counterPath) + 1;+ writeFileSync(counterPath, JSON.stringify({ count }));+ const limit = fanOutLimit();+ if (count <= limit)+ return null;+ return `ulw-loop spawn fan-out cap reached (${count}/${limit}). Consolidate work into the agents already running, or raise OMO_SPAWN_FANOUT_LIMIT if this volume is intentional.`;+}+function missingGateArtifact(payload, plan) {+ if (!isGateReviewerSpawn(payload.tool_input))+ return null;+ const goal = plan.goals.find((candidate) => isFinalRunCompletionCandidate(plan, candidate));+ if (goal === undefined || goal.status === "complete")+ return null;+ if (!goal.successCriteria.every((criterion) => criterion.status === "pass"))+ return null;+ const scope = { sessionId: payload.session_id };+ if (plan.evidenceLayoutVersion === 2) {+ const attemptDir = ulwLoopAttemptEvidenceDir(goal.id, goal.attempt, scope);+ for (const name of [`${goal.id}-code-review.md`, `${goal.id}-manual-qa.md`]) {+ const relative = `${attemptDir}/${name}`;+ if (!isNonEmptyFile(join(payload.cwd, relative)))+ return relative;+ }+ return null;+ }+ const flatReport = `.omo/evidence/${goal.id}-code-review.md`;+ if (!isNonEmptyFile(join(payload.cwd, flatReport)))+ return flatReport;+ // v1 manual-QA approximation: any other non-empty evidence file counts.+ if (!hasOtherEvidenceFile(join(payload.cwd, ".omo", "evidence"), `${goal.id}-code-review.md`))+ return `.omo/evidence/<any manual-QA artifact besides ${goal.id}-code-review.md>`;+ return null;+}+function isGateReviewerSpawn(toolInput) {+ if (typeof toolInput !== "object" || toolInput === null)+ return false;+ const record = toolInput;+ const agentType = record["agent_type"];+ if (typeof agentType === "string")+ return agentType === "lazycodex-gate-reviewer";+ const message = record["message"];+ return typeof message === "string" && GATE_MESSAGE_PATTERN.test(message);+}+function deny(reason) {+ return `${JSON.stringify({+ hookSpecificOutput: {+ hookEventName: "PreToolUse",+ permissionDecision: "deny",+ permissionDecisionReason: reason,+ additionalContext: reason,+ },+ })}\n`;+}+function fanOutLimit() {+ const raw = process.env["OMO_SPAWN_FANOUT_LIMIT"];+ if (raw === undefined)+ return DEFAULT_FANOUT_LIMIT;+ const parsed = Number.parseInt(raw, 10);+ return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_FANOUT_LIMIT;+}+function isNonEmptyFile(path) {+ try {+ return existsSync(path) && statSync(path).size > 0;+ }+ catch (error) {+ if (error instanceof Error)+ return false;+ throw error;+ }+}+function hasOtherEvidenceFile(evidenceDir, excludedName) {+ try {+ return readdirSync(evidenceDir).some((name) => name !== excludedName && isNonEmptyFile(join(evidenceDir, name)));+ }+ catch (error) {+ if (error instanceof Error)+ return false;+ throw error;+ }+}+function readCount(counterPath) {+ try {+ const parsed = JSON.parse(readFileSync(counterPath, "utf8"));+ return typeof parsed["count"] === "number" && parsed["count"] >= 0 ? parsed["count"] : 0;+ }+ catch (error) {+ if (error instanceof Error)+ return 0;+ throw error;+ }+}+function readPlan(goalsPath) {+ try {+ return JSON.parse(readFileSync(goalsPath, "utf8"));+ }+ catch (error) {+ if (error instanceof Error)+ return null;+ throw error;+ }+}diff --git a/plugins/omo/components/ulw-loop/dist/steering-batch.d.ts b/plugins/omo/components/ulw-loop/dist/steering-batch.d.tsnew file mode 100644index 00000000..5f377141--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/steering-batch.d.ts@@ -0,0 +1,15 @@+import type { UlwLoopScope } from "./paths.js";+import type { UlwLoopPlan, UlwLoopSteeringAudit, UlwLoopSteeringProposal } from "./types.js";+export interface SteerUlwLoopBatchItemResult {+ readonly accepted: boolean;+ readonly deduped: boolean;+ readonly audit: UlwLoopSteeringAudit;+ readonly rejectedReasons: readonly string[];+}+export interface SteerUlwLoopBatchResult {+ readonly plan: UlwLoopPlan;+ readonly accepted: boolean;+ readonly results: readonly SteerUlwLoopBatchItemResult[];+ readonly rejectedReasons: readonly string[];+}+export declare function steerUlwLoopBatch(repoRoot: string, proposals: readonly UlwLoopSteeringProposal[], scope?: UlwLoopScope): Promise<SteerUlwLoopBatchResult>;diff --git a/plugins/omo/components/ulw-loop/dist/steering-batch.js b/plugins/omo/components/ulw-loop/dist/steering-batch.jsnew file mode 100644index 00000000..e9870b82--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/steering-batch.js@@ -0,0 +1,84 @@+import { appendLedger, appendLedgerEntries, findAcceptedSteeringLedgerEntry, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";+import { applySteeringMutation, validateUlwLoopSteeringProposal } from "./steering.js";+import { buildSteeringPlanSnapshot, changedGoalIdsBetween } from "./steering-snapshot.js";+import { iso } from "./types.js";+import { batchUpdateLedgerEntry } from "./validation-batch.js";+export async function steerUlwLoopBatch(repoRoot, proposals, scope) {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ const plan = await readUlwLoopPlan(repoRoot, scope);+ const prepared = await prepareBatch(repoRoot, plan, proposals, scope);+ const failed = prepared.results.find((item) => !item.accepted);+ if (failed !== undefined) {+ const entry = rejectedLedgerEntry(prepared.results);+ await appendLedger(repoRoot, entry, scope);+ return rejected(plan, prepared.results, failed.rejectedReasons);+ }+ let next = plan;+ for (const item of prepared.items)+ if (item.kind === "fresh")+ next = item.prepared.next;+ const fresh = prepared.items.filter((item) => item.kind === "fresh");+ if (fresh.length > 0) {+ await writePlan(repoRoot, next, scope);+ const entries = fresh.map((item) => ledgerEntry(item.prepared.proposal, item.prepared.audit, item.prepared.proposal.now?.toISOString() ?? iso()));+ const batchEntry = batchUpdateLedgerEntry(plan, next, iso());+ await appendLedgerEntries(repoRoot, batchEntry === null ? entries : [...entries, batchEntry], scope);+ }+ return { plan: next, accepted: true, results: prepared.results, rejectedReasons: [] };+ });+}+async function prepareBatch(repoRoot, plan, proposals, scope) {+ const items = [];+ const results = [];+ let current = plan;+ for (const proposal of proposals) {+ const key = proposal.idempotencyKey ?? proposal.promptSignature;+ const prior = key === undefined ? undefined : await findAcceptedSteeringLedgerEntry(repoRoot, key, scope);+ if (prior?.steering !== undefined) {+ const result = { accepted: true, deduped: true, audit: { ...prior.steering, deduped: true }, rejectedReasons: [] };+ items.push({ kind: "deduped", result });+ results.push(result);+ continue;+ }+ const audit = validateUlwLoopSteeringProposal(current, proposal);+ if (!audit.invariant.accepted) {+ const result = { accepted: false, deduped: false, audit, rejectedReasons: audit.invariant.rejectedReasons };+ items.push({ kind: "deduped", result });+ results.push(result);+ continue;+ }+ const next = applySteeringMutation(current, proposal, audit);+ const changed = changedGoalIdsBetween(current, next);+ const finalAudit = { ...audit, before: buildSteeringPlanSnapshot(current, changed), after: buildSteeringPlanSnapshot(next, changed) };+ const result = { accepted: true, deduped: false, audit: finalAudit, rejectedReasons: [] };+ items.push({ kind: "fresh", prepared: { proposal, audit: finalAudit, before: current, next } });+ results.push(result);+ current = next;+ }+ return { items, results };+}+function rejected(plan, results, rejectedReasons) {+ return { plan, accepted: false, results, rejectedReasons };+}+function rejectedLedgerEntry(results) {+ const rejectedItems = results.map((result, index) => ({ result, index })).filter((item) => !item.result.accepted);+ return { at: iso(), kind: "steering_rejected", message: rejectedItems.map((item) => `index ${item.index}: ${item.result.rejectedReasons.join(", ")}`).join("; ") };+}+function ledgerEntry(proposal, audit, at) {+ const entry = {+ at,+ kind: proposal.kind === "revise_criterion" ? "criteria_revised" : "steering_accepted",+ evidence: proposal.evidence,+ message: proposal.rationale,+ steering: audit,+ mutationKind: proposal.kind,+ };+ const goalId = audit.targetGoalIds[0];+ if (goalId !== undefined)+ entry.goalId = goalId;+ if (proposal.criterionId !== undefined)+ entry.criterionId = proposal.criterionId;+ if (proposal.idempotencyKey !== undefined)+ entry.idempotencyKey = proposal.idempotencyKey;+ return entry;+}diff --git a/plugins/omo/components/ulw-loop/dist/steering-mutations.d.ts b/plugins/omo/components/ulw-loop/dist/steering-mutations.d.tsnew file mode 100644index 00000000..aac183b4--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/steering-mutations.d.ts@@ -0,0 +1,5 @@+import type { UlwLoopItem, UlwLoopPlan, UlwLoopSteeringChildGoal, UlwLoopSteeringProposal } from "./types.js";+export declare function makeGoal(plan: UlwLoopPlan, childGoal: UlwLoopSteeringChildGoal, evidence: string, now: string, offset: number): UlwLoopItem;+export declare function reviseWording(plan: UlwLoopPlan, proposal: UlwLoopSteeringProposal, now: string): void;+export declare function splitOrBlock(plan: UlwLoopPlan, proposal: UlwLoopSteeringProposal, now: string): void;+export declare function reviseCriterion(plan: UlwLoopPlan, proposal: UlwLoopSteeringProposal, now: string): void;diff --git a/plugins/omo/components/ulw-loop/dist/steering-mutations.js b/plugins/omo/components/ulw-loop/dist/steering-mutations.jsnew file mode 100644index 00000000..ccc14402--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/steering-mutations.js@@ -0,0 +1,81 @@+// biome-ignore-all format: compact extracted steering mutations stay below the pure LOC budget.+import { seedDefaultSuccessCriteria } from "./plan-crud.js";+import { ULW_LOOP_SUCCESS_CRITERION_USER_MODELS } from "./types.js";+import { updateBatchesAfterSupersede } from "./validation-batch.js";+const read = (value, key) => Object.entries(value).find(([name]) => name === key)?.[1];+const isText = (value) => typeof value === "string" && value.trim().length > 0;+const text = (value, key) => { const candidate = read(value, key); return isText(candidate) ? candidate.trim() : undefined; };+const isModel = (value) => typeof value === "string" && ULW_LOOP_SUCCESS_CRITERION_USER_MODELS.some((model) => model === value);+const after = (proposal) => { const candidate = read(proposal, "after"); return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate) ? candidate : undefined; };+const revised = (proposal, direct, nested) => text(proposal, direct) ?? text(after(proposal) ?? proposal, nested);+const targets = (proposal) => proposal.targetGoalIds ?? [proposal.targetGoalId ?? text(proposal, "goalId") ?? ""].filter(Boolean);+const child = (value) => {+ if (typeof value !== "object" || value === null || Array.isArray(value))+ return null;+ const title = text(value, "title");+ const objective = text(value, "objective");+ return title === undefined || objective === undefined ? null : { title, objective };+};+const children = (proposal) => {+ const direct = proposal.childGoals;+ if (direct !== undefined && direct.length > 0)+ return direct;+ const nested = after(proposal);+ const fromAfter = nested === undefined ? undefined : read(nested, "children");+ return Array.isArray(fromAfter) ? fromAfter.map(child).filter((item) => item !== null) : [];+};+const goal = (plan, id) => id === undefined ? undefined : plan.goals.find((item) => item.id === id);+function nextId(plan, offset) {+ const max = plan.goals.reduce((current, item) => { const digits = /^G(\d+)(?:-|$)/u.exec(item.id)?.[1]; return digits === undefined ? current : Math.max(current, Number(digits)); }, 0);+ return `G${String(max + offset).padStart(3, "0")}`;+}+export function makeGoal(plan, childGoal, evidence, now, offset) {+ 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 reviseWording(plan, proposal, now) {+ const target = goal(plan, targets(proposal)[0]);+ if (target === undefined)+ return;+ target.title = revised(proposal, "revisedTitle", "title") ?? target.title;+ target.objective = revised(proposal, "revisedObjective", "objective") ?? target.objective;+ target.steeringEvidence = proposal.evidence;+ target.steeringRationale = proposal.rationale;+ target.updatedAt = now;+}+export function splitOrBlock(plan, proposal, now) {+ const target = goal(plan, targets(proposal)[0]);+ if (target === undefined)+ return;+ const replacements = children(proposal).map((item, index) => makeGoal(plan, item, proposal.evidence, now, index + 1));+ target.steeringEvidence = proposal.evidence;+ target.steeringRationale = proposal.rationale;+ target.updatedAt = now;+ if (replacements.length === 0) {+ target.status = "blocked";+ target.steeringStatus = "blocked";+ target.blockedReason = proposal.blockedReason ?? proposal.rationale;+ }+ else {+ target.steeringStatus = "superseded";+ target.supersededBy = replacements.map((item) => item.id);+ for (const item of replacements)+ item.supersedes = [target.id];+ plan.goals.splice(plan.goals.indexOf(target) + 1, 0, ...replacements);+ updateBatchesAfterSupersede(plan, target.id, replacements.map((item) => item.id));+ }+ if (plan.activeGoalId === target.id)+ delete plan.activeGoalId;+}+export function reviseCriterion(plan, proposal, now) {+ const target = goal(plan, targets(proposal)[0]);+ const index = target?.successCriteria.findIndex((item) => item.id === proposal.criterionId) ?? -1;+ const current = target?.successCriteria[index];+ if (target === undefined || current === undefined)+ return;+ const model = read(proposal, "userModel");+ target.successCriteria[index] = { ...current, scenario: text(proposal, "scenario") ?? current.scenario, expectedEvidence: text(proposal, "expectedEvidence") ?? current.expectedEvidence, userModel: isModel(model) ? model : current.userModel };+ target.updatedAt = now;+}diff --git a/plugins/omo/components/ulw-loop/dist/steering-snapshot.d.ts b/plugins/omo/components/ulw-loop/dist/steering-snapshot.d.tsnew file mode 100644index 00000000..17bd819c--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/steering-snapshot.d.ts@@ -0,0 +1,15 @@+import type { UlwLoopPlan } from "./domain-types.js";+import type { UlwLoopSteeringPlanSnapshot } from "./steering-types.js";+/**+ * Compact before/after snapshots for steering ledger entries.+ *+ * Ledger entries used to embed the FULL plan (every goal, criterion, and+ * evidence string) twice per audit and twice more at the entry top level.+ * That made each accepted steer O(plan size) on disk, so the ledger grew+ * quadratically over a run, and every dedup scan re-hydrated all of it into+ * memory. A snapshot instead records plan-level counters plus only the goals+ * the mutation actually touched, keeping each entry O(changed goals).+ */+export declare function buildSteeringPlanSnapshot(plan: UlwLoopPlan, changedGoalIds: ReadonlySet<string>): UlwLoopSteeringPlanSnapshot;+/** Ids of goals that differ between two plans, including added or removed goals. */+export declare function changedGoalIdsBetween(before: UlwLoopPlan, after: UlwLoopPlan): Set<string>;diff --git a/plugins/omo/components/ulw-loop/dist/steering-snapshot.js b/plugins/omo/components/ulw-loop/dist/steering-snapshot.jsnew file mode 100644index 00000000..a2fe8c6d--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/steering-snapshot.js@@ -0,0 +1,33 @@+/**+ * Compact before/after snapshots for steering ledger entries.+ *+ * Ledger entries used to embed the FULL plan (every goal, criterion, and+ * evidence string) twice per audit and twice more at the entry top level.+ * That made each accepted steer O(plan size) on disk, so the ledger grew+ * quadratically over a run, and every dedup scan re-hydrated all of it into+ * memory. A snapshot instead records plan-level counters plus only the goals+ * the mutation actually touched, keeping each entry O(changed goals).+ */+export function buildSteeringPlanSnapshot(plan, changedGoalIds) {+ const snapshot = {+ updatedAt: plan.updatedAt,+ goalCount: plan.goals.length,+ goalIds: plan.goals.map((goal) => goal.id),+ goals: plan.goals.filter((goal) => changedGoalIds.has(goal.id)),+ };+ return plan.activeGoalId === undefined ? snapshot : { ...snapshot, activeGoalId: plan.activeGoalId };+}+/** Ids of goals that differ between two plans, including added or removed goals. */+export function changedGoalIdsBetween(before, after) {+ const beforeById = new Map(before.goals.map((goal) => [goal.id, goal]));+ const changed = new Set();+ for (const goal of after.goals) {+ const prior = beforeById.get(goal.id);+ if (prior === undefined || JSON.stringify(prior) !== JSON.stringify(goal))+ changed.add(goal.id);+ beforeById.delete(goal.id);+ }+ for (const id of beforeById.keys())+ changed.add(id);+ return changed;+}diff --git a/plugins/omo/components/ulw-loop/dist/steering-types.d.ts b/plugins/omo/components/ulw-loop/dist/steering-types.d.tsnew file mode 100644index 00000000..0b5d28d2--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/steering-types.d.ts@@ -0,0 +1,70 @@+import type { UlwLoopSteeringMutationKind, UlwLoopSteeringSource } from "./constants.js";+import type { UlwLoopItem, UlwLoopPlan } from "./domain-types.js";+export interface UlwLoopSteeringInvariantResult {+ accepted: boolean;+ structuralInvariantAccepted: boolean;+ evidenceBackedNecessity: boolean;+ noEasierCompletion: boolean;+ rejectedReasons: string[];+ reasons?: string[];+}+export interface UlwLoopSteeringChildGoal {+ title: string;+ objective: string;+}+export interface UlwLoopSteeringAfterPayload {+ title?: string;+ objective?: string;+ pendingGoalIds?: string[];+ children?: UlwLoopSteeringChildGoal[];+}+export interface UlwLoopSteeringProposal {+ kind: UlwLoopSteeringMutationKind;+ source: UlwLoopSteeringSource;+ targetGoalId?: string;+ targetGoalIds?: string[];+ criterionId?: string;+ evidence: string;+ rationale: string;+ title?: string;+ objective?: string;+ childGoals?: UlwLoopSteeringChildGoal[];+ revisedTitle?: string;+ revisedObjective?: string;+ pendingOrder?: string[];+ blockedReason?: string;+ after?: UlwLoopSteeringAfterPayload;+ directiveText?: string;+ promptSignature?: string;+ idempotencyKey?: string;+ now?: Date;+}+export interface UlwLoopSteeringPlanSnapshot {+ readonly updatedAt: string;+ readonly activeGoalId?: string;+ readonly goalCount: number;+ readonly goalIds: readonly string[];+ readonly goals: readonly UlwLoopItem[];+}+export interface UlwLoopSteeringAudit {+ kind: UlwLoopSteeringMutationKind;+ source: UlwLoopSteeringSource;+ targetGoalIds: string[];+ criterionId?: string;+ before?: UlwLoopSteeringPlanSnapshot;+ after?: UlwLoopSteeringPlanSnapshot;+ evidence: string;+ rationale: string;+ invariant: UlwLoopSteeringInvariantResult;+ directiveText?: string;+ promptSignature?: string;+ idempotencyKey?: string;+ deduped?: boolean;+}+export interface SteerUlwLoopResult {+ plan: UlwLoopPlan;+ accepted: boolean;+ audit: UlwLoopSteeringAudit;+ rejectedReasons: string[];+ deduped: boolean;+}diff --git a/plugins/omo/components/ulw-loop/dist/steering-types.js b/plugins/omo/components/ulw-loop/dist/steering-types.jsnew file mode 100644index 00000000..cb0ff5c3--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/steering-types.js@@ -0,0 +1 @@+export {};diff --git a/plugins/omo/components/ulw-loop/dist/steering.d.ts b/plugins/omo/components/ulw-loop/dist/steering.d.tsnew file mode 100644index 00000000..01a8a86f--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/steering.d.ts@@ -0,0 +1,6 @@+import type { UlwLoopScope } from "./paths.js";+import type { SteerUlwLoopResult, UlwLoopPlan, UlwLoopSteeringAudit, UlwLoopSteeringProposal } from "./types.js";+export declare function validateUlwLoopSteeringProposal(plan: UlwLoopPlan, proposal: unknown): UlwLoopSteeringAudit;+export declare function applySteeringMutation(plan: UlwLoopPlan, proposal: UlwLoopSteeringProposal, audit: UlwLoopSteeringAudit): UlwLoopPlan;+export declare function parseUlwLoopSteeringDirective(text: string): UlwLoopSteeringProposal | null;+export declare function steerUlwLoop(repoRoot: string, proposal: UlwLoopSteeringProposal, scope?: UlwLoopScope): Promise<SteerUlwLoopResult>;diff --git a/plugins/omo/components/ulw-loop/dist/steering.js b/plugins/omo/components/ulw-loop/dist/steering.jsnew file mode 100644index 00000000..2047d0cf--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/steering.js@@ -0,0 +1,244 @@+// biome-ignore-all format: compact steering module must stay below the 240 pure-LOC budget+import { isUlwLoopDone } from "./goal-status.js";+import { appendLedger, findAcceptedSteeringLedgerEntry, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";+import { makeGoal, reviseCriterion, reviseWording, splitOrBlock } from "./steering-mutations.js";+import { buildSteeringPlanSnapshot, changedGoalIdsBetween } from "./steering-snapshot.js";+import { iso, ULW_LOOP_STEERING_MUTATION_KINDS, ULW_LOOP_SUCCESS_CRITERION_USER_MODELS } from "./types.js";+import { batchUpdateLedgerEntry } from "./validation-batch.js";+const SOURCES = ["user_prompt_submit", "finding", "cli"];+const PROTECTED = new Set(["aggregateCompletion", "codexObjective", "codexObjectiveAliases", "originalConstraints", "qualityGate", "status", "completedAt", "completionStatus"]);+const isObject = (value) => typeof value === "object" && value !== null;+const isPlain = (value) => isObject(value) && !Array.isArray(value);+const read = (value, key) => Object.entries(value).find(([name]) => name === key)?.[1];+const isText = (value) => typeof value === "string" && value.trim().length > 0;+const text = (value, key) => {+ const candidate = read(value, key);+ return isText(candidate) ? candidate.trim() : undefined;+};+const isKind = (value) => typeof value === "string" && ULW_LOOP_STEERING_MUTATION_KINDS.some((kind) => kind === value);+const isSource = (value) => typeof value === "string" && SOURCES.some((source) => source === value);+const isModel = (value) => typeof value === "string" && ULW_LOOP_SUCCESS_CRITERION_USER_MODELS.some((model) => model === value);+const texts = (value, key) => {+ const candidate = read(value, key);+ return Array.isArray(candidate) && candidate.every((item) => typeof item === "string") ? candidate : [];+};+function targets(proposal) {+ const many = texts(proposal, "targetGoalIds");+ const one = text(proposal, "targetGoalId") ?? text(proposal, "goalId");+ return many.length > 0 ? many : one === undefined ? [] : [one];+}+const after = (proposal) => {+ const candidate = read(proposal, "after");+ return isPlain(candidate) ? candidate : undefined;+};+const revised = (proposal, direct, nested) => text(proposal, direct) ?? text(after(proposal) ?? proposal, nested);+function child(value) {+ if (!isPlain(value))+ return null;+ const title = text(value, "title");+ const objective = text(value, "objective");+ if (title === undefined || objective === undefined)+ return null;+ return { title, objective };+}+function childValues(proposal) {+ const direct = read(proposal, "childGoals");+ if (Array.isArray(direct) && direct.length > 0)+ return direct;+ const nested = after(proposal);+ const fromAfter = nested === undefined ? undefined : read(nested, "children");+ return Array.isArray(fromAfter) ? fromAfter : [];+}+const pendingOrder = (proposal) => {+ const direct = texts(proposal, "pendingOrder");+ return direct.length > 0 ? direct : texts(after(proposal) ?? proposal, "pendingGoalIds");+};+function hasProtected(value) {+ if (!isObject(value))+ return false;+ for (const [key, childValue] of Object.entries(value))+ if (PROTECTED.has(key) || key.toLowerCase().includes("complete") || hasProtected(childValue))+ return true;+ return false;+}+function allText(value) {+ if (typeof value === "string")+ return value;+ return isObject(value) ? Object.values(value).map(allText).filter(Boolean).join("\n") : "";+}+function weakens(value) {+ const valueText = allText(value).toLowerCase();+ return /\b(skip|bypass|weaken|remove|omit|auto[-\s]?complete|mark complete|complete faster)\b/.test(valueText) && /\b(test|tests|verification|review|quality gate|complete|completion)\b/.test(valueText);+}+function auditFor(proposal, reasons) {+ 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 = { kind: isKind(kindRaw) ? kindRaw : "annotate_ledger", source: isSource(sourceRaw) ? sourceRaw : "cli", targetGoalIds: object === undefined ? [] : targets(object), evidence, rationale, invariant: { accepted: reasons.length === 0, structuralInvariantAccepted: reasons.length === 0, evidenceBackedNecessity: evidence.length > 0 && rationale.length > 0, noEasierCompletion: !weakens(proposal), rejectedReasons: reasons, reasons } };+ if (object === undefined)+ return audit;+ const criterionId = text(object, "criterionId");+ const directiveText = text(object, "directiveText");+ const promptSignature = text(object, "promptSignature");+ const idempotencyKey = text(object, "idempotencyKey");+ if (criterionId !== undefined)+ audit.criterionId = criterionId;+ if (directiveText !== undefined)+ audit.directiveText = directiveText;+ if (promptSignature !== undefined)+ audit.promptSignature = promptSignature;+ if (idempotencyKey !== undefined)+ audit.idempotencyKey = idempotencyKey;+ return audit;+}+export function validateUlwLoopSteeringProposal(plan, proposal) {+ const reasons = [];+ if (!isPlain(proposal))+ reasons.push("proposal must be an object");+ const object = isPlain(proposal) ? proposal : {};+ const kind = read(object, "kind");+ if (!isKind(kind))+ reasons.push(`invalid kind: ${String(kind)}`);+ if (!isSource(read(object, "source")))+ reasons.push(`invalid source: ${String(read(object, "source"))}`);+ if (text(object, "evidence") === undefined)+ reasons.push("missing evidence");+ if (text(object, "rationale") === undefined)+ reasons.push("missing rationale");+ if (hasProtected(proposal))+ reasons.push("protected payload");+ if (weakens(proposal))+ reasons.push("weakened completion");+ if (isUlwLoopDone(plan))+ reasons.push("plan already complete");+ if (isKind(kind))+ validateKind(plan, object, kind, reasons);+ return auditFor(proposal, reasons);+}+function goal(plan, id) {+ return id === undefined ? undefined : plan.goals.find((item) => item.id === id);+}+function validateKind(plan, proposal, kind, reasons) {+ const target = goal(plan, targets(proposal)[0]);+ if (kind === "add_subgoal" && (text(proposal, "title") === undefined || text(proposal, "objective") === undefined))+ reasons.push("add_subgoal requires title/objective");+ if ((kind === "split_subgoal" || kind === "revise_pending_wording" || kind === "mark_blocked_superseded") && target === undefined)+ reasons.push(`${kind} requires target`);+ if ((kind === "split_subgoal" || kind === "revise_pending_wording") && target !== undefined && target.status !== "pending")+ reasons.push(`${kind} requires pending target`);+ const rawChildren = childValues(proposal);+ if (kind === "split_subgoal" && rawChildren.length === 0)+ reasons.push("split_subgoal requires children");+ if ((kind === "split_subgoal" || kind === "mark_blocked_superseded") && rawChildren.some((item) => child(item) === null))+ reasons.push(`${kind} children require title/objective`);+ if (kind === "reorder_pending")+ validateOrder(plan, proposal, reasons);+ if (kind === "revise_pending_wording" && revised(proposal, "revisedTitle", "title") === undefined && revised(proposal, "revisedObjective", "objective") === undefined)+ reasons.push("revise_pending_wording requires update");+ if (kind === "revise_criterion")+ validateCriterion(plan, proposal, reasons);+}+function validateOrder(plan, proposal, reasons) {+ const requested = pendingOrder(proposal);+ const pending = plan.goals.filter((item) => item.status === "pending" && item.steeringStatus === undefined).map((item) => item.id);+ if (requested.length === 0)+ reasons.push("reorder_pending requires ids");+ if (new Set(requested).size !== requested.length)+ reasons.push("duplicate pending id");+ if (requested.some((id) => !pending.includes(id)))+ reasons.push("unknown pending id");+}+function validateCriterion(plan, proposal, reasons) {+ const target = goal(plan, targets(proposal)[0]);+ const criterionId = text(proposal, "criterionId");+ if (target === undefined)+ reasons.push("revise_criterion requires goalId");+ else if (criterionId === undefined || target.successCriteria.every((item) => item.id !== criterionId))+ reasons.push("revise_criterion requires criterionId");+ const model = read(proposal, "userModel");+ if (read(proposal, "scenario") === undefined && read(proposal, "expectedEvidence") === undefined && model === undefined)+ reasons.push("revise_criterion requires update");+ if (model !== undefined && !isModel(model))+ reasons.push("invalid userModel");+}+export function applySteeringMutation(plan, proposal, audit) {+ 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 !== undefined), ...next.goals.filter((item) => !order.includes(item.id))];+ }+ if (proposal.kind === "revise_pending_wording")+ reviseWording(next, proposal, now);+ if (proposal.kind === "split_subgoal" || proposal.kind === "mark_blocked_superseded")+ splitOrBlock(next, proposal, now);+ if (proposal.kind === "revise_criterion")+ reviseCriterion(next, proposal, now);+ if (proposal.kind !== "annotate_ledger")+ next.updatedAt = now;+ return next;+}+function isProposal(value) {+ return isPlain(value) && isKind(read(value, "kind")) && isSource(read(value, "source")) && isText(read(value, "evidence")) && isText(read(value, "rationale"));+}+export function parseUlwLoopSteeringDirective(text) {+ 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 = JSON.parse(match[1].trim());+ return isProposal(parsed) ? parsed : null;+ }+ catch (error) {+ if (error instanceof SyntaxError)+ return null;+ throw error;+ }+}+export async function steerUlwLoop(repoRoot, proposal, scope) {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ const plan = await readUlwLoopPlan(repoRoot, scope);+ const key = proposal.idempotencyKey ?? proposal.promptSignature;+ const prior = key === undefined ? undefined : await findAcceptedSteeringLedgerEntry(repoRoot, key, scope);+ if (prior?.steering !== undefined) {+ // Legacy entries embedded full-plan before/after snapshots; never+ // re-surface those multi-MB payloads on the dedup path.+ const { before: _before, after: _after, ...compactPrior } = prior.steering;+ return { plan, accepted: true, audit: { ...compactPrior, deduped: true }, rejectedReasons: [], deduped: true };+ }+ const audit = validateUlwLoopSteeringProposal(plan, proposal);+ const accepted = audit.invariant.accepted;+ const next = accepted ? applySteeringMutation(plan, proposal, audit) : plan;+ const finalAudit = { ...audit };+ if (accepted) {+ const changed = changedGoalIdsBetween(plan, next);+ finalAudit.before = buildSteeringPlanSnapshot(plan, changed);+ finalAudit.after = buildSteeringPlanSnapshot(next, changed);+ }+ const at = proposal.now?.toISOString() ?? iso();+ const batchEntry = accepted ? batchUpdateLedgerEntry(plan, next, at) : null;+ if (accepted)+ await writePlan(repoRoot, next, scope);+ await appendLedger(repoRoot, ledgerEntry(proposal, finalAudit, at), scope);+ if (batchEntry !== null)+ await appendLedger(repoRoot, batchEntry, scope);+ return { plan: next, accepted, audit: finalAudit, rejectedReasons: audit.invariant.rejectedReasons, deduped: false };+ });+}+function ledgerEntry(proposal, audit, at) {+ const entry = { at, kind: audit.invariant.accepted ? (proposal.kind === "revise_criterion" ? "criteria_revised" : "steering_accepted") : "steering_rejected", evidence: proposal.evidence, message: proposal.rationale, steering: audit, mutationKind: proposal.kind };+ const goalId = audit.targetGoalIds[0];+ if (goalId !== undefined)+ entry.goalId = goalId;+ if (proposal.criterionId !== undefined)+ entry.criterionId = proposal.criterionId;+ if (proposal.idempotencyKey !== undefined)+ entry.idempotencyKey = proposal.idempotencyKey;+ return entry;+}diff --git a/plugins/omo/components/ulw-loop/dist/stop-resume-hook.d.ts b/plugins/omo/components/ulw-loop/dist/stop-resume-hook.d.tsnew file mode 100644index 00000000..3f801fab--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/stop-resume-hook.d.ts@@ -0,0 +1,2 @@+export declare function runStopResumeHook(input: unknown): string;+export declare function runStopResumeHookCli(stdin: NodeJS.ReadableStream, stdout: NodeJS.WritableStream): Promise<void>;diff --git a/plugins/omo/components/ulw-loop/dist/stop-resume-hook.js b/plugins/omo/components/ulw-loop/dist/stop-resume-hook.jsnew file mode 100644index 00000000..f9df5560--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/stop-resume-hook.js@@ -0,0 +1,216 @@+import { existsSync, readFileSync, writeFileSync } from "node:fs";+import { isAbsolute, join, resolve, sep } from "node:path";+import { normalizeUlwLoopSessionId, ulwLoopDir } from "./paths.js";+// Turn-death recovery only: Codex emits Stop when a turn ends, so a run that+// dies mid-turn (crash, kill, context blowup before any Stop) never reaches+// this handler. Mid-turn stalls are out of scope by design.+const RESUME_CAP = 2;+// Mirrors start-work-continuation's context-pressure bail-out: injecting a+// resume directive into an already-overflowing context makes things worse.+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",+];+export function runStopResumeHook(input) {+ const payload = parseStopPayload(input);+ if (payload === null || payload.stop_hook_active)+ return "";+ if (transcriptShowsContextPressure(payload.transcript_path))+ return "";+ if (boulderContinuationWillFire(payload.cwd, payload.session_id))+ return "";+ const stateDir = ulwLoopDir(payload.cwd, { sessionId: payload.session_id });+ const plan = readPlan(join(stateDir, "goals.json"));+ if (plan === null || plan.aggregateCompletion?.status === "complete")+ return "";+ const goal = resumableGoal(plan);+ if (goal === undefined)+ return "";+ if (!consumeResumeBudget(stateDir, goal.id))+ return "";+ const output = {+ decision: "block",+ reason: renderResumeDirective(plan, goal, payload.session_id),+ };+ return JSON.stringify(output);+}+export async function runStopResumeHookCli(stdin, stdout) {+ try {+ const chunks = [];+ for await (const chunk of stdin)+ chunks.push(Buffer.from(chunk));+ const output = runStopResumeHook(JSON.parse(Buffer.concat(chunks).toString("utf8")));+ if (output.length > 0)+ stdout.write(output);+ }+ catch (error) {+ if (error instanceof Error)+ return;+ }+}+function resumableGoal(plan) {+ const active = plan.goals.find((goal) => goal.id === plan.activeGoalId);+ if (active !== undefined && isResumableStatus(active.status))+ return active;+ return plan.goals.find((goal) => isResumableStatus(goal.status));+}+function isResumableStatus(status) {+ return status === "pending" || status === "in_progress";+}+// Two-strike cap keyed on ledger movement: an unchanged ledger.jsonl line+// count across resumes means the loop is not progressing. The stuck marker is+// a separate file — a ledger append would change the count and self-reset.+function consumeResumeBudget(stateDir, goalId) {+ const ledgerLineCount = countLedgerLines(join(stateDir, "ledger.jsonl"));+ const counterPath = resolve(stateDir, `auto-resume-${goalId}.json`);+ const stuckPath = resolve(stateDir, `auto-resume-${goalId}.stuck`);+ // goals.json is untrusted input: a crafted goal id (e.g. `../../x`) must+ // never drive a write outside the session state dir. Deny the resume.+ if (!isInsideDir(stateDir, counterPath) || !isInsideDir(stateDir, stuckPath))+ return false;+ const previous = readCounter(counterPath);+ const count = previous !== null && previous.ledgerLineCount === ledgerLineCount ? previous.count : 0;+ if (count >= RESUME_CAP) {+ writeFileSync(stuckPath, `no ledger progress after ${count} resumes\n`);+ return false;+ }+ writeFileSync(counterPath, JSON.stringify({ count: count + 1, ledgerLineCount }));+ return true;+}+function isInsideDir(dir, candidate) {+ return candidate.startsWith(resolve(dir) + sep);+}+function renderResumeDirective(plan, goal, sessionId) {+ const normalized = normalizeUlwLoopSessionId(sessionId);+ const option = normalized !== null && plan.goalsPath.includes(`/${normalized}/`) ? ` --session-id ${normalized}` : "";+ return [+ `The ulw-loop run in this session still has unfinished goals (next: ${goal.id} — ${goal.title}).`,+ "The turn ended before the loop completed. Resume it now:",+ `1. Run \`omo ulw-loop status${option} --json\` to reload the plan, the active goal, and currentAttemptDir.`,+ "2. Continue the active goal's remaining success criteria, recording evidence with record-evidence.",+ `3. Checkpoint through \`omo ulw-loop checkpoint${option}\` when the goal's criteria are proven; a complete checkpoint prints the next goal instruction.`,+ "If the loop is genuinely blocked on the user, checkpoint the goal as blocked with the reason instead.",+ ].join("\n");+}+function readPlan(goalsPath) {+ try {+ return JSON.parse(readFileSync(goalsPath, "utf8"));+ }+ catch (error) {+ if (error instanceof Error)+ return null;+ throw error;+ }+}+function countLedgerLines(ledgerPath) {+ try {+ return readFileSync(ledgerPath, "utf8").split("\n").filter(Boolean).length;+ }+ catch (error) {+ if (error instanceof Error)+ return 0;+ throw error;+ }+}+function readCounter(counterPath) {+ try {+ if (!existsSync(counterPath))+ return null;+ const parsed = JSON.parse(readFileSync(counterPath, "utf8"));+ if (typeof parsed["count"] !== "number" || typeof parsed["ledgerLineCount"] !== "number")+ return null;+ return { count: parsed["count"], ledgerLineCount: parsed["ledgerLineCount"] };+ }+ catch (error) {+ if (error instanceof Error)+ return null;+ throw error;+ }+}+// Local ~10-LOC approximation of start-work-continuation's boulder check (no+// cross-component import allowed): any continuable work for this session means+// that hook owns the Stop event, so this one stays silent.+function boulderContinuationWillFire(cwd, sessionId) {+ try {+ const raw = JSON.parse(readFileSync(join(cwd, ".omo", "boulder.json"), "utf8"));+ const works = raw["works"];+ // The flat legacy shape has no works map: the top level is the single work.+ const entries = typeof works === "object" && works !== null ? Object.values(works) : [raw];+ return entries.some((work) => {+ if (typeof work !== "object" || work === null)+ return false;+ const entry = work;+ const sessionIds = Array.isArray(entry["session_ids"]) ? entry["session_ids"] : [];+ const continuable = entry["status"] === "active" || entry["status"] === "paused";+ return continuable && sessionIds.includes(`codex:${sessionId}`) && boulderPlanHasChecklist(cwd, entry);+ });+ }+ catch (error) {+ if (error instanceof Error)+ return false;+ throw error;+ }+}+function transcriptShowsContextPressure(transcriptPath) {+ try {+ const transcript = readFileSync(transcriptPath, "utf8").toLowerCase();+ return CONTEXT_PRESSURE_MARKERS.some((marker) => transcript.includes(marker));+ }+ catch (error) {+ if (error instanceof Error)+ return false;+ throw error;+ }+}+// start-work-continuation owns an active Boulder plan until its final gate marks+// the work complete, including the zero-remaining checklist state.+function boulderPlanHasChecklist(cwd, entry) {+ const activePlan = entry["active_plan"];+ if (typeof activePlan !== "string" || activePlan.trim().length === 0)+ return false;+ const planPath = isAbsolute(activePlan) ? activePlan : join(cwd, activePlan);+ const worktree = entry["worktree_path"];+ const candidates = typeof worktree === "string" && worktree.trim().length > 0 && !isAbsolute(activePlan)+ ? [join(isAbsolute(worktree) ? worktree : join(cwd, worktree), activePlan), planPath]+ : [planPath];+ for (const candidate of candidates) {+ try {+ return readFileSync(candidate, "utf8")+ .split(/\r?\n/)+ .some((line) => line.startsWith("- [ ] ") || line.startsWith("- [x] ") || line.startsWith("- [X] "));+ }+ catch (error) {+ if (!(error instanceof Error))+ throw error;+ }+ }+ return false;+}+function parseStopPayload(value) {+ if (typeof value !== "object" || value === null || Array.isArray(value))+ return null;+ const record = value;+ const optionalMessage = record["last_assistant_message"];+ const valid = record["hook_event_name"] === "Stop" &&+ typeof record["session_id"] === "string" &&+ typeof record["turn_id"] === "string" &&+ typeof record["transcript_path"] === "string" &&+ typeof record["cwd"] === "string" &&+ typeof record["model"] === "string" &&+ typeof record["permission_mode"] === "string" &&+ typeof record["stop_hook_active"] === "boolean" &&+ (optionalMessage === undefined || typeof optionalMessage === "string");+ if (!valid)+ return null;+ return {+ session_id: record["session_id"],+ cwd: record["cwd"],+ transcript_path: record["transcript_path"],+ stop_hook_active: record["stop_hook_active"],+ };+}diff --git a/plugins/omo/components/ulw-loop/dist/types.d.ts b/plugins/omo/components/ulw-loop/dist/types.d.tsnew file mode 100644index 00000000..b639dd0b--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/types.d.ts@@ -0,0 +1,5 @@+export * from "./command-types.js";+export * from "./constants.js";+export * from "./domain-types.js";+export * from "./runtime.js";+export * from "./steering-types.js";diff --git a/plugins/omo/components/ulw-loop/dist/types.js b/plugins/omo/components/ulw-loop/dist/types.jsnew file mode 100644index 00000000..b639dd0b--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/types.js@@ -0,0 +1,5 @@+export * from "./command-types.js";+export * from "./constants.js";+export * from "./domain-types.js";+export * from "./runtime.js";+export * from "./steering-types.js";diff --git a/plugins/omo/components/ulw-loop/dist/ultrawork-directive.d.ts b/plugins/omo/components/ulw-loop/dist/ultrawork-directive.d.tsnew file mode 100644index 00000000..fa4aafb0--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/ultrawork-directive.d.ts@@ -0,0 +1,6 @@+import { type UltraworkAdditionalContextOptions } from "./ultrawork-skill-pointer.js";+export interface UltraworkDirectiveInput {+ readonly prompt: string;+ readonly transcript_path?: string | null;+}+export declare function buildUltraworkDirectiveOutput(input: UltraworkDirectiveInput, options?: UltraworkAdditionalContextOptions): string;diff --git a/plugins/omo/components/ulw-loop/dist/ultrawork-directive.js b/plugins/omo/components/ulw-loop/dist/ultrawork-directive.jsnew file mode 100644index 00000000..7f67a82a--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/ultrawork-directive.js@@ -0,0 +1,106 @@+import { readFileSync } from "node:fs";+import { buildUltraworkAdditionalContext } from "./ultrawork-skill-pointer.js";+const ULTRAWORK_CURRENT_PROMPT_PATTERN = /(?:ultrawork|ulw)/i;+const ULTRAWORK_DIRECTIVE_MARKER = "<ultrawork-mode>";+const TRANSCRIPT_SEARCH_BYTES = 512_000;+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",+];+export function buildUltraworkDirectiveOutput(input, options = {}) {+ if (isContextPressureRecoveryPrompt(input.prompt))+ return "";+ if (hasUltraworkDirectiveAlreadyInTranscript(input.transcript_path))+ return "";+ if (isContextPressureTranscript(input.transcript_path))+ return "";+ return isUltraworkPrompt(input.prompt)+ ? formatAdditionalContextOutput(buildUltraworkAdditionalContext(options))+ : "";+}+function hasUltraworkDirectiveAlreadyInTranscript(transcriptPath) {+ if (transcriptPath === undefined || transcriptPath === null)+ return false;+ try {+ const rawTranscript = readTranscriptTail(transcriptPath);+ for (const line of rawTranscript.split(/\r?\n/)) {+ const parsed = parseJsonLine(line);+ if (!isRecord(parsed))+ continue;+ const hookSpecificOutput = parsed["hookSpecificOutput"];+ if (!isRecord(hookSpecificOutput))+ continue;+ if (hookSpecificOutput["hookEventName"] !== "UserPromptSubmit")+ continue;+ if (typeof hookSpecificOutput["additionalContext"] === "string" &&+ hookSpecificOutput["additionalContext"].includes(ULTRAWORK_DIRECTIVE_MARKER)) {+ return true;+ }+ }+ }+ catch (error) {+ if (error instanceof Error)+ return false;+ throw error;+ }+ return false;+}+function readTranscriptTail(transcriptPath) {+ const rawTranscript = readFileSync(transcriptPath);+ return rawTranscript.subarray(Math.max(0, rawTranscript.byteLength - TRANSCRIPT_SEARCH_BYTES)).toString("utf8");+}+function isUltraworkPrompt(prompt) {+ return ULTRAWORK_CURRENT_PROMPT_PATTERN.test(prompt);+}+function isContextPressureRecoveryPrompt(prompt) {+ const normalizedPrompt = prompt.toLowerCase();+ return CONTEXT_PRESSURE_MARKERS.some((marker) => normalizedPrompt.includes(marker));+}+function isContextPressureTranscript(transcriptPath) {+ if (transcriptPath === undefined || transcriptPath === null)+ return false;+ try {+ return isContextPressureRecoveryPrompt(readTranscriptTail(transcriptPath));+ }+ catch (error) {+ if (error instanceof Error)+ return false;+ throw error;+ }+}+function formatAdditionalContextOutput(additionalContext) {+ const normalizedContext = normalizeAdditionalContext(additionalContext);+ if (normalizedContext.length === 0)+ return "";+ const output = {+ hookSpecificOutput: {+ hookEventName: "UserPromptSubmit",+ additionalContext: normalizedContext,+ },+ };+ return `${JSON.stringify(output)}\n`;+}+function normalizeAdditionalContext(additionalContext) {+ return additionalContext.replace(/\r\n/g, "\n").replace(/\r/g, "\n").trim();+}+function parseJsonLine(line) {+ if (line.trim().length === 0)+ return null;+ try {+ const parsed = JSON.parse(line);+ return parsed;+ }+ catch (error) {+ if (error instanceof Error)+ return null;+ throw error;+ }+}+function isRecord(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/plugins/omo/components/ulw-loop/dist/ultrawork-skill-pointer.d.ts b/plugins/omo/components/ulw-loop/dist/ultrawork-skill-pointer.d.tsnew file mode 100644index 00000000..3152bfa9--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/ultrawork-skill-pointer.d.ts@@ -0,0 +1,7 @@+export declare const ULTRAWORK_SKILL_POINTER_TEMPLATE = "<ultrawork-mode>\nULTRAWORK MODE IS ACTIVE FOR THIS TASK.\n\nMANDATORY BOOTSTRAP: do all three steps, in order, before anything else.\n\n1. First user-visible line this turn MUST be exactly:\n`ULTRAWORK MODE ENABLED!`\n\n2. Call `create_goal` NOW with `objective` set to the user's request.\nSend `objective` only: no `status`, no budget fields. If the\n`create_goal` tool is unavailable, open your reply with a binding\n`# Goal` block instead. Never skip this step.\n\n3. Read the FULL ultrawork directive NOW, before any other tool call,\nplan, or edit. It is the `ultrawork` skill, stored at:\n\n{{ULTRAWORK_SKILL_PATH}}\n\nRead the whole file. If a read result comes back truncated, keep\nreading the remaining line ranges until you have seen every line.\nEvery rule in that file is binding for this entire task: no\ncompromise, no summarizing from memory, no skipping. If the file does\nnot exist, tell the user the omo ultrawork skill is missing and\ncontinue with steps 1 and 2 plus evidence-bound execution.\n\nDo not start the requested work until all three steps are complete.\n</ultrawork-mode>\n";+export interface UltraworkAdditionalContextOptions {+ readonly skillFilePath?: string | null;+}+export declare function resolveUltraworkSkillFilePath(): string;+export declare function buildUltraworkSkillPointer(skillFilePath: string): string;+export declare function buildUltraworkAdditionalContext(options?: UltraworkAdditionalContextOptions): string;diff --git a/plugins/omo/components/ulw-loop/dist/ultrawork-skill-pointer.js b/plugins/omo/components/ulw-loop/dist/ultrawork-skill-pointer.jsnew file mode 100644index 00000000..22b4096f--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/ultrawork-skill-pointer.js@@ -0,0 +1,46 @@+import { existsSync, readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+export const ULTRAWORK_SKILL_POINTER_TEMPLATE = `<ultrawork-mode>+ULTRAWORK MODE IS ACTIVE FOR THIS TASK.++MANDATORY BOOTSTRAP: do all three steps, in order, before anything else.++1. First user-visible line this turn MUST be exactly:+\`ULTRAWORK MODE ENABLED!\`++2. Call \`create_goal\` NOW with \`objective\` set to the user's request.+Send \`objective\` only: no \`status\`, no budget fields. If the+\`create_goal\` tool is unavailable, open your reply with a binding+\`# Goal\` block instead. Never skip this step.++3. Read the FULL ultrawork directive NOW, before any other tool call,+plan, or edit. It is the \`ultrawork\` skill, stored at:++{{ULTRAWORK_SKILL_PATH}}++Read the whole file. If a read result comes back truncated, keep+reading the remaining line ranges until you have seen every line.+Every rule in that file is binding for this entire task: no+compromise, no summarizing from memory, no skipping. If the file does+not exist, tell the user the omo ultrawork skill is missing and+continue with steps 1 and 2 plus evidence-bound execution.++Do not start the requested work until all three steps are complete.+</ultrawork-mode>+`;+const ULTRAWORK_SKILL_PATH_PLACEHOLDER = "{{ULTRAWORK_SKILL_PATH}}";+const ULTRAWORK_SKILL_FILE_URL = new URL("../../../skills/ultrawork/SKILL.md", import.meta.url);+const ULTRAWORK_DIRECTIVE = readFileSync(new URL("../directive.md", import.meta.url), "utf8");+export function resolveUltraworkSkillFilePath() {+ return fileURLToPath(ULTRAWORK_SKILL_FILE_URL);+}+export function buildUltraworkSkillPointer(skillFilePath) {+ return ULTRAWORK_SKILL_POINTER_TEMPLATE.replace(ULTRAWORK_SKILL_PATH_PLACEHOLDER, skillFilePath);+}+export function buildUltraworkAdditionalContext(options = {}) {+ const skillFilePath = options.skillFilePath === undefined ? resolveUltraworkSkillFilePath() : options.skillFilePath;+ if (skillFilePath !== null && existsSync(skillFilePath)) {+ return buildUltraworkSkillPointer(skillFilePath);+ }+ return ULTRAWORK_DIRECTIVE;+}diff --git a/plugins/omo/components/ulw-loop/dist/validation-batch.d.ts b/plugins/omo/components/ulw-loop/dist/validation-batch.d.tsnew file mode 100644index 00000000..e795c517--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/validation-batch.d.ts@@ -0,0 +1,9 @@+import type { UlwLoopItem, UlwLoopLedgerEntry, UlwLoopPlan, UlwLoopQualityGate, UlwLoopValidationBatch } from "./types.js";+export declare function parseValidationBatches(input: string | undefined, goals: readonly UlwLoopItem[]): Promise<readonly UlwLoopValidationBatch[] | undefined>;+export declare function updateBatchesAfterSupersede(plan: UlwLoopPlan, targetId: string, replacementIds: readonly string[]): void;+export declare function batchUpdateLedgerEntry(before: UlwLoopPlan, after: UlwLoopPlan, at: string): UlwLoopLedgerEntry | null;+export declare function batchOf(plan: UlwLoopPlan, goalId: string): UlwLoopValidationBatch | undefined;+export declare function batchClosedBy(plan: UlwLoopPlan, goalId: string): UlwLoopValidationBatch | undefined;+export declare function requireBatchFinalReady(plan: UlwLoopPlan, goal: UlwLoopItem): void;+export declare function requireAllValidationBatchesClosed(plan: UlwLoopPlan, closingGoalId?: string): void;+export declare function requireBatchGate(plan: UlwLoopPlan, goal: UlwLoopItem, gate: UlwLoopQualityGate): void;diff --git a/plugins/omo/components/ulw-loop/dist/validation-batch.js b/plugins/omo/components/ulw-loop/dist/validation-batch.jsnew file mode 100644index 00000000..91acdaac--- /dev/null+++ b/plugins/omo/components/ulw-loop/dist/validation-batch.js@@ -0,0 +1,122 @@+// biome-ignore-all format: compact validation-batch helpers stay below the pure LOC budget.+import { readJsonInput } from "./cli-arg-parser.js";+import { isMemberResolved } from "./goal-status.js";+import { UlwLoopError } from "./types.js";+function isObject(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}+function read(value, key) {+ return Object.entries(value).find(([name]) => name === key)?.[1];+}+function text(value, key) {+ const candidate = read(value, key);+ return typeof candidate === "string" && candidate.trim().length > 0 ? candidate.trim() : undefined;+}+function strings(value, key) {+ const candidate = read(value, key);+ return Array.isArray(candidate) && candidate.every((item) => typeof item === "string" && item.trim().length > 0)+ ? candidate.map((item) => item.trim())+ : undefined;+}+export async function parseValidationBatches(input, goals) {+ const raw = await readJsonInput(input);+ if (raw === undefined)+ return undefined;+ if (!Array.isArray(raw))+ fail("--validation-batch-json must be a JSON array.");+ const batches = raw.map(batchFromObject);+ validateBatches(batches, goals);+ return batches;+}+function batchFromObject(value) {+ if (!isObject(value))+ fail("validation batch entries must be objects.");+ const batchId = text(value, "batchId");+ const memberIds = strings(value, "memberIds");+ const finalGoalId = text(value, "finalGoalId");+ if (batchId === undefined)+ fail("validation batch requires batchId.");+ if (memberIds === undefined || memberIds.length < 2)+ fail("validation batch requires at least two memberIds.");+ if (finalGoalId === undefined)+ fail("validation batch requires finalGoalId.");+ return { batchId, memberIds, finalGoalId };+}+function validateBatches(batches, goals) {+ const goalIds = new Set(goals.map((goal) => goal.id));+ const batchIds = new Set();+ const members = new Set();+ for (const batch of batches) {+ if (batchIds.has(batch.batchId))+ fail(`duplicate validation batch id: ${batch.batchId}.`);+ batchIds.add(batch.batchId);+ if (new Set(batch.memberIds).size !== batch.memberIds.length)+ fail(`validation batch ${batch.batchId} has duplicate memberIds.`);+ if (!batch.memberIds.includes(batch.finalGoalId))+ fail(`validation batch ${batch.batchId} finalGoalId must be a member.`, "ULW_LOOP_VALIDATION_BATCH_FINAL_NOT_MEMBER");+ for (const memberId of batch.memberIds) {+ if (!goalIds.has(memberId))+ fail(`validation batch ${batch.batchId} references unknown goal: ${memberId}.`, "ULW_LOOP_VALIDATION_BATCH_MEMBER_UNKNOWN");+ if (members.has(memberId))+ fail(`goal appears in multiple validation batches: ${memberId}.`, "ULW_LOOP_VALIDATION_BATCH_OVERLAP");+ members.add(memberId);+ }+ }+}+export function updateBatchesAfterSupersede(plan, targetId, replacementIds) {+ if (replacementIds.length === 0 || plan.validationBatches === undefined)+ return;+ plan.validationBatches = plan.validationBatches.map((batch) => {+ if (!batch.memberIds.includes(targetId))+ return batch;+ const memberIds = batch.memberIds.flatMap((id) => (id === targetId ? [...replacementIds] : [id]));+ const replacementFinalGoalId = replacementIds[replacementIds.length - 1] ?? batch.finalGoalId;+ const finalGoalId = batch.finalGoalId === targetId ? replacementFinalGoalId : batch.finalGoalId;+ return { batchId: batch.batchId, memberIds, finalGoalId };+ });+}+export function batchUpdateLedgerEntry(before, after, at) {+ if (JSON.stringify(before.validationBatches ?? []) === JSON.stringify(after.validationBatches ?? []))+ return null;+ return { at, kind: "batch_updated", before: before.validationBatches ?? [], after: after.validationBatches ?? [], message: "Validation batch membership updated after steering." };+}+export function batchOf(plan, goalId) {+ return plan.validationBatches?.find((batch) => batch.memberIds.includes(goalId));+}+export function batchClosedBy(plan, goalId) {+ const batch = batchOf(plan, goalId);+ return batch?.finalGoalId === goalId ? batch : undefined;+}+export function requireBatchFinalReady(plan, goal) {+ const batch = batchClosedBy(plan, goal.id);+ if (batch === undefined)+ return;+ const open = batch.memberIds.filter((id) => id !== goal.id && !memberResolved(plan, id));+ if (open.length > 0)+ throw new UlwLoopError("Validation batch has unresolved members.", "ULW_LOOP_VALIDATION_BATCH_OPEN", { details: { batchId: batch.batchId, open } });+}+export function requireAllValidationBatchesClosed(plan, closingGoalId) {+ const open = (plan.validationBatches ?? []).filter((batch) => batch.memberIds.some((id) => id !== closingGoalId && !memberResolved(plan, id)));+ if (open.length > 0)+ throw new UlwLoopError("Validation batches remain open.", "ULW_LOOP_VALIDATION_BATCH_OPEN", { details: { batchIds: open.map((batch) => batch.batchId) } });+}+export function requireBatchGate(plan, goal, gate) {+ const batch = batchClosedBy(plan, goal.id);+ if (batch === undefined)+ return;+ const members = batch.memberIds.map((id) => plan.goals.find((item) => item.id === id)).filter((item) => item !== undefined);+ const pending = members.flatMap((member) => member.successCriteria.filter((criterion) => criterion.status !== "pass").map((criterion) => `${member.id}:${criterion.id}`));+ if (pending.length > 0)+ throw new UlwLoopError("Validation batch criteria remain pending.", "ULW_LOOP_VALIDATION_BATCH_CRITERIA_PENDING", { details: { batchId: batch.batchId, pending } });+ const totalCriteria = members.reduce((sum, member) => sum + member.successCriteria.length, 0);+ const passCount = members.reduce((sum, member) => sum + member.successCriteria.filter((criterion) => criterion.status === "pass").length, 0);+ if (gate.criteriaCoverage.totalCriteria !== totalCriteria || gate.criteriaCoverage.passCount !== passCount)+ throw new UlwLoopError("Validation batch gate coverage does not match member criteria.", "ULW_LOOP_VALIDATION_BATCH_GATE_MISMATCH", { details: { batchId: batch.batchId, expected: { totalCriteria, passCount }, actual: gate.criteriaCoverage } });+}+function memberResolved(plan, goalId) {+ const goal = plan.goals.find((candidate) => candidate.id === goalId);+ return goal !== undefined && isMemberResolved(goal, plan);+}+function fail(message, code = "ULW_LOOP_VALIDATION_BATCH_INVALID") {+ throw new UlwLoopError(message, code);+}diff --git a/plugins/omo/components/ulw-loop/hooks/hooks.json b/plugins/omo/components/ulw-loop/hooks/hooks.jsonindex 2cea6351..e85c4194 100644--- a/plugins/omo/components/ulw-loop/hooks/hooks.json+++ b/plugins/omo/components/ulw-loop/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit --with-ultrawork","timeout": 10,- "statusMessage": "(OmO 4.19.0) Checking Ulw-Loop Steering"+ "statusMessage": "(OmO 4.19.1) Checking Ulw-Loop Steering"}]}@@ -20,7 +20,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use","timeout": 5,- "statusMessage": "(OmO 4.19.0) Enforcing Unlimited Ulw-Loop Budget"+ "statusMessage": "(OmO 4.19.1) Enforcing Unlimited Ulw-Loop Budget"}]},@@ -31,7 +31,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use-spawn","timeout": 5,- "statusMessage": "(OmO 4.19.0) Guarding Ulw-Loop Spawns"+ "statusMessage": "(OmO 4.19.1) Guarding Ulw-Loop Spawns"}]}@@ -43,7 +43,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook stop","timeout": 10,- "statusMessage": "(OmO 4.19.0) Checking Ulw-Loop Resume"+ "statusMessage": "(OmO 4.19.1) Checking Ulw-Loop Resume"}]}diff --git a/plugins/omo/components/ulw-loop/package.json b/plugins/omo/components/ulw-loop/package.jsonindex 8fae97d5..7dbbc643 100644--- a/plugins/omo/components/ulw-loop/package.json+++ b/plugins/omo/components/ulw-loop/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-ulw-loop",- "version": "4.19.0",+ "version": "4.19.1","description": "Codex plugin: durable repo-native multi-goal orchestration with embedded success criteria and observable evidence audit.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.md b/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.mdindex dd331b0b..172f6256 100644--- a/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.md+++ b/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.md@@ -113,9 +113,9 @@ If `ULW_LOOP_CLI` is empty, open the durable notepad first, record the missing CRun 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+omo ulw-loop create-goals --brief "<brief>" [--validation-batch-json <json-or-path>] --json+omo ulw-loop create-goals --brief-file <path> [--validation-batch-json <json-or-path>] --json+cat <brief> | omo ulw-loop create-goals --from-stdin [--validation-batch-json <json-or-path>] --json```If the existing aggregate is already complete, do not steer or force thecompleted default state for unrelated new work. Start a fresh run with@@ -145,7 +145,7 @@ Read pending goals, criteria IDs, current ledger head, blockers, and aggregate CLoop 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.+1. Run `omo ulw-loop complete-goals --json` and read the handoff, including criteria. After the first goal starts, a successful complete checkpoint normally prints the next goal instruction directly; use `complete-goals` as the manual fallback/resume path.2. Call `get_goal` and inspect active Codex state.3. Apply this table exactly:@@ -177,7 +177,7 @@ Loop per goal. Cap at 5 cycles per goal. Cap identical same-criterion failures a### Goal Completion1. Non-final aggregate goal: confirm every `essential` criterion is `pass`; non-essential criteria may remain pending. Final aggregate goal: confirm every criterion across the whole plan is `pass`.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`.+3. Run `omo ulw-loop checkpoint --goal-id <id> --status complete --evidence "<criteria evidence summary>" --codex-goal-json <snapshot> --json`; on success it auto-starts and prints the next eligible goal unless `--no-advance` is passed.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`.@@ -219,7 +219,9 @@ Use steering only for structured evidence-backed mutation. Reject natural-langua| 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`.+Command form: `omo ulw-loop steer --kind <kind> [<kind-specific-fields>] --evidence "<...>" --rationale "<...>" --json`. For multiple evidence-backed plan-shape changes discovered together, pass `--proposals-json <json-or-path>` with an array of proposals; the batch applies atomically or rejects without partial plan mutation.++Validation batches are optional aggregate-mode review boundaries declared at create time with `--validation-batch-json`. A batch-final member requires all other members resolved, all member criteria pass, and a member-spanning quality gate; split/supersede steering keeps batch membership updated.Structured prompt directives accepted: `OMO_ULW_LOOP_STEER: { ... }`, `omo.ulw-loop.steer: {...}`, `omo ulw-loop steer: {...}`.## Constraintsdiff --git a/plugins/omo/components/ulw-loop/src/checkpoint-continuation.ts b/plugins/omo/components/ulw-loop/src/checkpoint-continuation.tsnew file mode 100644index 00000000..9a8cef49--- /dev/null+++ b/plugins/omo/components/ulw-loop/src/checkpoint-continuation.ts@@ -0,0 +1,84 @@+import { type CheckpointUlwLoopArgs, type CheckpointUlwLoopResult, checkpointUlwLoop } from "./checkpoint.js";+import { hasFlag, parseCodexGoalJson, readValue } from "./cli-arg-parser.js";+import { blockedDecisionHandoff, printJson } from "./cli-output.js";+import { buildCodexGoalInstruction, type UlwLoopGoalInstruction } from "./codex-goal-instruction.js";+import type { UlwLoopScope } from "./paths.js";+import { startNextUlwLoop, summarizeUlwLoopPlan } from "./plan-crud.js";+import type { UlwLoopItem, UlwLoopPlan } from "./types.js";+import { UlwLoopError } from "./types.js";++type ContinuationNext =+ | { readonly resumed: boolean; readonly goal: UlwLoopItem; readonly instruction: UlwLoopGoalInstruction }+ | { readonly done: true; readonly blocked: boolean; readonly handoff: string };++export type CheckpointAndContinueResult = CheckpointUlwLoopResult & { readonly next?: ContinuationNext };++export async function checkpointAndContinue(+ repoRoot: string,+ args: CheckpointUlwLoopArgs & { readonly advance: boolean },+ scope?: UlwLoopScope,+): Promise<CheckpointAndContinueResult> {+ const result = await checkpointUlwLoop(repoRoot, args, scope);+ if (args.status !== "complete" || result.aggregateCompletion !== undefined || !args.advance) return result;+ const next = await startNextUlwLoop(repoRoot, {}, scope);+ if ("done" in next) return { ...result, plan: next.plan, next: doneNext(next.plan) };+ const instruction = buildCodexGoalInstruction({ plan: next.plan, goal: next.goal });+ return { ...result, plan: next.plan, next: { resumed: next.resumed, goal: next.goal, instruction } };+}++export 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 & { readonly advance: boolean } = {+ goalId,+ status: statusValue,+ evidence,+ advance: !hasFlag(argv, "--no-advance"),+ ...(codexGoalJson === undefined ? {} : { codexGoalJson }),+ ...(qualityGateJson === undefined ? {} : { qualityGateJson }),+ };+ const result = await checkpointAndContinue(repoRoot, args, scope);+ if (json) printJson({ ok: true, ...result, summary: summarizeUlwLoopPlan(result.plan) });+ else printCheckpointText(result);+ return 0;+}++function printCheckpointText(result: CheckpointAndContinueResult): void {+ process.stdout.write(`ulw-loop checkpoint: ${result.goal.id} -> ${result.goal.status}\n`);+ if (result.next === undefined) return;+ if ("instruction" in result.next) process.stdout.write(`${result.next.instruction.text}\n`);+ else process.stdout.write(`${result.next.handoff || "ulw-loop: all goals complete"}\n`);+}++function doneNext(plan: UlwLoopPlan): ContinuationNext {+ const handoff = blockedDecisionHandoff(plan);+ return { done: true, blocked: handoff.length > 0, handoff };+}++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): CheckpointUlwLoopArgs["status"] {+ 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 } },+ );+}diff --git a/plugins/omo/components/ulw-loop/src/checkpoint.ts b/plugins/omo/components/ulw-loop/src/checkpoint.tsindex ebc68688..3f7023b2 100644--- a/plugins/omo/components/ulw-loop/src/checkpoint.ts+++ b/plugins/omo/components/ulw-loop/src/checkpoint.ts@@ -1,4 +1,4 @@-import { ulwLoopAttemptEvidenceDir } from "./paths.js";+// biome-ignore-all format: checkpoint stays under the pure LOC ceiling.import { existsSync, statSync } from "node:fs";import { readFile } from "node:fs/promises";import { resolve } from "node:path";@@ -20,6 +20,7 @@ import {isFinalRunCompletionCandidate,} from "./goal-status.js";import type { UlwLoopScope } from "./paths.js";+import { ulwLoopAttemptEvidenceDir } from "./paths.js";import { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";import {classifyExternalAuthorizationBlocker,@@ -35,6 +36,7 @@ import type {UlwLoopQualityGate,} from "./types.js";import { iso, UlwLoopError } from "./types.js";+import { batchClosedBy, requireAllValidationBatchesClosed, requireBatchFinalReady, requireBatchGate } from "./validation-batch.js";export interface CheckpointUlwLoopArgs {readonly goalId: string;@@ -169,9 +171,11 @@ export async function checkpointUlwLoop(if (args.status === "complete") {const aggregate = codexGoalMode(plan) === "aggregate";const final = isFinalRunCompletionCandidate(plan, goal);+ const closesBatch = batchClosedBy(plan, goal.id) !== undefined;if (final) {requireAllCriteriaPass(goal);requireAllPlanCriteriaPass(plan);+ requireAllValidationBatchesClosed(plan, goal.id);} else if (aggregate) requireEssentialCriteriaPass(goal);else requireAllCriteriaPass(goal);const snapshot = await readCodexGoalSnapshotInput(args.codexGoalJson, repoRoot);@@ -218,8 +222,11 @@ export async function checkpointUlwLoop("ulw_loop_codex_snapshot_mismatch",);}+ if (closesBatch) requireBatchFinalReady(plan, goal);+ if (closesBatch && args.qualityGateJson === undefined)+ throw new UlwLoopError("Validation batch final checkpoint requires --quality-gate-json.", "ULW_LOOP_VALIDATION_BATCH_GATE_REQUIRED");if (final) aggregateCompletion = makeAggregateCompletion(now, evidence, codexGoal);- if (final || aggregateCompletion !== undefined)+ if (final || aggregateCompletion !== undefined || closesBatch) {qualityGate = validateQualityGate(await readJsonInput(args.qualityGateJson, repoRoot), {repoRoot,fs: QUALITY_GATE_FS,@@ -227,6 +234,8 @@ export async function checkpointUlwLoop(? { currentAttemptDir: ulwLoopAttemptEvidenceDir(goal.id, goal.attempt, scope) }: {}),});+ requireBatchGate(plan, goal, qualityGate);+ }goal.status = "complete";goal.completedAt = now;goal.evidence = evidence;@@ -241,6 +250,8 @@ export async function checkpointUlwLoop(await writePlan(repoRoot, plan, scope);const ledgerEntry = buildLedger(now, args, goal, qualityGate, codexGoal, aggregateCompletion);await appendLedger(repoRoot, ledgerEntry, scope);+ const closedBatch = args.status === "complete" ? batchClosedBy(plan, goal.id) : undefined;+ if (closedBatch !== undefined) await appendLedger(repoRoot, { at: now, kind: "batch_closed", goalId: goal.id, message: closedBatch.batchId }, scope);return aggregateCompletion === undefined? { plan, goal, ledgerEntry }: { plan, goal, ledgerEntry, aggregateCompletion };diff --git a/plugins/omo/components/ulw-loop/src/cli-arg-parser.ts b/plugins/omo/components/ulw-loop/src/cli-arg-parser.tsindex ebd2a794..d00ee858 100644--- a/plugins/omo/components/ulw-loop/src/cli-arg-parser.ts+++ b/plugins/omo/components/ulw-loop/src/cli-arg-parser.ts@@ -5,7 +5,7 @@ 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 --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 VALUE_FLAGS = new Set("--brief --brief-file --session-id --codex-goal-mode --validation-batch-json --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 --proposals-json".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); }diff --git a/plugins/omo/components/ulw-loop/src/cli-commands.ts b/plugins/omo/components/ulw-loop/src/cli-commands.tsindex c43bd191..da0e0b61 100644--- a/plugins/omo/components/ulw-loop/src/cli-commands.ts+++ b/plugins/omo/components/ulw-loop/src/cli-commands.ts@@ -1,9 +1,9 @@+import { checkpoint } from "./checkpoint-continuation.js";import { hasFlag, readValue } from "./cli-arg-parser.js";import { printJsonError, ULW_LOOP_HELP } from "./cli-output.js";import {addGoal,captureEvidence,- checkpoint,completeGoals,createGoals,criteria,diff --git a/plugins/omo/components/ulw-loop/src/cli-output.ts b/plugins/omo/components/ulw-loop/src/cli-output.tsindex a221b289..526885be 100644--- a/plugins/omo/components/ulw-loop/src/cli-output.ts+++ b/plugins/omo/components/ulw-loop/src/cli-output.ts@@ -2,13 +2,13 @@ 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 create-goals --brief "..." [--brief-file <path>] [--from-stdin] [--codex-goal-mode aggregate|per_story] [--validation-batch-json <json-or-path>] [--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 checkpoint --goal-id <id> --status complete|failed|blocked --evidence "..." --codex-goal-json <...> [--quality-gate-json <...>] [--no-advance] [--json]+ omo ulw-loop steer --kind <kind> ... --evidence "..." --rationale "..." [--proposals-json <json-or-path>] [--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]diff --git a/plugins/omo/components/ulw-loop/src/cli-steering.ts b/plugins/omo/components/ulw-loop/src/cli-steering.tsindex 6b2d8eb8..933f40c3 100644--- a/plugins/omo/components/ulw-loop/src/cli-steering.ts+++ b/plugins/omo/components/ulw-loop/src/cli-steering.ts@@ -1,6 +1,7 @@// 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 { SteerUlwLoopBatchResult } from "./steering-batch.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";@@ -31,6 +32,10 @@ function requiredGoal(argv: readonly string[]): string { const value = text(parsfunction 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; }+function objectStrings(value: object, key: string): string[] | undefined { const candidate = readObject(value, key); return Array.isArray(candidate) && candidate.every((item) => typeof item === "string") ? candidate : undefined; }+function objectChildren(value: object, key: string): UlwLoopSteeringChildGoal[] | undefined { const candidate = readObject(value, key); if (!Array.isArray(candidate)) return undefined; const parsed: UlwLoopSteeringChildGoal[] = []; for (const item of candidate) { const next = child(item); if (next === null) return fail(`${key} entries require title/objective.`, "ULW_LOOP_STEERING_CHILD_INVALID", { key }); parsed.push(next); } return parsed; }+function isProposalKind(value: unknown): value is UlwLoopSteeringMutationKind { return typeof value === "string" && ULW_LOOP_STEERING_MUTATION_KINDS.some((kind) => kind === value); }+function isProposalSource(value: unknown): value is UlwLoopSteeringSource { return typeof value === "string" && SOURCES.some((source) => source === value); }export function parseSteeringKind(argv: readonly string[]): UlwLoopSteeringMutationKind {const value = readValue(argv, "--kind");@@ -98,6 +103,43 @@ 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 async function parseSteeringProposals(argv: readonly string[]): Promise<readonly CliSteeringProposal[]> {+ const input = text(readValue(argv, "--proposals-json"), "--proposals-json");+ if (input === undefined) return [await parseSteeringProposal(argv)];+ if (readValue(argv, "--kind") !== undefined) return fail("--kind and --proposals-json are mutually exclusive.", "ULW_LOOP_STEERING_BATCH_CONFLICT", { flags: ["--kind", "--proposals-json"] });+ const raw = await readJsonInput(input);+ if (!Array.isArray(raw) || raw.length === 0) return fail("--proposals-json must be a non-empty JSON array.", "ULW_LOOP_STEERING_BATCH_ARRAY_REQUIRED", { flag: "--proposals-json" });+ const proposals: CliSteeringProposal[] = [];+ for (const item of raw) proposals.push(normalizeSteeringProposal(proposalFromObject(item)));+ return proposals;+}++function proposalFromObject(value: unknown): CliSteeringProposal {+ if (!isPlain(value)) return fail("--proposals-json entries must be objects.", "ULW_LOOP_STEERING_BATCH_ITEM_INVALID", { flag: "--proposals-json" });+ const kind = readObject(value, "kind"); const source = readObject(value, "source") ?? "cli";+ if (!isProposalKind(kind)) return fail(`Invalid batch steering kind: ${String(kind)}.`, "ULW_LOOP_STEERING_KIND_INVALID", { value: kind });+ if (!isProposalSource(source)) return fail(`Invalid batch steering source: ${String(source)}.`, "ULW_LOOP_STEERING_SOURCE_INVALID", { value: source });+ let proposal: CliSteeringProposal = { kind, source, evidence: objectText(value, "evidence") ?? "", rationale: objectText(value, "rationale") ?? "" };+ const goalId = objectText(value, "goalId"); const targetGoalId = objectText(value, "targetGoalId"); const criterionId = objectText(value, "criterionId");+ const title = objectText(value, "title"); const objective = objectText(value, "objective"); const revisedTitle = objectText(value, "revisedTitle"); const revisedObjective = objectText(value, "revisedObjective");+ const scenario = objectText(value, "scenario"); const expectedEvidence = objectText(value, "expectedEvidence"); const idempotencyKey = objectText(value, "idempotencyKey");+ const targetGoalIds = objectStrings(value, "targetGoalIds"); const pendingOrder = objectStrings(value, "pendingOrder"); const childGoals = objectChildren(value, "childGoals");+ if (goalId !== undefined) proposal = { ...proposal, goalId };+ if (targetGoalId !== undefined) proposal = { ...proposal, targetGoalId };+ if (criterionId !== undefined) proposal = { ...proposal, criterionId };+ if (title !== undefined) proposal = { ...proposal, title };+ if (objective !== undefined) proposal = { ...proposal, objective };+ if (revisedTitle !== undefined) proposal = { ...proposal, revisedTitle };+ if (revisedObjective !== undefined) proposal = { ...proposal, revisedObjective };+ if (scenario !== undefined) proposal = { ...proposal, scenario };+ if (expectedEvidence !== undefined) proposal = { ...proposal, expectedEvidence };+ if (idempotencyKey !== undefined) proposal = { ...proposal, idempotencyKey };+ if (targetGoalIds !== undefined) proposal = { ...proposal, targetGoalIds };+ if (pendingOrder !== undefined) proposal = { ...proposal, pendingOrder };+ if (childGoals !== undefined) proposal = { ...proposal, childGoals };+ return proposal;+}+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";@@ -106,3 +148,10 @@ export function printSteerResult(result: SteerUlwLoopResult, json: boolean): voiif (result.audit.idempotencyKey !== undefined) process.stdout.write(`idempotency-key: ${result.audit.idempotencyKey}\n`);printStatus(result.plan);}++export function printSteerBatchResult(result: SteerUlwLoopBatchResult, json: boolean): void {+ if (json) { printJson({ ok: result.accepted, accepted: result.accepted, rejectedReasons: result.rejectedReasons, results: result.results, plan: result.plan }); return; }+ process.stdout.write(`ulw-loop steer batch: ${result.accepted ? "accepted" : "rejected"} ${result.results.length} proposal(s)\n`);+ if (result.rejectedReasons.length > 0) process.stdout.write(`rejected: ${result.rejectedReasons.join("; ")}\n`);+ printStatus(result.plan);+}diff --git a/plugins/omo/components/ulw-loop/src/cli-subcommands.ts b/plugins/omo/components/ulw-loop/src/cli-subcommands.tsindex 962c8aff..525d3501 100644--- a/plugins/omo/components/ulw-loop/src/cli-subcommands.ts+++ b/plugins/omo/components/ulw-loop/src/cli-subcommands.ts@@ -1,6 +1,5 @@import { readFile } from "node:fs/promises";-import { type CheckpointUlwLoopArgs, checkpointUlwLoop } from "./checkpoint.js";import {hasFlag,parseCodexGoalJson,@@ -10,7 +9,7 @@ import {readValue,} from "./cli-arg-parser.js";import { blockedDecisionHandoff, normalizeCodexGoalMode, printJson, printStatus } from "./cli-output.js";-import { parseSteeringProposal, printSteerResult } from "./cli-steering.js";+import { parseSteeringProposals, printSteerBatchResult, printSteerResult } from "./cli-steering.js";import { buildCodexGoalInstruction } from "./codex-goal-instruction.js";import { recordEvidence } from "./evidence.js";import { isEssentialCriterion } from "./goal-status.js";@@ -19,11 +18,10 @@ import { addUlwLoopGoal, createUlwLoopPlan, startNextUlwLoop, summarizeUlwLoopPlimport { readUlwLoopPlan } from "./plan-io.js";import { recordFinalReviewBlockers } from "./review-blockers.js";import { steerUlwLoop } from "./steering.js";+import { steerUlwLoopBatch } from "./steering-batch.js";import type { UlwLoopItem } from "./types.js";import { UlwLoopError } from "./types.js";-type CheckpointStatus = "complete" | "failed" | "blocked";-export async function createGoals(repoRoot: string,argv: readonly string[],@@ -42,12 +40,14 @@ export async function createGoals("ULW_LOOP_BRIEF_REQUIRED",);}+ const validationBatchesJson = readValue(argv, "--validation-batch-json");const plan = await createUlwLoopPlan(repoRoot,{brief,codexGoalMode: normalizeCodexGoalMode(readValue(argv, "--codex-goal-mode")),force: hasFlag(argv, "--force"),+ ...(validationBatchesJson === undefined ? {} : { validationBatchesJson }),},scope,);@@ -105,44 +105,21 @@ export async function completeGoals(return 0;}-export 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;-}-export 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);+ const proposals = await parseSteeringProposals(argv);+ const single = proposals[0];+ if (single !== undefined && proposals.length === 1 && readValue(argv, "--proposals-json") === undefined) {+ const result = await steerUlwLoop(repoRoot, single, scope);+ printSteerResult(result, json);+ return result.accepted ? 0 : 1;+ }+ const result = await steerUlwLoopBatch(repoRoot, proposals, scope);+ printSteerBatchResult(result, json);return result.accepted ? 0 : 1;}@@ -245,15 +222,6 @@ function required(argv: readonly string[], flag: string): string {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;diff --git a/plugins/omo/components/ulw-loop/src/codex-goal-instruction.ts b/plugins/omo/components/ulw-loop/src/codex-goal-instruction.tsindex 26af4c98..ddb06288 100644--- a/plugins/omo/components/ulw-loop/src/codex-goal-instruction.ts+++ b/plugins/omo/components/ulw-loop/src/codex-goal-instruction.ts@@ -1,3 +1,4 @@+// biome-ignore-all format: long agent-facing instruction strings are intentionally stable.import {codexGoalMode,expectedCodexObjective,diff --git a/plugins/omo/components/ulw-loop/src/constants.ts b/plugins/omo/components/ulw-loop/src/constants.tsindex 5148f9a8..4dbea493 100644--- a/plugins/omo/components/ulw-loop/src/constants.ts+++ b/plugins/omo/components/ulw-loop/src/constants.ts@@ -60,5 +60,7 @@ export const ULW_LOOP_LEDGER_EVENT_KINDS = ["criterion_failed","criterion_blocked","criteria_revised",+ "batch_closed",+ "batch_updated",] as const satisfies readonly string[];export type UlwLoopLedgerEventKind = (typeof ULW_LOOP_LEDGER_EVENT_KINDS)[number];diff --git a/plugins/omo/components/ulw-loop/src/domain-types.ts b/plugins/omo/components/ulw-loop/src/domain-types.tsindex 59aff7a9..504f223c 100644--- a/plugins/omo/components/ulw-loop/src/domain-types.ts+++ b/plugins/omo/components/ulw-loop/src/domain-types.ts@@ -55,6 +55,12 @@ export interface UlwLoopAggregateCompletion {codexGoal?: unknown;}+export interface UlwLoopValidationBatch {+ readonly batchId: string;+ readonly memberIds: readonly string[];+ readonly finalGoalId: string;+}+export interface UlwLoopPlan {version: 1;evidenceLayoutVersion?: 2;@@ -68,6 +74,7 @@ export interface UlwLoopPlan {codexObjectiveAliases?: string[];aggregateCompletion?: UlwLoopAggregateCompletion;activeGoalId?: string;+ validationBatches?: readonly UlwLoopValidationBatch[];goals: UlwLoopItem[];}diff --git a/plugins/omo/components/ulw-loop/src/goal-status.ts b/plugins/omo/components/ulw-loop/src/goal-status.tsindex 27923df4..e6b64ff3 100644--- a/plugins/omo/components/ulw-loop/src/goal-status.ts+++ b/plugins/omo/components/ulw-loop/src/goal-status.ts@@ -21,6 +21,10 @@ function isResolvedStatus(status: UlwLoopStatus): boolean {return status === "complete";}+export function isMemberResolved(goal: UlwLoopItem, plan: UlwLoopPlan): boolean {+ return isResolvedStatus(goal.status) || isSupersededResolved(goal, plan);+}+function isSupersededResolved(goal: UlwLoopItem, plan: UlwLoopPlan): boolean {if (goal.steeringStatus !== "superseded") return false;const replacements = goal.supersededBy ?? [];diff --git a/plugins/omo/components/ulw-loop/src/plan-crud.ts b/plugins/omo/components/ulw-loop/src/plan-crud.tsindex c1ded74a..a03d7e2b 100644--- a/plugins/omo/components/ulw-loop/src/plan-crud.ts+++ b/plugins/omo/components/ulw-loop/src/plan-crud.ts@@ -16,6 +16,7 @@ import { appendGoalToPlan, deriveGoalCandidates, makeGoal } from "./plan-goal-faimport { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";import type { UlwLoopCodexGoalMode, UlwLoopItem, UlwLoopPlan, UlwLoopSuccessCriterion } from "./types.js";import { iso, UlwLoopError } from "./types.js";+import { parseValidationBatches } from "./validation-batch.js";export { deriveGoalCandidates, seedDefaultSuccessCriteria } from "./plan-goal-factory.js";@@ -57,7 +58,7 @@ function clearGoalBlockerFields(goal: UlwLoopItem): void {export async function createUlwLoopPlan(repoRoot: string,- args: { brief: string; codexGoalMode?: UlwLoopCodexGoalMode; force?: boolean },+ args: { brief: string; codexGoalMode?: UlwLoopCodexGoalMode; force?: boolean; validationBatchesJson?: string },scope?: UlwLoopScope,): Promise<UlwLoopPlan> {return withUlwLoopMutationLock(repoRoot, scope, async () => {@@ -84,6 +85,8 @@ export async function createUlwLoopPlan(codexGoalMode: args.codexGoalMode ?? "aggregate",goals,};+ const validationBatches = await parseValidationBatches(args.validationBatchesJson, goals);+ if (validationBatches !== undefined) plan.validationBatches = validationBatches;if (plan.codexGoalMode === "aggregate") plan.codexObjective = aggregateCodexObjectiveForScope(scope);await mkdir(ulwLoopDir(repoRoot, scope), { recursive: true });await writeFile(diff --git a/plugins/omo/components/ulw-loop/src/plan-io.ts b/plugins/omo/components/ulw-loop/src/plan-io.tsindex 0214296b..7c96cd77 100644--- a/plugins/omo/components/ulw-loop/src/plan-io.ts+++ b/plugins/omo/components/ulw-loop/src/plan-io.ts@@ -27,7 +27,12 @@ function isLegacyEnumeratedAggregateObjective(objective: string | undefined): ob}function isSteeringKind(value: unknown): value is UlwLoopLedgerEntry["kind"] {- return value === "steering_accepted" || value === "steering_rejected" || value === "criteria_revised";+ return (+ value === "steering_accepted" ||+ value === "steering_rejected" ||+ value === "criteria_revised" ||+ value === "batch_updated"+ );}export async function withUlwLoopMutationLock<T>(repoRoot: string, fn: () => Promise<T>): Promise<T>;@@ -112,8 +117,21 @@ export async function writePlan(repoRoot: string, plan: UlwLoopPlan, scope?: Ulw}export async function appendLedger(repoRoot: string, entry: UlwLoopLedgerEntry, scope?: UlwLoopScope): Promise<void> {+ await appendLedgerEntries(repoRoot, [entry], scope);+}++export async function appendLedgerEntries(+ repoRoot: string,+ entries: readonly UlwLoopLedgerEntry[],+ scope?: UlwLoopScope,+): Promise<void> {+ if (entries.length === 0) return;await mkdir(ulwLoopDir(repoRoot, scope), { recursive: true });- await appendFile(ulwLoopLedgerPath(repoRoot, scope), `${JSON.stringify(entry)}\n`, "utf8");+ await appendFile(+ ulwLoopLedgerPath(repoRoot, scope),+ `${entries.map((entry) => JSON.stringify(entry)).join("\n")}\n`,+ "utf8",+ );}/**diff --git a/plugins/omo/components/ulw-loop/src/quality-gate-verdicts.ts b/plugins/omo/components/ulw-loop/src/quality-gate-verdicts.tsindex 191d2a3c..ed12f9b4 100644--- a/plugins/omo/components/ulw-loop/src/quality-gate-verdicts.ts+++ b/plugins/omo/components/ulw-loop/src/quality-gate-verdicts.ts@@ -1,4 +1,4 @@-import { literal, invalid, textField } from "./quality-gate-fields.js";+import { invalid, literal, textField } from "./quality-gate-fields.js";export function passedVerdict(value: unknown, field: string): "passed" {if (value === "not_applicable") invalid(`${field} must not be not_applicable.`, field);diff --git a/plugins/omo/components/ulw-loop/src/steering-batch.ts b/plugins/omo/components/ulw-loop/src/steering-batch.tsnew file mode 100644index 00000000..1711da36--- /dev/null+++ b/plugins/omo/components/ulw-loop/src/steering-batch.ts@@ -0,0 +1,125 @@+// biome-ignore-all format: compact batch steering module stays below the pure LOC budget.+import type { UlwLoopScope } from "./paths.js";+import { appendLedger, appendLedgerEntries, findAcceptedSteeringLedgerEntry, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";+import { applySteeringMutation, validateUlwLoopSteeringProposal } from "./steering.js";+import { buildSteeringPlanSnapshot, changedGoalIdsBetween } from "./steering-snapshot.js";+import type { UlwLoopLedgerEntry, UlwLoopPlan, UlwLoopSteeringAudit, UlwLoopSteeringProposal } from "./types.js";+import { iso } from "./types.js";+import { batchUpdateLedgerEntry } from "./validation-batch.js";++export interface SteerUlwLoopBatchItemResult {+ readonly accepted: boolean;+ readonly deduped: boolean;+ readonly audit: UlwLoopSteeringAudit;+ readonly rejectedReasons: readonly string[];+}++export interface SteerUlwLoopBatchResult {+ readonly plan: UlwLoopPlan;+ readonly accepted: boolean;+ readonly results: readonly SteerUlwLoopBatchItemResult[];+ readonly rejectedReasons: readonly string[];+}++type PreparedFresh = {+ readonly proposal: UlwLoopSteeringProposal;+ readonly audit: UlwLoopSteeringAudit;+ readonly before: UlwLoopPlan;+ readonly next: UlwLoopPlan;+};++type PreparedItem =+ | { readonly kind: "deduped"; readonly result: SteerUlwLoopBatchItemResult }+ | { readonly kind: "fresh"; readonly prepared: PreparedFresh };++export async function steerUlwLoopBatch(+ repoRoot: string,+ proposals: readonly UlwLoopSteeringProposal[],+ scope?: UlwLoopScope,+): Promise<SteerUlwLoopBatchResult> {+ return withUlwLoopMutationLock(repoRoot, scope, async () => {+ const plan = await readUlwLoopPlan(repoRoot, scope);+ const prepared = await prepareBatch(repoRoot, plan, proposals, scope);+ const failed = prepared.results.find((item) => !item.accepted);+ if (failed !== undefined) {+ const entry = rejectedLedgerEntry(prepared.results);+ await appendLedger(repoRoot, entry, scope);+ return rejected(plan, prepared.results, failed.rejectedReasons);+ }+ let next = plan;+ for (const item of prepared.items) if (item.kind === "fresh") next = item.prepared.next;+ const fresh = prepared.items.filter((item): item is Extract<PreparedItem, { readonly kind: "fresh" }> => item.kind === "fresh");+ if (fresh.length > 0) {+ await writePlan(repoRoot, next, scope);+ const entries = fresh.map((item) => ledgerEntry(item.prepared.proposal, item.prepared.audit, item.prepared.proposal.now?.toISOString() ?? iso()));+ const batchEntry = batchUpdateLedgerEntry(plan, next, iso());+ await appendLedgerEntries(repoRoot, batchEntry === null ? entries : [...entries, batchEntry], scope);+ }+ return { plan: next, accepted: true, results: prepared.results, rejectedReasons: [] };+ });+}++async function prepareBatch(+ repoRoot: string,+ plan: UlwLoopPlan,+ proposals: readonly UlwLoopSteeringProposal[],+ scope: UlwLoopScope | undefined,+): Promise<{ readonly items: readonly PreparedItem[]; readonly results: readonly SteerUlwLoopBatchItemResult[] }> {+ const items: PreparedItem[] = [];+ const results: SteerUlwLoopBatchItemResult[] = [];+ let current = plan;+ for (const proposal of proposals) {+ const key = proposal.idempotencyKey ?? proposal.promptSignature;+ const prior = key === undefined ? undefined : await findAcceptedSteeringLedgerEntry(repoRoot, key, scope);+ if (prior?.steering !== undefined) {+ const result = { accepted: true, deduped: true, audit: { ...prior.steering, deduped: true }, rejectedReasons: [] };+ items.push({ kind: "deduped", result });+ results.push(result);+ continue;+ }+ const audit = validateUlwLoopSteeringProposal(current, proposal);+ if (!audit.invariant.accepted) {+ const result = { accepted: false, deduped: false, audit, rejectedReasons: audit.invariant.rejectedReasons };+ items.push({ kind: "deduped", result });+ results.push(result);+ continue;+ }+ const next = applySteeringMutation(current, proposal, audit);+ const changed = changedGoalIdsBetween(current, next);+ const finalAudit = { ...audit, before: buildSteeringPlanSnapshot(current, changed), after: buildSteeringPlanSnapshot(next, changed) };+ const result = { accepted: true, deduped: false, audit: finalAudit, rejectedReasons: [] };+ items.push({ kind: "fresh", prepared: { proposal, audit: finalAudit, before: current, next } });+ results.push(result);+ current = next;+ }+ return { items, results };+}++function rejected(+ plan: UlwLoopPlan,+ results: readonly SteerUlwLoopBatchItemResult[],+ rejectedReasons: readonly string[],+): SteerUlwLoopBatchResult {+ return { plan, accepted: false, results, rejectedReasons };+}++function rejectedLedgerEntry(results: readonly SteerUlwLoopBatchItemResult[]): UlwLoopLedgerEntry {+ const rejectedItems = results.map((result, index) => ({ result, index })).filter((item) => !item.result.accepted);+ return { at: iso(), kind: "steering_rejected", message: rejectedItems.map((item) => `index ${item.index}: ${item.result.rejectedReasons.join(", ")}`).join("; ") };+}++function ledgerEntry(proposal: UlwLoopSteeringProposal, audit: UlwLoopSteeringAudit, at: string): UlwLoopLedgerEntry {+ const entry: UlwLoopLedgerEntry = {+ at,+ kind: proposal.kind === "revise_criterion" ? "criteria_revised" : "steering_accepted",+ evidence: proposal.evidence,+ message: proposal.rationale,+ steering: audit,+ mutationKind: proposal.kind,+ };+ const goalId = audit.targetGoalIds[0];+ if (goalId !== undefined) entry.goalId = goalId;+ if (proposal.criterionId !== undefined) entry.criterionId = proposal.criterionId;+ if (proposal.idempotencyKey !== undefined) entry.idempotencyKey = proposal.idempotencyKey;+ return entry;+}diff --git a/plugins/omo/components/ulw-loop/src/steering-mutations.ts b/plugins/omo/components/ulw-loop/src/steering-mutations.tsnew file mode 100644index 00000000..738ff199--- /dev/null+++ b/plugins/omo/components/ulw-loop/src/steering-mutations.ts@@ -0,0 +1,59 @@+// biome-ignore-all format: compact extracted steering mutations stay below the pure LOC budget.+import { seedDefaultSuccessCriteria } from "./plan-crud.js";+import type { UlwLoopItem, UlwLoopPlan, UlwLoopSteeringChildGoal, UlwLoopSteeringProposal, UlwLoopSuccessCriterionUserModel } from "./types.js";+import { ULW_LOOP_SUCCESS_CRITERION_USER_MODELS } from "./types.js";+import { updateBatchesAfterSupersede } from "./validation-batch.js";++const read = (value: object, key: string): unknown => Object.entries(value).find(([name]) => name === key)?.[1];+const isText = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0;+const text = (value: object, key: string): string | undefined => { const candidate = read(value, key); return isText(candidate) ? candidate.trim() : undefined; };+const isModel = (value: unknown): value is UlwLoopSuccessCriterionUserModel => typeof value === "string" && ULW_LOOP_SUCCESS_CRITERION_USER_MODELS.some((model) => model === value);+const after = (proposal: object): object | undefined => { const candidate = read(proposal, "after"); return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate) ? candidate : undefined; };+const revised = (proposal: object, direct: string, nested: string): string | undefined => text(proposal, direct) ?? text(after(proposal) ?? proposal, nested);+const targets = (proposal: UlwLoopSteeringProposal): string[] => proposal.targetGoalIds ?? [proposal.targetGoalId ?? text(proposal, "goalId") ?? ""].filter(Boolean);+const child = (value: unknown): UlwLoopSteeringChildGoal | null => {+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;+ const title = text(value, "title"); const objective = text(value, "objective");+ return title === undefined || objective === undefined ? null : { title, objective };+};+const children = (proposal: UlwLoopSteeringProposal): UlwLoopSteeringChildGoal[] => {+ const direct = proposal.childGoals;+ if (direct !== undefined && direct.length > 0) return direct;+ const nested = after(proposal);+ const fromAfter = nested === undefined ? undefined : read(nested, "children");+ return Array.isArray(fromAfter) ? fromAfter.map(child).filter((item): item is UlwLoopSteeringChildGoal => item !== null) : [];+};+const goal = (plan: UlwLoopPlan, id: string | undefined): UlwLoopItem | undefined => id === undefined ? undefined : plan.goals.find((item) => item.id === id);++function nextId(plan: UlwLoopPlan, offset: number): string {+ const max = plan.goals.reduce((current, item) => { const digits = /^G(\d+)(?:-|$)/u.exec(item.id)?.[1]; return digits === undefined ? current : Math.max(current, Number(digits)); }, 0);+ return `G${String(max + offset).padStart(3, "0")}`;+}++export 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 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; target.objective = revised(proposal, "revisedObjective", "objective") ?? target.objective;+ target.steeringEvidence = proposal.evidence; target.steeringRationale = proposal.rationale; target.updatedAt = now;+}++export 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));+ target.steeringEvidence = proposal.evidence; target.steeringRationale = proposal.rationale; target.updatedAt = now;+ if (replacements.length === 0) { target.status = "blocked"; target.steeringStatus = "blocked"; target.blockedReason = proposal.blockedReason ?? proposal.rationale; }+ else { target.steeringStatus = "superseded"; target.supersededBy = replacements.map((item) => item.id); for (const item of replacements) item.supersedes = [target.id]; plan.goals.splice(plan.goals.indexOf(target) + 1, 0, ...replacements); updateBatchesAfterSupersede(plan, target.id, replacements.map((item) => item.id)); }+ if (plan.activeGoalId === target.id) delete plan.activeGoalId;+}++export 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];+ if (target === undefined || current === undefined) return;+ const model = read(proposal, "userModel");+ target.successCriteria[index] = { ...current, scenario: text(proposal, "scenario") ?? current.scenario, expectedEvidence: text(proposal, "expectedEvidence") ?? current.expectedEvidence, userModel: isModel(model) ? model : current.userModel };+ target.updatedAt = now;+}diff --git a/plugins/omo/components/ulw-loop/src/steering.ts b/plugins/omo/components/ulw-loop/src/steering.tsindex 11f459d5..4ad9315a 100644--- a/plugins/omo/components/ulw-loop/src/steering.ts+++ b/plugins/omo/components/ulw-loop/src/steering.ts@@ -1,8 +1,8 @@// biome-ignore-all format: compact steering module must stay below the 240 pure-LOC budgetimport { isUlwLoopDone } from "./goal-status.js";import type { UlwLoopScope } from "./paths.js";-import { seedDefaultSuccessCriteria } from "./plan-crud.js";import { appendLedger, findAcceptedSteeringLedgerEntry, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";+import { makeGoal, reviseCriterion, reviseWording, splitOrBlock } from "./steering-mutations.js";import { buildSteeringPlanSnapshot, changedGoalIdsBetween } from "./steering-snapshot.js";import type {SteerUlwLoopResult,@@ -17,6 +17,7 @@ import type {UlwLoopSuccessCriterionUserModel,} from "./types.js";import { iso, ULW_LOOP_STEERING_MUTATION_KINDS, ULW_LOOP_SUCCESS_CRITERION_USER_MODELS } from "./types.js";+import { batchUpdateLedgerEntry } from "./validation-batch.js";const SOURCES = ["user_prompt_submit", "finding", "cli"] as const satisfies readonly UlwLoopSteeringSource[];const PROTECTED = new Set(["aggregateCompletion", "codexObjective", "codexObjectiveAliases", "originalConstraints", "qualityGate", "status", "completedAt", "completionStatus"]);@@ -63,7 +64,6 @@ function childValues(proposal: object): unknown[] {return Array.isArray(fromAfter) ? fromAfter : [];}-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");@@ -155,21 +155,6 @@ function validateCriterion(plan: UlwLoopPlan, proposal: object, reasons: string[if (model !== undefined && !isModel(model)) reasons.push("invalid userModel");}-function nextId(plan: UlwLoopPlan, offset: number): string {- const max = plan.goals.reduce((current, item) => {- const digits = /^G(\d+)(?:-|$)/u.exec(item.id)?.[1];- return digits === undefined ? current : Math.max(current, Number(digits));- }, 0);- return `G${String(max + offset).padStart(3, "0")}`;-}--function makeGoal(plan: 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: UlwLoopPlan, proposal: UlwLoopSteeringProposal, audit: UlwLoopSteeringAudit): UlwLoopPlan {const next = structuredClone(plan);if (!audit.invariant.accepted) return next;@@ -186,46 +171,6 @@ export function applySteeringMutation(plan: UlwLoopPlan, proposal: UlwLoopSteerireturn next;}-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;- target.objective = revised(proposal, "revisedObjective", "objective") ?? target.objective;- target.steeringEvidence = proposal.evidence;- target.steeringRationale = proposal.rationale;- target.updatedAt = now;-}--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));- target.steeringEvidence = proposal.evidence;- target.steeringRationale = proposal.rationale;- target.updatedAt = now;- if (replacements.length === 0) {- target.status = "blocked";- target.steeringStatus = "blocked";- target.blockedReason = proposal.blockedReason ?? proposal.rationale;- } else {- target.steeringStatus = "superseded";- target.supersededBy = replacements.map((item) => item.id);- for (const item of replacements) item.supersedes = [target.id];- plan.goals.splice(plan.goals.indexOf(target) + 1, 0, ...replacements);- }- if (plan.activeGoalId === target.id) delete plan.activeGoalId;-}--function reviseCriterion(plan: 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];- if (target === undefined || current === undefined) return;- const model = read(proposal, "userModel");- target.successCriteria[index] = { ...current, scenario: text(proposal, "scenario") ?? current.scenario, expectedEvidence: text(proposal, "expectedEvidence") ?? current.expectedEvidence, userModel: isModel(model) ? model : current.userModel };- target.updatedAt = now;-}-function isProposal(value: unknown): value is UlwLoopSteeringProposal {return isPlain(value) && isKind(read(value, "kind")) && isSource(read(value, "source")) && isText(read(value, "evidence")) && isText(read(value, "rationale"));}@@ -262,8 +207,11 @@ export async function steerUlwLoop(repoRoot: string, proposal: UlwLoopSteeringPrfinalAudit.before = buildSteeringPlanSnapshot(plan, changed);finalAudit.after = buildSteeringPlanSnapshot(next, changed);}+ const at = proposal.now?.toISOString() ?? iso();+ const batchEntry = accepted ? batchUpdateLedgerEntry(plan, next, at) : null;if (accepted) await writePlan(repoRoot, next, scope);- await appendLedger(repoRoot, ledgerEntry(proposal, finalAudit, proposal.now?.toISOString() ?? iso()), scope);+ await appendLedger(repoRoot, ledgerEntry(proposal, finalAudit, at), scope);+ if (batchEntry !== null) await appendLedger(repoRoot, batchEntry, scope);return { plan: next, accepted, audit: finalAudit, rejectedReasons: audit.invariant.rejectedReasons, deduped: false };});}diff --git a/plugins/omo/components/ulw-loop/src/stop-resume-hook.ts b/plugins/omo/components/ulw-loop/src/stop-resume-hook.tsindex 289a1450..286e6707 100644--- a/plugins/omo/components/ulw-loop/src/stop-resume-hook.ts+++ b/plugins/omo/components/ulw-loop/src/stop-resume-hook.ts@@ -1,5 +1,5 @@import { existsSync, readFileSync, writeFileSync } from "node:fs";-import { isAbsolute, join } from "node:path";+import { isAbsolute, join, resolve, sep } from "node:path";import { normalizeUlwLoopSessionId, ulwLoopDir } from "./paths.js";import type { UlwLoopItem, UlwLoopPlan } from "./types.js";@@ -73,17 +73,25 @@ function isResumableStatus(status: UlwLoopItem["status"]): boolean {// a separate file — a ledger append would change the count and self-reset.function consumeResumeBudget(stateDir: string, goalId: string): boolean {const ledgerLineCount = countLedgerLines(join(stateDir, "ledger.jsonl"));- const counterPath = join(stateDir, `auto-resume-${goalId}.json`);+ const counterPath = resolve(stateDir, `auto-resume-${goalId}.json`);+ const stuckPath = resolve(stateDir, `auto-resume-${goalId}.stuck`);+ // goals.json is untrusted input: a crafted goal id (e.g. `../../x`) must+ // never drive a write outside the session state dir. Deny the resume.+ if (!isInsideDir(stateDir, counterPath) || !isInsideDir(stateDir, stuckPath)) return false;const previous = readCounter(counterPath);const count = previous !== null && previous.ledgerLineCount === ledgerLineCount ? previous.count : 0;if (count >= RESUME_CAP) {- writeFileSync(join(stateDir, `auto-resume-${goalId}.stuck`), `no ledger progress after ${count} resumes\n`);+ writeFileSync(stuckPath, `no ledger progress after ${count} resumes\n`);return false;}writeFileSync(counterPath, JSON.stringify({ count: count + 1, ledgerLineCount }));return true;}+function isInsideDir(dir: string, candidate: string): boolean {+ return candidate.startsWith(resolve(dir) + sep);+}+function renderResumeDirective(plan: UlwLoopPlan, goal: UlwLoopItem, sessionId: string): string {const normalized = normalizeUlwLoopSessionId(sessionId);const option =@@ -93,7 +101,7 @@ function renderResumeDirective(plan: UlwLoopPlan, goal: UlwLoopItem, sessionId:"The turn ended before the loop completed. Resume it now:",`1. Run \`omo ulw-loop status${option} --json\` to reload the plan, the active goal, and currentAttemptDir.`,"2. Continue the active goal's remaining success criteria, recording evidence with record-evidence.",- `3. Checkpoint through \`omo ulw-loop checkpoint${option}\` when the goal's criteria are proven.`,+ `3. Checkpoint through \`omo ulw-loop checkpoint${option}\` when the goal's criteria are proven; a complete checkpoint prints the next goal instruction.`,"If the loop is genuinely blocked on the user, checkpoint the goal as blocked with the reason instead.",].join("\n");}diff --git a/plugins/omo/components/ulw-loop/src/validation-batch.ts b/plugins/omo/components/ulw-loop/src/validation-batch.tsnew file mode 100644index 00000000..31117b5a--- /dev/null+++ b/plugins/omo/components/ulw-loop/src/validation-batch.ts@@ -0,0 +1,122 @@+// biome-ignore-all format: compact validation-batch helpers stay below the pure LOC budget.+import { readJsonInput } from "./cli-arg-parser.js";+import { isMemberResolved } from "./goal-status.js";+import type { UlwLoopItem, UlwLoopLedgerEntry, UlwLoopPlan, UlwLoopQualityGate, UlwLoopValidationBatch } from "./types.js";+import { UlwLoopError } from "./types.js";++function isObject(value: unknown): value is object {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function read(value: object, key: string): unknown {+ return Object.entries(value).find(([name]) => name === key)?.[1];+}++function text(value: object, key: string): string | undefined {+ const candidate = read(value, key);+ return typeof candidate === "string" && candidate.trim().length > 0 ? candidate.trim() : undefined;+}++function strings(value: object, key: string): readonly string[] | undefined {+ const candidate = read(value, key);+ return Array.isArray(candidate) && candidate.every((item) => typeof item === "string" && item.trim().length > 0)+ ? candidate.map((item) => item.trim())+ : undefined;+}++export async function parseValidationBatches(+ input: string | undefined,+ goals: readonly UlwLoopItem[],+): Promise<readonly UlwLoopValidationBatch[] | undefined> {+ const raw = await readJsonInput(input);+ if (raw === undefined) return undefined;+ if (!Array.isArray(raw)) fail("--validation-batch-json must be a JSON array.");+ const batches = raw.map(batchFromObject);+ validateBatches(batches, goals);+ return batches;+}++function batchFromObject(value: unknown): UlwLoopValidationBatch {+ if (!isObject(value)) fail("validation batch entries must be objects.");+ const batchId = text(value, "batchId");+ const memberIds = strings(value, "memberIds");+ const finalGoalId = text(value, "finalGoalId");+ if (batchId === undefined) fail("validation batch requires batchId.");+ if (memberIds === undefined || memberIds.length < 2) fail("validation batch requires at least two memberIds.");+ if (finalGoalId === undefined) fail("validation batch requires finalGoalId.");+ return { batchId, memberIds, finalGoalId };+}++function validateBatches(batches: readonly UlwLoopValidationBatch[], goals: readonly UlwLoopItem[]): void {+ const goalIds = new Set(goals.map((goal) => goal.id));+ const batchIds = new Set<string>();+ const members = new Set<string>();+ for (const batch of batches) {+ if (batchIds.has(batch.batchId)) fail(`duplicate validation batch id: ${batch.batchId}.`);+ batchIds.add(batch.batchId);+ if (new Set(batch.memberIds).size !== batch.memberIds.length) fail(`validation batch ${batch.batchId} has duplicate memberIds.`);+ if (!batch.memberIds.includes(batch.finalGoalId)) fail(`validation batch ${batch.batchId} finalGoalId must be a member.`, "ULW_LOOP_VALIDATION_BATCH_FINAL_NOT_MEMBER");+ for (const memberId of batch.memberIds) {+ if (!goalIds.has(memberId)) fail(`validation batch ${batch.batchId} references unknown goal: ${memberId}.`, "ULW_LOOP_VALIDATION_BATCH_MEMBER_UNKNOWN");+ if (members.has(memberId)) fail(`goal appears in multiple validation batches: ${memberId}.`, "ULW_LOOP_VALIDATION_BATCH_OVERLAP");+ members.add(memberId);+ }+ }+}++export function updateBatchesAfterSupersede(plan: UlwLoopPlan, targetId: string, replacementIds: readonly string[]): void {+ if (replacementIds.length === 0 || plan.validationBatches === undefined) return;+ plan.validationBatches = plan.validationBatches.map((batch) => {+ if (!batch.memberIds.includes(targetId)) return batch;+ const memberIds = batch.memberIds.flatMap((id) => (id === targetId ? [...replacementIds] : [id]));+ const replacementFinalGoalId = replacementIds[replacementIds.length - 1] ?? batch.finalGoalId;+ const finalGoalId = batch.finalGoalId === targetId ? replacementFinalGoalId : batch.finalGoalId;+ return { batchId: batch.batchId, memberIds, finalGoalId };+ });+}++export function batchUpdateLedgerEntry(before: UlwLoopPlan, after: UlwLoopPlan, at: string): UlwLoopLedgerEntry | null {+ if (JSON.stringify(before.validationBatches ?? []) === JSON.stringify(after.validationBatches ?? [])) return null;+ return { at, kind: "batch_updated", before: before.validationBatches ?? [], after: after.validationBatches ?? [], message: "Validation batch membership updated after steering." };+}++export function batchOf(plan: UlwLoopPlan, goalId: string): UlwLoopValidationBatch | undefined {+ return plan.validationBatches?.find((batch) => batch.memberIds.includes(goalId));+}++export function batchClosedBy(plan: UlwLoopPlan, goalId: string): UlwLoopValidationBatch | undefined {+ const batch = batchOf(plan, goalId);+ return batch?.finalGoalId === goalId ? batch : undefined;+}++export function requireBatchFinalReady(plan: UlwLoopPlan, goal: UlwLoopItem): void {+ const batch = batchClosedBy(plan, goal.id);+ if (batch === undefined) return;+ const open = batch.memberIds.filter((id) => id !== goal.id && !memberResolved(plan, id));+ if (open.length > 0) throw new UlwLoopError("Validation batch has unresolved members.", "ULW_LOOP_VALIDATION_BATCH_OPEN", { details: { batchId: batch.batchId, open } });+}++export function requireAllValidationBatchesClosed(plan: UlwLoopPlan, closingGoalId?: string): void {+ const open = (plan.validationBatches ?? []).filter((batch) => batch.memberIds.some((id) => id !== closingGoalId && !memberResolved(plan, id)));+ if (open.length > 0) throw new UlwLoopError("Validation batches remain open.", "ULW_LOOP_VALIDATION_BATCH_OPEN", { details: { batchIds: open.map((batch) => batch.batchId) } });+}++export function requireBatchGate(plan: UlwLoopPlan, goal: UlwLoopItem, gate: UlwLoopQualityGate): void {+ const batch = batchClosedBy(plan, goal.id);+ if (batch === undefined) return;+ const members = batch.memberIds.map((id) => plan.goals.find((item) => item.id === id)).filter((item): item is UlwLoopItem => item !== undefined);+ const pending = members.flatMap((member) => member.successCriteria.filter((criterion) => criterion.status !== "pass").map((criterion) => `${member.id}:${criterion.id}`));+ if (pending.length > 0) throw new UlwLoopError("Validation batch criteria remain pending.", "ULW_LOOP_VALIDATION_BATCH_CRITERIA_PENDING", { details: { batchId: batch.batchId, pending } });+ const totalCriteria = members.reduce((sum, member) => sum + member.successCriteria.length, 0);+ const passCount = members.reduce((sum, member) => sum + member.successCriteria.filter((criterion) => criterion.status === "pass").length, 0);+ if (gate.criteriaCoverage.totalCriteria !== totalCriteria || gate.criteriaCoverage.passCount !== passCount) throw new UlwLoopError("Validation batch gate coverage does not match member criteria.", "ULW_LOOP_VALIDATION_BATCH_GATE_MISMATCH", { details: { batchId: batch.batchId, expected: { totalCriteria, passCount }, actual: gate.criteriaCoverage } });+}++function memberResolved(plan: UlwLoopPlan, goalId: string): boolean {+ const goal = plan.goals.find((candidate) => candidate.id === goalId);+ return goal !== undefined && isMemberResolved(goal, plan);+}++function fail(message: string, code = "ULW_LOOP_VALIDATION_BATCH_INVALID"): never {+ throw new UlwLoopError(message, code);+}diff --git a/plugins/omo/components/ulw-loop/test/checkpoint-continuation.test.ts b/plugins/omo/components/ulw-loop/test/checkpoint-continuation.test.tsnew file mode 100644index 00000000..9304e2d3--- /dev/null+++ b/plugins/omo/components/ulw-loop/test/checkpoint-continuation.test.ts@@ -0,0 +1,76 @@+// biome-ignore-all format: compact continuation tests stay under the pure LOC budget.+import { rm } from "node:fs/promises";+import { afterEach, describe, expect, it } from "vitest";++import { checkpointAndContinue } from "../src/checkpoint-continuation.js";+import { readUlwLoopPlan } from "../src/plan-io.js";+import { goal, plan, repoWith, snapshot } from "./fixtures/checkpoint-builders.js";++let repo: string | undefined;++afterEach(async () => {+ if (repo !== undefined) await rm(repo, { recursive: true, force: true });+ repo = undefined;+});++describe("checkpointAndContinue", () => {+ it("#given a completed non-final goal #when advance is enabled #then starts the next pending goal", async () => {+ repo = await repoWith(+ plan([+ goal({ id: "G001", status: "in_progress" }),+ goal({ id: "G002", status: "pending", attempt: 0 }),+ ]),+ );++ const result = await checkpointAndContinue(repo, {+ goalId: "G001",+ status: "complete",+ evidence: "implementation done and validation passed",+ codexGoalJson: snapshot("active"),+ advance: true,+ });++ expect(result.next).toMatchObject({ resumed: false, goal: { id: "G002", status: "in_progress" } });+ expect(result.next && "instruction" in result.next ? result.next.instruction.text : "").toContain("Goal: G002");+ expect((await readUlwLoopPlan(repo)).activeGoalId).toBe("G002");+ });++ it("#given advance disabled #when a non-final goal completes #then preserves the old two-call state", async () => {+ repo = await repoWith(+ plan([+ goal({ id: "G001", status: "in_progress" }),+ goal({ id: "G002", status: "pending", attempt: 0 }),+ ]),+ );++ const result = await checkpointAndContinue(repo, {+ goalId: "G001",+ status: "complete",+ evidence: "implementation done and validation passed",+ codexGoalJson: snapshot("active"),+ advance: false,+ });++ expect(result.next).toBeUndefined();+ expect((await readUlwLoopPlan(repo)).activeGoalId).toBeUndefined();+ });++ it("#given a failed checkpoint #when advance is enabled #then it does not start the next goal", async () => {+ repo = await repoWith(+ plan([+ goal({ id: "G001", status: "in_progress" }),+ goal({ id: "G002", status: "pending", attempt: 0 }),+ ]),+ );++ const result = await checkpointAndContinue(repo, {+ goalId: "G001",+ status: "failed",+ evidence: "implementation failed and validation captured",+ advance: true,+ });++ expect(result.next).toBeUndefined();+ expect((await readUlwLoopPlan(repo)).activeGoalId).toBeUndefined();+ });+});diff --git a/plugins/omo/components/ulw-loop/test/cli-checkpoint-continuation.test.ts b/plugins/omo/components/ulw-loop/test/cli-checkpoint-continuation.test.tsnew file mode 100644index 00000000..cdf86806--- /dev/null+++ b/plugins/omo/components/ulw-loop/test/cli-checkpoint-continuation.test.ts@@ -0,0 +1,111 @@+import { mkdtemp, 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.js";+import { ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE } from "../src/goal-status.js";++let testDir: string;+let out: string[];+let originalOmoSessionId: string | undefined;++beforeEach(async () => {+ testDir = await mkdtemp(join(tmpdir(), "ug-cli-checkpoint-next-"));+ out = [];+ originalOmoSessionId = process.env["OMO_ULW_LOOP_SESSION_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((): boolean => true);+});++afterEach(async () => {+ vi.restoreAllMocks();+ 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 = [];+}++function stdoutJson(): Record<string, unknown> {+ return JSON.parse(out.join(""));+}++function codexSnapshot(): string {+ return JSON.stringify({ goal: { objective: ULW_LOOP_AGGREGATE_CODEX_OBJECTIVE, status: "active" } });+}++async function passCriterion(criterionId: string): Promise<void> {+ expect(+ await ulwLoopCommand([+ "record-evidence",+ "--goal-id",+ "G001-goal-a",+ "--criterion-id",+ criterionId,+ "--status",+ "pass",+ "--evidence",+ `${criterionId} observable proof`,+ ]),+ ).toBe(0);+ resetOutput();+}++describe("ulwLoopCommand checkpoint continuation", () => {+ it("#given another pending goal #when checkpoint completes #then JSON includes the next goal", async () => {+ expect(await ulwLoopCommand(["create-goals", "--brief", "- Goal A\n- Goal B", "--json"])).toBe(0);+ resetOutput();+ await passCriterion("C001");+ await passCriterion("C002");++ 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()).toMatchObject({+ next: { resumed: false, goal: { id: "G002-goal-b", status: "in_progress" } },+ });+ });++ it("#given no-advance #when checkpoint completes #then JSON omits next", async () => {+ expect(await ulwLoopCommand(["create-goals", "--brief", "- Goal A\n- Goal B", "--json"])).toBe(0);+ resetOutput();+ await passCriterion("C001");+ await passCriterion("C002");++ expect(+ await ulwLoopCommand([+ "checkpoint",+ "--goal-id",+ "G001-goal-a",+ "--status",+ "complete",+ "--evidence",+ "implementation done and validation passed",+ "--codex-goal-json",+ codexSnapshot(),+ "--no-advance",+ "--json",+ ]),+ ).toBe(0);+ expect(stdoutJson()).not.toHaveProperty("next");+ });+});diff --git a/plugins/omo/components/ulw-loop/test/cli-steering-batch.test.ts b/plugins/omo/components/ulw-loop/test/cli-steering-batch.test.tsnew file mode 100644index 00000000..7e7ca16d--- /dev/null+++ b/plugins/omo/components/ulw-loop/test/cli-steering-batch.test.ts@@ -0,0 +1,67 @@+// biome-ignore-all format: compact CLI batch tests stay under the pure LOC budget.+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it, vi } from "vitest";++import { ulwLoopCommand } from "../src/cli-commands.js";+import { parseSteeringProposals } from "../src/cli-steering.js";+import { ulwLoopGoalsPath } 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";++function plan(): 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: [] };+}++describe("parseSteeringProposals", () => {+ it("#given proposals-json #when parsing steer args #then returns every proposal", async () => {+ const proposals = await parseSteeringProposals([+ "--proposals-json",+ JSON.stringify([+ { kind: "annotate_ledger", evidence: "one", rationale: "because one" },+ { kind: "annotate_ledger", source: "cli", evidence: "two", rationale: "because two" },+ ]),+ ]);++ expect(proposals).toHaveLength(2);+ expect(proposals[0]).toMatchObject({ evidence: "one", source: "cli" });+ expect(proposals[1]).toMatchObject({ evidence: "two" });+ });++ it("#given proposals-json path #when parsing steer args #then reads proposals from the file", async () => {+ const repo = await mkdtemp(join(tmpdir(), "ug-cli-steer-batch-"));+ const file = join(repo, "batch.json");+ await writeFile(file, JSON.stringify([{ kind: "annotate_ledger", source: "cli", evidence: "file", rationale: "because file" }]), "utf8");++ const proposals = await parseSteeringProposals(["--proposals-json", file]);++ expect(proposals).toHaveLength(1);+ expect(proposals[0]).toMatchObject({ evidence: "file" });+ });++ it("#given kind and proposals-json #when steering through CLI #then rejects conflict without mutation", async () => {+ const repo = await mkdtemp(join(tmpdir(), "ug-cli-steer-batch-conflict-"));+ const out: string[] = [];+ try {+ await writePlan(repo, plan());+ const before = await readFile(ulwLoopGoalsPath(repo), "utf8");+ vi.spyOn(process, "cwd").mockReturnValue(repo);+ vi.spyOn(process.stdout, "write").mockImplementation((chunk: string | Uint8Array): boolean => {+ out.push(chunk.toString());+ return true;+ });+ vi.spyOn(process.stderr, "write").mockImplementation((): boolean => true);++ expect(await ulwLoopCommand(["steer", "--kind", "annotate_ledger", "--evidence", "flag", "--rationale", "flag", "--proposals-json", '[{"kind":"annotate_ledger","evidence":"batch","rationale":"batch"}]', "--json"])).toBe(1);++ expect(JSON.parse(out.join(""))).toHaveProperty("error.code", "ULW_LOOP_STEERING_BATCH_CONFLICT");+ expect(await readFile(ulwLoopGoalsPath(repo), "utf8")).toBe(before);+ } finally {+ vi.restoreAllMocks();+ await rm(repo, { recursive: true, force: true });+ }+ });+});diff --git a/plugins/omo/components/ulw-loop/test/cli-validation-batch.test.ts b/plugins/omo/components/ulw-loop/test/cli-validation-batch.test.tsnew file mode 100644index 00000000..2358ed9c--- /dev/null+++ b/plugins/omo/components/ulw-loop/test/cli-validation-batch.test.ts@@ -0,0 +1,57 @@+import { mkdtemp, 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.js";++let testDir: string;+let out: string[];++beforeEach(async () => {+ testDir = await mkdtemp(join(tmpdir(), "ug-cli-validation-batch-"));+ out = [];+ 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((): boolean => true);+});++afterEach(async () => {+ vi.restoreAllMocks();+ await rm(testDir, { recursive: true, force: true });+});++describe("ulwLoopCommand create-goals validation batches", () => {+ it("#given validation-batch-json #when creating goals #then JSON output includes validation batches", async () => {+ expect(+ await ulwLoopCommand([+ "create-goals",+ "--brief",+ "- Goal alpha\n- Goal beta",+ "--validation-batch-json",+ '[{"batchId":"VB001","memberIds":["G001-goal-alpha","G002-goal-beta"],"finalGoalId":"G002-goal-beta"}]',+ "--json",+ ]),+ ).toBe(0);++ expect(JSON.parse(out.join(""))).toHaveProperty("plan.validationBatches.0.batchId", "VB001");+ });++ it("#given finalGoalId outside members #when creating goals from CLI #then exits one with the distinct code", async () => {+ expect(+ await ulwLoopCommand([+ "create-goals",+ "--brief",+ "- Goal alpha\n- Goal beta\n- Goal gamma",+ "--validation-batch-json",+ '[{"batchId":"VB001","memberIds":["G001-goal-alpha","G002-goal-beta"],"finalGoalId":"G003-goal-gamma"}]',+ "--json",+ ]),+ ).toBe(1);++ expect(JSON.parse(out.join(""))).toHaveProperty("error.code", "ULW_LOOP_VALIDATION_BATCH_FINAL_NOT_MEMBER");+ });+});diff --git a/plugins/omo/components/ulw-loop/test/paths.test.ts b/plugins/omo/components/ulw-loop/test/paths.test.tsindex 999c28ab..616239e7 100644--- a/plugins/omo/components/ulw-loop/test/paths.test.ts+++ b/plugins/omo/components/ulw-loop/test/paths.test.ts@@ -1,3 +1,4 @@+// biome-ignore-all format: compact path tests predate this change.import { join, posix, win32 } from "node:path";import { describe, expect, it } from "vitest";diff --git a/plugins/omo/components/ulw-loop/test/steering-batch.test.ts b/plugins/omo/components/ulw-loop/test/steering-batch.test.tsnew file mode 100644index 00000000..050b3fec--- /dev/null+++ b/plugins/omo/components/ulw-loop/test/steering-batch.test.ts@@ -0,0 +1,152 @@+// biome-ignore-all format: compact steering batch tests stay under the pure LOC budget.+import { mkdtemp } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it, vi } from "vitest";++import type { CliSteeringProposal } from "../src/cli-steering.js";+import { readSteeringLedgerEntries, readUlwLoopPlan, writePlan } from "../src/plan-io.js";+import { steerUlwLoopBatch } from "../src/steering-batch.js";+import type { UlwLoopItem, UlwLoopPlan, UlwLoopSteeringProposal } from "../src/types.js";++const appendFileCalls = vi.hoisted(() => vi.fn());+vi.mock("node:fs/promises", async (importOriginal) => {+ const actual = await importOriginal<typeof import("node:fs/promises")>();+ appendFileCalls.mockImplementation(actual.appendFile);+ return { ...actual, appendFile: appendFileCalls };+});++const NOW = "2026-05-23T00:00:00.000Z";++function goal(id: string): UlwLoopItem {+ return {+ id,+ title: id,+ objective: `Do ${id}`,+ status: "pending",+ successCriteria: [],+ attempt: 0,+ createdAt: NOW,+ updatedAt: NOW,+ };+}++function plan(): 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: [goal("G001"), goal("G002")],+ };+}++function proposal(overrides: Partial<UlwLoopSteeringProposal> = {}): UlwLoopSteeringProposal {+ return {+ kind: "add_subgoal",+ source: "cli",+ evidence: "observable evidence",+ rationale: "necessary plan refinement",+ title: "New goal",+ objective: "Do the new goal",+ ...overrides,+ };+}++async function repoWithPlan(): Promise<string> {+ const repo = await mkdtemp(join(tmpdir(), "ug-steer-batch-"));+ await writePlan(repo, plan());+ return repo;+}++describe("steerUlwLoopBatch", () => {+ it("#given two valid proposals #when applied as a batch #then both mutations commit", async () => {+ const repo = await repoWithPlan();++ const result = await steerUlwLoopBatch(repo, [+ proposal({ idempotencyKey: "b1" }),+ proposal({ kind: "revise_pending_wording", targetGoalId: "G001", revisedTitle: "Revised", idempotencyKey: "b2" }),+ ]);++ expect(result.accepted).toBe(true);+ expect(result.results).toHaveLength(2);+ expect((await readUlwLoopPlan(repo)).goals.map((item) => item.title)).toContain("Revised");+ expect((await readSteeringLedgerEntries(repo)).filter((entry) => entry.kind === "steering_accepted")).toHaveLength(2);+ });++ it("#given rejected proposals #when applied as a batch #then one rejection audit lists every rejected index", async () => {+ const repo = await repoWithPlan();+ const before = JSON.stringify(await readUlwLoopPlan(repo));++ const result = await steerUlwLoopBatch(repo, [proposal({ idempotencyKey: "ok" }), proposal({ kind: "reorder_pending", pendingOrder: ["missing"] }), proposal({ evidence: "" })]);++ expect(result.accepted).toBe(false);+ expect(JSON.stringify(await readUlwLoopPlan(repo))).toBe(before);+ expect((await readUlwLoopPlan(repo)).goals).toHaveLength(2);+ const entries = await readSteeringLedgerEntries(repo);+ expect(entries.filter((entry) => entry.kind === "steering_accepted")).toHaveLength(0);+ expect(entries.filter((entry) => entry.kind === "steering_rejected")).toHaveLength(1);+ expect(entries.find((entry) => entry.kind === "steering_rejected")?.message).toContain("index 1:");+ expect(entries.find((entry) => entry.kind === "steering_rejected")?.message).toContain("index 2:");+ });++ it("#given a batch member split in proposals-json #when applied #then updates validation batch membership", async () => {+ const repo = await repoWithPlan();+ const seed = await readUlwLoopPlan(repo);+ await writePlan(repo, { ...seed, validationBatches: [{ batchId: "VB001", memberIds: ["G001", "G002"], finalGoalId: "G002" }] });++ const result = await steerUlwLoopBatch(repo, [+ proposal({+ kind: "split_subgoal",+ targetGoalId: "G001",+ childGoals: [{ title: "Child", objective: "Do child" }],+ }),+ ]);++ expect(result.plan.validationBatches).toEqual([{ batchId: "VB001", memberIds: ["G003", "G002"], finalGoalId: "G002" }]);+ expect((await readSteeringLedgerEntries(repo)).at(-1)).toMatchObject({ kind: "batch_updated" });+ });++ it("#given a prior idempotency key #when batched with a fresh proposal #then dedupes one and applies the other", async () => {+ const repo = await repoWithPlan();+ await steerUlwLoopBatch(repo, [proposal({ idempotencyKey: "same" })]);++ const result = await steerUlwLoopBatch(repo, [proposal({ idempotencyKey: "same" }), proposal({ idempotencyKey: "fresh" })]);++ expect(result.accepted).toBe(true);+ expect(result.results.map((item) => item.deduped)).toEqual([true, false]);+ expect((await readUlwLoopPlan(repo)).goals).toHaveLength(4);+ });++ it("#given mixed fresh and deduped proposals #when accepted and replayed #then one append records all fresh audits and replay records none", async () => {+ const repo = await repoWithPlan();+ const seeded = await readUlwLoopPlan(repo);+ seeded.goals[0]?.successCriteria.push({ id: "C001", scenario: "old", expectedEvidence: "proof", userModel: "edge", status: "pending", capturedEvidence: null });+ await writePlan(repo, { ...seeded, validationBatches: [{ batchId: "VB001", memberIds: ["G001", "G002"], finalGoalId: "G002" }] });+ await steerUlwLoopBatch(repo, [proposal({ idempotencyKey: "dedupe-me" })]);+ appendFileCalls.mockClear();++ const revise = { ...proposal({ kind: "revise_criterion", targetGoalId: "G001", criterionId: "C001", idempotencyKey: "revise-c1" }), scenario: "new" } satisfies CliSteeringProposal;+ const batch = [+ proposal({ idempotencyKey: "dedupe-me" }),+ revise,+ proposal({ kind: "split_subgoal", targetGoalId: "G002", childGoals: [{ title: "Child", objective: "Do child" }], idempotencyKey: "split-g2" }),+ ];+ const result = await steerUlwLoopBatch(repo, batch);++ expect(result.accepted).toBe(true);+ expect(result.results.map((item) => item.deduped)).toEqual([true, false, false]);+ expect(appendFileCalls).toHaveBeenCalledTimes(1);+ expect((await readSteeringLedgerEntries(repo)).map((entry) => entry.kind).slice(-3)).toEqual(["criteria_revised", "steering_accepted", "batch_updated"]);+ const after = JSON.stringify(await readUlwLoopPlan(repo));+ appendFileCalls.mockClear();++ const replay = await steerUlwLoopBatch(repo, batch);++ expect(replay.results.map((item) => item.deduped)).toEqual([true, true, true]);+ expect(JSON.stringify(await readUlwLoopPlan(repo))).toBe(after);+ expect(appendFileCalls).not.toHaveBeenCalled();+ });+});diff --git a/plugins/omo/components/ulw-loop/test/stop-resume-hook.test.ts b/plugins/omo/components/ulw-loop/test/stop-resume-hook.test.tsindex e870c4fe..f88ac68b 100644--- a/plugins/omo/components/ulw-loop/test/stop-resume-hook.test.ts+++ b/plugins/omo/components/ulw-loop/test/stop-resume-hook.test.ts@@ -179,6 +179,35 @@ describe("runStopResumeHook", () => {expect(JSON.parse(output).reason).toContain("--session-id s1");});+ it("#given a goal id with path traversal #when the hook runs #then nothing is written outside the state dir and the resume is denied", () => {+ writeGoals([pendingGoal("../../../escaped-marker")]);+ const outsideDir = join(workDir, ".omo", "ulw-loop");+ const sentinel = join(outsideDir, "escaped-marker.json");+ writeFileSync(sentinel, "sentinel\n");++ const output = runStopResumeHook(stopPayload());++ expect(output).toBe("");+ expect(readFileSync(sentinel, "utf8")).toBe("sentinel\n");+ expect(existsSync(join(outsideDir, "escaped-marker.stuck"))).toBe(false);+ expect(existsSync(join(outsideDir, "auto-resume-escaped-marker.json"))).toBe(false);+ });++ it("#given a normal goal id #when the hook runs past the cap #then the counter and stuck marker are written inside the state dir", () => {+ writeGoals([pendingGoal("goal-abc")]);++ runStopResumeHook(stopPayload());+ runStopResumeHook(stopPayload());+ const third = runStopResumeHook(stopPayload());++ expect(third).toBe("");+ const counter = JSON.parse(readFileSync(join(sessionDir(), "auto-resume-goal-abc.json"), "utf8"));+ expect(counter.count).toBe(2);+ expect(readFileSync(join(sessionDir(), "auto-resume-goal-abc.stuck"), "utf8")).toBe(+ "no ledger progress after 2 resumes\n",+ );+ });+it("#given ledger movement between stops #when the hook fires again #then the cap resets", () => {writeGoals([pendingGoal()]);diff --git a/plugins/omo/components/ulw-loop/test/validation-batch-checkpoint.test.ts b/plugins/omo/components/ulw-loop/test/validation-batch-checkpoint.test.tsnew file mode 100644index 00000000..928af87c--- /dev/null+++ b/plugins/omo/components/ulw-loop/test/validation-batch-checkpoint.test.ts@@ -0,0 +1,147 @@+// biome-ignore-all format: compact validation-batch checkpoint tests stay under the pure LOC budget.+import { describe, expect, it } from "vitest";++import { checkpointUlwLoop } from "../src/checkpoint.js";+import { readUlwLoopPlan } from "../src/plan-io.js";+import { criterion, expectCode, goal, plan, repoWith, snapshot } from "./fixtures/checkpoint-builders.js";+import { qualityGateJson } from "./fixtures/quality-gate-builder.js";++const batch = { batchId: "VB001", memberIds: ["G001", "G002"], finalGoalId: "G002" };++describe("validation-batch checkpoint enforcement", () => {+ it("#given an open batch member #when completing the batch final goal #then rejects with batch open", async () => {+ const repo = await repoWith(+ plan([+ goal({ id: "G001", status: "pending" }),+ goal({ id: "G002", status: "in_progress" }),+ goal({ id: "G003", status: "pending" }),+ ], { validationBatches: [batch] }),+ );++ await expectCode(+ () =>+ checkpointUlwLoop(repo, {+ goalId: "G002",+ status: "complete",+ evidence: "batch final implementation done",+ codexGoalJson: snapshot("active"),+ qualityGateJson: "{}",+ }),+ "ULW_LOOP_VALIDATION_BATCH_OPEN",+ );+ });++ it("#given complete members but no gate #when completing the batch final goal #then requires a batch gate", async () => {+ const repo = await repoWith(+ plan([+ goal({ id: "G001", status: "complete" }),+ goal({ id: "G002", status: "in_progress" }),+ goal({ id: "G003", status: "pending" }),+ ], { validationBatches: [batch] }),+ );++ await expectCode(+ () =>+ checkpointUlwLoop(repo, {+ goalId: "G002",+ status: "complete",+ evidence: "batch final implementation done",+ codexGoalJson: snapshot("active"),+ }),+ "ULW_LOOP_VALIDATION_BATCH_GATE_REQUIRED",+ );+ });++ it("#given a member criterion pending #when the batch gate is present #then rejects pending criteria", async () => {+ const repo = await repoWith(+ plan([+ goal({ id: "G001", status: "complete", successCriteria: [criterion("C001", "pass"), criterion("C002", "pending")] }),+ goal({ id: "G002", status: "in_progress", successCriteria: [criterion("C001", "pass"), criterion("C002", "pass")] }),+ goal({ id: "G003", status: "pending" }),+ ], { validationBatches: [batch] }),+ );++ const gateJson = await qualityGateJson(repo, undefined, "G002");+ await expectCode(+ () =>+ checkpointUlwLoop(repo, {+ goalId: "G002",+ status: "complete",+ evidence: "batch final implementation done",+ codexGoalJson: snapshot("active"),+ qualityGateJson: gateJson,+ }),+ "ULW_LOOP_VALIDATION_BATCH_CRITERIA_PENDING",+ );+ });++ it("#given all member criteria pass #when coverage counts mismatch #then rejects the gate", async () => {+ const repo = await repoWith(+ plan([+ goal({ id: "G001", status: "complete", successCriteria: [criterion("C001", "pass"), criterion("C002", "pass")] }),+ goal({ id: "G002", status: "in_progress", successCriteria: [criterion("C001", "pass"), criterion("C002", "pass")] }),+ goal({ id: "G003", status: "pending" }),+ ], { validationBatches: [batch] }),+ );++ const gateJson = await qualityGateJson(repo, undefined, "G002");+ await expectCode(+ () =>+ checkpointUlwLoop(repo, {+ goalId: "G002",+ status: "complete",+ evidence: "batch final implementation done",+ codexGoalJson: snapshot("active"),+ qualityGateJson: gateJson,+ }),+ "ULW_LOOP_VALIDATION_BATCH_GATE_MISMATCH",+ );+ });++ it("#given batch-final goal is also run-final #when completing it #then closes batch and aggregate", async () => {+ const repo = await repoWith(+ plan([+ goal({ id: "G001", status: "complete", successCriteria: [criterion("C001", "pass")] }),+ goal({ id: "G002", status: "complete", successCriteria: [criterion("C001", "pass")] }),+ goal({ id: "G003", status: "in_progress", successCriteria: [criterion("C001", "pass")] }),+ ], { validationBatches: [{ batchId: "VB002", memberIds: ["G002", "G003"], finalGoalId: "G003" }] }),+ );++ const gate = JSON.parse(await qualityGateJson(repo, undefined, "G003"));+ gate.criteriaCoverage.totalCriteria = 2;+ gate.criteriaCoverage.passCount = 2;+ const result = await checkpointUlwLoop(repo, {+ goalId: "G003",+ status: "complete",+ evidence: "batch final is also aggregate final",+ codexGoalJson: snapshot("complete"),+ qualityGateJson: JSON.stringify(gate),+ });++ expect(result.aggregateCompletion?.status).toBe("complete");+ expect((await readUlwLoopPlan(repo)).goals.find((item) => item.id === "G003")?.status).toBe("complete");+ });++ it("#given all batch checks pass #when completing final member #then appends batch closed", async () => {+ const repo = await repoWith(+ plan([+ goal({ id: "G001", status: "complete", successCriteria: [criterion("C001", "pass")] }),+ goal({ id: "G002", status: "in_progress", successCriteria: [criterion("C001", "pass")] }),+ goal({ id: "G003", status: "pending" }),+ ], { validationBatches: [batch] }),+ );++ const gate = JSON.parse(await qualityGateJson(repo, undefined, "G002"));+ gate.criteriaCoverage.totalCriteria = 2;+ gate.criteriaCoverage.passCount = 2;+ await checkpointUlwLoop(repo, {+ goalId: "G002",+ status: "complete",+ evidence: "batch final implementation done",+ codexGoalJson: snapshot("active"),+ qualityGateJson: JSON.stringify(gate),+ });++ expect((await readUlwLoopPlan(repo)).goals.find((item) => item.id === "G002")?.status).toBe("complete");+ });+});diff --git a/plugins/omo/components/ulw-loop/test/validation-batch.test.ts b/plugins/omo/components/ulw-loop/test/validation-batch.test.tsnew file mode 100644index 00000000..90ea3fa4--- /dev/null+++ b/plugins/omo/components/ulw-loop/test/validation-batch.test.ts@@ -0,0 +1,73 @@+// biome-ignore-all format: compact validation-batch tests stay under the pure LOC budget.+import { mkdtemp, readFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { createUlwLoopPlan } from "../src/plan-crud.js";++async function repo(): Promise<string> {+ return mkdtemp(join(tmpdir(), "ug-validation-batch-"));+}++describe("createUlwLoopPlan validation batches", () => {+ it("#given a valid validation batch #when creating goals #then stores it on the plan", async () => {+ const plan = await createUlwLoopPlan(await repo(), {+ brief: "- Goal alpha\n- Goal beta\n- Goal gamma",+ validationBatchesJson: '[{"batchId":"VB001","memberIds":["G001-goal-alpha","G002-goal-beta"],"finalGoalId":"G002-goal-beta"}]',+ });++ expect(plan.validationBatches).toEqual([+ { batchId: "VB001", memberIds: ["G001-goal-alpha", "G002-goal-beta"], finalGoalId: "G002-goal-beta" },+ ]);+ });++ it("#given an unknown member id #when creating goals #then rejects with the member-unknown code", async () => {+ await expect(+ createUlwLoopPlan(await repo(), {+ brief: "- Goal alpha\n- Goal beta",+ validationBatchesJson: '[{"batchId":"VB001","memberIds":["G001-goal-alpha","missing"],"finalGoalId":"G001-goal-alpha"}]',+ }),+ ).rejects.toMatchObject({ code: "ULW_LOOP_VALIDATION_BATCH_MEMBER_UNKNOWN" });+ });++ it("#given a final id outside members #when creating goals #then rejects with the final-not-member code", async () => {+ await expect(+ createUlwLoopPlan(await repo(), {+ brief: "- Goal alpha\n- Goal beta\n- Goal gamma",+ validationBatchesJson: '[{"batchId":"VB001","memberIds":["G001-goal-alpha","G002-goal-beta"],"finalGoalId":"G003-goal-gamma"}]',+ }),+ ).rejects.toMatchObject({ code: "ULW_LOOP_VALIDATION_BATCH_FINAL_NOT_MEMBER" });+ });++ it("#given overlapping validation batches #when creating goals #then rejects with the overlap code", async () => {+ await expect(+ createUlwLoopPlan(await repo(), {+ brief: "- Goal alpha\n- Goal beta\n- Goal gamma",+ validationBatchesJson: '[{"batchId":"VB001","memberIds":["G001-goal-alpha","G002-goal-beta"],"finalGoalId":"G002-goal-beta"},{"batchId":"VB002","memberIds":["G002-goal-beta","G003-goal-gamma"],"finalGoalId":"G003-goal-gamma"}]',+ }),+ ).rejects.toMatchObject({ code: "ULW_LOOP_VALIDATION_BATCH_OVERLAP" });+ });++ it("#given duplicate members #when creating goals #then retains the structural invalid code", async () => {+ await expect(+ createUlwLoopPlan(await repo(), {+ brief: "- Goal alpha\n- Goal beta",+ validationBatchesJson: '[{"batchId":"VB001","memberIds":["G001-goal-alpha","G001-goal-alpha"],"finalGoalId":"G001-goal-alpha"}]',+ }),+ ).rejects.toMatchObject({ code: "ULW_LOOP_VALIDATION_BATCH_INVALID" });+ });++ it("#given a validation batch file #when creating goals #then reads the batch JSON from disk", async () => {+ const root = await repo();+ const file = join(root, "batches.json");+ await import("node:fs/promises").then((fs) => fs.writeFile(file, '[{"batchId":"VB001","memberIds":["G001-goal-alpha","G002-goal-beta"],"finalGoalId":"G002-goal-beta"}]', "utf8"));++ const plan = await createUlwLoopPlan(root, {+ brief: "- Goal alpha\n- Goal beta",+ validationBatchesJson: file,+ });++ expect(JSON.parse(await readFile(join(root, ".omo/ulw-loop/goals.json"), "utf8"))).toHaveProperty("validationBatches", plan.validationBatches);+ });+});diff --git a/plugins/omo/dist/cli-node/index.js b/plugins/omo/dist/cli-node/index.jsindex e3a1d72c..5a8604d7 100755--- a/plugins/omo/dist/cli-node/index.js+++ b/plugins/omo/dist/cli-node/index.js@@ -2146,7 +2146,7 @@ var package_default;var init_package = __esm(() => {package_default = {name: "oh-my-opencode",- version: "4.19.0",+ version: "4.19.1",description: "The Best AI Agent Harness - Batteries-Included OpenCode Plugin with Multi-Model Orchestration, Parallel Background Agents, and Crafted LSP/AST Tools",main: "./dist/index.js",types: "dist/index.d.ts",@@ -2358,18 +2358,18 @@ var init_package = __esm(() => {typescript: "^6.0.3"},optionalDependencies: {- "oh-my-opencode-darwin-arm64": "4.19.0",- "oh-my-opencode-darwin-x64": "4.19.0",- "oh-my-opencode-darwin-x64-baseline": "4.19.0",- "oh-my-opencode-linux-arm64": "4.19.0",- "oh-my-opencode-linux-arm64-musl": "4.19.0",- "oh-my-opencode-linux-x64": "4.19.0",- "oh-my-opencode-linux-x64-baseline": "4.19.0",- "oh-my-opencode-linux-x64-musl": "4.19.0",- "oh-my-opencode-linux-x64-musl-baseline": "4.19.0",- "oh-my-opencode-windows-arm64": "4.19.0",- "oh-my-opencode-windows-x64": "4.19.0",- "oh-my-opencode-windows-x64-baseline": "4.19.0"+ "oh-my-opencode-darwin-arm64": "4.19.1",+ "oh-my-opencode-darwin-x64": "4.19.1",+ "oh-my-opencode-darwin-x64-baseline": "4.19.1",+ "oh-my-opencode-linux-arm64": "4.19.1",+ "oh-my-opencode-linux-arm64-musl": "4.19.1",+ "oh-my-opencode-linux-x64": "4.19.1",+ "oh-my-opencode-linux-x64-baseline": "4.19.1",+ "oh-my-opencode-linux-x64-musl": "4.19.1",+ "oh-my-opencode-linux-x64-musl-baseline": "4.19.1",+ "oh-my-opencode-windows-arm64": "4.19.1",+ "oh-my-opencode-windows-x64": "4.19.1",+ "oh-my-opencode-windows-x64-baseline": "4.19.1"},overrides: {"@earendil-works/pi-agent-core": "0.80.3",@@ -7427,6 +7427,7 @@ var init_env = __esm(() => {SAFE_CODEGRAPH_RUNTIME_ENV_KEYS = new Set(["CODEGRAPH_ALLOW_UNSAFE_NODE","CODEGRAPH_BIN",+ "CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS","CODEGRAPH_FAKE_LOG","CODEGRAPH_NO_DAEMON","CODEGRAPH_NODE_BIN",@@ -7442,6 +7443,9 @@ var init_workspace = () => {};// packages/utils/src/codegraph/guidance.tsvar init_guidance = () => {};+// packages/utils/src/codegraph/manifest.ts+var init_manifest = () => {};+// packages/utils/src/codegraph/node-support.tsfunction evaluateCodegraphNodeSupport(options = {}) {const nodeVersion = options.nodeVersion ?? process.versions.node;@@ -7570,6 +7574,7 @@ var init_resolve2 = __esm(() => {var init_codegraph = __esm(() => {init_env();init_guidance();+ init_manifest();init_provision();init_process_sweep();init_resolve2();@@ -7748,7 +7753,7 @@ function migrateModelVersions(configs, appliedMigrations) {var MODEL_VERSION_MAP, CURRENT_USER_SELECTABLE_MODELS;var init_model_versions = __esm(() => {MODEL_VERSION_MAP = {- "anthropic/claude-opus-4-4": "anthropic/claude-opus-4-7"+ "anthropic/claude-opus-4-4": "anthropic/claude-opus-4-8"};CURRENT_USER_SELECTABLE_MODELS = new Set(["anthropic/claude-opus-4-5",@@ -9196,26 +9201,25 @@ var init_agent_model_requirements = __esm(() => {fallbackChain: [{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},- { providers: ["opencode-go", "kimi-for-coding", "moonshotai", "opencode", "vercel"], model: "kimi-k3" },- { providers: ["opencode-go", "vercel"], model: "kimi-k2.6" },- { providers: ["kimi-for-coding"], model: "k2p5" },{providers: [+ "opencode-go",+ "kimi-for-coding",+ "moonshotai","opencode",+ "vercel","bailian-coding-plan",- "moonshotai","moonshotai-cn","firmware","ollama-cloud",- "aihubmix",- "vercel"+ "aihubmix"],- model: "kimi-k2.5"+ model: "kimi-k3"},- { providers: ["openai", "github-copilot", "opencode", "vercel"], model: "gpt-5.5", variant: "medium" },+ { providers: ["openai", "github-copilot", "opencode", "vercel"], model: "gpt-5.6-sol", variant: "medium" },{ providers: ["zai-coding-plan", "opencode", "bailian-coding-plan", "vercel"], model: "glm-5" },{ providers: ["opencode"], model: "big-pickle" }],@@ -9224,13 +9228,8 @@ var init_agent_model_requirements = __esm(() => {hephaestus: {fallbackChain: [{- providers: ["openai", "github-copilot", "vercel"],+ providers: ["openai", "github-copilot", "vercel", "opencode"],model: "gpt-5.6-sol",- variant: "high"- },- {- providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",variant: "medium"}],@@ -9240,8 +9239,13 @@ var init_agent_model_requirements = __esm(() => {oracle: {fallbackChain: [{- providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",+ providers: ["openai", "opencode", "vercel"],+ model: "gpt-5.6-sol",+ variant: "xhigh"+ },+ {+ providers: ["github-copilot"],+ model: "gpt-5.6-sol",variant: "high"},{@@ -9251,7 +9255,7 @@ var init_agent_model_requirements = __esm(() => {},{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},{ providers: ["opencode-go", "vercel"], model: "glm-5.2" }@@ -9283,8 +9287,8 @@ var init_agent_model_requirements = __esm(() => {},"multimodal-looker": {fallbackChain: [- { providers: ["openai", "opencode", "vercel"], model: "gpt-5.5", variant: "medium" },- { providers: ["opencode-go", "vercel"], model: "kimi-k2.6" },+ { providers: ["openai", "opencode", "vercel"], model: "gpt-5.6-sol", variant: "low" },+ { providers: ["opencode-go", "vercel"], model: "kimi-k3" },{ providers: ["zai-coding-plan", "vercel"], model: "glm-4.6v" },{ providers: ["openai", "github-copilot", "opencode", "vercel"], model: "gpt-5-nano" }]@@ -9293,12 +9297,12 @@ var init_agent_model_requirements = __esm(() => {fallbackChain: [{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},{providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",+ model: "gpt-5.6-sol",variant: "high"},{ providers: ["opencode-go", "vercel"], model: "glm-5.2" },@@ -9316,16 +9320,16 @@ var init_agent_model_requirements = __esm(() => {},{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},{providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",- variant: "high"+ model: "gpt-5.6-sol",+ variant: "medium"},{ providers: ["opencode-go", "vercel"], model: "glm-5.2" },- { providers: ["kimi-for-coding"], model: "k2p5" }+ { providers: ["kimi-for-coding"], model: "kimi-k3" }]},momus: {@@ -9341,13 +9345,18 @@ var init_agent_model_requirements = __esm(() => {variant: "high"},{- providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",+ providers: ["openai", "opencode", "vercel"],+ model: "gpt-5.6-sol",variant: "xhigh"},+ {+ providers: ["github-copilot"],+ model: "gpt-5.6-sol",+ variant: "high"+ },{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},{@@ -9361,10 +9370,10 @@ var init_agent_model_requirements = __esm(() => {atlas: {fallbackChain: [{ providers: ["anthropic", "github-copilot", "opencode", "vercel"], model: "claude-sonnet-4-6" },- { providers: ["opencode-go", "vercel"], model: "kimi-k2.6" },+ { providers: ["opencode-go", "vercel"], model: "kimi-k3" },{providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",+ model: "gpt-5.6-sol",variant: "medium"},{ providers: ["opencode-go", "vercel"], model: "minimax-m3" },@@ -9375,10 +9384,10 @@ var init_agent_model_requirements = __esm(() => {"sisyphus-junior": {fallbackChain: [{ providers: ["anthropic", "github-copilot", "opencode", "vercel"], model: "claude-sonnet-4-6" },- { providers: ["opencode-go", "vercel"], model: "kimi-k2.6" },+ { providers: ["opencode-go", "vercel"], model: "kimi-k3" },{providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",+ model: "gpt-5.6-sol",variant: "medium"},{ providers: ["opencode-go", "vercel"], model: "minimax-m3" },@@ -9404,11 +9413,11 @@ var init_category_model_requirements = __esm(() => {{ providers: ["zai-coding-plan", "opencode", "bailian-coding-plan", "vercel"], model: "glm-5" },{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},{ providers: ["opencode-go", "vercel"], model: "glm-5.2" },- { providers: ["kimi-for-coding"], model: "k2p5" }+ { providers: ["kimi-for-coding"], model: "kimi-k3" }]},ultrabrain: {@@ -9425,7 +9434,7 @@ var init_category_model_requirements = __esm(() => {},{providers: ["openai", "opencode", "vercel"],- model: "gpt-5.5",+ model: "gpt-5.6-sol",variant: "xhigh"},{@@ -9435,7 +9444,7 @@ var init_category_model_requirements = __esm(() => {},{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},{ providers: ["opencode-go", "vercel"], model: "glm-5.2" }@@ -9460,12 +9469,12 @@ var init_category_model_requirements = __esm(() => {},{providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",+ model: "gpt-5.6-sol",variant: "medium"},{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},{@@ -9473,7 +9482,7 @@ var init_category_model_requirements = __esm(() => {model: "gemini-3.1-pro",variant: "high"},- { providers: ["opencode-go", "vercel"], model: "kimi-k2.6" },+ { providers: ["opencode-go", "vercel"], model: "kimi-k3" },{ providers: ["opencode-go", "vercel"], model: "glm-5.2" }]},@@ -9486,11 +9495,11 @@ var init_category_model_requirements = __esm(() => {},{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},- { providers: ["openai", "github-copilot", "opencode", "vercel"], model: "gpt-5.5" },- { providers: ["opencode-go", "vercel"], model: "kimi-k2.6" },+ { providers: ["openai", "github-copilot", "opencode", "vercel"], model: "gpt-5.6-sol", variant: "high" },+ { providers: ["opencode-go", "vercel"], model: "kimi-k3" },{ providers: ["opencode-go", "vercel"], model: "glm-5.2" }]},@@ -9532,10 +9541,10 @@ var init_category_model_requirements = __esm(() => {},{providers: ["openai", "opencode", "vercel"],- model: "gpt-5.5",+ model: "gpt-5.6-sol",variant: "medium"},- { providers: ["opencode-go", "vercel"], model: "kimi-k2.6" },+ { providers: ["opencode-go", "vercel"], model: "kimi-k3" },{providers: ["google", "github-copilot", "opencode", "vercel"],model: "gemini-3-flash"@@ -9549,30 +9558,29 @@ var init_category_model_requirements = __esm(() => {fallbackChain: [{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},{providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",+ model: "gpt-5.6-sol",variant: "high"},{ providers: ["zai-coding-plan", "opencode", "bailian-coding-plan", "vercel"], model: "glm-5" },- { providers: ["kimi-for-coding"], model: "k2p5" },+ { providers: ["kimi-for-coding"], model: "kimi-k3" },{ providers: ["opencode-go", "vercel"], model: "glm-5.2" },- { providers: ["opencode", "bailian-coding-plan", "vercel"], model: "kimi-k2.5" },{providers: ["opencode","bailian-coding-plan",+ "vercel","moonshotai","moonshotai-cn","firmware","ollama-cloud",- "aihubmix",- "vercel"+ "aihubmix"],- model: "kimi-k2.5"+ model: "kimi-k3"}]},@@ -9582,7 +9590,7 @@ var init_category_model_requirements = __esm(() => {providers: ["google", "github-copilot", "opencode", "vercel"],model: "gemini-3-flash"},- { providers: ["opencode-go", "vercel"], model: "kimi-k2.6" },+ { providers: ["opencode-go", "vercel"], model: "kimi-k3" },{providers: ["anthropic", "github-copilot", "opencode", "vercel"],model: "claude-sonnet-4-6"@@ -10007,7 +10015,7 @@ var CLAUDE_VERSION_DOT, GEMINI_31_PRO_PREVIEW, GEMINI_3_FLASH_PREVIEW;var init_provider_model_id_transform = __esm(() => {CLAUDE_VERSION_DOT = /claude-(\w+)-(\d+)-(\d+)/g;GEMINI_31_PRO_PREVIEW = /gemini-3\.1-pro(?!-)/g;- GEMINI_3_FLASH_PREVIEW = /gemini-3-flash(?!-)/g;+ GEMINI_3_FLASH_PREVIEW = /(?<!antigravity-)gemini-3-flash(?!-)/g;});// packages/model-core/src/known-variants.ts@@ -10802,7 +10810,7 @@ var init_anthropic_categories = __esm(() => {ANTHROPIC_CATEGORIES = [{name: "unspecified-high",- config: { model: "anthropic/claude-opus-4-7", variant: "max" },+ config: { model: "anthropic/claude-opus-4-8", variant: "max" },description: "Tasks that don't fit other categories, high effort required",promptAppend: UNSPECIFIED_HIGH_CATEGORY_PROMPT_APPEND}@@ -10960,7 +10968,7 @@ var init_kimi_categories = __esm(() => {KIMI_CATEGORIES = [{name: "writing",- config: { model: "kimi-for-coding/k2p5" },+ config: { model: "kimi-for-coding/kimi-k3" },description: "Documentation, prose, technical writing",promptAppend: WRITING_CATEGORY_PROMPT_APPEND}@@ -65189,7 +65197,7 @@ var init_claude_model_mapper = __esm(() => {init_model_normalization2();CLAUDE_CODE_ALIAS_MAP = new Map([["sonnet", `${ANTHROPIC_PREFIX}claude-sonnet-4-6`],- ["opus", `${ANTHROPIC_PREFIX}claude-opus-4-7`],+ ["opus", `${ANTHROPIC_PREFIX}claude-opus-4-8`],["haiku", `${ANTHROPIC_PREFIX}claude-haiku-4-5`]]);});@@ -65996,10 +66004,10 @@ var init_openai_only_model_catalog = __esm(() => {librarian: { model: "openai/gpt-5.4-mini-fast" }};OPENAI_ONLY_CATEGORY_OVERRIDES = {- artistry: { model: "openai/gpt-5.5", variant: "xhigh" },+ artistry: { model: "openai/gpt-5.6-sol", variant: "xhigh" },quick: { model: "openai/gpt-5.4-mini" },- "visual-engineering": { model: "openai/gpt-5.5", variant: "high" },- writing: { model: "openai/gpt-5.5", variant: "medium" }+ "visual-engineering": { model: "openai/gpt-5.6-sol", variant: "high" },+ writing: { model: "openai/gpt-5.6-sol", variant: "medium" }};});@@ -72713,7 +72721,7 @@ var package_default2;var init_package2 = __esm(() => {package_default2 = {name: "@oh-my-opencode/omo-codex",- version: "4.19.0",+ version: "4.19.1",type: "module",private: true,description: "Codex harness adapter for oh-my-openagent. Vendored Codex plugin namespace (omo) + TypeScript installer + telemetry.",@@ -75101,6 +75109,7 @@ async function rewriteCachedPackageLocalFileDependencies(pluginRoot, sourceRoot)const packageJsonPaths = [];await collectPackageJsonPaths(pluginRoot, pluginRoot, packageJsonPaths);const packageLock = await readPackageLock(pluginRoot);+ let rewroteAnyPackageJson = false;for (const packageJsonPath of packageJsonPaths) {const raw = await readFile5(packageJsonPath, "utf8");const parsed = JSON.parse(raw);@@ -75136,13 +75145,16 @@ async function rewriteCachedPackageLocalFileDependencies(pluginRoot, sourceRoot)changed = true;}}- if (changed)+ if (changed) {await writeFile2(packageJsonPath, `${JSON.stringify(parsed, null, "\t")}`);+ rewroteAnyPackageJson = true;+ }}if (packageLock.changed)await writeFile2(packageLock.path, `${JSON.stringify(packageLock.value, null, "\t")}`);+ return rewroteAnyPackageJson;}async function readPackageLock(pluginRoot) {const path7 = join30(pluginRoot, "package-lock.json");@@ -75448,10 +75460,11 @@ async function installCachedPlugin(input) {await rm4(tempPath, { recursive: true, force: true });try {await copyDirectory(input.sourcePath, tempPath);- await rewriteCachedPackageLocalFileDependencies(tempPath, input.sourcePath);+ const rewroteLocalFileDependencies = await rewriteCachedPackageLocalFileDependencies(tempPath, input.sourcePath);await copyBundledMcpRuntimeDists({ pluginRoot: tempPath, sourceRoot: input.sourcePath });await copyRootRuntimeDists({ pluginRoot: tempPath, sourcePath: input.sourcePath });- await maybeRunNpmInstall(tempPath, input.runCommand, npmInstallEnv, ["ci", "--omit=dev"]);+ const installArgs = rewroteLocalFileDependencies ? ["install", "--omit=dev", "--no-audit", "--no-fund"] : ["ci", "--omit=dev"];+ await maybeRunNpmInstall(tempPath, input.runCommand, npmInstallEnv, installArgs);await removeCachedManagedNpmBinShims(tempPath);if (input.buildSource === false)await maybeRunNpmSyncSkills(tempPath, input.runCommand, env2);@@ -77139,11 +77152,11 @@ async function trustedHookStatesForPlugin(input) {const manifestPath = join40(input.pluginRoot, ".codex-plugin", "plugin.json");if (!await exists(manifestPath))return [];- const manifest = JSON.parse(await readFile12(manifestPath, "utf8"));- if (!isPlainRecord3(manifest))+ const manifest2 = JSON.parse(await readFile12(manifestPath, "utf8"));+ if (!isPlainRecord3(manifest2))return [];const states = [];- for (const hookPath of hookManifestPaths2(manifest.hooks)) {+ for (const hookPath of hookManifestPaths2(manifest2.hooks)) {const hooksPath = join40(input.pluginRoot, hookPath);if (!await exists(hooksPath))continue;@@ -77324,6 +77337,10 @@ var MANAGED_REASONING_DEFAULT_UPGRADES = new Map([{previous: { model: "gpt-5.6-sol", effort: "xhigh" },current: { model: "gpt-5.6-sol", effort: "max" }+ },+ {+ previous: { model: "gpt-5.6-sol", effort: "max" },+ current: { model: "gpt-5.6-sol", effort: "high" }}]],@@ -77333,6 +77350,37 @@ var MANAGED_REASONING_DEFAULT_UPGRADES = new Map([{previous: { model: "gpt-5.6-sol", effort: "high" },current: { model: "gpt-5.6-luna", effort: "max" }+ },+ {+ previous: { model: "gpt-5.6-luna", effort: "max" },+ current: { model: "gpt-5.6-terra", effort: "high" }+ }+ ]+ ],+ [+ "lazycodex-worker-high",+ [+ {+ previous: { model: "gpt-5.6-sol", effort: "max" },+ current: { model: "gpt-5.6-sol", effort: "medium" }+ }+ ]+ ],+ [+ "lazycodex-code-reviewer",+ [+ {+ previous: { model: "gpt-5.6-sol", effort: "xhigh" },+ current: { model: "gpt-5.6-terra", effort: "medium" }+ }+ ]+ ],+ [+ "lazycodex-clone-fidelity-reviewer",+ [+ {+ previous: { model: "gpt-5.6-sol", effort: "xhigh" },+ current: { model: "gpt-5.6-terra", effort: "high" }}]],@@ -77351,6 +77399,10 @@ var MANAGED_REASONING_DEFAULT_UPGRADES = new Map([{previous: { model: "gpt-5.6-sol", effort: "xhigh" },current: { model: "gpt-5.6-sol", effort: "high" }+ },+ {+ previous: { model: "gpt-5.6-sol", effort: "high" },+ current: { model: "gpt-5.6-sol", effort: "low" }}]]@@ -77977,7 +78029,7 @@ function normalizeHookStatusVersion(version) {// packages/omo-codex/src/install/codex-process.tsinit_bun_spawn_shim();-var WINDOWS_CMD_SHIM_COMMANDS = new Set(["npm", "npx"]);+var WINDOWS_CMD_SHIM_COMMANDS = new Set(["codex", "npm", "npx"]);function resolveRunCommandInvocation(command, args, platform = process.platform) {if (platform !== "win32" || !WINDOWS_CMD_SHIM_COMMANDS.has(command.toLowerCase())) {return { command, args: [...args] };@@ -78682,12 +78734,12 @@ async function runCodexInstaller(options = {}) {const agentConfigs = new Map;for (const entry of marketplace.plugins) {const sourcePath = resolvePluginSource(codexPackageRoot, entry, { pathOverride: "./plugin" });- const manifest = await readPluginManifest(sourcePath);- if (manifest.name !== entry.name) {- throw new Error(`plugin manifest name ${JSON.stringify(manifest.name)} does not match marketplace name ${JSON.stringify(entry.name)}`);+ const manifest2 = await readPluginManifest(sourcePath);+ if (manifest2.name !== entry.name) {+ throw new Error(`plugin manifest name ${JSON.stringify(manifest2.name)} does not match marketplace name ${JSON.stringify(entry.name)}`);}const version2 = resolveLazyCodexPluginVersion({- manifestVersion: manifest.version,+ manifestVersion: manifest2.version,marketplaceName: marketplace.name,pluginName: entry.name,distributionManifest,@@ -97130,7 +97182,9 @@ var ClaudeCodeConfigSchema = exports_external.object({var CodegraphConfigSchema = exports_external.object({auto_init: exports_external.boolean().default(true),auto_provision: exports_external.boolean().default(true),+ daemon: exports_external.boolean().default(false),enabled: exports_external.boolean().default(true),+ excluded_roots: exports_external.array(exports_external.string()).optional(),install_dir: exports_external.string().optional(),telemetry: exports_external.boolean().optional(),watch_debounce_ms: exports_external.number().nonnegative().optional()@@ -102115,10 +102169,10 @@ async function gatherCodexSummary(deps = {}) {const binDir = resolveCodexInstallerBinDir({ binDir: deps.binDir, codexHome, env: process.env });const detection = await (deps.detectCodexInstallation ?? detectCodexInstallation)();const pluginRoot = await resolveInstalledPluginRoot(codexHome);- const manifest = pluginRoot === null ? null : await readJson(join82(pluginRoot, ".codex-plugin", "plugin.json"));+ const manifest2 = pluginRoot === null ? null : await readJson(join82(pluginRoot, ".codex-plugin", "plugin.json"));const installSnapshot = pluginRoot === null ? null : await readJson(join82(pluginRoot, "lazycodex-install.json"));const configPath = join82(codexHome, "config.toml");- const pluginVersion = stringField(manifest, "version");+ const pluginVersion = stringField(manifest2, "version");return {codexPath: detection.found && "path" in detection ? detection.path : null,codexSource: detection.found ? detection.source : null,@@ -102465,12 +102519,12 @@ async function auditBundleTargets(pluginRoot) {const broken = [];let referencedCount = 0;for (const manifestPath of await findManifestPaths(pluginRoot, ".mcp.json")) {- const manifest = await readJson2(manifestPath);- if (manifest === null || !isRecord6(manifest["mcpServers"]))+ const manifest2 = await readJson2(manifestPath);+ if (manifest2 === null || !isRecord6(manifest2["mcpServers"]))continue;const manifestRoot = dirname32(manifestPath);const isRootManifest = resolve23(manifestRoot) === resolve23(pluginRoot);- for (const server2 of Object.values(manifest["mcpServers"])) {+ for (const server2 of Object.values(manifest2["mcpServers"])) {if (!isRecord6(server2) || !Array.isArray(server2["args"]))continue;for (const arg of server2["args"]) {@@ -102484,11 +102538,11 @@ async function auditBundleTargets(pluginRoot) {}}for (const hookManifestPath of await findHookManifestPaths(pluginRoot)) {- const manifest = await readJson2(hookManifestPath);- if (manifest === null)+ const manifest2 = await readJson2(hookManifestPath);+ if (manifest2 === null)continue;const commands2 = [];- collectHookCommands(manifest, commands2);+ collectHookCommands(manifest2, commands2);const hookPluginRoot = dirname32(dirname32(hookManifestPath));for (const command of commands2) {for (const relativePath of extractPluginRootPaths(command)) {diff --git a/plugins/omo/dist/cli/index.js b/plugins/omo/dist/cli/index.jsindex c77e71ac..9122f26e 100755--- a/plugins/omo/dist/cli/index.js+++ b/plugins/omo/dist/cli/index.js@@ -2145,7 +2145,7 @@ var package_default;var init_package = __esm(() => {package_default = {name: "oh-my-opencode",- version: "4.19.0",+ version: "4.19.1",description: "The Best AI Agent Harness - Batteries-Included OpenCode Plugin with Multi-Model Orchestration, Parallel Background Agents, and Crafted LSP/AST Tools",main: "./dist/index.js",types: "dist/index.d.ts",@@ -2357,18 +2357,18 @@ var init_package = __esm(() => {typescript: "^6.0.3"},optionalDependencies: {- "oh-my-opencode-darwin-arm64": "4.19.0",- "oh-my-opencode-darwin-x64": "4.19.0",- "oh-my-opencode-darwin-x64-baseline": "4.19.0",- "oh-my-opencode-linux-arm64": "4.19.0",- "oh-my-opencode-linux-arm64-musl": "4.19.0",- "oh-my-opencode-linux-x64": "4.19.0",- "oh-my-opencode-linux-x64-baseline": "4.19.0",- "oh-my-opencode-linux-x64-musl": "4.19.0",- "oh-my-opencode-linux-x64-musl-baseline": "4.19.0",- "oh-my-opencode-windows-arm64": "4.19.0",- "oh-my-opencode-windows-x64": "4.19.0",- "oh-my-opencode-windows-x64-baseline": "4.19.0"+ "oh-my-opencode-darwin-arm64": "4.19.1",+ "oh-my-opencode-darwin-x64": "4.19.1",+ "oh-my-opencode-darwin-x64-baseline": "4.19.1",+ "oh-my-opencode-linux-arm64": "4.19.1",+ "oh-my-opencode-linux-arm64-musl": "4.19.1",+ "oh-my-opencode-linux-x64": "4.19.1",+ "oh-my-opencode-linux-x64-baseline": "4.19.1",+ "oh-my-opencode-linux-x64-musl": "4.19.1",+ "oh-my-opencode-linux-x64-musl-baseline": "4.19.1",+ "oh-my-opencode-windows-arm64": "4.19.1",+ "oh-my-opencode-windows-x64": "4.19.1",+ "oh-my-opencode-windows-x64-baseline": "4.19.1"},overrides: {"@earendil-works/pi-agent-core": "0.80.3",@@ -7426,6 +7426,7 @@ var init_env = __esm(() => {SAFE_CODEGRAPH_RUNTIME_ENV_KEYS = new Set(["CODEGRAPH_ALLOW_UNSAFE_NODE","CODEGRAPH_BIN",+ "CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS","CODEGRAPH_FAKE_LOG","CODEGRAPH_NO_DAEMON","CODEGRAPH_NODE_BIN",@@ -7441,6 +7442,9 @@ var init_workspace = () => {};// packages/utils/src/codegraph/guidance.tsvar init_guidance = () => {};+// packages/utils/src/codegraph/manifest.ts+var init_manifest = () => {};+// packages/utils/src/codegraph/node-support.tsfunction evaluateCodegraphNodeSupport(options = {}) {const nodeVersion = options.nodeVersion ?? process.versions.node;@@ -7569,6 +7573,7 @@ var init_resolve2 = __esm(() => {var init_codegraph = __esm(() => {init_env();init_guidance();+ init_manifest();init_provision();init_process_sweep();init_resolve2();@@ -7747,7 +7752,7 @@ function migrateModelVersions(configs, appliedMigrations) {var MODEL_VERSION_MAP, CURRENT_USER_SELECTABLE_MODELS;var init_model_versions = __esm(() => {MODEL_VERSION_MAP = {- "anthropic/claude-opus-4-4": "anthropic/claude-opus-4-7"+ "anthropic/claude-opus-4-4": "anthropic/claude-opus-4-8"};CURRENT_USER_SELECTABLE_MODELS = new Set(["anthropic/claude-opus-4-5",@@ -9195,26 +9200,25 @@ var init_agent_model_requirements = __esm(() => {fallbackChain: [{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},- { providers: ["opencode-go", "kimi-for-coding", "moonshotai", "opencode", "vercel"], model: "kimi-k3" },- { providers: ["opencode-go", "vercel"], model: "kimi-k2.6" },- { providers: ["kimi-for-coding"], model: "k2p5" },{providers: [+ "opencode-go",+ "kimi-for-coding",+ "moonshotai","opencode",+ "vercel","bailian-coding-plan",- "moonshotai","moonshotai-cn","firmware","ollama-cloud",- "aihubmix",- "vercel"+ "aihubmix"],- model: "kimi-k2.5"+ model: "kimi-k3"},- { providers: ["openai", "github-copilot", "opencode", "vercel"], model: "gpt-5.5", variant: "medium" },+ { providers: ["openai", "github-copilot", "opencode", "vercel"], model: "gpt-5.6-sol", variant: "medium" },{ providers: ["zai-coding-plan", "opencode", "bailian-coding-plan", "vercel"], model: "glm-5" },{ providers: ["opencode"], model: "big-pickle" }],@@ -9223,13 +9227,8 @@ var init_agent_model_requirements = __esm(() => {hephaestus: {fallbackChain: [{- providers: ["openai", "github-copilot", "vercel"],+ providers: ["openai", "github-copilot", "vercel", "opencode"],model: "gpt-5.6-sol",- variant: "high"- },- {- providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",variant: "medium"}],@@ -9239,8 +9238,13 @@ var init_agent_model_requirements = __esm(() => {oracle: {fallbackChain: [{- providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",+ providers: ["openai", "opencode", "vercel"],+ model: "gpt-5.6-sol",+ variant: "xhigh"+ },+ {+ providers: ["github-copilot"],+ model: "gpt-5.6-sol",variant: "high"},{@@ -9250,7 +9254,7 @@ var init_agent_model_requirements = __esm(() => {},{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},{ providers: ["opencode-go", "vercel"], model: "glm-5.2" }@@ -9282,8 +9286,8 @@ var init_agent_model_requirements = __esm(() => {},"multimodal-looker": {fallbackChain: [- { providers: ["openai", "opencode", "vercel"], model: "gpt-5.5", variant: "medium" },- { providers: ["opencode-go", "vercel"], model: "kimi-k2.6" },+ { providers: ["openai", "opencode", "vercel"], model: "gpt-5.6-sol", variant: "low" },+ { providers: ["opencode-go", "vercel"], model: "kimi-k3" },{ providers: ["zai-coding-plan", "vercel"], model: "glm-4.6v" },{ providers: ["openai", "github-copilot", "opencode", "vercel"], model: "gpt-5-nano" }]@@ -9292,12 +9296,12 @@ var init_agent_model_requirements = __esm(() => {fallbackChain: [{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},{providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",+ model: "gpt-5.6-sol",variant: "high"},{ providers: ["opencode-go", "vercel"], model: "glm-5.2" },@@ -9315,16 +9319,16 @@ var init_agent_model_requirements = __esm(() => {},{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},{providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",- variant: "high"+ model: "gpt-5.6-sol",+ variant: "medium"},{ providers: ["opencode-go", "vercel"], model: "glm-5.2" },- { providers: ["kimi-for-coding"], model: "k2p5" }+ { providers: ["kimi-for-coding"], model: "kimi-k3" }]},momus: {@@ -9340,13 +9344,18 @@ var init_agent_model_requirements = __esm(() => {variant: "high"},{- providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",+ providers: ["openai", "opencode", "vercel"],+ model: "gpt-5.6-sol",variant: "xhigh"},+ {+ providers: ["github-copilot"],+ model: "gpt-5.6-sol",+ variant: "high"+ },{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},{@@ -9360,10 +9369,10 @@ var init_agent_model_requirements = __esm(() => {atlas: {fallbackChain: [{ providers: ["anthropic", "github-copilot", "opencode", "vercel"], model: "claude-sonnet-4-6" },- { providers: ["opencode-go", "vercel"], model: "kimi-k2.6" },+ { providers: ["opencode-go", "vercel"], model: "kimi-k3" },{providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",+ model: "gpt-5.6-sol",variant: "medium"},{ providers: ["opencode-go", "vercel"], model: "minimax-m3" },@@ -9374,10 +9383,10 @@ var init_agent_model_requirements = __esm(() => {"sisyphus-junior": {fallbackChain: [{ providers: ["anthropic", "github-copilot", "opencode", "vercel"], model: "claude-sonnet-4-6" },- { providers: ["opencode-go", "vercel"], model: "kimi-k2.6" },+ { providers: ["opencode-go", "vercel"], model: "kimi-k3" },{providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",+ model: "gpt-5.6-sol",variant: "medium"},{ providers: ["opencode-go", "vercel"], model: "minimax-m3" },@@ -9403,11 +9412,11 @@ var init_category_model_requirements = __esm(() => {{ providers: ["zai-coding-plan", "opencode", "bailian-coding-plan", "vercel"], model: "glm-5" },{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},{ providers: ["opencode-go", "vercel"], model: "glm-5.2" },- { providers: ["kimi-for-coding"], model: "k2p5" }+ { providers: ["kimi-for-coding"], model: "kimi-k3" }]},ultrabrain: {@@ -9424,7 +9433,7 @@ var init_category_model_requirements = __esm(() => {},{providers: ["openai", "opencode", "vercel"],- model: "gpt-5.5",+ model: "gpt-5.6-sol",variant: "xhigh"},{@@ -9434,7 +9443,7 @@ var init_category_model_requirements = __esm(() => {},{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},{ providers: ["opencode-go", "vercel"], model: "glm-5.2" }@@ -9459,12 +9468,12 @@ var init_category_model_requirements = __esm(() => {},{providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",+ model: "gpt-5.6-sol",variant: "medium"},{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},{@@ -9472,7 +9481,7 @@ var init_category_model_requirements = __esm(() => {model: "gemini-3.1-pro",variant: "high"},- { providers: ["opencode-go", "vercel"], model: "kimi-k2.6" },+ { providers: ["opencode-go", "vercel"], model: "kimi-k3" },{ providers: ["opencode-go", "vercel"], model: "glm-5.2" }]},@@ -9485,11 +9494,11 @@ var init_category_model_requirements = __esm(() => {},{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},- { providers: ["openai", "github-copilot", "opencode", "vercel"], model: "gpt-5.5" },- { providers: ["opencode-go", "vercel"], model: "kimi-k2.6" },+ { providers: ["openai", "github-copilot", "opencode", "vercel"], model: "gpt-5.6-sol", variant: "high" },+ { providers: ["opencode-go", "vercel"], model: "kimi-k3" },{ providers: ["opencode-go", "vercel"], model: "glm-5.2" }]},@@ -9531,10 +9540,10 @@ var init_category_model_requirements = __esm(() => {},{providers: ["openai", "opencode", "vercel"],- model: "gpt-5.5",+ model: "gpt-5.6-sol",variant: "medium"},- { providers: ["opencode-go", "vercel"], model: "kimi-k2.6" },+ { providers: ["opencode-go", "vercel"], model: "kimi-k3" },{providers: ["google", "github-copilot", "opencode", "vercel"],model: "gemini-3-flash"@@ -9548,30 +9557,29 @@ var init_category_model_requirements = __esm(() => {fallbackChain: [{providers: ["anthropic", "github-copilot", "opencode", "vercel"],- model: "claude-opus-4-7",+ model: "claude-opus-4-8",variant: "max"},{providers: ["openai", "github-copilot", "opencode", "vercel"],- model: "gpt-5.5",+ model: "gpt-5.6-sol",variant: "high"},{ providers: ["zai-coding-plan", "opencode", "bailian-coding-plan", "vercel"], model: "glm-5" },- { providers: ["kimi-for-coding"], model: "k2p5" },+ { providers: ["kimi-for-coding"], model: "kimi-k3" },{ providers: ["opencode-go", "vercel"], model: "glm-5.2" },- { providers: ["opencode", "bailian-coding-plan", "vercel"], model: "kimi-k2.5" },{providers: ["opencode","bailian-coding-plan",+ "vercel","moonshotai","moonshotai-cn","firmware","ollama-cloud",- "aihubmix",- "vercel"+ "aihubmix"],- model: "kimi-k2.5"+ model: "kimi-k3"}]},@@ -9581,7 +9589,7 @@ var init_category_model_requirements = __esm(() => {providers: ["google", "github-copilot", "opencode", "vercel"],model: "gemini-3-flash"},- { providers: ["opencode-go", "vercel"], model: "kimi-k2.6" },+ { providers: ["opencode-go", "vercel"], model: "kimi-k3" },{providers: ["anthropic", "github-copilot", "opencode", "vercel"],model: "claude-sonnet-4-6"@@ -10006,7 +10014,7 @@ var CLAUDE_VERSION_DOT, GEMINI_31_PRO_PREVIEW, GEMINI_3_FLASH_PREVIEW;var init_provider_model_id_transform = __esm(() => {CLAUDE_VERSION_DOT = /claude-(\w+)-(\d+)-(\d+)/g;GEMINI_31_PRO_PREVIEW = /gemini-3\.1-pro(?!-)/g;- GEMINI_3_FLASH_PREVIEW = /gemini-3-flash(?!-)/g;+ GEMINI_3_FLASH_PREVIEW = /(?<!antigravity-)gemini-3-flash(?!-)/g;});// packages/model-core/src/known-variants.ts@@ -10801,7 +10809,7 @@ var init_anthropic_categories = __esm(() => {ANTHROPIC_CATEGORIES = [{name: "unspecified-high",- config: { model: "anthropic/claude-opus-4-7", variant: "max" },+ config: { model: "anthropic/claude-opus-4-8", variant: "max" },description: "Tasks that don't fit other categories, high effort required",promptAppend: UNSPECIFIED_HIGH_CATEGORY_PROMPT_APPEND}@@ -10959,7 +10967,7 @@ var init_kimi_categories = __esm(() => {KIMI_CATEGORIES = [{name: "writing",- config: { model: "kimi-for-coding/k2p5" },+ config: { model: "kimi-for-coding/kimi-k3" },description: "Documentation, prose, technical writing",promptAppend: WRITING_CATEGORY_PROMPT_APPEND}@@ -65188,7 +65196,7 @@ var init_claude_model_mapper = __esm(() => {init_model_normalization2();CLAUDE_CODE_ALIAS_MAP = new Map([["sonnet", `${ANTHROPIC_PREFIX}claude-sonnet-4-6`],- ["opus", `${ANTHROPIC_PREFIX}claude-opus-4-7`],+ ["opus", `${ANTHROPIC_PREFIX}claude-opus-4-8`],["haiku", `${ANTHROPIC_PREFIX}claude-haiku-4-5`]]);});@@ -65940,10 +65948,10 @@ var init_openai_only_model_catalog = __esm(() => {librarian: { model: "openai/gpt-5.4-mini-fast" }};OPENAI_ONLY_CATEGORY_OVERRIDES = {- artistry: { model: "openai/gpt-5.5", variant: "xhigh" },+ artistry: { model: "openai/gpt-5.6-sol", variant: "xhigh" },quick: { model: "openai/gpt-5.4-mini" },- "visual-engineering": { model: "openai/gpt-5.5", variant: "high" },- writing: { model: "openai/gpt-5.5", variant: "medium" }+ "visual-engineering": { model: "openai/gpt-5.6-sol", variant: "high" },+ writing: { model: "openai/gpt-5.6-sol", variant: "medium" }};});@@ -72657,7 +72665,7 @@ var package_default2;var init_package2 = __esm(() => {package_default2 = {name: "@oh-my-opencode/omo-codex",- version: "4.19.0",+ version: "4.19.1",type: "module",private: true,description: "Codex harness adapter for oh-my-openagent. Vendored Codex plugin namespace (omo) + TypeScript installer + telemetry.",@@ -75045,6 +75053,7 @@ async function rewriteCachedPackageLocalFileDependencies(pluginRoot, sourceRoot)const packageJsonPaths = [];await collectPackageJsonPaths(pluginRoot, pluginRoot, packageJsonPaths);const packageLock = await readPackageLock(pluginRoot);+ let rewroteAnyPackageJson = false;for (const packageJsonPath of packageJsonPaths) {const raw = await readFile5(packageJsonPath, "utf8");const parsed = JSON.parse(raw);@@ -75080,13 +75089,16 @@ async function rewriteCachedPackageLocalFileDependencies(pluginRoot, sourceRoot)changed = true;}}- if (changed)+ if (changed) {await writeFile2(packageJsonPath, `${JSON.stringify(parsed, null, "\t")}`);+ rewroteAnyPackageJson = true;+ }}if (packageLock.changed)await writeFile2(packageLock.path, `${JSON.stringify(packageLock.value, null, "\t")}`);+ return rewroteAnyPackageJson;}async function readPackageLock(pluginRoot) {const path7 = join30(pluginRoot, "package-lock.json");@@ -75392,10 +75404,11 @@ async function installCachedPlugin(input) {await rm4(tempPath, { recursive: true, force: true });try {await copyDirectory(input.sourcePath, tempPath);- await rewriteCachedPackageLocalFileDependencies(tempPath, input.sourcePath);+ const rewroteLocalFileDependencies = await rewriteCachedPackageLocalFileDependencies(tempPath, input.sourcePath);await copyBundledMcpRuntimeDists({ pluginRoot: tempPath, sourceRoot: input.sourcePath });await copyRootRuntimeDists({ pluginRoot: tempPath, sourcePath: input.sourcePath });- await maybeRunNpmInstall(tempPath, input.runCommand, npmInstallEnv, ["ci", "--omit=dev"]);+ const installArgs = rewroteLocalFileDependencies ? ["install", "--omit=dev", "--no-audit", "--no-fund"] : ["ci", "--omit=dev"];+ await maybeRunNpmInstall(tempPath, input.runCommand, npmInstallEnv, installArgs);await removeCachedManagedNpmBinShims(tempPath);if (input.buildSource === false)await maybeRunNpmSyncSkills(tempPath, input.runCommand, env2);@@ -77083,11 +77096,11 @@ async function trustedHookStatesForPlugin(input) {const manifestPath = join40(input.pluginRoot, ".codex-plugin", "plugin.json");if (!await exists(manifestPath))return [];- const manifest = JSON.parse(await readFile12(manifestPath, "utf8"));- if (!isPlainRecord3(manifest))+ const manifest2 = JSON.parse(await readFile12(manifestPath, "utf8"));+ if (!isPlainRecord3(manifest2))return [];const states = [];- for (const hookPath of hookManifestPaths2(manifest.hooks)) {+ for (const hookPath of hookManifestPaths2(manifest2.hooks)) {const hooksPath = join40(input.pluginRoot, hookPath);if (!await exists(hooksPath))continue;@@ -77268,6 +77281,10 @@ var MANAGED_REASONING_DEFAULT_UPGRADES = new Map([{previous: { model: "gpt-5.6-sol", effort: "xhigh" },current: { model: "gpt-5.6-sol", effort: "max" }+ },+ {+ previous: { model: "gpt-5.6-sol", effort: "max" },+ current: { model: "gpt-5.6-sol", effort: "high" }}]],@@ -77277,6 +77294,37 @@ var MANAGED_REASONING_DEFAULT_UPGRADES = new Map([{previous: { model: "gpt-5.6-sol", effort: "high" },current: { model: "gpt-5.6-luna", effort: "max" }+ },+ {+ previous: { model: "gpt-5.6-luna", effort: "max" },+ current: { model: "gpt-5.6-terra", effort: "high" }+ }+ ]+ ],+ [+ "lazycodex-worker-high",+ [+ {+ previous: { model: "gpt-5.6-sol", effort: "max" },+ current: { model: "gpt-5.6-sol", effort: "medium" }+ }+ ]+ ],+ [+ "lazycodex-code-reviewer",+ [+ {+ previous: { model: "gpt-5.6-sol", effort: "xhigh" },+ current: { model: "gpt-5.6-terra", effort: "medium" }+ }+ ]+ ],+ [+ "lazycodex-clone-fidelity-reviewer",+ [+ {+ previous: { model: "gpt-5.6-sol", effort: "xhigh" },+ current: { model: "gpt-5.6-terra", effort: "high" }}]],@@ -77295,6 +77343,10 @@ var MANAGED_REASONING_DEFAULT_UPGRADES = new Map([{previous: { model: "gpt-5.6-sol", effort: "xhigh" },current: { model: "gpt-5.6-sol", effort: "high" }+ },+ {+ previous: { model: "gpt-5.6-sol", effort: "high" },+ current: { model: "gpt-5.6-sol", effort: "low" }}]]@@ -77921,7 +77973,7 @@ function normalizeHookStatusVersion(version) {// packages/omo-codex/src/install/codex-process.tsinit_bun_spawn_shim();-var WINDOWS_CMD_SHIM_COMMANDS = new Set(["npm", "npx"]);+var WINDOWS_CMD_SHIM_COMMANDS = new Set(["codex", "npm", "npx"]);function resolveRunCommandInvocation(command, args, platform = process.platform) {if (platform !== "win32" || !WINDOWS_CMD_SHIM_COMMANDS.has(command.toLowerCase())) {return { command, args: [...args] };@@ -78626,12 +78678,12 @@ async function runCodexInstaller(options = {}) {const agentConfigs = new Map;for (const entry of marketplace.plugins) {const sourcePath = resolvePluginSource(codexPackageRoot, entry, { pathOverride: "./plugin" });- const manifest = await readPluginManifest(sourcePath);- if (manifest.name !== entry.name) {- throw new Error(`plugin manifest name ${JSON.stringify(manifest.name)} does not match marketplace name ${JSON.stringify(entry.name)}`);+ const manifest2 = await readPluginManifest(sourcePath);+ if (manifest2.name !== entry.name) {+ throw new Error(`plugin manifest name ${JSON.stringify(manifest2.name)} does not match marketplace name ${JSON.stringify(entry.name)}`);}const version2 = resolveLazyCodexPluginVersion({- manifestVersion: manifest.version,+ manifestVersion: manifest2.version,marketplaceName: marketplace.name,pluginName: entry.name,distributionManifest,@@ -97074,7 +97126,9 @@ var ClaudeCodeConfigSchema = exports_external.object({var CodegraphConfigSchema = exports_external.object({auto_init: exports_external.boolean().default(true),auto_provision: exports_external.boolean().default(true),+ daemon: exports_external.boolean().default(false),enabled: exports_external.boolean().default(true),+ excluded_roots: exports_external.array(exports_external.string()).optional(),install_dir: exports_external.string().optional(),telemetry: exports_external.boolean().optional(),watch_debounce_ms: exports_external.number().nonnegative().optional()@@ -102059,10 +102113,10 @@ async function gatherCodexSummary(deps = {}) {const binDir = resolveCodexInstallerBinDir({ binDir: deps.binDir, codexHome, env: process.env });const detection = await (deps.detectCodexInstallation ?? detectCodexInstallation)();const pluginRoot = await resolveInstalledPluginRoot(codexHome);- const manifest = pluginRoot === null ? null : await readJson(join82(pluginRoot, ".codex-plugin", "plugin.json"));+ const manifest2 = pluginRoot === null ? null : await readJson(join82(pluginRoot, ".codex-plugin", "plugin.json"));const installSnapshot = pluginRoot === null ? null : await readJson(join82(pluginRoot, "lazycodex-install.json"));const configPath = join82(codexHome, "config.toml");- const pluginVersion = stringField(manifest, "version");+ const pluginVersion = stringField(manifest2, "version");return {codexPath: detection.found && "path" in detection ? detection.path : null,codexSource: detection.found ? detection.source : null,@@ -102409,12 +102463,12 @@ async function auditBundleTargets(pluginRoot) {const broken = [];let referencedCount = 0;for (const manifestPath of await findManifestPaths(pluginRoot, ".mcp.json")) {- const manifest = await readJson2(manifestPath);- if (manifest === null || !isRecord6(manifest["mcpServers"]))+ const manifest2 = await readJson2(manifestPath);+ if (manifest2 === null || !isRecord6(manifest2["mcpServers"]))continue;const manifestRoot = dirname32(manifestPath);const isRootManifest = resolve23(manifestRoot) === resolve23(pluginRoot);- for (const server2 of Object.values(manifest["mcpServers"])) {+ for (const server2 of Object.values(manifest2["mcpServers"])) {if (!isRecord6(server2) || !Array.isArray(server2["args"]))continue;for (const arg of server2["args"]) {@@ -102428,11 +102482,11 @@ async function auditBundleTargets(pluginRoot) {}}for (const hookManifestPath of await findHookManifestPaths(pluginRoot)) {- const manifest = await readJson2(hookManifestPath);- if (manifest === null)+ const manifest2 = await readJson2(hookManifestPath);+ if (manifest2 === null)continue;const commands2 = [];- collectHookCommands(manifest, commands2);+ collectHookCommands(manifest2, commands2);const hookPluginRoot = dirname32(dirname32(hookManifestPath));for (const command of commands2) {for (const relativePath of extractPluginRootPaths(command)) {diff --git a/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json b/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.jsonindex 61a13335..b4ff1396 100644--- a/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json+++ b/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/git-bash/dist/cli.js\" hook post-compact","timeout": 5,- "statusMessage": "(OmO 4.19.0) Resetting Git Bash MCP Reminder",+ "statusMessage": "(OmO 4.19.1) Resetting Git Bash MCP Reminder","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\git-bash\\dist\\cli.js\" hook post-compact"}],diff --git a/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json b/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.jsonindex ba3b333b..cc46d857 100644--- a/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json+++ b/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/lsp/dist/cli.js\" hook post-compact","timeout": 5,- "statusMessage": "(OmO 4.19.0) Resetting LSP Diagnostics Cache",+ "statusMessage": "(OmO 4.19.1) Resetting LSP Diagnostics Cache","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\lsp\\dist\\cli.js\" hook post-compact"}],diff --git a/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json b/plugins/omo/hooks/post-compact-resetting-project-rule-cache.jsonindex ce18d1ae..cc380385 100644--- a/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json+++ b/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook post-compact","timeout": 10,- "statusMessage": "(OmO 4.19.0) Resetting Project Rule Cache",+ "statusMessage": "(OmO 4.19.1) Resetting Project Rule Cache","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook post-compact"}],diff --git a/plugins/omo/hooks/post-tool-use-checking-codegraph-init-guidance.json b/plugins/omo/hooks/post-tool-use-checking-codegraph-init-guidance.jsonindex abd58fd3..69e4d371 100644--- a/plugins/omo/hooks/post-tool-use-checking-codegraph-init-guidance.json+++ b/plugins/omo/hooks/post-tool-use-checking-codegraph-init-guidance.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/codegraph/dist/cli.js\" hook post-tool-use","timeout": 5,- "statusMessage": "(OmO 4.19.0) Checking CodeGraph Init Guidance",+ "statusMessage": "(OmO 4.19.1) Checking CodeGraph Init Guidance","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\codegraph\\dist\\cli.js\" hook post-tool-use"}],diff --git a/plugins/omo/hooks/post-tool-use-checking-comments.json b/plugins/omo/hooks/post-tool-use-checking-comments.jsonindex bf6a92cc..7d924a4a 100644--- a/plugins/omo/hooks/post-tool-use-checking-comments.json+++ b/plugins/omo/hooks/post-tool-use-checking-comments.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/comment-checker/dist/cli.js\" hook post-tool-use","timeout": 30,- "statusMessage": "(OmO 4.19.0) Checking Comments",+ "statusMessage": "(OmO 4.19.1) Checking Comments","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\comment-checker\\dist\\cli.js\" hook post-tool-use"}],diff --git a/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json b/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.jsonindex d280bf9d..b2511df4 100644--- a/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json+++ b/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/lsp/dist/cli.js\" hook post-tool-use","timeout": 60,- "statusMessage": "(OmO 4.19.0) Checking LSP Diagnostics",+ "statusMessage": "(OmO 4.19.1) Checking LSP Diagnostics","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\lsp\\dist\\cli.js\" hook post-tool-use"}],diff --git a/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json b/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.jsonindex bd63a2a8..3da5e83e 100644--- a/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json+++ b/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/teammode/dist/cli.js\" hook post-tool-use","timeout": 10,- "statusMessage": "(OmO 4.19.0) Checking Thread Title Hygiene",+ "statusMessage": "(OmO 4.19.1) Checking Thread Title Hygiene","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\teammode\\dist\\cli.js\" hook post-tool-use"}]diff --git a/plugins/omo/hooks/post-tool-use-matching-project-rules.json b/plugins/omo/hooks/post-tool-use-matching-project-rules.jsonindex 9ac1b544..2741c951 100644--- a/plugins/omo/hooks/post-tool-use-matching-project-rules.json+++ b/plugins/omo/hooks/post-tool-use-matching-project-rules.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook post-tool-use","timeout": 10,- "statusMessage": "(OmO 4.19.0) Matching Project Rules",+ "statusMessage": "(OmO 4.19.1) Matching Project Rules","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook post-tool-use"}],diff --git a/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json b/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.jsonindex 4cf02b36..a5248321 100644--- a/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json+++ b/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook pre-tool-use","timeout": 5,- "statusMessage": "(OmO 4.19.0) Enforcing Unlimited Goal Budget",+ "statusMessage": "(OmO 4.19.1) Enforcing Unlimited Goal Budget","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook pre-tool-use"}],diff --git a/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json b/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.jsonindex bc3e728c..a8b409d8 100644--- a/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json+++ b/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook pre-tool-use-spawn","timeout": 5,- "statusMessage": "(OmO 4.19.0) Guarding Ulw-Loop Spawns",+ "statusMessage": "(OmO 4.19.1) Guarding Ulw-Loop Spawns","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook pre-tool-use-spawn"}]diff --git a/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json b/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.jsonindex cb8499a3..90043764 100644--- a/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json+++ b/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/git-bash/dist/cli.js\" hook pre-tool-use","timeout": 5,- "statusMessage": "(OmO 4.19.0) Recommending Git Bash MCP",+ "statusMessage": "(OmO 4.19.1) Recommending Git Bash MCP","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\git-bash\\dist\\cli.js\" hook pre-tool-use"}],diff --git a/plugins/omo/hooks/session-start-checking-auto-update.json b/plugins/omo/hooks/session-start-checking-auto-update.jsonindex 96859f50..06d841f9 100644--- a/plugins/omo/hooks/session-start-checking-auto-update.json+++ b/plugins/omo/hooks/session-start-checking-auto-update.json@@ -6,8 +6,8 @@{"type": "command","command": "node \"${PLUGIN_ROOT}/scripts/auto-update.mjs\" hook session-start",- "timeout": 5,- "statusMessage": "(OmO 4.19.0) Checking Auto Update",+ "timeout": 15,+ "statusMessage": "(OmO 4.19.1) Checking Auto Update","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\scripts\\auto-update.mjs\" hook session-start"}],diff --git a/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json b/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.jsonindex d4592619..5d7c1f01 100644--- a/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json+++ b/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json@@ -8,7 +8,7 @@"command": "node \"${PLUGIN_ROOT}/components/bootstrap/dist/cli.js\" hook session-start","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\bootstrap.ps1\"","timeout": 30,- "statusMessage": "(OmO 4.19.0) Checking Bootstrap Provisioning"+ "statusMessage": "(OmO 4.19.1) Checking Bootstrap Provisioning"}]}diff --git a/plugins/omo/hooks/session-start-checking-codegraph-bootstrap.json b/plugins/omo/hooks/session-start-checking-codegraph-bootstrap.jsonindex 97ad004c..59927e1e 100644--- a/plugins/omo/hooks/session-start-checking-codegraph-bootstrap.json+++ b/plugins/omo/hooks/session-start-checking-codegraph-bootstrap.json@@ -6,8 +6,8 @@{"type": "command","command": "node \"${PLUGIN_ROOT}/components/codegraph/dist/cli.js\" hook session-start",- "timeout": 5,- "statusMessage": "(OmO 4.19.0) Checking CodeGraph Bootstrap",+ "timeout": 15,+ "statusMessage": "(OmO 4.19.1) Checking CodeGraph Bootstrap","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\codegraph\\dist\\cli.js\" hook session-start"}]diff --git a/plugins/omo/hooks/session-start-loading-project-rules.json b/plugins/omo/hooks/session-start-loading-project-rules.jsonindex 709309ad..f488f3dd 100644--- a/plugins/omo/hooks/session-start-loading-project-rules.json+++ b/plugins/omo/hooks/session-start-loading-project-rules.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook session-start","timeout": 10,- "statusMessage": "(OmO 4.19.0) Loading Project Rules",+ "statusMessage": "(OmO 4.19.1) Loading Project Rules","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook session-start"}]diff --git a/plugins/omo/hooks/session-start-recording-session-telemetry.json b/plugins/omo/hooks/session-start-recording-session-telemetry.jsonindex 77c924b7..55f6df07 100644--- a/plugins/omo/hooks/session-start-recording-session-telemetry.json+++ b/plugins/omo/hooks/session-start-recording-session-telemetry.json@@ -6,8 +6,8 @@{"type": "command","command": "node \"${PLUGIN_ROOT}/components/telemetry/dist/cli.js\" hook session-start",- "timeout": 5,- "statusMessage": "(OmO 4.19.0) Recording Session Telemetry",+ "timeout": 15,+ "statusMessage": "(OmO 4.19.1) Recording Session Telemetry","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\telemetry\\dist\\cli.js\" hook session-start"}]diff --git a/plugins/omo/hooks/stop-checking-start-work-continuation.json b/plugins/omo/hooks/stop-checking-start-work-continuation.jsonindex 469c5054..f5cc1749 100644--- a/plugins/omo/hooks/stop-checking-start-work-continuation.json+++ b/plugins/omo/hooks/stop-checking-start-work-continuation.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js\" hook stop","timeout": 10,- "statusMessage": "(OmO 4.19.0) Checking Start-Work Continuation",+ "statusMessage": "(OmO 4.19.1) Checking Start-Work Continuation","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\start-work-continuation\\dist\\cli.js\" hook stop"}]diff --git a/plugins/omo/hooks/stop-checking-ulw-loop-resume.json b/plugins/omo/hooks/stop-checking-ulw-loop-resume.jsonindex 90f78876..469becaf 100644--- a/plugins/omo/hooks/stop-checking-ulw-loop-resume.json+++ b/plugins/omo/hooks/stop-checking-ulw-loop-resume.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook stop","timeout": 10,- "statusMessage": "(OmO 4.19.0) Checking Ulw-Loop Resume",+ "statusMessage": "(OmO 4.19.1) Checking Ulw-Loop Resume","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook stop"}]diff --git a/plugins/omo/hooks/subagent-stop-checking-start-work-continuation.json b/plugins/omo/hooks/subagent-stop-checking-start-work-continuation.jsonindex defd9e88..d1c1a381 100644--- a/plugins/omo/hooks/subagent-stop-checking-start-work-continuation.json+++ b/plugins/omo/hooks/subagent-stop-checking-start-work-continuation.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js\" hook subagent-stop","timeout": 10,- "statusMessage": "(OmO 4.19.0) Checking Start-Work Continuation",+ "statusMessage": "(OmO 4.19.1) Checking Start-Work Continuation","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\start-work-continuation\\dist\\cli.js\" hook subagent-stop"}]diff --git a/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json b/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.jsonindex 9cd95202..c236d67c 100644--- a/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json+++ b/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/lazycodex-executor-verify/dist/cli.js\" hook subagent-stop","timeout": 10,- "statusMessage": "(OmO 4.19.0) Verifying LazyCodex Executor Evidence",+ "statusMessage": "(OmO 4.19.1) Verifying LazyCodex Executor Evidence","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\lazycodex-executor-verify\\dist\\cli.js\" hook subagent-stop"}],diff --git a/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json b/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.jsonindex bd301798..f390ad54 100644--- a/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json+++ b/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ultrawork/dist/cli.js\" hook user-prompt-submit","timeout": 5,- "statusMessage": "(OmO 4.19.0) Checking Ultrawork Trigger",+ "statusMessage": "(OmO 4.19.1) Checking Ultrawork Trigger","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ultrawork\\dist\\cli.js\" hook user-prompt-submit"}]diff --git a/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json b/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.jsonindex 3a46a18c..64739599 100644--- a/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json+++ b/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook user-prompt-submit","timeout": 10,- "statusMessage": "(OmO 4.19.0) Checking Ulw-Loop Steering",+ "statusMessage": "(OmO 4.19.1) Checking Ulw-Loop Steering","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook user-prompt-submit"}]diff --git a/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json b/plugins/omo/hooks/user-prompt-submit-loading-project-rules.jsonindex 3488e402..30765b6f 100644--- a/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json+++ b/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook user-prompt-submit","timeout": 10,- "statusMessage": "(OmO 4.19.0) Loading Project Rules",+ "statusMessage": "(OmO 4.19.1) Loading Project Rules","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook user-prompt-submit"}]diff --git a/plugins/omo/package-lock.json b/plugins/omo/package-lock.jsonindex f13f0c6a..2bdc21bf 100644--- a/plugins/omo/package-lock.json+++ b/plugins/omo/package-lock.json@@ -1,12 +1,12 @@{"name": "@sisyphuslabs/omo-codex-plugin",- "version": "4.19.0",+ "version": "4.19.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@sisyphuslabs/omo-codex-plugin",- "version": "4.19.0",+ "version": "4.19.1","workspaces": ["components/codegraph","components/comment-checker",@@ -100,7 +100,7 @@},"components/codegraph": {"name": "@sisyphuslabs/codex-codegraph",- "version": "4.19.0",+ "version": "4.19.1","bin": {"omo-codegraph": "dist/cli.js"},@@ -114,12 +114,12 @@"node": ">=20.0.0"},"optionalDependencies": {- "@colbymchenry/codegraph": "1.0.1"+ "@colbymchenry/codegraph": "1.4.1"}},"components/comment-checker": {"name": "@code-yeongyu/codex-comment-checker",- "version": "4.19.0",+ "version": "4.19.1","license": "MIT","bin": {"omo-comment-checker": "dist/cli.js"@@ -140,7 +140,7 @@},"components/git-bash": {"name": "@sisyphuslabs/codex-git-bash-hook",- "version": "4.19.0",+ "version": "4.19.1","bin": {"omo-git-bash-hook": "dist/cli.js"},@@ -155,7 +155,7 @@},"components/lazycodex-executor-verify": {"name": "@code-yeongyu/codex-lazycodex-executor-verify",- "version": "4.19.0",+ "version": "4.19.1","license": "MIT","bin": {"lazycodex-executor-verify": "dist/cli.js"@@ -172,7 +172,7 @@},"components/lsp": {"name": "@code-yeongyu/codex-lsp",- "version": "4.19.0",+ "version": "4.19.1","license": "MIT","dependencies": {"@code-yeongyu/lsp-daemon": "file:../../../../lsp-daemon",@@ -193,7 +193,7 @@},"components/rules": {"name": "@code-yeongyu/codex-rules",- "version": "4.19.0",+ "version": "4.19.1","license": "MIT","dependencies": {"picomatch": "^4.0.3"@@ -215,7 +215,7 @@},"components/start-work-continuation": {"name": "@code-yeongyu/codex-start-work-continuation",- "version": "4.19.0",+ "version": "4.19.1","license": "MIT","bin": {"omo-start-work-continuation": "dist/cli.js"@@ -232,7 +232,7 @@},"components/teammode": {"name": "@sisyphuslabs/codex-teammode",- "version": "4.19.0",+ "version": "4.19.1","devDependencies": {"@types/node": "^25.9.3","bun-types": "^1.3.1",@@ -245,7 +245,7 @@},"components/telemetry": {"name": "@code-yeongyu/codex-telemetry",- "version": "4.19.0",+ "version": "4.19.1","license": "MIT","bin": {"omo-telemetry": "dist/cli.js"@@ -263,7 +263,7 @@},"components/ultrawork": {"name": "@code-yeongyu/codex-ultrawork",- "version": "4.19.0",+ "version": "4.19.1","license": "MIT","bin": {"omo-ultrawork": "dist/cli.js"@@ -281,7 +281,7 @@},"components/ulw-loop": {"name": "@code-yeongyu/codex-ulw-loop",- "version": "4.19.0",+ "version": "4.19.1","license": "MIT","bin": {"omo-ulw-loop": "dist/cli.js",@@ -512,27 +512,27 @@"link": true},"node_modules/@colbymchenry/codegraph": {- "version": "1.0.1",- "resolved": "https://registry.npmjs.org/@colbymchenry/codegraph/-/codegraph-1.0.1.tgz",- "integrity": "sha512-Y4ZMk7wxSRI9g2wQTcW21TfLr+fw7td1Dadkll6Udl9Ll8wX3H6qtov7K/VGtHG2AFX2j1e5Lm48PTHi74mImg==",+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/@colbymchenry/codegraph/-/codegraph-1.4.1.tgz",+ "integrity": "sha512-xZayboJt6T3QBzBsBsI0eJ3J/tN4vYs6LMuvrxJVdM71yQFjrFKFeV3KsbicAgkj6AHnTXxUNk26g9BYwkNMgg==","license": "MIT","optional": true,"bin": {"codegraph": "npm-shim.js"},"optionalDependencies": {- "@colbymchenry/codegraph-darwin-arm64": "1.0.1",- "@colbymchenry/codegraph-darwin-x64": "1.0.1",- "@colbymchenry/codegraph-linux-arm64": "1.0.1",- "@colbymchenry/codegraph-linux-x64": "1.0.1",- "@colbymchenry/codegraph-win32-arm64": "1.0.1",- "@colbymchenry/codegraph-win32-x64": "1.0.1"+ "@colbymchenry/codegraph-darwin-arm64": "1.4.1",+ "@colbymchenry/codegraph-darwin-x64": "1.4.1",+ "@colbymchenry/codegraph-linux-arm64": "1.4.1",+ "@colbymchenry/codegraph-linux-x64": "1.4.1",+ "@colbymchenry/codegraph-win32-arm64": "1.4.1",+ "@colbymchenry/codegraph-win32-x64": "1.4.1"}},"node_modules/@colbymchenry/codegraph-darwin-arm64": {- "version": "1.0.1",- "resolved": "https://registry.npmjs.org/@colbymchenry/codegraph-darwin-arm64/-/codegraph-darwin-arm64-1.0.1.tgz",- "integrity": "sha512-4z3aNzR3Ml31MBVzAvFQm+bk83erdHkjnaJ0PoeM6I9T7xuTIcdAGV36i3qYwgBE4tdrghRdR0mP5MNM+OrGFA==",+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/@colbymchenry/codegraph-darwin-arm64/-/codegraph-darwin-arm64-1.4.1.tgz",+ "integrity": "sha512-USSpExjuxZWN0OeNexZp2V5fCfOI4ZekqE79CJiBdGdPbqGTB+857ImIqzWGyF/rAyyED94Wc0Cd82t+uWD30w==","cpu": ["arm64"],@@ -543,9 +543,9 @@]},"node_modules/@colbymchenry/codegraph-darwin-x64": {- "version": "1.0.1",- "resolved": "https://registry.npmjs.org/@colbymchenry/codegraph-darwin-x64/-/codegraph-darwin-x64-1.0.1.tgz",- "integrity": "sha512-KBSKl+tLCSIgV4iyi21SqYlpXL0P8DPqAnVHvvStdyYsCmkc2Heqf4oQIko+TYyFmuo65m4VpX989JkYZVGIVQ==",+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/@colbymchenry/codegraph-darwin-x64/-/codegraph-darwin-x64-1.4.1.tgz",+ "integrity": "sha512-syLC7QPsNui2hPrK58El0XQrjjdSYhsoKS5i26ieD8DVrb0adzFQrBRP8qId/wfGp078xdC54rdKvqgmbIL1WQ==","cpu": ["x64"],@@ -556,9 +556,9 @@]},"node_modules/@colbymchenry/codegraph-linux-arm64": {- "version": "1.0.1",- "resolved": "https://registry.npmjs.org/@colbymchenry/codegraph-linux-arm64/-/codegraph-linux-arm64-1.0.1.tgz",- "integrity": "sha512-2TOeL/Lx3kME+dmv2Q9hbIQFBvT6uKLdZONDRaYto+1Bcl3GrJuIu6bsu3jiJuifPhnYIL2xwUV6y+TZQ8MbTw==",+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/@colbymchenry/codegraph-linux-arm64/-/codegraph-linux-arm64-1.4.1.tgz",+ "integrity": "sha512-XC6GJ9/fTicW9CE3k2fOcUOcbtDU8mS53t+PUfzq3Py9+JiX3PtJgtBB8bmf6e45NZUF5foaLUwFXfxTTl961g==","cpu": ["arm64"],@@ -569,9 +569,9 @@]},"node_modules/@colbymchenry/codegraph-linux-x64": {- "version": "1.0.1",- "resolved": "https://registry.npmjs.org/@colbymchenry/codegraph-linux-x64/-/codegraph-linux-x64-1.0.1.tgz",- "integrity": "sha512-UENXSURJJUhcvdKoYsB5Wj6Z6O9C2afhYfG0LnL13KFWJhGXugqYKjF4KwkaeE8Po8TFul9k3f+8eXjmJwwwaQ==",+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/@colbymchenry/codegraph-linux-x64/-/codegraph-linux-x64-1.4.1.tgz",+ "integrity": "sha512-bjfa+0IyjbxpZz7ghznN4qMPoYVSiZafeZu/rXGdg3VI+kEPOPZrk2vmtWIU9tBPGVJbeU2Kwa/0Z2DkUGOJ9A==","cpu": ["x64"],@@ -582,9 +582,9 @@]},"node_modules/@colbymchenry/codegraph-win32-arm64": {- "version": "1.0.1",- "resolved": "https://registry.npmjs.org/@colbymchenry/codegraph-win32-arm64/-/codegraph-win32-arm64-1.0.1.tgz",- "integrity": "sha512-ZEG+HOakHiAe1AWMa2LgD52HyIEbWsY2FyNvDmon4Ss2889OghqUyA8BOLu5hNW+EI42JwwSXijVevn2Zn0hlg==",+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/@colbymchenry/codegraph-win32-arm64/-/codegraph-win32-arm64-1.4.1.tgz",+ "integrity": "sha512-mb5bFDhwcP49U0P2IBRhH1O5ZmnlgE8lIXTlg2dqpfLeL+XfxzyeJ+i4I0KU0h1hlNWP/u3d2k+1EGem2swDBw==","cpu": ["arm64"],@@ -595,9 +595,9 @@]},"node_modules/@colbymchenry/codegraph-win32-x64": {- "version": "1.0.1",- "resolved": "https://registry.npmjs.org/@colbymchenry/codegraph-win32-x64/-/codegraph-win32-x64-1.0.1.tgz",- "integrity": "sha512-qU6jjyma635qKJ0aaL8XU8QtYUGkWly0Mu4Wm2cSWRcNDL1v6sVoHMElgfUY7E9tK0gnU+/LbZW3MfmtqLG1GA==",+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/@colbymchenry/codegraph-win32-x64/-/codegraph-win32-x64-1.4.1.tgz",+ "integrity": "sha512-ipN6WvTKa0cSXIL6DTdACq57WnNYTjVq2wtC5uPT8F22o6Ucbcu3/w3OzKkkfwP4mkXv2cDMbuvExbnYNULyuw==","cpu": ["x64"],diff --git a/plugins/omo/package.json b/plugins/omo/package.jsonindex a7173571..c09d33ef 100644--- a/plugins/omo/package.json+++ b/plugins/omo/package.json@@ -1,6 +1,6 @@{"name": "@sisyphuslabs/omo-codex-plugin",- "version": "4.19.0",+ "version": "4.19.1","description": "Aggregate Codex plugin root for OMO components.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/shared/test/config-loader.test.ts b/plugins/omo/shared/test/config-loader.test.tsindex f2456bc9..b9baa270 100644--- a/plugins/omo/shared/test/config-loader.test.ts+++ b/plugins/omo/shared/test/config-loader.test.ts@@ -85,6 +85,49 @@ describe("getCodexOmoConfig", () => {expect(result.codegraph?.excluded_roots).toEqual(["/tmp/omo-research", "/private/tmp/omo-research"])})+ it("#given no codegraph.daemon key #when loading config #then daemon defaults to off", () => {+ // given+ const homeDir = createTemporaryDirectory("omo-codex-shared-daemon-default-home-")+ const cwd = createTemporaryDirectory("omo-codex-shared-daemon-default-project-")+ writeOmoConfig(homeDir, JSON.stringify({ codegraph: { enabled: true } }))++ // when+ const result = getCodexOmoConfig({ cwd, homeDir, env: {} })++ // then+ expect(result.codegraph?.daemon).toBeUndefined()+ expect(result.codegraph?.daemon === true).toBe(false)+ expect(result.warnings).toEqual([])+ })++ it("#given codex SOT sets codegraph.daemon=true #when loading config #then daemon opt-in is returned", () => {+ // given+ const homeDir = createTemporaryDirectory("omo-codex-shared-daemon-on-home-")+ const cwd = createTemporaryDirectory("omo-codex-shared-daemon-on-project-")+ writeOmoConfig(homeDir, JSON.stringify({ "[codex]": { codegraph: { daemon: true } } }))++ // when+ const result = getCodexOmoConfig({ cwd, homeDir, env: {} })++ // then+ expect(result.codegraph?.daemon).toBe(true)+ expect(result.warnings).toEqual([])+ })++ it("#given codex SOT sets codegraph.daemon to a non-boolean #when loading config #then the value is rejected with a warning", () => {+ // given+ const homeDir = createTemporaryDirectory("omo-codex-shared-daemon-invalid-home-")+ const cwd = createTemporaryDirectory("omo-codex-shared-daemon-invalid-project-")+ writeOmoConfig(homeDir, JSON.stringify({ "[codex]": { codegraph: { daemon: "yes" } } }))++ // when+ const result = getCodexOmoConfig({ cwd, homeDir, env: {} })++ // then+ expect(result.codegraph?.daemon).toBeUndefined()+ expect(result.warnings).toContain("config.[codex].codegraph.daemon must be a boolean")+ })+it("#given legacy env override and SOT value #when loading config #then env wins over the SOT", () => {// givenconst homeDir = createTemporaryDirectory("omo-codex-shared-env-")diff --git a/plugins/omo/skills/programming/scripts/typescript/check-no-excuse-rules.ts b/plugins/omo/skills/programming/scripts/typescript/check-no-excuse-rules.tsindex 4ad7875f..4cdb991a 100644--- a/plugins/omo/skills/programming/scripts/typescript/check-no-excuse-rules.ts+++ b/plugins/omo/skills/programming/scripts/typescript/check-no-excuse-rules.ts@@ -19,6 +19,10 @@* Usage:* bun run scripts/check-no-excuse-rules.ts <file-or-dir>...*+ * The `typescript` package is resolved from the caller project (process.cwd()),+ * not from this script's location, so the script works when executed from an+ * installed skill-cache path (e.g. ~/.codex/...) against a project checkout.+ ** Exit codes:* 0 - no violations* 1 - violations found@@ -26,9 +30,35 @@*/import fs from "node:fs"+import { createRequire } from "node:module"import path from "node:path"import process from "node:process"-import ts from "typescript"+import type * as tsTypes from "typescript"++type TsModule = typeof import("typescript")++function loadTypescriptFromCaller(): TsModule {+ // A static `import ts from "typescript"` resolves from this script's location —+ // an installed skill-cache path (e.g. ~/.codex/...) with no node_modules of its+ // own — and fails even when the checked project has typescript. Resolve from the+ // caller project (cwd) instead. When the caller has no local typescript, Bun+ // falls back to a version-only stub from its global install cache instead of+ // throwing, so the loaded module's API shape is verified as well.+ const callerRequire = createRequire(path.join(process.cwd(), "no-excuse-anchor.cjs"))+ try {+ const loaded: Partial<TsModule> = callerRequire("typescript")+ if (typeof loaded.createSourceFile === "function") return loaded as TsModule+ } catch { // no-excuse-ok: catch+ // fall through to the clear error below+ }+ console.error(+ `error: cannot resolve "typescript" from the caller project (${process.cwd()}). ` ++ "Install it in the project being checked (e.g. `bun add -d typescript`) and re-run.",+ )+ process.exit(2)+}++const ts: TsModule = loadTypescriptFromCaller()type RuleId =| "no-any-assertion"@@ -95,7 +125,7 @@ function discoverFiles(inputs: string[]): string[] {return files}-function getLineText(sourceFile: ts.SourceFile, line: number): string {+function getLineText(sourceFile: tsTypes.SourceFile, line: number): string {const lineStarts = sourceFile.getLineStarts()const start = lineStarts[line]const end = line + 1 < lineStarts.length ? lineStarts[line + 1] : sourceFile.getEnd()@@ -107,17 +137,17 @@ function analyzeFile(filePath: string): Violation[] {const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true)const violations: Violation[] = []- function pos(node: ts.Node): { line: number; column: number } {+ function pos(node: tsTypes.Node): { line: number; column: number } {const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile))return { line: line + 1, column: character + 1 }}- function lineHasOptOut(node: ts.Node): boolean {+ function lineHasOptOut(node: tsTypes.Node): boolean {const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile))return OPT_OUT_RE.test(getLineText(sourceFile, line))}- function visit(node: ts.Node): void {+ function visit(node: tsTypes.Node): void {// ── as any / as unknown ──if (ts.isAsExpression(node)) {const typeText = node.type.getText(sourceFile)diff --git a/plugins/omo/skills/ulw-loop/references/full-workflow.md b/plugins/omo/skills/ulw-loop/references/full-workflow.mdindex dd331b0b..172f6256 100644--- a/plugins/omo/skills/ulw-loop/references/full-workflow.md+++ b/plugins/omo/skills/ulw-loop/references/full-workflow.md@@ -113,9 +113,9 @@ If `ULW_LOOP_CLI` is empty, open the durable notepad first, record the missing CRun 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+omo ulw-loop create-goals --brief "<brief>" [--validation-batch-json <json-or-path>] --json+omo ulw-loop create-goals --brief-file <path> [--validation-batch-json <json-or-path>] --json+cat <brief> | omo ulw-loop create-goals --from-stdin [--validation-batch-json <json-or-path>] --json```If the existing aggregate is already complete, do not steer or force thecompleted default state for unrelated new work. Start a fresh run with@@ -145,7 +145,7 @@ Read pending goals, criteria IDs, current ledger head, blockers, and aggregate CLoop 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.+1. Run `omo ulw-loop complete-goals --json` and read the handoff, including criteria. After the first goal starts, a successful complete checkpoint normally prints the next goal instruction directly; use `complete-goals` as the manual fallback/resume path.2. Call `get_goal` and inspect active Codex state.3. Apply this table exactly:@@ -177,7 +177,7 @@ Loop per goal. Cap at 5 cycles per goal. Cap identical same-criterion failures a### Goal Completion1. Non-final aggregate goal: confirm every `essential` criterion is `pass`; non-essential criteria may remain pending. Final aggregate goal: confirm every criterion across the whole plan is `pass`.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`.+3. Run `omo ulw-loop checkpoint --goal-id <id> --status complete --evidence "<criteria evidence summary>" --codex-goal-json <snapshot> --json`; on success it auto-starts and prints the next eligible goal unless `--no-advance` is passed.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`.@@ -219,7 +219,9 @@ Use steering only for structured evidence-backed mutation. Reject natural-langua| 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`.+Command form: `omo ulw-loop steer --kind <kind> [<kind-specific-fields>] --evidence "<...>" --rationale "<...>" --json`. For multiple evidence-backed plan-shape changes discovered together, pass `--proposals-json <json-or-path>` with an array of proposals; the batch applies atomically or rejects without partial plan mutation.++Validation batches are optional aggregate-mode review boundaries declared at create time with `--validation-batch-json`. A batch-final member requires all other members resolved, all member criteria pass, and a member-spanning quality gate; split/supersede steering keeps batch membership updated.Structured prompt directives accepted: `OMO_ULW_LOOP_STEER: { ... }`, `omo.ulw-loop.steer: {...}`, `omo ulw-loop steer: {...}`.## Constraintsdiff --git a/plugins/omo/skills/ulw-plan/SKILL.md b/plugins/omo/skills/ulw-plan/SKILL.mdindex 8dd26d48..17e3290a 100644--- a/plugins/omo/skills/ulw-plan/SKILL.md+++ b/plugins/omo/skills/ulw-plan/SKILL.md@@ -13,11 +13,30 @@ You are **Prometheus**, a planning consultant. You turn a vague or large requestOutcome-first: explore a lot, ask few sharp questions - or none, when the intent is fuzzy (see routing) - and stop the moment the plan is done.+## MANDATORY OPENING ANNOUNCEMENT++The FIRST user-visible line of the turn that activates this skill MUST be exactly:++`ULW-PLAN MODE ENABLED!`++If another active mode mandates its own first line (ultrawork does), print that line first and this marker on the next line - both contracts stay satisfied.++Directly under the marker, before any exploration, state the working contract once, in your own words, carrying ALL of these commitments:++1. **Persona + no-implementation pledge** - from now on you work as Prometheus, a planning consultant, and you will never start implementation - no product-code edits, no implementer subagents - until the user explicitly says okay; even then, approval authorizes writing the plan only, and execution starts in a separate worker session (e.g. `$start-work`).+2. **Workflow preview** - the order of what happens next: parallel read-only exploration (plus outside research when the repo cannot answer) until the open unknowns are resolved; the intent verdict from INTENT ROUTING, announced; questions to the user ONLY when a genuine owner-decision survives exploration - or when exploration and research both come back empty on a fork the plan cannot proceed without; then the approval brief, and the plan is written only after the explicit okay.++Example opening (adapt the wording, keep every commitment):++> ULW-PLAN MODE ENABLED!+> From now on I am working as Prometheus, a planning consultant. I will not start any implementation until you explicitly say okay - and approval authorizes writing the plan only; execution starts separately (e.g. `$start-work`).+> Next, in order: (1) parallel read-only exploration and research, (2) intent verdict announced (CLEAR or UNCLEAR, plus whether high-accuracy review is required), (3) questions only for the forks exploration cannot settle - or where research finds nothing on a blocking decision, (4) approval brief, then (5) the plan is written after your okay.+## INTENT ROUTING - pick ONE intent reference**Review modifiers are a gate trigger, not a style cue.** If the user says "high accuracy", "ultra high accuracy", "고정밀", "deep review", or equivalent - in ANY turn, even appended to a follow-up question and even after the plan already exists - set `review_required: true` in the draft: the dual high-accuracy review (native `momus` + the independent Codex CLI review) is now REQUIRED before handoff, and if the plan already exists you run it this same turn. Answering the current question more carefully does NOT satisfy it. This does NOT choose CLEAR/UNCLEAR and does NOT suppress interview.-After grounding, make ONE judgment, record `intent: clear|unclear` plus `review_required`, **ANNOUNCE both to the user in one line**, then load ONE intent reference (you ALSO read `references/full-workflow.md` for the shared mechanics - see below). The test keys on whether the desired **OUTCOME** is clear, NOT on request length. The announcement is the user's first signal of whether they will be interviewed and whether high-accuracy review is already requested - never skip it.+After grounding, make ONE judgment, record `intent: clear|unclear` plus `review_required`, **ANNOUNCE both to the user in one line**, then load ONE intent reference (you ALSO read `references/full-workflow.md` for the shared mechanics - see below). The test keys on whether the desired **OUTCOME** is clear, NOT on request length. This verdict line and the opening announcement above are the two mandatory user-visible signals of a planning session - it tells the user whether they will be interviewed and whether high-accuracy review is already requested; never skip either.> "Intent: **CLEAR**, review required - you specified the endpoint and asked for high accuracy. I will ask only the genuine forks, then run the high-accuracy review after approval."> "Intent: **UNCLEAR**, review required - 'make auth better' is open-ended and you asked for high accuracy. I will choose best-practice defaults, then run the high-accuracy review automatically."diff --git a/plugins/omo/test/aggregate-agents.test.mjs b/plugins/omo/test/aggregate-agents.test.mjsindex 5f2d9bc3..9f30d643 100644--- a/plugins/omo/test/aggregate-agents.test.mjs+++ b/plugins/omo/test/aggregate-agents.test.mjs@@ -52,7 +52,7 @@ const lazycodexAgentInvariants = new Map(["plan.toml",{model: "gpt-5.6-sol",- effort: "max",+ effort: "high",includes: [/strategic planning consultant/i, /\.omo\/plans\/<slug>\.md/, /never implements/i],},],@@ -67,8 +67,8 @@ const lazycodexAgentInvariants = new Map([["lazycodex-worker-medium.toml",{- model: "gpt-5.6-luna",- effort: "max",+ model: "gpt-5.6-terra",+ effort: "high",includes: [/EVIDENCE_RECORDED: <path>/, /medium-difficulty/i, /smallest correct change/i],},],@@ -76,23 +76,23 @@ const lazycodexAgentInvariants = new Map(["lazycodex-worker-high.toml",{model: "gpt-5.6-sol",- effort: "max",+ effort: "medium",includes: [/EVIDENCE_RECORDED: <path>/, /high-difficulty/i, /smallest correct change/i],},],["lazycodex-clone-fidelity-reviewer.toml",{- model: "gpt-5.6-sol",- effort: "xhigh",+ model: "gpt-5.6-terra",+ effort: "high",includes: [/recommendation/, /blockers/, /\.omo\/evidence\/<goal>-clone-fidelity\.md/],},],["lazycodex-code-reviewer.toml",{- model: "gpt-5.6-sol",- effort: "xhigh",+ model: "gpt-5.6-terra",+ effort: "medium",includes: [/codeQualityStatus/, /recommendation/, /<attemptDir>\/<goalId>-code-review\.md/, /currentAttemptDir/],},],@@ -108,7 +108,7 @@ const lazycodexAgentInvariants = new Map(["lazycodex-gate-reviewer.toml",{model: "gpt-5.6-sol",- effort: "high",+ effort: "low",includes: [/APPROVE\/REJECT/, /blockers/, /<attemptDir>\/<goalId>-gate-review\.md/, /currentAttemptDir/],},],diff --git a/plugins/omo/test/aggregate-hooks.test.mjs b/plugins/omo/test/aggregate-hooks.test.mjsindex f08e94d7..9ec04889 100644--- a/plugins/omo/test/aggregate-hooks.test.mjs+++ b/plugins/omo/test/aggregate-hooks.test.mjs@@ -225,6 +225,32 @@ test("#given aggregate SessionStart hooks #when inspected #then LazyCodex auto-uassert(sessionStartCommands.some((command) => command.includes("scripts/auto-update.mjs")));});+test("#given aggregate SessionStart hooks #when inspected #then cold-start-prone hooks carry 15s timeout headroom", async () => {+ // given+ const manifests = await readAggregateHookManifests();++ // when+ const sessionStartHooks = manifests+ .filter(({ hooks }) => hooks.hooks.SessionStart)+ .flatMap(({ source, hooks }) =>+ hooks.hooks.SessionStart.flatMap((group) =>+ group.hooks.map((handler) => ({ source, command: handler.command, timeout: handler.timeout })),+ ),+ );+ const coldStartHooks = sessionStartHooks.filter(+ ({ command }) =>+ command.includes("components/telemetry/dist/cli.js") ||+ command.includes("scripts/auto-update.mjs") ||+ command.includes("components/codegraph/dist/cli.js"),+ );++ // then+ assert.equal(coldStartHooks.length, 3);+ for (const hook of coldStartHooks) {+ assert.equal(hook.timeout, 15, `${hook.source} must carry timeout 15 for cold-start headroom`);+ }+});+test("#given aggregate PostToolUse hooks #when inspected #then CodeGraph init guidance is registered for CodeGraph tools", async () => {// givenconst commandHooks = await readAggregateCommandHooks();diff --git a/plugins/omo/test/bootstrap-setup.test.mjs b/plugins/omo/test/bootstrap-setup.test.mjsindex 6f2d99c2..4ef33110 100644--- a/plugins/omo/test/bootstrap-setup.test.mjs+++ b/plugins/omo/test/bootstrap-setup.test.mjs@@ -127,6 +127,47 @@ test("#given a completed first run #when the worker setup runs again #then confi});});+test("#given a config.toml that already declares [agents.explorer] at a different path (Orca mirror) #when the worker setup runs #then no second colliding registration is added for that role", async () => {+ await withSetupFixture(async (fixture) => {+ const orcaMirrorPath = "/orca-mirrored-home/.codex/agents/explorer.toml";+ await writeFile(+ join(fixture.codexHome, "config.toml"),+ `[marketplaces.sisyphuslabs]\n${MARKETPLACE_SOURCE_LINE}\n\n[agents.explorer]\nconfig_file = "${orcaMirrorPath}"\n`,+ );++ const outcome = await runWorkerSetup(setupOptions(fixture));++ assert.deepEqual(outcome.degraded, []);+ const config = await readConfig(fixture);+ assert.equal(config.match(/\[agents\.explorer\]/g)?.length, 1, "exactly one [agents.explorer] block");+ assert.ok(+ config.includes(`[agents.explorer]\nconfig_file = "${orcaMirrorPath}"`),+ "the pre-existing mirrored entry stays untouched",+ );+ assert.ok(+ !config.includes('config_file = "./agents/explorer.toml"'),+ "no colliding ./agents registration for the mirrored role",+ );+ assert.match(config, /\[agents\.metis\]\nconfig_file = "\.\/agents\/metis\.toml"/);+ assert.equal(+ await readFile(join(fixture.codexHome, "agents", "explorer.toml"), "utf8"),+ BUNDLED_EXPLORER_TOML,+ "the linked toml is still staged for Codex directory discovery",+ );+ });+});++test("#given a config.toml with no pre-existing agent entries #when the worker setup runs #then all bundled registrations are written", async () => {+ await withSetupFixture(async (fixture) => {+ const outcome = await runWorkerSetup(setupOptions(fixture));++ assert.deepEqual(outcome.degraded, []);+ const config = await readConfig(fixture);+ assert.match(config, /\[agents\.explorer\]\nconfig_file = "\.\/agents\/explorer\.toml"/);+ assert.match(config, /\[agents\.metis\]\nconfig_file = "\.\/agents\/metis\.toml"/);+ });+});+test("#given a package-relative CodeGraph MCP path #when worker setup runs #then the path is stamped absolute", async () => {await withSetupFixture(async (fixture) => {await writeFile(