Skip to content

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

chore: sync Codex marketplace v5.0.0-beta.63

github-actions[bot]4c76e726313d
diff --git a/plugins/omo/.codex-plugin/plugin.json b/plugins/omo/.codex-plugin/plugin.json
index 67a3ca81..f57dacc2 100644
--- a/plugins/omo/.codex-plugin/plugin.json
+++ b/plugins/omo/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "omo",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"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.js
index 2fae858b..2ad01c02 100755
--- a/plugins/omo/components/bootstrap/dist/cli.js
+++ b/plugins/omo/components/bootstrap/dist/cli.js
@@ -6106,6 +6106,7 @@ var OmoTaskSettingsSchema = object({
model_concurrency: record(string2(), number2().int().nonnegative()).optional(),
max_depth: number2().int().nonnegative().default(1),
residency_max_children: ResidencyMaxChildrenInputSchema.default(8),
+ resident_idle_timeout_ms: number2().int().positive().max(Number.MAX_SAFE_INTEGER).default(900000),
ttl_ms: number2().int().positive().default(86400000),
state_dir: string2().optional(),
reattach_on_reconcile: boolean2().optional(),
@@ -6150,6 +6151,7 @@ var OmoTaskSettingsLayerSchema = object({
model_concurrency: record(string2(), number2().int().nonnegative()).optional(),
max_depth: number2().int().nonnegative().optional(),
residency_max_children: ResidencyMaxChildrenInputSchema.optional(),
+ resident_idle_timeout_ms: number2().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
ttl_ms: number2().int().positive().optional(),
state_dir: string2().optional(),
reattach_on_reconcile: boolean2().optional(),
diff --git a/plugins/omo/components/bootstrap/hooks/hooks.json b/plugins/omo/components/bootstrap/hooks/hooks.json
index 1f87fda6..dbd59590 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 5.0.0-beta.62) Checking Bootstrap Provisioning"
+ "statusMessage": "(OmO 5.0.0-beta.63) Checking Bootstrap Provisioning"
}
]
}
diff --git a/plugins/omo/components/bootstrap/package.json b/plugins/omo/components/bootstrap/package.json
index 0065fd18..17812102 100644
--- a/plugins/omo/components/bootstrap/package.json
+++ b/plugins/omo/components/bootstrap/package.json
@@ -1,6 +1,6 @@
{
"name": "@sisyphuslabs/codex-bootstrap",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"description": "Codex SessionStart bootstrap component that provisions LazyCodex runtime dependencies from a detached worker.",
"type": "module",
"private": true,
diff --git a/plugins/omo/components/comment-checker/hooks/hooks.json b/plugins/omo/components/comment-checker/hooks/hooks.json
index dafe1ce1..61c72bcf 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 5.0.0-beta.62) Checking Comments"
+ "statusMessage": "(OmO 5.0.0-beta.63) Checking Comments"
}
]
}
diff --git a/plugins/omo/components/comment-checker/package.json b/plugins/omo/components/comment-checker/package.json
index ff6eb333..b1fa2949 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": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"description": "Codex plugin that runs comment-checker after edit-like PostToolUse hooks.",
"type": "module",
"packageManager": "[email protected]",
diff --git a/plugins/omo/components/git-bash/hooks/hooks.json b/plugins/omo/components/git-bash/hooks/hooks.json
index 075d8bef..a200719d 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 5.0.0-beta.62) Recommending Git Bash MCP"
+ "statusMessage": "(OmO 5.0.0-beta.63) Recommending Git Bash MCP"
}
]
}
@@ -20,7 +20,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.62) Resetting Git Bash MCP Reminder"
+ "statusMessage": "(OmO 5.0.0-beta.63) Resetting Git Bash MCP Reminder"
}
]
}
diff --git a/plugins/omo/components/git-bash/package.json b/plugins/omo/components/git-bash/package.json
index a4bc7a34..dee4173f 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": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"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.json
index 58693aa2..9270d1ac 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 5.0.0-beta.62) Verifying LazyCodex Executor Evidence"
+ "statusMessage": "(OmO 5.0.0-beta.63) Verifying LazyCodex Executor Evidence"
}
]
}
diff --git a/plugins/omo/components/lazycodex-executor-verify/package.json b/plugins/omo/components/lazycodex-executor-verify/package.json
index 10b48b23..60437222 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": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"description": "Codex SubagentStop evidence verifier for LazyCodex executor completions.",
"type": "module",
"packageManager": "[email protected]",
diff --git a/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json b/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json
index 116ec94e..336a3236 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": "5.0.0-beta.62",
- "inputDigest": "sha256:e446f10ad4c491792dbc8ed087ce021ad5586be482dffee363dd2f14c242f003",
+ "version": "5.0.0-beta.63",
+ "inputDigest": "sha256:3a61242cf504041a49eedabaef45c33f1b57d48589074efffeccfa0820dcfdef",
"outputs": [
{
"path": "cli.d.ts",
diff --git a/plugins/omo/components/lsp/hooks/hooks.json b/plugins/omo/components/lsp/hooks/hooks.json
index 6c247793..2129011f 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 5.0.0-beta.62) Checking LSP Diagnostics"
+ "statusMessage": "(OmO 5.0.0-beta.63) Checking LSP Diagnostics"
}
]
}
@@ -21,7 +21,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.62) Resetting LSP Diagnostics Cache"
+ "statusMessage": "(OmO 5.0.0-beta.63) Resetting LSP Diagnostics Cache"
}
]
}
diff --git a/plugins/omo/components/lsp/package.json b/plugins/omo/components/lsp/package.json
index d029e1a1..f4b519a6 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": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"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/hooks/hooks.json b/plugins/omo/components/rules/hooks/hooks.json
index cb6ff0d2..631cb5d1 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 5.0.0-beta.62) Loading Project Rules"
+ "statusMessage": "(OmO 5.0.0-beta.63) Loading Project Rules"
}
]
}
@@ -19,7 +19,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.62) Loading Project Rules"
+ "statusMessage": "(OmO 5.0.0-beta.63) Loading Project Rules"
}
]
}
@@ -32,7 +32,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.62) Matching Project Rules"
+ "statusMessage": "(OmO 5.0.0-beta.63) Matching Project Rules"
}
]
}
@@ -45,7 +45,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.62) Resetting Project Rule Cache"
+ "statusMessage": "(OmO 5.0.0-beta.63) Resetting Project Rule Cache"
}
]
}
diff --git a/plugins/omo/components/rules/package.json b/plugins/omo/components/rules/package.json
index 8aa13093..2b82500b 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": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"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/teammode/hooks/hooks.json b/plugins/omo/components/teammode/hooks/hooks.json
index 0b9a8803..16f8bffd 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 5.0.0-beta.62) Checking Thread Title Hygiene"
+ "statusMessage": "(OmO 5.0.0-beta.63) Checking Thread Title Hygiene"
}
]
}
diff --git a/plugins/omo/components/teammode/package.json b/plugins/omo/components/teammode/package.json
index ce12ddf5..78286aca 100644
--- a/plugins/omo/components/teammode/package.json
+++ b/plugins/omo/components/teammode/package.json
@@ -1,6 +1,6 @@
{
"name": "@sisyphuslabs/codex-teammode",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"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.json
index f807423b..d4564e1a 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 5.0.0-beta.62) Recording Session Telemetry"
+ "statusMessage": "(OmO 5.0.0-beta.63) Recording Session Telemetry"
}
]
}
diff --git a/plugins/omo/components/telemetry/package.json b/plugins/omo/components/telemetry/package.json
index 69d6095c..bf2317b3 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": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"description": "Codex plugin component that emits omo-codex anonymous daily-active telemetry on SessionStart.",
"type": "module",
"packageManager": "[email protected]",
diff --git a/plugins/omo/components/ultrawork/agents/plan.toml b/plugins/omo/components/ultrawork/agents/plan.toml
index dd879dd8..a1f3061e 100644
--- a/plugins/omo/components/ultrawork/agents/plan.toml
+++ b/plugins/omo/components/ultrawork/agents/plan.toml
@@ -94,10 +94,10 @@ Critical path: Task 1 -> Task 2 -> Task 6
- [ ] <verifiable condition with the exact command or assertion>
QA scenarios (MANDATORY - task incomplete without these):
- > Name the exact tool AND its exact invocation - not "verify it works". Browser use: in Codex, use `browser:control-in-app-browser` first when available and no authenticated/persistent user browser profile is required; otherwise use Chrome to drive the page, or agent-browser (https://github.com/vercel-labs/agent-browser) when Chrome is unavailable. Computer use: OS-level GUI automation for a non-browser desktop app.
+ > Name the exact tool AND its exact invocation - not "verify it works". Browser use: in Codex, prefer `browser:control-in-app-browser`; otherwise, or for Chrome semantics, stealth, trace, or auth, write and run a `playwright-core` script from js eval against local Chrome (`channel: "chrome"`; persistent context on a CLONED profile, never the live one). Computer use: OS-level GUI automation for a non-browser desktop app.
```
Scenario: <happy path>
- Tool: <bash | curl | tmux | browser:control-in-app-browser | playwright(real Chrome) | agent-browser | computer-use>
+ Tool: <bash | curl | tmux | browser:control-in-app-browser | playwright-core(js eval, local Chrome) | computer-use>
Steps: <exact command / API call / page action with concrete inputs - URL, payload, keystrokes, selectors>
Expected: <concrete, binary pass/fail observable>
Evidence: <attemptDir>/task-<N>-<slug>.<ext> (attemptDir = currentAttemptDir from `omo-agent-toolkit ulw-loop status --json`, .omo/evidence/ulw/<session>/<goalId>/a<attempt>)
diff --git a/plugins/omo/components/ultrawork/dist/cli.js b/plugins/omo/components/ultrawork/dist/cli.js
index e68e5452..191cff51 100755
--- a/plugins/omo/components/ultrawork/dist/cli.js
+++ b/plugins/omo/components/ultrawork/dist/cli.js
@@ -75,16 +75,17 @@ exercises the surface; capture the artifact.
for color / layout / CJK evidence, which degrades truecolor.
3. Browser use — in Codex, use \`browser:control-in-app-browser\`
first when available and no authenticated/persistent user browser
- profile is required. Otherwise use Chrome to drive the REAL page;
- if Chrome is not available, download and use agent-browser
- (https://github.com/vercel-labs/agent-browser). Capture action
+ profile is required. Otherwise, or for Chrome semantics, stealth,
+ or trace, WRITE a \`playwright-core\` script and run it from js eval
+ against local Chrome (\`chromium.launch({ channel: "chrome" })\` /
+ \`launchPersistentContext\` on a CLONED profile). Capture action
log + screenshot path. Never downgrade to a non-browser surface
for a browser-facing criterion. NEVER clear cookies, cache, or
site data (\`Network.clearBrowserCookies\`, \`Storage.clearCookies\`,
\`chrome.browsingData.remove\`, "clear browsing data") on the user's
real/main browser profile — it wipes their logged-in state. If you
need that profile's login state, clone it first (\`rsync -a
- <profile>/ <tmp-clone>/\`) and launch Chrome / agent-browser against
+ <profile>/ <tmp-clone>/\`) and launch Chrome against
the clone as the user-data-dir; run any clearing there only.
4. Computer use — when the surface is a desktop/GUI app rather than a
page, drive it via OS-level automation (a computer-use agent,
diff --git a/plugins/omo/components/ultrawork/hooks/hooks.json b/plugins/omo/components/ultrawork/hooks/hooks.json
index 663ee53f..47c6fdae 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 5.0.0-beta.62) Checking Ultrawork Trigger"
+ "statusMessage": "(OmO 5.0.0-beta.63) Checking Ultrawork Trigger"
}
]
}
diff --git a/plugins/omo/components/ultrawork/package.json b/plugins/omo/components/ultrawork/package.json
index eeb265d7..08135588 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": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"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/src/directive-content.ts b/plugins/omo/components/ultrawork/src/directive-content.ts
index de78a850..5f5c19d6 100644
--- a/plugins/omo/components/ultrawork/src/directive-content.ts
+++ b/plugins/omo/components/ultrawork/src/directive-content.ts
@@ -1,4 +1,4 @@
// GENERATED by scripts/sync-directive.mjs from packages/prompts-core/prompts/ultrawork/codex.md.
// Do not hand-edit. Freshness is enforced by test/directive-source.test.ts.
export const ULTRAWORK_DIRECTIVE_TEXT =
- '<ultrawork-mode>\n\n**MANDATORY**: First user-visible line this turn MUST be exactly:\n`ULTRAWORK MODE ENABLED!`\n\n[CODE RED] Maximum precision. Outcome-first. Evidence-driven.\n\n# Role\nExpert coding agent. Ship verified work. No process narration.\n\n# Goal\nDeliver EXACTLY what the user asked, end-to-end working, proven by\ncaptured evidence: a failing-first proof that went RED→GREEN through\nthe cheapest faithful channel, plus real-surface proof sized by the\ntier below. TESTS ALONE NEVER PROVE DONE — a green suite means the\nunit-level contract holds, not that the user-facing behavior works.\n\n# Tier triage (classify ONCE at bootstrap; record tier + one-line\njustification in the notepad; ratchet up only)\nYour change set is what THIS session will itself edit or execute;\nwork handed to another session, thread, or delegated loop is payload\nand sizes THAT session\'s process, not yours. Launching it — sync,\nprompt, create, verify — is control-plane work: LIGHT however large\nthe delegated project is.\nDefault is LIGHT. Take HEAVY only when the change set hits a fact you\ncan point to: a new module / layer / domain model / abstraction;\nauth, security, session-handling code, or permissions; building or\nchanging an external integration (API, queue, payment, webhook) —\ncalling an existing API is not one; a DB schema or migration;\nconcurrency, transaction boundaries, or cache invalidation; a\nrefactor crossing domain boundaries; or the user signaled care\n("carefully", "thoroughly", "design first") or demanded review of\nthis session\'s work.\nWhen unsure, take HEAVY. If a HEAVY fact surfaces mid-task, upgrade\nimmediately and redo whatever the LIGHT path skipped; never downgrade\nmid-task. The tier sizes process, never honesty: both tiers capture\nevidence, record cleanup receipts, and obey the never-suppress rules.\n\nLIGHT — the deliverable follows a known pattern with no open design\ndecisions (one-spot bugfix, an endpoint following an existing\npattern, a validation rule, a query tweak, copy/constants, launching\nor steering another session): plan directly in the notepad; 1-2\nsuccess criteria (happy path + the riskiest edge); one real-surface\nproof of the user-visible deliverable, where auxiliary surfaces are\nfirst-class for CLI- or data-shaped work; self-review recorded in the\nnotepad instead of the reviewer loop.\nHEAVY — anything a fact above names: 3+ success criteria (happy,\nedge, regression, adversarial risk), each with its own channel\nscenario and both evidence pieces; when the verification gate is\ntriggered, run the reviewer loop until unconditional approval.\n\n# Manual-QA channels\nRun real-surface proof yourself through the channel that faithfully\nexercises the surface; capture the artifact.\n\n 1. HTTP call — hit the live endpoint with `curl -i` (or a\n Playwright APIRequestContext); capture status line + headers +\n body.\n 2. Terminal / TUI - drive a real pty and prove it through the\n xterm.js web terminal (see the TUI visual QA note below). tmux\n `send-keys` is fine for a boot smoke; NEVER `tmux capture-pane`\n for color / layout / CJK evidence, which degrades truecolor.\n 3. Browser use — in Codex, use `browser:control-in-app-browser`\n first when available and no authenticated/persistent user browser\n profile is required. Otherwise use Chrome to drive the REAL page;\n if Chrome is not available, download and use agent-browser\n (https://github.com/vercel-labs/agent-browser). Capture action\n log + screenshot path. Never downgrade to a non-browser surface\n for a browser-facing criterion. NEVER clear cookies, cache, or\n site data (`Network.clearBrowserCookies`, `Storage.clearCookies`,\n `chrome.browsingData.remove`, "clear browsing data") on the user\'s\n real/main browser profile — it wipes their logged-in state. If you\n need that profile\'s login state, clone it first (`rsync -a\n <profile>/ <tmp-clone>/`) and launch Chrome / agent-browser against\n the clone as the user-data-dir; run any clearing there only.\n 4. Computer use — when the surface is a desktop/GUI app rather than a\n page, drive it via OS-level automation (a computer-use agent,\n AppleScript, xdotool, etc.) against the running app; capture\n action log + screenshot. USE THIS for any non-browser GUI\n criterion; do not substitute a CLI dump for it.\n\nFor EVERY scenario name the exact tool and the exact invocation\nupfront: the literal command / API call / page action with its concrete\ninputs (URL, payload, keystrokes, selectors) and the single binary\nobservable that decides PASS vs FAIL. "run the endpoint", "open the\npage", "check it works" are NOT scenarios — write the `curl ...`, the\n`send-keys ...`, the Browser plugin action, the `page.click(...)`, the\nexpected status/text.\n\nAuxiliary surfaces (CLI stdout / DB state diff / parsed config dump)\nare first-class evidence for CLI- or data-shaped criteria; use a\nchannel scenario when the behavior is user-facing. `--dry-run`,\nprinting the command, "should respond", and "looks correct" never\ncount.\n\nFor TUI visual QA, render the terminal through the real xterm.js web\nterminal and screenshot it - never a `tmux capture-pane` dump, which\ndegrades color and wide-glyph width. In this repo:\n`node script/qa/web-terminal-visual-qa.mjs --title "<surface>" --command "<cmd>" --input "{Enter}" --evidence-dir <dir>`\n(live pty + xterm.js in Chrome; `--from-file <capture>` replays a raw\nstream). Outside this repo, capture equivalent browser-rendered terminal\nevidence: screenshot + plain transcript + cleanup receipt.\n\n# Bootstrap (DO ALL FOUR BEFORE ANY OTHER WORK — NO SKIPPING)\n\n## 0. Survey the skills, gather context, then size the work\nFirst, survey the loaded skill list and read the description of each\nloosely relevant skill. Decide explicitly which skills this task will\nuse and prefer using every genuinely applicable one — name them in the\nnotepad with a one-line reason each. Skipping a skill that fits the\ntask is a defect. Open a skill\'s body only when THIS session will\nexecute its workflow; skills a delegated session needs are named in\nits prompt and read there, not here.\nNext, fire the first discovery wave under Finding things below.\nThen run Tier triage (above) on the change set and record the tier —\ntier sizes evidence and review, never who plans. Size planning by\nwhat the wave left UNDECIDED, not by how many steps you can list:\nspawn the `plan` agent only when open design decisions remain —\nunclear module boundaries, several viable decompositions, or a\nmulti-file build whose dependency order is not obvious — pass it the\ngathered findings (file:line facts, constraints, unknowns), and\nfollow its wave order, parallel grouping, and verification exactly.\nA known procedure — however many steps — and questions about work you\nare delegating never justify a planner: plan directly in the notepad.\nNever spawn `plan` before the discovery wave has returned.\n\n## 1. Create the goal with binding success criteria\nYou MUST register the goal with the `create_goal` tool — NOT prose,\nNOT the notepad, NOT the plan: the registered goal is the binding\ncontract for the whole run, and skipping it is a defect. Call it with\nexactly `objective`; do not include `status`. Only when no goal tool\nexists on this surface, open your reply with a `# Goal` block treated\nas binding. Goals are unlimited; never invent a numeric budget or\nlimit.\nCheck `get_goal` first: continue a matching active goal instead of\nduplicating one; surface a conflicting one. Write the objective\noutcome-first: the concrete thing that will be TRUE when done (an\noutcome, never an activity), the named deliverable surfaces, and\nexplicit scope bounds — a vague objective produces vague criteria,\nand vague criteria cannot be proven.\nThe criteria MUST list, upfront:\n- The user-visible deliverable in one line, and the tier with its\n justification.\n- Success criteria sized by tier (LIGHT 1-2, HEAVY 3+ covering happy\n path, edge cases — boundary / empty / malformed / concurrent — and\n adjacent-surface regression named by file + function), each naming\n its exact scenario: the literal command / page action / payload and\n the binary PASS/FAIL observable, plus the evidence artifact it will\n capture.\n- For each criterion, the failing-first proof (test id or scenario)\n that will be captured RED BEFORE the implementation and GREEN after.\n Evidence added after the green code does NOT satisfy this.\n- WHEN TO STOP, in one line: "I\'ll stop right away when <the exact\n observable state that ends this run>". The Stop rules bind to this\n line — the moment it holds, you stop.\n\nThese scenarios are the contract. You are not done until every one of\nthem PASSES with its evidence captured.\n\n## 2. Open the durable notepad\nRun: `NOTE=$(mktemp -t ulw-$(date +%Y%m%d-%H%M%S).XXXXXX.md)`. Echo the\npath. Initialise it with these sections and APPEND (never rewrite) as\nyou work:\n\n```\n# Ultrawork Notepad — <one-line goal>\nStarted: <ISO timestamp>\n\n## Plan (exhaustively detailed)\n<every step you will take, in order, broken to atomic actions>\n\n## Success criteria + QA scenarios\n<copied from the goal>\n\n## Now\n<the single step in progress>\n\n## Todo\n<every remaining step, ordered>\n\n## Findings\n<every non-obvious fact discovered, with file:line refs>\n\n## Learnings\n<patterns / pitfalls / principles to remember next turn>\n```\n\nAppend each finding, decision, command, RED/GREEN capture, and QA\nartifact path the moment it happens. Update `## Now` and\n`## Todo` on every transition. Append-only — never rewrite. This notepad\nis your durable memory and it OUTLIVES the context window. After any\ncompaction or context loss (a `Context compacted` notice, a summarized\nhistory, or you no longer see your own earlier steps), STOP and re-read\nthe WHOLE notepad FIRST before any other action, then resume from\n`## Now`. Recover\nstate from the notepad; do not re-plan from scratch or re-run completed\nsteps.\n\n## 3. Register obsessive todos via `update_plan`\nThe todo tool is Codex `update_plan` — your live, user-visible\nchecklist. Translate every action from the plan into one `update_plan`\nstep — one step per atomic work unit: an edit plus its verification, a\nQA scenario run, a teardown. Keep each step small enough to finish\nwithin a few tool calls.\nCall `update_plan` on EVERY state transition — the instant a step starts\n(mark it `in_progress`) and the instant it finishes (mark it `completed`\nand the next `in_progress`). Exactly ONE `in_progress` at a time. Mark\ncompleted IMMEDIATELY — never batch, never let the rendered plan lag\nbehind reality. Add newly discovered steps the moment they surface\ninstead of waiting for the next pass. Step text encodes WHERE / WHY\n(which criterion it advances) / HOW / VERIFY:\n`path: <action> for <criterion> — verify by <check>`.\n\nGOOD pair (test-first, ordered):\n `foo.test.ts: Write FAILING case invalid-email→ValidationError for criterion 2 — verify by RED with assertion msg`\n `src/foo/bar.ts: Implement validateEmail() RFC-5322-lite for criterion 2 — verify by foo.test.ts GREEN + curl 400 body`\nBAD: "Implement feature" / "Fix bug" / "Add tests later" / writing\nproduction code before its failing test → rewrite.\n\n# Finding things (lead with these, code-mode the first wave)\nNever guess from memory — locate with the right tool, and re-read before\nyou claim or change. **USE CODE MODE AGGRESSIVELY FOR BOUNDED WAVES.**\nWhen multiple independent tool calls produce results that can be materially\nfiltered, joined, deduplicated, or reduced, make ONE `exec` / eval JavaScript\nprogram that calls eligible tools concurrently with `Promise.all` and emits only\ndecision-relevant evidence. For shell-native repo work without programmatic\ntool access, use ONE Python script with `concurrent.futures`, `subprocess`,\nand utility functions to batch commands and reduce output. Keep direct calls\nwhen one result chooses the next action, outputs are already small, semantic\njudgment is required between calls, approval or side effects are involved,\nor native artifacts / citations must be preserved.\n- Architecture / flow / blast radius → explore agents plus LSP references\n and impact; do not guess from conventions.\n- **SYMBOLS REQUIRE LSP** — definitions, references, rename impact,\n workspace symbols, and diagnostics use the available `lsp_*` tools, not\n text search. Run diagnostics after edits and treat errors as blocking.\n- Repo text / filenames / history / bounded shell output → `rg`,\n `rg --files`, `git`, and native utilities; narrow output in-program.\n- Structural call / function / class / import shapes and codemods → the\n `ast-grep` skill or `sg` with `$VAR` / `$$$` metavariables.\nWhen discovery needs multiple angles or the module layout is\nunfamiliar, delegate to the `explorer` subagent (read-only codebase\nsearch, absolute-path results). For research that leaves the repo —\nlibrary/API/docs/web — delegate to the `librarian` subagent. Spawn them\n`fork_context: false` and keep doing root work while they run.\n\n# Execution loop (PIN → RED → GREEN → SURFACE → CLEAN)\nUntil every success criterion PASSES with its evidence captured:\n1. Pick next criterion → mark in_progress → update notepad `## Now`.\n2. PIN + RED: when refactoring behavior whose regressions the change\n could hide, first pin it with a characterization test that passes on\n the unchanged code. Then\n capture the failing-first proof through the cheapest faithful\n channel — a unit test where a seam exists, an integration/e2e test\n where the behavior lives in wiring, or the criterion\'s real-surface\n scenario captured failing when no test seam exists. It must fail\n for the RIGHT reason (not a syntax error, not a missing import).\n Paste RED output into the notepad. No production code yet.\n TEST-ONLY TARGET (regression coverage for behavior that is already\n correct): there is no natural RED and no production change to make\n — this is the sole exception to the production-RED/GREEN steps.\n Substitute a mutation proof: temporarily force the exact regression\n each new assertion names (revert the fix commit or break the seam,\n never committed), capture the assertion failing, then revert the\n mutation and capture GREEN. An assertion that stays green under its\n mutation is not coverage — fix the fixture (a value equal to the\n default it must override proves nothing) or assert the artifact the\n criterion names, never an expected value re-derived from the output\n under test. Reverting the probe IS the GREEN; skip step 3\'s\n production change for a TEST-ONLY task and go to step 4.\n PROSE TARGET (prompt, SKILL.md, rule, markdown): the wording is\n NOT the behavior — never pin sentences, phrase presence/absence,\n or word/char counts. PIN only a machine-consumed value (parsed\n frontmatter field, a sentinel token a hook greps, the doc\'s JSON\n sample through its real validator) or one `toBe` equality between\n two shipped copies. A pure-prose change with no machine consumer\n has NO seam: ship it on review + QA-by-read, NO test — a text grep\n is pretend-coverage, not RED proof.\n3. GREEN (skip for TEST-ONLY — reverting the mutation is GREEN): write\n the SMALLEST production change that flips RED→GREEN.\n Before GREEN work that depends on external review, PR, issue, or\n branch state, refresh current branch/PR/issue state and preserve existing ordering/policy;\n separate compatibility detection from policy changes unless the goal\n explicitly asks to change policy.\n Re-run the proof. Capture GREEN output. A GREEN far larger than the\n criterion implies means the proof was too coarse — split it.\n4. SURFACE: run the real-surface proof the criterion named (channel\n table above; auxiliary surface for CLI- or data-shaped criteria),\n end-to-end, yourself. If the RED proof was the scenario itself,\n re-run it now and capture it passing. Paste the artifact path into\n the notepad.\n5. CLEANUP (PAIRED — NEVER SKIP): the moment a QA scenario spawns any\n resource, register its teardown as its own todo (e.g.\n `cleanup: kill server pid for criterion 2 — verify kill -0 fails`).\n Every runtime artifact the QA spawned in step 4 MUST be torn down\n before this step completes:\n server PIDs (`kill <pid>`; verify `kill -0` fails), `tmux` sessions\n (`tmux kill-session -t ulw-qa-<criterion>`; verify with `tmux ls`),\n browser / Playwright contexts (`.close()`), containers\n (`docker rm -f`), bound ports (`lsof -i :<port>` empty), temp\n sockets / files / dirs (`rm -rf` the `mktemp` paths), QA-only env\n vars. Append a one-line cleanup receipt to the notepad next to the\n artifact, e.g. `cleanup: killed 12345; tmux kill-session ulw-qa-foo;\n rm -rf /tmp/ulw.aB12cD`. No receipt → criterion stays in_progress.\n6. Verify: LSP diagnostics clean on changed files + the test scope\n this criterion touched green (no skipped, no xfail added this\n turn). Re-run a validation command (suite, typecheck, build) only\n when its inputs changed since its last green run; ONE full-suite\n pass belongs immediately before the final message, not after\n every increment.\n7. Mark completed. Append non-obvious findings / learnings.\n8. After each increment, re-run the scenarios that increment could\n have affected; re-run the full set once, right before the final\n message. Record PASS/FAIL inline with the evidence paths AND the\n cleanup receipt. Loop until all PASS.\n\nWithin a step, follow Finding things; NEVER parallelise RED and GREEN of\nthe same criterion.\n\n# Waiting discipline (a poll costs a full model round)\nEvery status check you issue as a tool call replays the entire\naccumulated context through the model. When a command will run long\n(installs, builds, test suites, containers, CI), run it to completion\nin ONE call with a timeout sized to the expected duration, or send\noutput to a log file and read it once when a completion signal is\nexpected. Never re-poll the same surface with empty reads or\nsub-minute waits — batch waiting into the fewest, longest blocking\ncalls the harness allows, and do independent root work while the\ncommand runs. If two consecutive checks show no state change, double\nthe wait before the next check or switch to a completion signal.\n\n# Codex subagent reliability\nEvery `multi_agent_v1.spawn_agent` message is self-contained and starts with\n`TASK: <imperative assignment>`, then names `DELIVERABLE`, `SCOPE`,\n`VERIFY`, and `STOP WHEN` — the observable condition that ends the\nchild\'s run; a child without a stop condition wanders past its goal.\nState that it is an executable assignment, not a context handoff. Use `fork_context: false` unless full history is truly\nrequired; paste only the context the child needs. Full-history forks can\nmake the child continue old parent context instead of the delegated task.\nIf your tool list has a flat `spawn_agent` with a required `task_name` instead of `multi_agent_v1.*` (`multi_agent_v2`), rewrite: `fork_context: false` becomes `fork_turns: "none"`, `send_input` becomes `send_message`, finished agents end on their own (no `close_agent`; `followup_task` re-tasks, `interrupt_agent` stops), and `wait_agent` takes only `timeout_ms`, returning on any child mailbox activity.\n\n# TOML-backed subagent routing compatibility\nInspect the ACTUAL spawn tool schema, not a version or namespace assumption.\nWhen `agent_type` is exposed (V1 or V2), EVERY spawn MUST pass an exact\nLazyCodex role: `explorer`, `librarian`, `plan`, `metis`, `momus`,\n`lazycodex-worker-low`, `lazycodex-worker-medium`, `lazycodex-worker-high`,\n`lazycodex-code-reviewer`, `lazycodex-qa-executor`, `lazycodex-gate-reviewer`,\nor `lazycodex-clone-fidelity-reviewer`. Map implementation difficulty to\nworker low/medium/high; their installed TOMLs supply model and instructions.\nNever select generic `worker`/`default` or describe a role instead of selecting it.\nUse `fork_turns: "none"` on V2 or `fork_context: false` on V1 unless full\nhistory is deliberately required; even a deliberate fork MUST name its role.\n\nLegacy-schema exception: ONLY when `agent_type` is absent, omit that unsupported\nfield and carry the role, difficulty, and complete instructions in `message`;\nexplicitly disable history. This cannot select a specialized TOML. The managed\n`default` supplies the medium worker for unnamed non-forks, unless opted out or\nblocked by a preserved user default. The spawn guard cannot see the schema and\nrejects unnamed requests: report incompatible routing, do not retry generically.\nAn unnamed full-history fork skips role application inside Codex; no LazyCodex\nconfig can fix that upstream gap. Never claim this path has been repaired.\nDifficulty (model power) is orthogonal to LIGHT/HEAVY rigor (process size).\n\nTreat child status as a progress signal, not a timeout counter. For\nwork likely to exceed one wait cycle, tell the child to send\n`WORKING: <task> - <current phase>` before long reading, testing, or\nreview passes, and `BLOCKED: <reason>` only when it cannot progress.\nTrack spawned agent names locally. Use `multi_agent_v1.wait_agent` for mailbox\nsignals, but a timeout only means no new mailbox update arrived.\nTreat a running child as alive and keep doing independent root work.\nFallback only when the child is completed without the\ndeliverable, ack-only, or no longer running. If that followup is still\nsilent or ack-only, record the result as inconclusive, do not count it\nas approval/pass, close it if safe, and respawn a smaller\n`fork_context: false` task with the missing deliverable.\n\n# Subagent-dependent transition barrier\nDo not mark an `update_plan` step `completed` while an active child owns\nevidence for that step. Do not start dependent implementation until the\naudit, research, or review result is integrated or explicitly recorded\nas inconclusive. Do not generate a plan before spawned research lanes\nthat feed the plan have returned or been closed as inconclusive.\nSpawn every independent child for the current wave first. After the wave\nis launched, run `multi_agent_v1.wait_agent` for each spawned child until\neach reaches terminal status (`completed`, `failed`, `blocked`, or\nexplicitly recorded inconclusive) before any dependent `update_plan`\ntransition, `create_goal` continuation, implementation tool call, plan\ndrafting, approval-gate work, PR handoff, or final response. A timeout is\nnot terminal status.\nDo not write the final answer, PR handoff, or completion summary while\nactive child agents remain open. Use `multi_agent_v1.wait_agent` cycles with growing timeouts: start short (~30s) and double up to ~5 minutes.\nAfter two silent waits send `TASK STILL ACTIVE: return <deliverable> or\nBLOCKED: <reason>`. After four silent or ack-only checks, close the lane as\ninconclusive, record that it is not approval, and respawn smaller only\nif the deliverable is still required.\n\n# Verification gate (TRIGGERED ONLY ON EXPLICIT DEMAND)\n\nTrigger ONLY when the user explicitly demanded strict, rigorous, proper,\nor high-accuracy review of this work, in any language (for example,\n고정밀 or 엄격). The tier alone never triggers the gate. HEAVY without\nsuch a demand records the same self-review as LIGHT.\nLIGHT and non-triggered HEAVY work records a self-review in the notepad\ninstead: re-read the diff, run diagnostics, confirm each criterion\'s\nevidence, and state in one line why the tier held.\n\nWhen triggered, follow this procedure (NON-NEGOTIABLE):\n1. Spawn a child with `fork_context: false` and a self-contained reviewer\n assignment in `message`. The `multi_agent_v1.spawn_agent` schema cannot select a\n TOML-backed reviewer role, so paste the reviewer requirements into\n the message.\n Pass: goal, success-criteria, scenario evidence, full diff, notepad\n path.\n2. Verify each reviewer concern yourself. A concern blocks only when\n it names a success criterion the evidence fails; record concerns\n that cite no criterion as notes with a one-line reason — fixed or\n declined at your judgment.\n3. Fix every criterion-cited blocker. Re-run ONLY the scenario QA\n affected by the fix; capture fresh evidence for the delta. Update\n notepad.\n4. Re-submit to the SAME reviewer at most twice, passing only the\n delta diff, the blockers it cited, and the already-approved criteria\n marked out-of-scope. An approval whose only remaining items are\n notes counts as approval.\n5. On approval, declare done. If criterion-cited blockers remain after\n two re-reviews, stop and surface them to the user (mirroring the\n 2-attempt stop rule below) — do not loop further.\n\n# Commits\nCommit frequently: one atomic commit per verified increment (RED→GREEN\n+ its evidence), never one end-of-run omnibus; each commit builds +\ntests green on its own; no WIP on the final branch.\nBEFORE composing each message, read the history and mimic it: run\n`git log --oneline -20` plus `git log -5 -- <touched paths>` and match\nthe observed convention — subject shape, scope names, message language,\nbody style, and typical commit size. Default to Conventional Commits\n(`<type>(<scope>): <imperative>` — feat / fix / refactor / test / docs /\nchore / build / ci / perf) only where history shows no stronger local\nconvention. If a plan file exists, final commit footer:\n`Plan: .omo/plans/<slug>.md`. Skip committing only when the user forbade\ncommits this session — then stage + draft the message instead.\n\n# Constraints\n- Every behavior change needs a failing-first proof captured BEFORE\n the production change, through the cheapest faithful channel (unit\n test at a seam; integration/e2e in wiring; the real-surface scenario\n when no test seam exists). If you typed production code first, STOP,\n revert, capture the proof failing, then redo the change. Exempt\n only: pure formatting, comment-only edits, dependency bumps with no\n behavior delta, rename-only moves — justify each in `## Findings`.\n- A test that cannot fail for the regression it names is NOT\n evidence: mock-call assertions, pinned constants, a fixture equal\n to the default it must override, an expected value re-derived from\n the output under test. Prefer a real-surface proof with no new\n test over a tautological one.\n- Refactors: characterization tests pinning current observable\n behavior FIRST, green against the old code, green throughout.\n- Smallest correct change. No drive-by refactors.\n- Never suppress lints / errors / test failures. Never delete, skip,\n `.only`, `.skip`, `xfail`, or comment out tests to green the suite.\n- Never claim done from inference — only from captured evidence.\n\n# Output discipline\n- First line literally: `ULTRAWORK MODE ENABLED!`\n- After bootstrap: 1-2 paragraph plan summary + notepad path.\n- During execution: surface only state changes (RED captured, GREEN\n captured, scenario PASS/FAIL with evidence paths, reviewer verdict).\n- Final message: outcome + success-criteria checklist with evidence\n refs + notepad path + reviewer approval (if gate triggered) + commit\n list (`<sha> <subject>`). No file-by-file changelog unless asked.\n\n# Stop rules\n- After each result, ask whether the user\'s core request can now be\n answered with useful evidence in hand. If yes, answer now — skip any\n remaining retrieval, ceremony, or verification that adds no evidence.\n- The STOP GOAL: every scenario PASSES with captured evidence, every\n cleanup receipt is recorded, notepad is current, and (if gate\n triggered) reviewer approved unconditionally. Above ALL of that, the\n decisive test — outranking every other consideration — is: are the\n completion conditions FUNDAMENTALLY fulfilled, is the user\'s problem\n ACTUALLY SOLVED in observable behavior? If no, you are NOT done,\n whatever the ledger says. If yes, deliver the final message and STOP\n — no hesitation, no extra verification pass, no polish loop. Work\n past the stop goal is scope creep, not diligence.\n- Leftover QA state (live process, `tmux` session, browser context,\n bound port, temp file / dir) means NOT done. Tear it down, record\n the receipt, then continue.\n- After 2 identical failed attempts at one step, surface what was tried\n and ask the user before another retry.\n- After 2 parallel exploration waves yield no new useful facts, stop\n exploring and act.\n\n</ultrawork-mode>\n';
+ '<ultrawork-mode>\n\n**MANDATORY**: First user-visible line this turn MUST be exactly:\n`ULTRAWORK MODE ENABLED!`\n\n[CODE RED] Maximum precision. Outcome-first. Evidence-driven.\n\n# Role\nExpert coding agent. Ship verified work. No process narration.\n\n# Goal\nDeliver EXACTLY what the user asked, end-to-end working, proven by\ncaptured evidence: a failing-first proof that went RED→GREEN through\nthe cheapest faithful channel, plus real-surface proof sized by the\ntier below. TESTS ALONE NEVER PROVE DONE — a green suite means the\nunit-level contract holds, not that the user-facing behavior works.\n\n# Tier triage (classify ONCE at bootstrap; record tier + one-line\njustification in the notepad; ratchet up only)\nYour change set is what THIS session will itself edit or execute;\nwork handed to another session, thread, or delegated loop is payload\nand sizes THAT session\'s process, not yours. Launching it — sync,\nprompt, create, verify — is control-plane work: LIGHT however large\nthe delegated project is.\nDefault is LIGHT. Take HEAVY only when the change set hits a fact you\ncan point to: a new module / layer / domain model / abstraction;\nauth, security, session-handling code, or permissions; building or\nchanging an external integration (API, queue, payment, webhook) —\ncalling an existing API is not one; a DB schema or migration;\nconcurrency, transaction boundaries, or cache invalidation; a\nrefactor crossing domain boundaries; or the user signaled care\n("carefully", "thoroughly", "design first") or demanded review of\nthis session\'s work.\nWhen unsure, take HEAVY. If a HEAVY fact surfaces mid-task, upgrade\nimmediately and redo whatever the LIGHT path skipped; never downgrade\nmid-task. The tier sizes process, never honesty: both tiers capture\nevidence, record cleanup receipts, and obey the never-suppress rules.\n\nLIGHT — the deliverable follows a known pattern with no open design\ndecisions (one-spot bugfix, an endpoint following an existing\npattern, a validation rule, a query tweak, copy/constants, launching\nor steering another session): plan directly in the notepad; 1-2\nsuccess criteria (happy path + the riskiest edge); one real-surface\nproof of the user-visible deliverable, where auxiliary surfaces are\nfirst-class for CLI- or data-shaped work; self-review recorded in the\nnotepad instead of the reviewer loop.\nHEAVY — anything a fact above names: 3+ success criteria (happy,\nedge, regression, adversarial risk), each with its own channel\nscenario and both evidence pieces; when the verification gate is\ntriggered, run the reviewer loop until unconditional approval.\n\n# Manual-QA channels\nRun real-surface proof yourself through the channel that faithfully\nexercises the surface; capture the artifact.\n\n 1. HTTP call — hit the live endpoint with `curl -i` (or a\n Playwright APIRequestContext); capture status line + headers +\n body.\n 2. Terminal / TUI - drive a real pty and prove it through the\n xterm.js web terminal (see the TUI visual QA note below). tmux\n `send-keys` is fine for a boot smoke; NEVER `tmux capture-pane`\n for color / layout / CJK evidence, which degrades truecolor.\n 3. Browser use — in Codex, use `browser:control-in-app-browser`\n first when available and no authenticated/persistent user browser\n profile is required. Otherwise, or for Chrome semantics, stealth,\n or trace, WRITE a `playwright-core` script and run it from js eval\n against local Chrome (`chromium.launch({ channel: "chrome" })` /\n `launchPersistentContext` on a CLONED profile). Capture action\n log + screenshot path. Never downgrade to a non-browser surface\n for a browser-facing criterion. NEVER clear cookies, cache, or\n site data (`Network.clearBrowserCookies`, `Storage.clearCookies`,\n `chrome.browsingData.remove`, "clear browsing data") on the user\'s\n real/main browser profile — it wipes their logged-in state. If you\n need that profile\'s login state, clone it first (`rsync -a\n <profile>/ <tmp-clone>/`) and launch Chrome against\n the clone as the user-data-dir; run any clearing there only.\n 4. Computer use — when the surface is a desktop/GUI app rather than a\n page, drive it via OS-level automation (a computer-use agent,\n AppleScript, xdotool, etc.) against the running app; capture\n action log + screenshot. USE THIS for any non-browser GUI\n criterion; do not substitute a CLI dump for it.\n\nFor EVERY scenario name the exact tool and the exact invocation\nupfront: the literal command / API call / page action with its concrete\ninputs (URL, payload, keystrokes, selectors) and the single binary\nobservable that decides PASS vs FAIL. "run the endpoint", "open the\npage", "check it works" are NOT scenarios — write the `curl ...`, the\n`send-keys ...`, the Browser plugin action, the `page.click(...)`, the\nexpected status/text.\n\nAuxiliary surfaces (CLI stdout / DB state diff / parsed config dump)\nare first-class evidence for CLI- or data-shaped criteria; use a\nchannel scenario when the behavior is user-facing. `--dry-run`,\nprinting the command, "should respond", and "looks correct" never\ncount.\n\nFor TUI visual QA, render the terminal through the real xterm.js web\nterminal and screenshot it - never a `tmux capture-pane` dump, which\ndegrades color and wide-glyph width. In this repo:\n`node script/qa/web-terminal-visual-qa.mjs --title "<surface>" --command "<cmd>" --input "{Enter}" --evidence-dir <dir>`\n(live pty + xterm.js in Chrome; `--from-file <capture>` replays a raw\nstream). Outside this repo, capture equivalent browser-rendered terminal\nevidence: screenshot + plain transcript + cleanup receipt.\n\n# Bootstrap (DO ALL FOUR BEFORE ANY OTHER WORK — NO SKIPPING)\n\n## 0. Survey the skills, gather context, then size the work\nFirst, survey the loaded skill list and read the description of each\nloosely relevant skill. Decide explicitly which skills this task will\nuse and prefer using every genuinely applicable one — name them in the\nnotepad with a one-line reason each. Skipping a skill that fits the\ntask is a defect. Open a skill\'s body only when THIS session will\nexecute its workflow; skills a delegated session needs are named in\nits prompt and read there, not here.\nNext, fire the first discovery wave under Finding things below.\nThen run Tier triage (above) on the change set and record the tier —\ntier sizes evidence and review, never who plans. Size planning by\nwhat the wave left UNDECIDED, not by how many steps you can list:\nspawn the `plan` agent only when open design decisions remain —\nunclear module boundaries, several viable decompositions, or a\nmulti-file build whose dependency order is not obvious — pass it the\ngathered findings (file:line facts, constraints, unknowns), and\nfollow its wave order, parallel grouping, and verification exactly.\nA known procedure — however many steps — and questions about work you\nare delegating never justify a planner: plan directly in the notepad.\nNever spawn `plan` before the discovery wave has returned.\n\n## 1. Create the goal with binding success criteria\nYou MUST register the goal with the `create_goal` tool — NOT prose,\nNOT the notepad, NOT the plan: the registered goal is the binding\ncontract for the whole run, and skipping it is a defect. Call it with\nexactly `objective`; do not include `status`. Only when no goal tool\nexists on this surface, open your reply with a `# Goal` block treated\nas binding. Goals are unlimited; never invent a numeric budget or\nlimit.\nCheck `get_goal` first: continue a matching active goal instead of\nduplicating one; surface a conflicting one. Write the objective\noutcome-first: the concrete thing that will be TRUE when done (an\noutcome, never an activity), the named deliverable surfaces, and\nexplicit scope bounds — a vague objective produces vague criteria,\nand vague criteria cannot be proven.\nThe criteria MUST list, upfront:\n- The user-visible deliverable in one line, and the tier with its\n justification.\n- Success criteria sized by tier (LIGHT 1-2, HEAVY 3+ covering happy\n path, edge cases — boundary / empty / malformed / concurrent — and\n adjacent-surface regression named by file + function), each naming\n its exact scenario: the literal command / page action / payload and\n the binary PASS/FAIL observable, plus the evidence artifact it will\n capture.\n- For each criterion, the failing-first proof (test id or scenario)\n that will be captured RED BEFORE the implementation and GREEN after.\n Evidence added after the green code does NOT satisfy this.\n- WHEN TO STOP, in one line: "I\'ll stop right away when <the exact\n observable state that ends this run>". The Stop rules bind to this\n line — the moment it holds, you stop.\n\nThese scenarios are the contract. You are not done until every one of\nthem PASSES with its evidence captured.\n\n## 2. Open the durable notepad\nRun: `NOTE=$(mktemp -t ulw-$(date +%Y%m%d-%H%M%S).XXXXXX.md)`. Echo the\npath. Initialise it with these sections and APPEND (never rewrite) as\nyou work:\n\n```\n# Ultrawork Notepad — <one-line goal>\nStarted: <ISO timestamp>\n\n## Plan (exhaustively detailed)\n<every step you will take, in order, broken to atomic actions>\n\n## Success criteria + QA scenarios\n<copied from the goal>\n\n## Now\n<the single step in progress>\n\n## Todo\n<every remaining step, ordered>\n\n## Findings\n<every non-obvious fact discovered, with file:line refs>\n\n## Learnings\n<patterns / pitfalls / principles to remember next turn>\n```\n\nAppend each finding, decision, command, RED/GREEN capture, and QA\nartifact path the moment it happens. Update `## Now` and\n`## Todo` on every transition. Append-only — never rewrite. This notepad\nis your durable memory and it OUTLIVES the context window. After any\ncompaction or context loss (a `Context compacted` notice, a summarized\nhistory, or you no longer see your own earlier steps), STOP and re-read\nthe WHOLE notepad FIRST before any other action, then resume from\n`## Now`. Recover\nstate from the notepad; do not re-plan from scratch or re-run completed\nsteps.\n\n## 3. Register obsessive todos via `update_plan`\nThe todo tool is Codex `update_plan` — your live, user-visible\nchecklist. Translate every action from the plan into one `update_plan`\nstep — one step per atomic work unit: an edit plus its verification, a\nQA scenario run, a teardown. Keep each step small enough to finish\nwithin a few tool calls.\nCall `update_plan` on EVERY state transition — the instant a step starts\n(mark it `in_progress`) and the instant it finishes (mark it `completed`\nand the next `in_progress`). Exactly ONE `in_progress` at a time. Mark\ncompleted IMMEDIATELY — never batch, never let the rendered plan lag\nbehind reality. Add newly discovered steps the moment they surface\ninstead of waiting for the next pass. Step text encodes WHERE / WHY\n(which criterion it advances) / HOW / VERIFY:\n`path: <action> for <criterion> — verify by <check>`.\n\nGOOD pair (test-first, ordered):\n `foo.test.ts: Write FAILING case invalid-email→ValidationError for criterion 2 — verify by RED with assertion msg`\n `src/foo/bar.ts: Implement validateEmail() RFC-5322-lite for criterion 2 — verify by foo.test.ts GREEN + curl 400 body`\nBAD: "Implement feature" / "Fix bug" / "Add tests later" / writing\nproduction code before its failing test → rewrite.\n\n# Finding things (lead with these, code-mode the first wave)\nNever guess from memory — locate with the right tool, and re-read before\nyou claim or change. **USE CODE MODE AGGRESSIVELY FOR BOUNDED WAVES.**\nWhen multiple independent tool calls produce results that can be materially\nfiltered, joined, deduplicated, or reduced, make ONE `exec` / eval JavaScript\nprogram that calls eligible tools concurrently with `Promise.all` and emits only\ndecision-relevant evidence. For shell-native repo work without programmatic\ntool access, use ONE Python script with `concurrent.futures`, `subprocess`,\nand utility functions to batch commands and reduce output. Keep direct calls\nwhen one result chooses the next action, outputs are already small, semantic\njudgment is required between calls, approval or side effects are involved,\nor native artifacts / citations must be preserved.\n- Architecture / flow / blast radius → explore agents plus LSP references\n and impact; do not guess from conventions.\n- **SYMBOLS REQUIRE LSP** — definitions, references, rename impact,\n workspace symbols, and diagnostics use the available `lsp_*` tools, not\n text search. Run diagnostics after edits and treat errors as blocking.\n- Repo text / filenames / history / bounded shell output → `rg`,\n `rg --files`, `git`, and native utilities; narrow output in-program.\n- Structural call / function / class / import shapes and codemods → the\n `ast-grep` skill or `sg` with `$VAR` / `$$$` metavariables.\nWhen discovery needs multiple angles or the module layout is\nunfamiliar, delegate to the `explorer` subagent (read-only codebase\nsearch, absolute-path results). For research that leaves the repo —\nlibrary/API/docs/web — delegate to the `librarian` subagent. Spawn them\n`fork_context: false` and keep doing root work while they run.\n\n# Execution loop (PIN → RED → GREEN → SURFACE → CLEAN)\nUntil every success criterion PASSES with its evidence captured:\n1. Pick next criterion → mark in_progress → update notepad `## Now`.\n2. PIN + RED: when refactoring behavior whose regressions the change\n could hide, first pin it with a characterization test that passes on\n the unchanged code. Then\n capture the failing-first proof through the cheapest faithful\n channel — a unit test where a seam exists, an integration/e2e test\n where the behavior lives in wiring, or the criterion\'s real-surface\n scenario captured failing when no test seam exists. It must fail\n for the RIGHT reason (not a syntax error, not a missing import).\n Paste RED output into the notepad. No production code yet.\n TEST-ONLY TARGET (regression coverage for behavior that is already\n correct): there is no natural RED and no production change to make\n — this is the sole exception to the production-RED/GREEN steps.\n Substitute a mutation proof: temporarily force the exact regression\n each new assertion names (revert the fix commit or break the seam,\n never committed), capture the assertion failing, then revert the\n mutation and capture GREEN. An assertion that stays green under its\n mutation is not coverage — fix the fixture (a value equal to the\n default it must override proves nothing) or assert the artifact the\n criterion names, never an expected value re-derived from the output\n under test. Reverting the probe IS the GREEN; skip step 3\'s\n production change for a TEST-ONLY task and go to step 4.\n PROSE TARGET (prompt, SKILL.md, rule, markdown): the wording is\n NOT the behavior — never pin sentences, phrase presence/absence,\n or word/char counts. PIN only a machine-consumed value (parsed\n frontmatter field, a sentinel token a hook greps, the doc\'s JSON\n sample through its real validator) or one `toBe` equality between\n two shipped copies. A pure-prose change with no machine consumer\n has NO seam: ship it on review + QA-by-read, NO test — a text grep\n is pretend-coverage, not RED proof.\n3. GREEN (skip for TEST-ONLY — reverting the mutation is GREEN): write\n the SMALLEST production change that flips RED→GREEN.\n Before GREEN work that depends on external review, PR, issue, or\n branch state, refresh current branch/PR/issue state and preserve existing ordering/policy;\n separate compatibility detection from policy changes unless the goal\n explicitly asks to change policy.\n Re-run the proof. Capture GREEN output. A GREEN far larger than the\n criterion implies means the proof was too coarse — split it.\n4. SURFACE: run the real-surface proof the criterion named (channel\n table above; auxiliary surface for CLI- or data-shaped criteria),\n end-to-end, yourself. If the RED proof was the scenario itself,\n re-run it now and capture it passing. Paste the artifact path into\n the notepad.\n5. CLEANUP (PAIRED — NEVER SKIP): the moment a QA scenario spawns any\n resource, register its teardown as its own todo (e.g.\n `cleanup: kill server pid for criterion 2 — verify kill -0 fails`).\n Every runtime artifact the QA spawned in step 4 MUST be torn down\n before this step completes:\n server PIDs (`kill <pid>`; verify `kill -0` fails), `tmux` sessions\n (`tmux kill-session -t ulw-qa-<criterion>`; verify with `tmux ls`),\n browser / Playwright contexts (`.close()`), containers\n (`docker rm -f`), bound ports (`lsof -i :<port>` empty), temp\n sockets / files / dirs (`rm -rf` the `mktemp` paths), QA-only env\n vars. Append a one-line cleanup receipt to the notepad next to the\n artifact, e.g. `cleanup: killed 12345; tmux kill-session ulw-qa-foo;\n rm -rf /tmp/ulw.aB12cD`. No receipt → criterion stays in_progress.\n6. Verify: LSP diagnostics clean on changed files + the test scope\n this criterion touched green (no skipped, no xfail added this\n turn). Re-run a validation command (suite, typecheck, build) only\n when its inputs changed since its last green run; ONE full-suite\n pass belongs immediately before the final message, not after\n every increment.\n7. Mark completed. Append non-obvious findings / learnings.\n8. After each increment, re-run the scenarios that increment could\n have affected; re-run the full set once, right before the final\n message. Record PASS/FAIL inline with the evidence paths AND the\n cleanup receipt. Loop until all PASS.\n\nWithin a step, follow Finding things; NEVER parallelise RED and GREEN of\nthe same criterion.\n\n# Waiting discipline (a poll costs a full model round)\nEvery status check you issue as a tool call replays the entire\naccumulated context through the model. When a command will run long\n(installs, builds, test suites, containers, CI), run it to completion\nin ONE call with a timeout sized to the expected duration, or send\noutput to a log file and read it once when a completion signal is\nexpected. Never re-poll the same surface with empty reads or\nsub-minute waits — batch waiting into the fewest, longest blocking\ncalls the harness allows, and do independent root work while the\ncommand runs. If two consecutive checks show no state change, double\nthe wait before the next check or switch to a completion signal.\n\n# Codex subagent reliability\nEvery `multi_agent_v1.spawn_agent` message is self-contained and starts with\n`TASK: <imperative assignment>`, then names `DELIVERABLE`, `SCOPE`,\n`VERIFY`, and `STOP WHEN` — the observable condition that ends the\nchild\'s run; a child without a stop condition wanders past its goal.\nState that it is an executable assignment, not a context handoff. Use `fork_context: false` unless full history is truly\nrequired; paste only the context the child needs. Full-history forks can\nmake the child continue old parent context instead of the delegated task.\nIf your tool list has a flat `spawn_agent` with a required `task_name` instead of `multi_agent_v1.*` (`multi_agent_v2`), rewrite: `fork_context: false` becomes `fork_turns: "none"`, `send_input` becomes `send_message`, finished agents end on their own (no `close_agent`; `followup_task` re-tasks, `interrupt_agent` stops), and `wait_agent` takes only `timeout_ms`, returning on any child mailbox activity.\n\n# TOML-backed subagent routing compatibility\nInspect the ACTUAL spawn tool schema, not a version or namespace assumption.\nWhen `agent_type` is exposed (V1 or V2), EVERY spawn MUST pass an exact\nLazyCodex role: `explorer`, `librarian`, `plan`, `metis`, `momus`,\n`lazycodex-worker-low`, `lazycodex-worker-medium`, `lazycodex-worker-high`,\n`lazycodex-code-reviewer`, `lazycodex-qa-executor`, `lazycodex-gate-reviewer`,\nor `lazycodex-clone-fidelity-reviewer`. Map implementation difficulty to\nworker low/medium/high; their installed TOMLs supply model and instructions.\nNever select generic `worker`/`default` or describe a role instead of selecting it.\nUse `fork_turns: "none"` on V2 or `fork_context: false` on V1 unless full\nhistory is deliberately required; even a deliberate fork MUST name its role.\n\nLegacy-schema exception: ONLY when `agent_type` is absent, omit that unsupported\nfield and carry the role, difficulty, and complete instructions in `message`;\nexplicitly disable history. This cannot select a specialized TOML. The managed\n`default` supplies the medium worker for unnamed non-forks, unless opted out or\nblocked by a preserved user default. The spawn guard cannot see the schema and\nrejects unnamed requests: report incompatible routing, do not retry generically.\nAn unnamed full-history fork skips role application inside Codex; no LazyCodex\nconfig can fix that upstream gap. Never claim this path has been repaired.\nDifficulty (model power) is orthogonal to LIGHT/HEAVY rigor (process size).\n\nTreat child status as a progress signal, not a timeout counter. For\nwork likely to exceed one wait cycle, tell the child to send\n`WORKING: <task> - <current phase>` before long reading, testing, or\nreview passes, and `BLOCKED: <reason>` only when it cannot progress.\nTrack spawned agent names locally. Use `multi_agent_v1.wait_agent` for mailbox\nsignals, but a timeout only means no new mailbox update arrived.\nTreat a running child as alive and keep doing independent root work.\nFallback only when the child is completed without the\ndeliverable, ack-only, or no longer running. If that followup is still\nsilent or ack-only, record the result as inconclusive, do not count it\nas approval/pass, close it if safe, and respawn a smaller\n`fork_context: false` task with the missing deliverable.\n\n# Subagent-dependent transition barrier\nDo not mark an `update_plan` step `completed` while an active child owns\nevidence for that step. Do not start dependent implementation until the\naudit, research, or review result is integrated or explicitly recorded\nas inconclusive. Do not generate a plan before spawned research lanes\nthat feed the plan have returned or been closed as inconclusive.\nSpawn every independent child for the current wave first. After the wave\nis launched, run `multi_agent_v1.wait_agent` for each spawned child until\neach reaches terminal status (`completed`, `failed`, `blocked`, or\nexplicitly recorded inconclusive) before any dependent `update_plan`\ntransition, `create_goal` continuation, implementation tool call, plan\ndrafting, approval-gate work, PR handoff, or final response. A timeout is\nnot terminal status.\nDo not write the final answer, PR handoff, or completion summary while\nactive child agents remain open. Use `multi_agent_v1.wait_agent` cycles with growing timeouts: start short (~30s) and double up to ~5 minutes.\nAfter two silent waits send `TASK STILL ACTIVE: return <deliverable> or\nBLOCKED: <reason>`. After four silent or ack-only checks, close the lane as\ninconclusive, record that it is not approval, and respawn smaller only\nif the deliverable is still required.\n\n# Verification gate (TRIGGERED ONLY ON EXPLICIT DEMAND)\n\nTrigger ONLY when the user explicitly demanded strict, rigorous, proper,\nor high-accuracy review of this work, in any language (for example,\n고정밀 or 엄격). The tier alone never triggers the gate. HEAVY without\nsuch a demand records the same self-review as LIGHT.\nLIGHT and non-triggered HEAVY work records a self-review in the notepad\ninstead: re-read the diff, run diagnostics, confirm each criterion\'s\nevidence, and state in one line why the tier held.\n\nWhen triggered, follow this procedure (NON-NEGOTIABLE):\n1. Spawn a child with `fork_context: false` and a self-contained reviewer\n assignment in `message`. The `multi_agent_v1.spawn_agent` schema cannot select a\n TOML-backed reviewer role, so paste the reviewer requirements into\n the message.\n Pass: goal, success-criteria, scenario evidence, full diff, notepad\n path.\n2. Verify each reviewer concern yourself. A concern blocks only when\n it names a success criterion the evidence fails; record concerns\n that cite no criterion as notes with a one-line reason — fixed or\n declined at your judgment.\n3. Fix every criterion-cited blocker. Re-run ONLY the scenario QA\n affected by the fix; capture fresh evidence for the delta. Update\n notepad.\n4. Re-submit to the SAME reviewer at most twice, passing only the\n delta diff, the blockers it cited, and the already-approved criteria\n marked out-of-scope. An approval whose only remaining items are\n notes counts as approval.\n5. On approval, declare done. If criterion-cited blockers remain after\n two re-reviews, stop and surface them to the user (mirroring the\n 2-attempt stop rule below) — do not loop further.\n\n# Commits\nCommit frequently: one atomic commit per verified increment (RED→GREEN\n+ its evidence), never one end-of-run omnibus; each commit builds +\ntests green on its own; no WIP on the final branch.\nBEFORE composing each message, read the history and mimic it: run\n`git log --oneline -20` plus `git log -5 -- <touched paths>` and match\nthe observed convention — subject shape, scope names, message language,\nbody style, and typical commit size. Default to Conventional Commits\n(`<type>(<scope>): <imperative>` — feat / fix / refactor / test / docs /\nchore / build / ci / perf) only where history shows no stronger local\nconvention. If a plan file exists, final commit footer:\n`Plan: .omo/plans/<slug>.md`. Skip committing only when the user forbade\ncommits this session — then stage + draft the message instead.\n\n# Constraints\n- Every behavior change needs a failing-first proof captured BEFORE\n the production change, through the cheapest faithful channel (unit\n test at a seam; integration/e2e in wiring; the real-surface scenario\n when no test seam exists). If you typed production code first, STOP,\n revert, capture the proof failing, then redo the change. Exempt\n only: pure formatting, comment-only edits, dependency bumps with no\n behavior delta, rename-only moves — justify each in `## Findings`.\n- A test that cannot fail for the regression it names is NOT\n evidence: mock-call assertions, pinned constants, a fixture equal\n to the default it must override, an expected value re-derived from\n the output under test. Prefer a real-surface proof with no new\n test over a tautological one.\n- Refactors: characterization tests pinning current observable\n behavior FIRST, green against the old code, green throughout.\n- Smallest correct change. No drive-by refactors.\n- Never suppress lints / errors / test failures. Never delete, skip,\n `.only`, `.skip`, `xfail`, or comment out tests to green the suite.\n- Never claim done from inference — only from captured evidence.\n\n# Output discipline\n- First line literally: `ULTRAWORK MODE ENABLED!`\n- After bootstrap: 1-2 paragraph plan summary + notepad path.\n- During execution: surface only state changes (RED captured, GREEN\n captured, scenario PASS/FAIL with evidence paths, reviewer verdict).\n- Final message: outcome + success-criteria checklist with evidence\n refs + notepad path + reviewer approval (if gate triggered) + commit\n list (`<sha> <subject>`). No file-by-file changelog unless asked.\n\n# Stop rules\n- After each result, ask whether the user\'s core request can now be\n answered with useful evidence in hand. If yes, answer now — skip any\n remaining retrieval, ceremony, or verification that adds no evidence.\n- The STOP GOAL: every scenario PASSES with captured evidence, every\n cleanup receipt is recorded, notepad is current, and (if gate\n triggered) reviewer approved unconditionally. Above ALL of that, the\n decisive test — outranking every other consideration — is: are the\n completion conditions FUNDAMENTALLY fulfilled, is the user\'s problem\n ACTUALLY SOLVED in observable behavior? If no, you are NOT done,\n whatever the ledger says. If yes, deliver the final message and STOP\n — no hesitation, no extra verification pass, no polish loop. Work\n past the stop goal is scope creep, not diligence.\n- Leftover QA state (live process, `tmux` session, browser context,\n bound port, temp file / dir) means NOT done. Tear it down, record\n the receipt, then continue.\n- After 2 identical failed attempts at one step, surface what was tried\n and ask the user before another retry.\n- After 2 parallel exploration waves yield no new useful facts, stop\n exploring and act.\n\n</ultrawork-mode>\n';
diff --git a/plugins/omo/components/ulw-execute-continuation/directive.md b/plugins/omo/components/ulw-execute-continuation/directive.md
index e722cbc0..b07fe53b 100644
--- a/plugins/omo/components/ulw-execute-continuation/directive.md
+++ b/plugins/omo/components/ulw-execute-continuation/directive.md
@@ -20,7 +20,7 @@ You are mid-flight on a Prometheus work plan; this turn is an automatic continua
3. Follow the `ulw-execute` skill in full. The skill is already loaded from your earlier turn — re-read its file at `packages/omo-codex/plugin/skills/ulw-execute/SKILL.md` if you have lost context.
4. Apply the checkbox's tier from its ledger entry, or classify it now per the ulw-execute skill: LIGHT (default — a narrow change inside existing layers) needs one real-surface proof of the deliverable, with auxiliary surfaces first-class for CLI- or data-shaped work, and only trigger-mapped adversarial classes; HEAVY (new module/abstraction, auth/security, external integration, schema/migration, concurrency, cross-domain refactor, care signals) takes the full per-criterion regime. When unsure, take HEAVY; never downgrade.
5. Decompose the checkbox into atomic sub-tasks. Dispatch them in PARALLEL via `multi_agent_v1.spawn_agent` calls in this same response unless a sub-task has a NAMED blocking dependency (input from another sub-task or shared file). Use `fork_context: false` unless full history is truly required. Put role and specialty instructions inside `message`. Flat `spawn_agent` requiring `task_name` instead (`multi_agent_v2`)? Add `"task_name"`, use `fork_turns: "none"`, `wait_agent` takes only `timeout_ms`, finished agents end on their own.
-6. Every sub-task message MUST be self-contained, executable, not a context handoff: start with `TASK: <imperative assignment>`, then name `DELIVERABLE`, `SCOPE`, and `VERIFY`. It must include all 7 sections and a Manual-QA channel with exact invocation (`curl`, `send-keys`, `browser:control-in-app-browser` action, `page.click`) and PASS/FAIL observable, plus ultraqa classes, artifact, and cleanup receipt. Channels: HTTP (`curl -i`); terminal/TUI (`send-keys` for boot smoke; xterm.js web terminal for color/visual evidence, never `tmux capture-pane`); browser (Codex: `browser:control-in-app-browser` first unless auth/persistent profile needed; else Chrome/agent-browser); computer use.
+6. Every sub-task message MUST be self-contained, executable, not a context handoff: start with `TASK: <imperative assignment>`, then name `DELIVERABLE`, `SCOPE`, and `VERIFY`. It must include all 7 sections and a Manual-QA channel with exact invocation (`curl`, `send-keys`, `browser:control-in-app-browser` action, `page.click`) and PASS/FAIL observable, plus ultraqa classes, artifact, and cleanup receipt. Channels: HTTP (`curl -i`); terminal/TUI (`send-keys` for boot smoke; xterm.js web terminal for color/visual evidence, never `tmux capture-pane`); browser (Codex: `browser:control-in-app-browser`; otherwise, or for Chrome semantics/stealth/trace/auth, write and run a `playwright-core` script from js eval with `channel: "chrome"`, persistent contexts on CLONED profiles only); computer use.
7. Treat every worker DoneClaim as untrusted input. Run independent AdversarialVerify before any checkbox can become FullyDone; the main session may run AdversarialVerify when no separate reviewer is available. `confirmed` is the only pass verdict, while `false-positive`, `needs-fix`, and `needs-human-review` loop back to the executor with exact feedback.
8. Use `multi_agent_v1.wait_agent` for mailbox signals, not proof of completion — a timeout only means no new mailbox update arrived; a running child is alive. For sub-tasks likely to exceed one wait cycle, require `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. Send `TASK STILL ACTIVE: return <deliverable> or BLOCKED: <reason>` only when the child is completed without the deliverable, ack-only, or no longer running. If that followup is still silent or ack-only, record inconclusive, do not count it as pass/review approval, close if safe, and respawn a smaller `fork_context: false` task with the missing deliverable.
9. After verification of ALL sub-tasks under this checkbox: `apply_patch` the plan to change `- [ ]` → `- [x]`, re-read the plan to confirm the count decreased, append a `task-completed` line to the ledger, then continue.
diff --git a/plugins/omo/components/ulw-execute-continuation/hooks/hooks.json b/plugins/omo/components/ulw-execute-continuation/hooks/hooks.json
index 7e4c0480..36252b65 100644
--- a/plugins/omo/components/ulw-execute-continuation/hooks/hooks.json
+++ b/plugins/omo/components/ulw-execute-continuation/hooks/hooks.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/ulw-execute-continuation/dist/cli.js\" hook stop",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.62) Checking Ulw-Execute Continuation"
+ "statusMessage": "(OmO 5.0.0-beta.63) Checking Ulw-Execute Continuation"
}
]
}
diff --git a/plugins/omo/components/ulw-execute-continuation/package.json b/plugins/omo/components/ulw-execute-continuation/package.json
index aaf492d3..e722179c 100644
--- a/plugins/omo/components/ulw-execute-continuation/package.json
+++ b/plugins/omo/components/ulw-execute-continuation/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-ulw-execute-continuation",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"description": "Codex Stop hook continuation injector for omo-codex ulw-execute plans.",
"type": "module",
"packageManager": "[email protected]",
diff --git a/plugins/omo/components/ulw-loop/CHANGELOG.md b/plugins/omo/components/ulw-loop/CHANGELOG.md
index 3385dcac..438c19f8 100644
--- a/plugins/omo/components/ulw-loop/CHANGELOG.md
+++ b/plugins/omo/components/ulw-loop/CHANGELOG.md
@@ -2,6 +2,19 @@
## [0.1.0] - unreleased
+- Status nextActions and missing-plan recovery now follow the calling surface: omo-senpi teaches the eval SDK methods and current attempt directory without asking for a driver snapshot; LazyCodex retains its existing CLI guidance byte-for-byte.
+
+- Async `.state.lock` holders now keep their file descriptor open and refresh a 30-second lease through it. An expired lease can be reclaimed even while its process remains alive; sync hooks and older lease-less records retain dead-pid-only ownership. Windows filesystems that refuse unlinking an open lock fail closed. Interrupted kernels can recover after lease expiry without deleting a live owner's lock.
+- Plan and audit mutations publish one immutable `revisions/<revision>.json` record using create-only hard links. Published revision paths are never deleted or reused.
+- `ULW_LOOP_PUBLISH_CONFLICT` retries the complete mutation once while its lock token remains owned.
+- A displaced writer receives `ULW_LOOP_LOCK_LOST` instead of overwriting its successor's state.
+- Filesystems without atomic hard links fail closed with `ULW_LOOP_PUBLISH_UNSUPPORTED_FS` (no copy fallback).
+- Additive plan fields `revision`, `brief`, and `ledgerResetRevision`, plus ledger `revision` and `id`, remain optional on legacy reads. The first mutation hydrates a legacy brief, and objective migration is folded into that mutation rather than committed by a read. Force recreation advances the revision and filters older audit entries instead of truncating the ledger.
+- `goals.json`, `ledger.jsonl`, and `brief.md` are complete-file, temp-and-rename derived views. Shared readers reconcile committed records after a crash, including audit-only steering and idempotency, and locked reads repair lagging views. Logical audit order is revision/sequence, not completion order. Older CLIs see complete but possibly lagging or transiently regressed caches; after force recreation they may see pre-reset entries until views are replaced. Hook budget counters remain separate from plan/audit state. Reconciliation now materializes the logical ledger in memory, replacing the earlier streaming-only dedup implementation.
+- Reconciling a plan reads only the newest commit record (newest revision first, stopping at the first valid one) instead of parsing every record in `revisions/`, so a status probe stays independent of how many revisions a session has committed. The full scan remains where the audit trail needs every record.
+
+- SDK contexts now reject session IDs that normalize to null with `ULW_LOOP_SESSION_ID_INVALID`, before any session state directory is created.
+
- LazyCodex native spawns now require an explicit bundled role before plan, budget, or artifact checks. Unknown and unnamed roles fail loudly; Senpi admission is unchanged. Guidance follows the actual spawn schema, including V2 `agent_type` when exposed. Installer/bootstrap provide an opt-out-able, ownership-checked medium-worker `default` for unnamed non-forks. An unnamed full-history fork still skips role application inside Codex: configuration cannot repair that upstream gap, and enforcement depends on Codex invoking the trusted hook. Legacy schemas without `agent_type` retain message-carried instructions but are rejected by the schema-blind guard rather than silently falling through.
- Bundled `directive.md` picks up the ultrawork test-proportionality change: the execution-loop PIN step asks for characterization pins only when refactoring behavior whose regressions the change could hide. Stays byte-identical to `prompts-core/ultrawork/codex.md` and the ultrawork component's `directive.md`.
diff --git a/plugins/omo/components/ulw-loop/directive.md b/plugins/omo/components/ulw-loop/directive.md
index d34f69d5..eb79e5c0 100644
--- a/plugins/omo/components/ulw-loop/directive.md
+++ b/plugins/omo/components/ulw-loop/directive.md
@@ -62,16 +62,17 @@ exercises the surface; capture the artifact.
for color / layout / CJK evidence, which degrades truecolor.
3. Browser use — in Codex, use `browser:control-in-app-browser`
first when available and no authenticated/persistent user browser
- profile is required. Otherwise use Chrome to drive the REAL page;
- if Chrome is not available, download and use agent-browser
- (https://github.com/vercel-labs/agent-browser). Capture action
+ profile is required. Otherwise, or for Chrome semantics, stealth,
+ or trace, WRITE a `playwright-core` script and run it from js eval
+ against local Chrome (`chromium.launch({ channel: "chrome" })` /
+ `launchPersistentContext` on a CLONED profile). Capture action
log + screenshot path. Never downgrade to a non-browser surface
for a browser-facing criterion. NEVER clear cookies, cache, or
site data (`Network.clearBrowserCookies`, `Storage.clearCookies`,
`chrome.browsingData.remove`, "clear browsing data") on the user's
real/main browser profile — it wipes their logged-in state. If you
need that profile's login state, clone it first (`rsync -a
- <profile>/ <tmp-clone>/`) and launch Chrome / agent-browser against
+ <profile>/ <tmp-clone>/`) and launch Chrome against
the clone as the user-data-dir; run any clearing there only.
4. Computer use — when the surface is a desktop/GUI app rather than a
page, drive it via OS-level automation (a computer-use agent,
diff --git a/plugins/omo/components/ulw-loop/dist/checkpoint.js b/plugins/omo/components/ulw-loop/dist/checkpoint.js
index 09f8b9d0..8b6699b0 100644
--- a/plugins/omo/components/ulw-loop/dist/checkpoint.js
+++ b/plugins/omo/components/ulw-loop/dist/checkpoint.js
@@ -6,7 +6,8 @@ import { combineCheckpointValidationErrors, validateCheckpointCodexGoal, } from
import { requireAllCriteriaPass, requireAllPlanCriteriaPass, requireEssentialCriteriaPass } from "./evidence.js";
import { codexGoalMode, isFinalRunCompletionCandidate } from "./goal-status.js";
import { ulwLoopAttemptEvidenceDir } from "./paths.js";
-import { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";
+import { commit } from "./plan-commit.js";
+import { readUlwLoopPlan, withUlwLoopMutationLock } from "./plan-io.js";
import { classifyExternalAuthorizationBlocker, clearGoalBlockerFields, sameBlockerOccurrences, validateQualityGate, } from "./quality-gate.js";
import { resolveToolkitSurface } from "./surface.js";
import { iso, UlwLoopError } from "./types.js";
@@ -187,12 +188,12 @@ export async function checkpointUlwLoop(repoRoot, args, scope, dependencies) {
if (aggregateCompletion !== undefined)
nextActions = [...nextActions, 'aggregate complete — now update_goal({status:"complete"})'];
plan.updatedAt = now;
- await writePlan(repoRoot, plan, scope);
const ledgerEntry = buildLedger(now, args, goal, qualityGate, codexGoal, aggregateCompletion);
- await appendLedger(repoRoot, ledgerEntry, scope);
+ const entries = [ledgerEntry];
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);
+ entries.push({ at: now, kind: "batch_closed", goalId: goal.id, message: closedBatch.batchId });
+ await commit(repoRoot, scope, { plan, entries });
return aggregateCompletion === undefined
? { plan, goal, ledgerEntry, nextActions, warnings }
: { plan, goal, ledgerEntry, aggregateCompletion, nextActions, warnings };
diff --git a/plugins/omo/components/ulw-loop/dist/cli.js b/plugins/omo/components/ulw-loop/dist/cli.js
index c3e94ae7..ac8712b5 100644
--- a/plugins/omo/components/ulw-loop/dist/cli.js
+++ b/plugins/omo/components/ulw-loop/dist/cli.js
@@ -1,8 +1,8 @@
#!/usr/bin/env node
// components/ulw-loop/src/checkpoint.ts
-import { existsSync as existsSync3, statSync as statSync2 } from "node:fs";
-import { readFile as readFile4 } from "node:fs/promises";
+import { existsSync as existsSync4, statSync as statSync2 } from "node:fs";
+import { readFile as readFile3 } from "node:fs/promises";
import { resolve as resolve3 } from "node:path";
// components/ulw-loop/src/codex-goal-snapshot.ts
@@ -178,15 +178,9 @@ function ulwLoopGoalsRelativePath(scope) {
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 ulwLoopStateLockPath(repoRoot, scope) {
return join(ulwLoopDir(repoRoot, scope), ULW_LOOP_STATE_LOCK);
}
@@ -322,23 +316,142 @@ ${gateError.message}`, "ULW_LOOP_QUALITY_GATE_INVALID", {
});
}
+// components/ulw-loop/src/plan-commit.ts
+import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
+import { randomUUID as randomUUID2 } from "node:crypto";
+import { linkSync, mkdirSync as mkdirSync2, renameSync, rmSync, writeFileSync } from "node:fs";
+import { rename, writeFile } from "node:fs/promises";
+import { join as join4 } from "node:path";
+
+// components/ulw-loop/src/ledger.ts
+import { join as join3 } from "node:path";
+
+// components/ulw-loop/src/plan-log.ts
+import { existsSync as existsSync2, readdirSync, readFileSync } from "node:fs";
+import { join as join2 } from "node:path";
+function hasCode(error, code) {
+ return error instanceof Error && "code" in error && error.code === code;
+}
+function readOptional(path) {
+ try {
+ return readFileSync(path, "utf8");
+ } catch (error) {
+ if (hasCode(error, "ENOENT"))
+ return;
+ throw error;
+ }
+}
+function logNames(dir) {
+ try {
+ return readdirSync(join2(dir, "revisions")).filter((name) => /^\d{8,}\.json$/.test(name)).sort();
+ } catch (error) {
+ if (hasCode(error, "ENOENT"))
+ return [];
+ throw error;
+ }
+}
+function readRecord(dir, name) {
+ try {
+ const record = JSON.parse(readFileSync(join2(dir, "revisions", name), "utf8"));
+ return record.version === 1 && Number.isInteger(record.revision) && record.plan?.version === 1 && Array.isArray(record.plan.goals) && Array.isArray(record.ledger) ? record : undefined;
+ } catch (error) {
+ if (!(error instanceof SyntaxError))
+ throw error;
+ return;
+ }
+}
+function readRecords(dir) {
+ const records = [];
+ for (const name of logNames(dir)) {
+ const record = readRecord(dir, name);
+ if (record !== undefined)
+ records.push(record);
+ }
+ return records.sort((a, b) => a.revision - b.revision);
+}
+function readNewestRecord(dir) {
+ const names = logNames(dir).sort((a, b) => Number.parseInt(b, 10) - Number.parseInt(a, 10));
+ for (const name of names) {
+ const record = readRecord(dir, name);
+ if (record !== undefined)
+ return record;
+ }
+ return;
+}
+function reconcilePlan(dir) {
+ const raw = readOptional(join2(dir, "goals.json"));
+ let cached;
+ if (raw !== undefined) {
+ try {
+ cached = JSON.parse(raw);
+ } catch (error) {
+ if (!(error instanceof SyntaxError))
+ throw error;
+ }
+ }
+ const latest = readNewestRecord(dir);
+ return latest !== undefined && latest.revision >= (cached?.revision ?? 0) ? latest.plan : cached;
+}
+function planExists(repoRoot, scope) {
+ const dir = ulwLoopDir(repoRoot, scope);
+ return existsSync2(join2(dir, "goals.json")) || logNames(dir).length > 0;
+}
+
+// components/ulw-loop/src/ledger.ts
+function readLedgerAt(dir) {
+ const entries = new Map;
+ const lines = (readOptional(join3(dir, "ledger.jsonl")) ?? "").split(/\r?\n/);
+ for (const [index, line] of lines.entries()) {
+ if (line.trim().length === 0)
+ continue;
+ try {
+ const entry = JSON.parse(line);
+ entry.revision ??= 0;
+ entry.id ??= `legacy-${index + 1}`;
+ entries.set(entry.id, entry);
+ } catch (error) {
+ if (!(error instanceof SyntaxError))
+ throw error;
+ }
+ }
+ for (const record of readRecords(dir))
+ for (const [seq, entry] of record.ledger.entries()) {
+ const id = entry.id ?? `${record.revision}-${seq}`;
+ entries.set(id, { ...entry, revision: record.revision, id });
+ }
+ const reset = reconcilePlan(dir)?.ledgerResetRevision ?? 0;
+ const sequence = (entry) => Number(entry.id?.split("-").at(-1) ?? 0);
+ return [...entries.values()].filter((entry) => (entry.revision ?? 0) >= reset).sort((a, b) => (a.revision ?? 0) - (b.revision ?? 0) || sequence(a) - sequence(b));
+}
+function readLedger(repoRoot, scope) {
+ return readLedgerAt(ulwLoopDir(repoRoot, scope));
+}
+
// components/ulw-loop/src/plan-io.ts
import { AsyncLocalStorage } from "node:async_hooks";
-import { createReadStream, readdirSync } from "node:fs";
-import { appendFile, mkdir, readFile as readFile2, rename, writeFile } from "node:fs/promises";
-import { createInterface } from "node:readline";
+import { readdirSync as readdirSync2 } from "node:fs";
// components/ulw-loop/src/plan-missing-recovery.ts
var ULW_LOOP_CREATE_GOALS_COMMAND = 'omo-agent-toolkit ulw-loop create-goals --brief "<brief>" --json';
-function planMissingRecovery(existingSessionIds) {
- const lines = [`Recovery: bootstrap the plan with \`${ULW_LOOP_CREATE_GOALS_COMMAND}\`.`];
+function createGoalsAction(surface) {
+ return surface === "omo-senpi" ? 'agentToolkit.createGoals({ brief: "<brief>" })' : ULW_LOOP_CREATE_GOALS_COMMAND;
+}
+function planMissingRecovery(existingSessionIds, surface = "lazycodex") {
+ const lines = [`Recovery: bootstrap the plan with \`${createGoalsAction(surface)}\`.`];
if (existingSessionIds.length === 0)
return { message: lines.join(`
`) };
- lines.push(`Existing ulw-loop session ids under .omo/ulw-loop/: ${existingSessionIds.join(", ")}. Re-run with \`--session-id <id>\` to target one of them.`);
+ lines.push(surface === "omo-senpi" ? `Existing ulw-loop session ids under .omo/ulw-loop/: ${existingSessionIds.join(", ")}. The SDK is bound to the current session; resume the owning session to target its plan.` : `Existing ulw-loop session ids under .omo/ulw-loop/: ${existingSessionIds.join(", ")}. Re-run with \`--session-id <id>\` to target one of them.`);
return { message: lines.join(`
`), details: { existingSessionIds } };
}
+function planMissingError(planPath, existingSessionIds, surface = "lazycodex") {
+ const recovery = planMissingRecovery(existingSessionIds, surface);
+ return new UlwLoopError(`No ulw-loop plan found at ${planPath}.
+${recovery.message}`, "ULW_LOOP_PLAN_MISSING", {
+ ...recovery.details === undefined ? {} : { details: recovery.details }
+ });
+}
function sessionScopeRequiredMessage(flag, existingSessionIds) {
const lines = [
"No ulw-loop session scope: neither the session env (OMO_ULW_LOOP_SESSION_ID / CODEX_SESSION_ID / CODEX_THREAD_ID / PI_SESSION_ID) nor the flag names this run, and the shared .omo/ulw-loop root is never used implicitly because every session in this directory would read and overwrite it.",
@@ -361,155 +474,207 @@ function sessionIdRequiredMessage(flag) {
// components/ulw-loop/src/state-lock.ts
import { randomUUID } from "node:crypto";
-import { closeSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeSync } from "node:fs";
+import { closeSync, ftruncateSync, mkdirSync, openSync, readFileSync as readFileSync2, statSync, unlinkSync, writeSync } from "node:fs";
import { dirname } from "node:path";
-import { setTimeout as sleep } from "node:timers/promises";
var ULW_LOOP_LOCK_TIMEOUT_CODE = "ULW_LOOP_LOCK_TIMEOUT";
var DEFAULT_TIMEOUT_MS = 1e4;
var DEFAULT_STALE_MS = 60000;
-var MIN_DELAY_MS = 5;
-var MAX_DELAY_MS = 100;
+var DEFAULT_LEASE_MS = 30000;
var SLEEP_CELL = new Int32Array(new SharedArrayBuffer(4));
+var systemClock = {
+ now: Date.now,
+ schedule(fn, ms) {
+ const timer = setTimeout(fn, ms);
+ return {
+ unref: () => {
+ timer.unref();
+ },
+ cancel: () => clearTimeout(timer)
+ };
+ }
+};
async function withStateLock(lockPath, fn, options = {}) {
- const token = await acquireAsync(lockPath, options);
+ const holder = await acquireAsync(lockPath, options);
+ const clock = options.clock ?? systemClock;
+ let timer;
+ let heartbeatError;
+ const beat = () => {
+ try {
+ holder.record.leaseUntil = clock.now() + (options.leaseMs ?? DEFAULT_LEASE_MS);
+ writeRecord(holder);
+ schedule();
+ } catch (error) {
+ heartbeatError = error;
+ }
+ };
+ const schedule = () => {
+ if (options.heartbeatMs === 0)
+ return;
+ timer = clock.schedule(beat, options.heartbeatMs ?? (options.leaseMs ?? DEFAULT_LEASE_MS) / 3);
+ timer.unref();
+ };
+ schedule();
try {
- return await fn();
+ const result = await fn(holder.record.token);
+ if (heartbeatError !== undefined)
+ throw heartbeatError;
+ return result;
} finally {
- release(lockPath, token);
+ timer?.cancel();
+ closeSync(holder.fd);
+ release(lockPath, holder.record.token);
}
}
function withStateLockSync(lockPath, fn, options = {}) {
- const token = acquireSync(lockPath, options);
+ const holder = acquireSync(lockPath, options);
try {
return fn();
} finally {
- release(lockPath, token);
+ closeSync(holder.fd);
+ release(lockPath, holder.record.token);
}
}
function isStateLockTimeout(error) {
return error instanceof UlwLoopError && error.code === ULW_LOOP_LOCK_TIMEOUT_CODE;
}
async function acquireAsync(lockPath, options) {
- const deadline = Date.now() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
- const staleMs = options.staleMs ?? DEFAULT_STALE_MS;
+ const clock = options.clock ?? systemClock;
+ const deadline = clock.now() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
mkdirSync(dirname(lockPath), { recursive: true });
for (let attempt = 0;; ) {
- const outcome = attemptOnce(lockPath, staleMs);
+ const outcome = attemptOnce(lockPath, options, clock.now(), options.leaseMs ?? DEFAULT_LEASE_MS);
if (outcome.kind === "acquired")
- return outcome.token;
+ return outcome.holder;
if (outcome.kind === "retry")
continue;
- if (Date.now() >= deadline)
- throw lockTimeout(lockPath, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
- await sleep(backoffMs(attempt));
+ if (clock.now() >= deadline)
+ throw lockTimeout(lockPath, options);
+ await new Promise((resolve) => clock.schedule(resolve, backoffMs(attempt)));
attempt += 1;
}
}
function acquireSync(lockPath, options) {
const deadline = Date.now() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
- const staleMs = options.staleMs ?? DEFAULT_STALE_MS;
mkdirSync(dirname(lockPath), { recursive: true });
for (let attempt = 0;; ) {
- const outcome = attemptOnce(lockPath, staleMs);
+ const outcome = attemptOnce(lockPath, options, Date.now());
if (outcome.kind === "acquired")
- return outcome.token;
+ return outcome.holder;
if (outcome.kind === "retry")
continue;
if (Date.now() >= deadline)
- throw lockTimeout(lockPath, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
+ throw lockTimeout(lockPath, options);
Atomics.wait(SLEEP_CELL, 0, 0, backoffMs(attempt));
attempt += 1;
}
}
-function attemptOnce(lockPath, staleMs) {
+function attemptOnce(lockPath, options, now, leaseMs) {
try {
- const token = tryCreate(lockPath);
- if (token !== null)
- return { kind: "acquired", token };
- const snapshot = readSnapshot(lockPath);
+ const holder = tryCreate(lockPath, now, leaseMs);
+ if (holder !== null)
+ return { kind: "acquired", holder };
+ const snapshot = readSnapshot(lockPath, now);
if (snapshot === null)
return { kind: "retry" };
- if (isStale(snapshot, staleMs) && reclaim(lockPath, snapshot.raw))
+ const record = snapshot.record;
+ const stale = record === null ? snapshot.ageMs > (options.staleMs ?? DEFAULT_STALE_MS) : !isProcessAlive(record.pid) || record.leaseUntil !== undefined && now > record.leaseUntil;
+ if (stale && reclaim(lockPath, snapshot.raw))
return { kind: "retry" };
return { kind: "wait" };
} catch (error) {
- if (hasCode(error, "EINTR"))
+ if (hasCode2(error, "EINTR"))
return { kind: "wait" };
throw error;
}
}
-function tryCreate(lockPath) {
+function writeRecord(holder) {
+ const buf = Buffer.from(JSON.stringify(holder.record));
+ ftruncateSync(holder.fd, 0);
+ let offset = 0;
+ while (offset < buf.length) {
+ const written = writeSync(holder.fd, buf, offset, buf.length - offset, offset);
+ if (written === 0)
+ throw new Error("State lock write made no progress.");
+ offset += written;
+ }
+}
+function tryCreate(lockPath, now, leaseMs) {
let fd;
try {
fd = openSync(lockPath, "wx");
} catch (error) {
- if (hasCode(error, "EEXIST"))
+ if (hasCode2(error, "EEXIST"))
return null;
throw error;
}
- const record = { pid: process.pid, createdAt: new Date().toISOString(), token: randomUUID() };
+ const record = {
+ pid: process.pid,
+ createdAt: new Date(now).toISOString(),
+ token: randomUUID(),
+ ...leaseMs === undefined ? {} : { leaseUntil: now + leaseMs }
+ };
+ const holder = { fd, record };
try {
- writeSync(fd, JSON.stringify(record));
+ writeRecord(holder);
} catch (error) {
closeSync(fd);
try {
unlinkSync(lockPath);
- } catch {}
+ } catch (cleanup) {
+ if (!hasCode2(cleanup, "ENOENT"))
+ throw cleanup;
+ }
throw error;
}
- closeSync(fd);
- return record.token;
+ return holder;
}
-function readSnapshot(lockPath) {
+function readSnapshot(lockPath, now) {
try {
- const raw = readFileSync(lockPath, "utf8");
- const ageMs = Date.now() - statSync(lockPath).mtimeMs;
- return { raw, record: parseRecord(raw), ageMs };
+ const raw = readFileSync2(lockPath, "utf8");
+ return { raw, record: parseRecord(raw), ageMs: now - statSync(lockPath).mtimeMs };
} catch (error) {
- if (hasCode(error, "ENOENT"))
+ if (hasCode2(error, "ENOENT"))
return null;
throw error;
}
}
function parseRecord(raw) {
try {
- const parsed = JSON.parse(raw);
- if (typeof parsed !== "object" || parsed === null)
+ const record = JSON.parse(raw);
+ if (typeof record !== "object" || record === null)
+ return null;
+ if (!("pid" in record) || typeof record.pid !== "number" || !Number.isInteger(record.pid) || record.pid <= 0)
return null;
- const record = parsed;
- const pid = record["pid"];
- const createdAt = record["createdAt"];
- const token = record["token"];
- if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0 || typeof createdAt !== "string")
+ if (!("createdAt" in record) || typeof record.createdAt !== "string")
return null;
- if (typeof token !== "string" || token.length === 0)
+ if (!("token" in record) || typeof record.token !== "string" || record.token.length === 0)
return null;
- return { pid, createdAt, token };
+ return {
+ pid: record.pid,
+ createdAt: record.createdAt,
+ token: record.token,
+ ..."leaseUntil" in record && typeof record.leaseUntil === "number" ? { leaseUntil: record.leaseUntil } : {}
+ };
} catch (error) {
if (error instanceof SyntaxError)
return null;
throw error;
}
}
-function isStale(snapshot, staleMs) {
- if (snapshot.record === null)
- return snapshot.ageMs > staleMs;
- return !isProcessAlive(snapshot.record.pid);
-}
function isProcessAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch (error) {
- if (hasCode(error, "ESRCH"))
+ if (hasCode2(error, "ESRCH"))
return false;
- if (hasCode(error, "EPERM"))
+ if (hasCode2(error, "EPERM"))
return true;
throw error;
}
}
function reclaim(lockPath, expectedRaw) {
- const current = readSnapshot(lockPath);
+ const current = readSnapshot(lockPath, Date.now());
if (current === null)
return true;
if (current.raw !== expectedRaw)
@@ -517,63 +682,102 @@ function reclaim(lockPath, expectedRaw) {
try {
unlinkSync(lockPath);
} catch (error) {
- if (!hasCode(error, "ENOENT"))
+ if (hasCode2(error, "EPERM") || hasCode2(error, "EACCES"))
+ return false;
+ if (!hasCode2(error, "ENOENT"))
throw error;
}
return true;
}
function release(lockPath, token) {
- const current = readSnapshot(lockPath);
- if (current === null || current.record?.token !== token)
+ if (readSnapshot(lockPath, Date.now())?.record?.token !== token)
return;
try {
unlinkSync(lockPath);
} catch (error) {
- if (!hasCode(error, "ENOENT"))
+ if (!hasCode2(error, "ENOENT"))
throw error;
}
}
function backoffMs(attempt) {
- const exponential = Math.min(MAX_DELAY_MS, MIN_DELAY_MS * 2 ** attempt);
- return exponential + Math.random() * MIN_DELAY_MS;
+ return Math.min(100, 5 * 2 ** attempt) + Math.random() * 5;
}
-function lockTimeout(lockPath, timeoutMs) {
- const holder = readSnapshot(lockPath)?.record;
- const owner = holder === undefined || holder === null ? "another process" : `pid ${holder.pid}`;
- return new UlwLoopError(`ulw-loop state lock ${lockPath} is held by ${owner} for more than ${timeoutMs}ms; retry once that process finishes, or delete the lock file if that process is gone.`, ULW_LOOP_LOCK_TIMEOUT_CODE, {
- details: {
- lockPath,
- timeoutMs,
- ...holder === undefined || holder === null ? {} : { holderPid: holder.pid }
- }
- });
+function lockTimeout(lockPath, options) {
+ const holder = readSnapshot(lockPath, Date.now())?.record;
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ const owner = holder == null ? "another process" : `pid ${holder.pid}`;
+ return new UlwLoopError(`ulw-loop state lock ${lockPath} is held by ${owner} for more than ${timeoutMs}ms. The lock owner is still alive. If a JS eval kernel was interrupted while writing, wait for its lease to expire (${options.leaseMs ?? DEFAULT_LEASE_MS} ms) or restart the owning senpi process; never delete a lock owned by a live process.`, ULW_LOOP_LOCK_TIMEOUT_CODE, { details: { lockPath, timeoutMs, ...holder == null ? {} : { holderPid: holder.pid } } });
}
-function hasCode(error, code) {
+function hasCode2(error, code) {
return error instanceof Error && "code" in error && error.code === code;
}
// components/ulw-loop/src/plan-io.ts
+function readLedger2(repoRoot, scope) {
+ const lockPath = ulwLoopStateLockPath(repoRoot, scope);
+ if (heldLocks.getStore()?.has(lockPath)) {
+ assertStateLockOwned(lockPath);
+ materializeSync(ulwLoopDir(repoRoot, scope));
+ }
+ return readLedger(repoRoot, scope);
+}
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;
var heldLocks = new AsyncLocalStorage;
-function hasCode2(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));
+var lockOptions = new AsyncLocalStorage;
+function tokenAt(lockPath) {
+ const raw = readOptional(lockPath);
+ if (raw === undefined)
+ return;
+ try {
+ const record = JSON.parse(raw);
+ return typeof record === "object" && record !== null && "token" in record && typeof record.token === "string" ? record.token : undefined;
+ } catch (error) {
+ if (error instanceof SyntaxError)
+ return;
+ throw error;
+ }
}
-function isSteeringKind(value) {
- return value === "steering_accepted" || value === "steering_rejected" || value === "criteria_revised" || value === "batch_updated";
+function assertStateLockOwned(lockPath) {
+ const context = heldLocks.getStore()?.get(lockPath);
+ if (context === undefined)
+ return;
+ if (tokenAt(lockPath) !== context.token)
+ throw new UlwLoopError("The ulw-loop mutation lock changed owners.", "ULW_LOOP_LOCK_LOST");
+}
+function migrationEntries(plan) {
+ for (const context of heldLocks.getStore()?.values() ?? []) {
+ const entries = context.migrations.get(plan.goalsPath);
+ if (entries !== undefined) {
+ context.migrations.delete(plan.goalsPath);
+ return entries;
+ }
+ }
+ return [];
}
-async function withUlwLoopMutationLock(repoRoot, scopeOrFn, maybeFn) {
+async function withUlwLoopMutationLock(repoRoot, scopeOrFn, maybeFn, options = {}) {
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 lockPath = ulwLoopStateLockPath(repoRoot, scope);
- const locked = () => withStateLock(lockPath, () => heldLocks.run(new Set([...heldLocks.getStore() ?? [], lockKey]), fn));
+ const locked = () => withStateLock(lockPath, async (token) => {
+ return heldLocks.run(new Map([...heldLocks.getStore() ?? [], [lockPath, { token, migrations: new Map }]]), async () => {
+ for (let attempt = 0;; attempt += 1) {
+ try {
+ return await fn();
+ } catch (error) {
+ if (!(error instanceof UlwLoopError) || error.code !== "ULW_LOOP_PUBLISH_CONFLICT")
+ throw error;
+ assertStateLockOwned(lockPath);
+ if (attempt !== 0)
+ throw error;
+ }
+ }
+ });
+ }, { ...lockOptions.getStore(), ...options });
const prior = locks.get(lockKey) ?? Promise.resolve(undefined);
const run = prior.then(locked, locked);
const gate = run.then(() => {
@@ -588,98 +792,140 @@ async function withUlwLoopMutationLock(repoRoot, scopeOrFn, maybeFn) {
});
return run;
}
-async function readUlwLoopPlan(repoRoot, scope) {
+function readUlwLoopPlanSync(repoRoot, scope) {
const path = ulwLoopGoalsPath(repoRoot, scope);
- let raw;
- try {
- raw = await readFile2(path, "utf8");
- } catch (error) {
- if (!hasCode2(error, "ENOENT"))
- throw error;
- const recovery = planMissingRecovery(listUlwLoopSessionIds(repoRoot));
- throw new UlwLoopError(`No ulw-loop plan found at ${repoRelative(path, repoRoot)}.
-${recovery.message}`, "ULW_LOOP_PLAN_MISSING", { cause: error, ...recovery.details === undefined ? {} : { details: recovery.details } });
- }
- const parsed = JSON.parse(raw);
- if (parsed.version !== 1 || !Array.isArray(parsed.goals)) {
+ const parsed = reconcilePlan(ulwLoopDir(repoRoot, scope));
+ if (parsed === undefined)
+ throw planMissingError(repoRelative(path, repoRoot), listUlwLoopSessionIds(repoRoot));
+ 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)) {
- if (!(heldLocks.getStore()?.has(`${repoRoot}\x00${ulwLoopRelativeDir(scope)}`) ?? false)) {
- throw new UlwLoopError(`The ulw-loop plan at ${repoRelative(path, repoRoot)} carries a legacy enumerated aggregate objective that must be migrated before reads continue. Run any state-mutating ulw-loop command once (e.g. \`record-evidence\`, \`steer\`, \`checkpoint\`) to migrate it under the state lock, then retry.`, "ULW_LOOP_MIGRATION_REQUIRED");
- }
- const now = iso();
+ if ((parsed.codexGoalMode ?? "per_story") === "aggregate" && previousObjective !== undefined && (previousObjective === LEGACY_OBJECTIVE || previousObjective.startsWith(LEGACY_OBJECTIVE_PREFIX))) {
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);
+ heldLocks.getStore()?.get(ulwLoopStateLockPath(repoRoot, scope))?.migrations.set(parsed.goalsPath, [
+ {
+ at: iso(),
+ kind: "aggregate_objective_migrated",
+ before: { codexObjective: previousObjective },
+ after: { codexObjective: parsed.codexObjective }
+ }
+ ]);
}
return parsed;
}
+async function readUlwLoopPlan(repoRoot, scope) {
+ if (heldLocks.getStore()?.has(ulwLoopStateLockPath(repoRoot, scope))) {
+ assertStateLockOwned(ulwLoopStateLockPath(repoRoot, scope));
+ await materialize(ulwLoopDir(repoRoot, scope));
+ }
+ return readUlwLoopPlanSync(repoRoot, scope);
+}
function listUlwLoopSessionIds(repoRoot) {
try {
- return readdirSync(ulwLoopDir(repoRoot), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
+ return readdirSync2(ulwLoopDir(repoRoot), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
} catch {
return [];
}
}
-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);
+function isSteeringKind(value) {
+ return value === "steering_accepted" || value === "steering_rejected" || value === "criteria_revised" || value === "batch_updated";
}
-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 findAcceptedSteeringLedgerEntry(repoRoot, key, scope) {
+ return readLedger2(repoRoot, scope).find((entry) => isSteeringKind(entry.kind) && entry.steering?.invariant.accepted === true && (entry.idempotencyKey === key || entry.steering.idempotencyKey === key || entry.steering.promptSignature === key));
}
-async function* ledgerLines(repoRoot, scope) {
- const stream = createReadStream(ulwLoopLedgerPath(repoRoot, scope), { encoding: "utf8" });
- const lines = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });
+
+// components/ulw-loop/src/plan-commit.ts
+var hooks = new AsyncLocalStorage2;
+async function beforePlanMutation() {
+ await hooks.getStore()?.beforeMutation?.();
+}
+async function writeViewFile(path, content) {
+ await (hooks.getStore()?.writeView ?? writeFile)(path, content);
+}
+async function commit(repoRoot, scope, mutation) {
+ const { plan } = mutation;
+ const dir = ulwLoopDir(repoRoot, scope);
+ assertStateLockOwned(ulwLoopStateLockPath(repoRoot, scope));
+ await hooks.getStore()?.beforeCommit?.();
+ const next = (plan.revision ?? 0) + 1;
+ const brief = plan.brief ?? readOptional(join4(dir, "brief.md")) ?? "";
+ const entries = [...migrationEntries(plan), ...mutation.entries].map((entry, seq) => ({
+ ...entry,
+ revision: next,
+ id: `${next}-${seq}`
+ }));
+ const record = {
+ version: 1,
+ revision: next,
+ plan: { ...plan, revision: next, brief },
+ ledger: entries
+ };
+ mkdirSync2(join4(dir, "revisions"), { recursive: true });
+ mkdirSync2(join4(dir, "tmp"), { recursive: true });
+ const temp = join4(dir, "tmp", `${process.pid}-${randomUUID2()}.json`);
try {
- for await (const line of lines) {
- if (line.trim().length > 0)
- yield line;
- }
- } catch (error) {
- if (!hasCode2(error, "ENOENT"))
+ writeFileSync(temp, `${JSON.stringify(record)}
+`, { flag: "wx" });
+ try {
+ (hooks.getStore()?.link ?? linkSync)(temp, join4(dir, "revisions", `${String(next).padStart(8, "0")}.json`));
+ } catch (error) {
+ if (hasCode(error, "EEXIST"))
+ throw new UlwLoopError("Another writer published the read revision.", "ULW_LOOP_PUBLISH_CONFLICT", {
+ cause: error
+ });
+ if (["EPERM", "ENOTSUP", "EXDEV"].some((code) => hasCode(error, code)))
+ throw new UlwLoopError("Immutable ulw-loop publication requires atomic hard links.", "ULW_LOOP_PUBLISH_UNSUPPORTED_FS", { cause: error });
throw error;
+ }
} finally {
- lines.close();
- stream.destroy();
+ rmSync(temp, { force: true });
}
+ plan.revision = next;
+ plan.brief = brief;
+ for (const [index, entry] of mutation.entries.entries())
+ Object.assign(entry, entries[index + entries.length - mutation.entries.length]);
+ await hooks.getStore()?.afterCommit?.();
+ await materialize(dir);
+}
+function viewContents(dir) {
+ const plan = reconcilePlan(dir);
+ if (plan === undefined || readRecords(dir).length === 0)
+ return [];
+ const ledger = readLedgerAt(dir);
+ const views = [
+ ["goals.json", `${JSON.stringify(plan, null, 2)}
+`],
+ ["ledger.jsonl", ledger.length === 0 ? "" : `${ledger.map((entry) => JSON.stringify(entry)).join(`
+`)}
+`],
+ ["brief.md", plan.brief ?? readOptional(join4(dir, "brief.md")) ?? ""]
+ ];
+ return views.filter(([name, content]) => readOptional(join4(dir, name)) !== content);
}
-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;
+function materializeSync(dir) {
+ for (const [name, content] of viewContents(dir)) {
+ mkdirSync2(join4(dir, "tmp"), { recursive: true });
+ const temp = join4(dir, "tmp", `${process.pid}-${randomUUID2()}-${name}`);
+ try {
+ writeFileSync(temp, content, { flag: "wx" });
+ renameSync(temp, join4(dir, name));
+ } finally {
+ rmSync(temp, { force: true });
+ }
+ }
+}
+async function materialize(dir) {
+ for (const [name, content] of viewContents(dir)) {
+ mkdirSync2(join4(dir, "tmp"), { recursive: true });
+ const temp = join4(dir, "tmp", `${process.pid}-${randomUUID2()}-${name}`);
+ try {
+ await writeViewFile(temp, content);
+ await rename(temp, join4(dir, name));
+ } finally {
+ rmSync(temp, { force: true });
+ }
}
- return;
}
// components/ulw-loop/src/evidence.ts
@@ -729,7 +975,6 @@ async function recordEvidence(repoRoot, args, scope) {
criterion.notes = args.notes;
goal.updatedAt = capturedAt;
plan.updatedAt = capturedAt;
- await writePlan(repoRoot, plan, scope);
const ledgerEntry = {
at: capturedAt,
kind,
@@ -741,7 +986,7 @@ async function recordEvidence(repoRoot, args, scope) {
before: { status: prevStatus },
after: { goalId: goal.id, criterionId: criterion.id, status: args.status, evidence, capturedAt, prevStatus }
};
- await appendLedger(repoRoot, ledgerEntry, scope);
+ await commit(repoRoot, scope, { plan, entries: [ledgerEntry] });
return { plan, goal, criterion, ledgerEntry };
});
}
@@ -1011,8 +1256,8 @@ function adversarialVerdict(row, field) {
}
// components/ulw-loop/src/surface.ts
-import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
-import { dirname as dirname2, join as join2 } from "node:path";
+import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
+import { dirname as dirname2, join as join5 } from "node:path";
import { fileURLToPath } from "node:url";
var REVIEWER_ROLES_BY_SURFACE = {
lazycodex: {
@@ -1066,14 +1311,14 @@ function resolveToolkitSurface(options) {
if (fromEnv !== null)
return fromEnv;
const entryDir = options?.entryDir ?? dirname2(fileURLToPath(import.meta.url));
- const markerPath = join2(entryDir, SURFACE_MARKER_FILENAME);
+ const markerPath = join5(entryDir, SURFACE_MARKER_FILENAME);
return readMarkerSurface(markerPath) ?? "lazycodex";
}
function readMarkerSurface(markerPath) {
try {
- if (!existsSync2(markerPath))
+ if (!existsSync3(markerPath))
return null;
- const parsed = JSON.parse(readFileSync2(markerPath, "utf8"));
+ const parsed = JSON.parse(readFileSync3(markerPath, "utf8"));
return parseSurface(parsed["surface"]);
} catch (error) {
if (error instanceof Error)
@@ -1274,7 +1519,7 @@ function parseAdversarialCases(value, byId) {
}
// components/ulw-loop/src/cli-arg-parser.ts
-import { readFile as readFile3 } from "node:fs/promises";
+import { readFile as readFile2 } 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) {
@@ -1322,7 +1567,7 @@ async function readJsonInput(value) {
if (value === undefined)
return;
try {
- return JSON.parse(looksLikeJson(value) ? value : await readFile3(value, "utf8"));
+ return JSON.parse(looksLikeJson(value) ? value : await readFile2(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 });
@@ -1332,7 +1577,7 @@ async function parseCodexGoalJson(value) {
if (value === undefined)
return;
try {
- const raw = looksLikeJson(value) ? value : await readFile3(value, "utf8");
+ const raw = looksLikeJson(value) ? value : await readFile2(value, "utf8");
JSON.parse(raw);
return raw;
} catch (error) {
@@ -1483,7 +1728,7 @@ function fail(message, code = "ULW_LOOP_VALIDATION_BATCH_INVALID") {
}
// components/ulw-loop/src/checkpoint.ts
-var QUALITY_GATE_FS = { existsSync: existsSync3, statSync: statSync2 };
+var QUALITY_GATE_FS = { existsSync: existsSync4, statSync: statSync2 };
function ulwLoopFail2(message, code) {
throw new UlwLoopError(message, code);
}
@@ -1506,10 +1751,10 @@ async function readJsonInput2(raw, repoRoot) {
throw error;
}
const path = resolve3(repoRoot, trimmed);
- if (!existsSync3(path))
+ if (!existsSync4(path))
return ulwLoopFail2("Quality gate JSON is neither valid JSON nor a readable path.", "ulw_loop_json_input_invalid");
try {
- return JSON.parse(await readFile4(path, "utf8"));
+ return JSON.parse(await readFile3(path, "utf8"));
} catch (error) {
return ulwLoopFail2(`Quality gate path does not contain valid JSON${error instanceof Error ? `: ${error.message}` : "."}`, "ulw_loop_json_input_invalid");
}
@@ -1649,12 +1894,12 @@ async function checkpointUlwLoop(repoRoot, args, scope, dependencies) {
if (aggregateCompletion !== undefined)
nextActions = [...nextActions, 'aggregate complete — now update_goal({status:"complete"})'];
plan.updatedAt = now;
- await writePlan(repoRoot, plan, scope);
const ledgerEntry = buildLedger(now, args, goal, qualityGate, codexGoal, aggregateCompletion);
- await appendLedger(repoRoot, ledgerEntry, scope);
+ const entries = [ledgerEntry];
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);
+ entries.push({ at: now, kind: "batch_closed", goalId: goal.id, message: closedBatch.batchId });
+ await commit(repoRoot, scope, { plan, entries });
return aggregateCompletion === undefined ? { plan, goal, ledgerEntry, nextActions, warnings } : { plan, goal, ledgerEntry, aggregateCompletion, nextActions, warnings };
});
}
@@ -1990,10 +2235,6 @@ function joinLines(lines) {
`);
}
-// 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();
@@ -2099,18 +2340,31 @@ function clearGoalBlockerFields2(goal) {
])
delete goal[key];
}
-async function createUlwLoopPlan(repoRoot, args, scope) {
+async function createUlwLoopPlan(repoRoot, args, scope, surface = "lazycodex") {
return withUlwLoopMutationLock(repoRoot, scope, async () => {
- if (!args.force && existsSync4(ulwLoopGoalsPath(repoRoot, scope))) {
- const existing = await readUlwLoopPlan(repoRoot, scope);
+ let existing;
+ if (planExists(repoRoot, scope)) {
+ try {
+ existing = await readUlwLoopPlan(repoRoot, scope);
+ } catch (error) {
+ if (!args.force)
+ throw error;
+ }
+ }
+ if (!args.force && existing !== undefined) {
if (isUlwLoopDone(existing))
- throw completedPlanExistsError(scope);
+ throw completedPlanExistsError(scope, surface);
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,
+ revision: existing?.revision ?? 0,
+ ledgerResetRevision: (existing?.revision ?? 0) + 1,
+ brief: args.brief.endsWith(`
+`) ? args.brief : `${args.brief}
+`,
evidenceLayoutVersion: 2,
createdAt: now,
updatedAt: now,
@@ -2125,21 +2379,23 @@ async function createUlwLoopPlan(repoRoot, args, scope) {
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);
+ await beforePlanMutation();
+ await commit(repoRoot, scope, {
+ plan,
+ entries: [{ at: now, kind: "plan_created", message: `${goals.length} goal(s) created` }]
+ });
return plan;
});
}
-function completedPlanExistsError(scope) {
+function completedPlanExistsError(scope, surface) {
return new UlwLoopError([
`Existing ulw-loop aggregate is already complete at ${ulwLoopGoalsRelativePath(scope)}.`,
- "Start a new run with `omo-agent-toolkit ulw-loop create-goals --session-id <new-id> ...` to isolate fresh state.",
- "Use --force only when you intentionally want to overwrite the completed evidence."
+ ...surface === "omo-senpi" ? [
+ "Start a new run under a fresh session id (a new senpi session) or call agentToolkit.createGoals({ brief, force: true }) to recreate."
+ ] : [
+ "Start a new run with `omo-agent-toolkit 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) {
@@ -2147,8 +2403,10 @@ async function addUlwLoopGoal(repoRoot, args, scope) {
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);
+ await commit(repoRoot, scope, {
+ plan,
+ entries: [{ at: now, kind: "goal_added", goalId: goal.id, status: goal.status, message: goal.title }]
+ });
return { plan, goal };
});
}
@@ -2161,17 +2419,18 @@ async function startNextUlwLoop(repoRoot, args = {}, scope) {
const existing = plan.goals.find((goal) => goal.status === "in_progress" && isScheduleEligible(goal));
if (existing)
return { plan, goal: existing, resumed: true };
+ const entries = [];
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, {
+ entries.push({
at: now,
kind: "goal_retried",
goalId: next.id,
status: "pending",
...next.failureReason ? { message: next.failureReason } : {}
- }, scope);
+ });
}
if (!next)
return { done: true, plan };
@@ -2182,8 +2441,14 @@ async function startNextUlwLoop(repoRoot, args = {}, scope) {
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);
+ entries.push({
+ at: now,
+ kind: "goal_started",
+ goalId: next.id,
+ status: next.status,
+ message: `Attempt ${next.attempt}`
+ });
+ await commit(repoRoot, scope, { plan, entries });
return { plan, goal: next, resumed: false };
});
}
@@ -2279,7 +2544,7 @@ function checkpointStatus(value) {
}
// components/ulw-loop/src/cli-subcommands.ts
-import { readFile as readFile5 } from "node:fs/promises";
+import { readFile as readFile4 } from "node:fs/promises";
// components/ulw-loop/src/cli-steering.ts
var SOURCES = ["user_prompt_submit", "finding", "cli"];
@@ -2649,9 +2914,7 @@ async function recordFinalReviewBlockers(repoRoot, args, scope) {
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);
+ await commit(repoRoot, scope, { plan, entries: ledgerEntries });
return {
plan,
blockedGoal: goal,
@@ -2664,31 +2927,31 @@ async function recordFinalReviewBlockers(repoRoot, args, scope) {
}
// components/ulw-loop/src/status-next-actions.ts
-function statusNextActions(plan) {
+function statusNextActions(plan, surface = "lazycodex") {
const actions = [];
const active = plan.goals.find((goal) => goal.id === plan.activeGoalId);
if (plan.goals.length === 0)
- actions.push(`No goals yet: bootstrap with \`${ULW_LOOP_CREATE_GOALS_COMMAND}\`.`);
+ actions.push(`No goals yet: bootstrap with \`${createGoalsAction(surface)}\`.`);
else if (active !== undefined)
- actions.push(...activeGoalActions(plan, active));
+ actions.push(...activeGoalActions(plan, active, surface));
for (const goal of plan.goals.filter((candidate) => candidate.status === "review_blocked"))
- actions.push(`${goal.id} is review_blocked: capture the reviewer verdict with \`omo-agent-toolkit ulw-loop record-review-blockers --goal-id ${goal.id} --title "<title>" --objective "<objective>" --evidence "<verdict>" --codex-goal-json '<get_goal json>'\`.`);
+ actions.push(surface === "omo-senpi" ? `${goal.id} is review_blocked: capture the reviewer verdict with \`agentToolkit.recordReviewBlockers({ goalId: "${goal.id}", title: "<title>", objective: "<objective>", evidence: "<verdict>" })\`.` : `${goal.id} is review_blocked: capture the reviewer verdict with \`omo-agent-toolkit ulw-loop record-review-blockers --goal-id ${goal.id} --title "<title>" --objective "<objective>" --evidence "<verdict>" --codex-goal-json '<get_goal json>'\`.`);
if (plan.evidenceLayoutVersion !== 2 || active === undefined)
actions.push("plan is evidence-layout v1; artifacts go under .omo/evidence/");
return actions;
}
-function activeGoalActions(plan, active) {
+function activeGoalActions(plan, active, surface) {
const unresolved = active.successCriteria.filter((criterion) => criterion.status !== "pass");
if (unresolved.length > 0)
return [
- `${active.id} has ${unresolved.length} unresolved criterion(s) (${unresolved.map((criterion) => criterion.id).join(", ")}): record proof with \`omo-agent-toolkit ulw-loop record-evidence --goal-id ${active.id} --criterion-id <id> --status pass --evidence "<observable proof>"\`.`
+ surface === "omo-senpi" ? `${active.id} has ${unresolved.length} unresolved criterion(s) (${unresolved.map((criterion) => criterion.id).join(", ")}): record proof with \`agentToolkit.recordEvidence({ goalId: "${active.id}", criterionId: "<id>", status: "pass", evidence: "<observable proof>" })\`.` : `${active.id} has ${unresolved.length} unresolved criterion(s) (${unresolved.map((criterion) => criterion.id).join(", ")}): record proof with \`omo-agent-toolkit ulw-loop record-evidence --goal-id ${active.id} --criterion-id <id> --status pass --evidence "<observable proof>"\`.`
];
if (hasAllCriteriaPass(active) && isFinalRunCompletionCandidate(plan, active))
return [
- `${active.id} passes every criterion and is the final story: update_goal complete, then checkpoint --print-template to build the final quality gate. Use status --json's currentAttemptDir for all quality-gate artifacts.`
+ surface === "omo-senpi" ? `${active.id} passes every criterion and is the final story: complete the driver goal, then call \`agentToolkit.checkpoint({ goalId: "${active.id}", printTemplate: true })\` to build the final quality gate. Use status().result.currentAttemptDir for all quality-gate artifacts.` : `${active.id} passes every criterion and is the final story: update_goal complete, then checkpoint --print-template to build the final quality gate. Use status --json's currentAttemptDir for all quality-gate artifacts.`
];
return [
- `${active.id} passes every criterion: close it with \`omo-agent-toolkit ulw-loop checkpoint --goal-id ${active.id} --status complete --evidence "<proof>" --codex-goal-json '<get_goal json>'\`. Put quality-gate artifacts under the currentAttemptDir shown by status --json.`
+ surface === "omo-senpi" ? `${active.id} passes every criterion: close it with \`agentToolkit.checkpoint({ goalId: "${active.id}", status: "complete", evidence: "<proof>" })\`. Put quality-gate artifacts under status().result.currentAttemptDir.` : `${active.id} passes every criterion: close it with \`omo-agent-toolkit ulw-loop checkpoint --goal-id ${active.id} --status complete --evidence "<proof>" --codex-goal-json '<get_goal json>'\`. Put quality-gate artifacts under the currentAttemptDir shown by status --json.`
];
}
@@ -3020,11 +3283,10 @@ async function steerUlwLoop(repoRoot, proposal, scope) {
}
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);
+ const entries = [ledgerEntry(proposal, finalAudit, at)];
if (batchEntry !== null)
- await appendLedger(repoRoot, batchEntry, scope);
+ entries.push(batchEntry);
+ await commit(repoRoot, scope, { plan: next, entries });
return { plan: next, accepted, audit: finalAudit, rejectedReasons: audit.invariant.rejectedReasons, deduped: false };
});
}
@@ -3071,8 +3333,12 @@ function validateCodexGoalJson(raw) {
function validateContext(context) {
if (!context.cwd.trim())
throw new UlwLoopError("cwd is required.", "ULW_LOOP_CWD_REQUIRED");
- if (!context.sessionId.trim())
+ const sessionId = context.sessionId.trim();
+ if (!sessionId)
throw new UlwLoopError("ULW_LOOP_SESSION_ID_REQUIRED: sessionId is required.", "ULW_LOOP_SESSION_ID_REQUIRED");
+ const normalizedSessionId = normalizeUlwLoopSessionId(sessionId);
+ if (normalizedSessionId === null || /(?:^|[\\/])\.\.(?:[\\/]|$)/.test(sessionId))
+ throw new UlwLoopError("ULW_LOOP_SESSION_ID_INVALID: sessionId normalizes to null.", "ULW_LOOP_SESSION_ID_INVALID");
if (context.surface !== "omo-senpi" && context.surface !== "lazycodex")
throw new UlwLoopError("surface must be omo-senpi or lazycodex.", "ULW_LOOP_SURFACE_INVALID");
}
@@ -3115,6 +3381,8 @@ function createAgentToolkit(context, deps = {}) {
const nextActions = typeof result === "object" && result !== null ? nextActionsFrom(result) : [];
return await notify(operation, { ok: true, operation, result, nextActions });
} catch (error) {
+ if (error instanceof UlwLoopError && error.code === "ULW_LOOP_PLAN_MISSING" && context.surface === "omo-senpi")
+ return notify(operation, failure(operation, planMissingError(ulwLoopGoalsRelativePath(scope), listUlwLoopSessionIds(context.cwd), context.surface)));
const response = caught(operation, error instanceof Error ? error : new Error("ULW_LOOP_ERROR"));
return notify(operation, response);
}
@@ -3149,14 +3417,14 @@ function createAgentToolkit(context, deps = {}) {
}
},
help: () => invoke("help", async () => ULW_LOOP_MANIFEST),
- createGoals: (args) => invoke("create-goals", () => createUlwLoopPlan(context.cwd, args, scope)),
+ createGoals: (args) => invoke("create-goals", () => createUlwLoopPlan(context.cwd, args, scope, context.surface)),
status: () => invoke("status", async () => {
const plan = await readUlwLoopPlan(context.cwd, scope);
const active = plan.goals.find((goal) => goal.id === plan.activeGoalId);
return {
plan,
summary: summarizeUlwLoopPlan(plan),
- nextActions: statusNextActions(plan),
+ nextActions: statusNextActions(plan, context.surface),
...active === undefined || plan.evidenceLayoutVersion !== 2 ? {} : { currentAttemptDir: ulwLoopAttemptEvidenceDir(active.id, active.attempt, scope) }
};
}),
@@ -3184,7 +3452,7 @@ async function steerUlwLoopBatch(repoRoot, proposals, scope) {
const failed = prepared.results.find((item) => !item.accepted);
if (failed !== undefined) {
const entry = rejectedLedgerEntry(prepared.results);
- await appendLedger(repoRoot, entry, scope);
+ await commit(repoRoot, scope, { plan, entries: [entry] });
return rejected(plan, prepared.results, failed.rejectedReasons);
}
let next = plan;
@@ -3193,10 +3461,9 @@ async function steerUlwLoopBatch(repoRoot, proposals, scope) {
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);
+ await commit(repoRoot, scope, { plan: next, entries: batchEntry === null ? entries : [...entries, batchEntry] });
}
return { plan: next, accepted: true, results: prepared.results, rejectedReasons: [] };
});
@@ -3260,7 +3527,7 @@ function ledgerEntry2(proposal, audit, at) {
// 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 readFile5(briefFile, "utf8")) ?? (hasFlag(argv, "--from-stdin") ? await readStdin() : undefined) ?? positionalText(argv);
+ const brief = readValue(argv, "--brief") ?? (briefFile === undefined ? undefined : await readFile4(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");
}
@@ -3528,10 +3795,10 @@ function commandScope(repoRoot, argv) {
}
// components/ulw-loop/src/ultrawork-directive.ts
-import { readFileSync as readFileSync4 } from "node:fs";
+import { readFileSync as readFileSync5 } from "node:fs";
// components/ulw-loop/src/ultrawork-skill-pointer.ts
-import { existsSync as existsSync5, readFileSync as readFileSync3 } from "node:fs";
+import { existsSync as existsSync5, readFileSync as readFileSync4 } from "node:fs";
import { fileURLToPath as fileURLToPath2 } from "node:url";
var ULTRAWORK_SKILL_POINTER_TEMPLATE = `<ultrawork-mode>
ULTRAWORK MODE IS ACTIVE FOR THIS TASK.
@@ -3563,7 +3830,7 @@ Do not start the requested work until all three steps are complete.
`;
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 = readFileSync3(new URL("../directive.md", import.meta.url), "utf8");
+var ULTRAWORK_DIRECTIVE = readFileSync4(new URL("../directive.md", import.meta.url), "utf8");
function resolveUltraworkSkillFilePath() {
return fileURLToPath2(ULTRAWORK_SKILL_FILE_URL);
}
@@ -3626,7 +3893,7 @@ function hasUltraworkDirectiveAlreadyInTranscript(transcriptPath) {
return false;
}
function readTranscriptTail(transcriptPath) {
- const rawTranscript = readFileSync4(transcriptPath);
+ const rawTranscript = readFileSync5(transcriptPath);
return rawTranscript.subarray(Math.max(0, rawTranscript.byteLength - TRANSCRIPT_SEARCH_BYTES)).toString("utf8");
}
function isUltraworkPrompt(prompt) {
@@ -3819,9 +4086,64 @@ function readAll(stdin) {
}
// components/ulw-loop/src/spawn-guard.ts
+import { mkdirSync as mkdirSync3 } from "node:fs";
+import { join as join7 } from "node:path";
+
+// components/ulw-loop/src/spawn-budget-io.ts
import { randomBytes } from "node:crypto";
-import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync5, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
-import { dirname as dirname3, join as join3 } from "node:path";
+import { existsSync as existsSync6, readFileSync as readFileSync6, renameSync as renameSync2, statSync as statSync3, writeFileSync as writeFileSync2 } from "node:fs";
+import { dirname as dirname3, join as join6 } from "node:path";
+function readAdmissionBreaker(sessionId) {
+ const dataDir = process.env["PLUGIN_DATA"];
+ if (typeof dataDir !== "string")
+ return null;
+ try {
+ const value = JSON.parse(readFileSync6(join6(dataDir, "spawn-breaker", `${sessionId}.json`), "utf8"));
+ return typeof value === "object" && value !== null && "reason" in value && typeof value.reason === "string" ? value.reason : "capacity limit";
+ } catch {
+ return null;
+ }
+}
+function atomicWriteJson(targetPath, data) {
+ const tmp = join6(dirname3(targetPath), `.tmp-${randomBytes(6).toString("hex")}`);
+ writeFileSync2(tmp, JSON.stringify(data));
+ renameSync2(tmp, targetPath);
+}
+function isNonEmptyFile(path) {
+ try {
+ return existsSync6(path) && statSync3(path).size > 0;
+ } catch (error) {
+ if (error instanceof Error)
+ return false;
+ throw error;
+ }
+}
+function readCount(counterPath) {
+ try {
+ const parsed = JSON.parse(readFileSync6(counterPath, "utf8"));
+ return typeof parsed === "object" && parsed !== null && "count" in parsed && typeof parsed.count === "number" && parsed.count >= 0 ? parsed.count : 0;
+ } catch (error) {
+ if (error instanceof Error)
+ return 0;
+ throw error;
+ }
+}
+function readCounts(counterPath) {
+ try {
+ const parsed = JSON.parse(readFileSync6(counterPath, "utf8"));
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
+ return {};
+ const counts = {};
+ for (const [key, value] of Object.entries(parsed))
+ if (typeof value === "number" && value >= 0)
+ counts[key] = value;
+ return counts;
+ } catch (error) {
+ if (error instanceof Error)
+ return {};
+ throw error;
+ }
+}
// components/ulw-loop/src/spawn-role-guard.ts
var LAZYCODEX_SPAWN_ROLES = new Set([
@@ -3879,7 +4201,7 @@ function applySpawnBudgetGuards(payload, options = {}) {
return deny(`Subagent admission failed earlier in this session (${breaker}). Do not spawn more workers or reviewers; report the capacity block and wait for the user.`);
const scope = { sessionId: payload.session_id };
const stateDir = ulwLoopDir(payload.cwd, scope);
- const plan = readPlan(join3(stateDir, "goals.json"));
+ const plan = readPlan(payload.cwd, payload.session_id);
if (plan === null)
return "";
const lockOptions = options.lockTimeoutMs === undefined ? {} : { timeoutMs: options.lockTimeoutMs };
@@ -3918,10 +4240,10 @@ async function runSpawnAdmissionRecorderCli(stdin, stdout) {
const dataDir = process.env["PLUGIN_DATA"];
if (typeof dataDir !== "string" || typeof payload["session_id"] !== "string")
return;
- const markerDir = join3(dataDir, "spawn-breaker");
+ const markerDir = join7(dataDir, "spawn-breaker");
try {
- mkdirSync2(markerDir, { recursive: true });
- atomicWriteJson(join3(markerDir, `${payload["session_id"]}.json`), {
+ mkdirSync3(markerDir, { recursive: true });
+ atomicWriteJson(join7(markerDir, `${payload["session_id"]}.json`), {
reason: response,
at: new Date().toISOString()
});
@@ -3950,7 +4272,7 @@ async function runSpawnGuardCli(stdin, stdout) {
}
}
function peekFanOutBudget(stateDir) {
- const counterPath = join3(stateDir, "spawn-count.json");
+ const counterPath = join7(stateDir, "spawn-count.json");
const count = readCount(counterPath) + 1;
const limit = fanOutLimit();
if (count <= limit)
@@ -3958,7 +4280,7 @@ function peekFanOutBudget(stateDir) {
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 consumeFanOutBudget(stateDir) {
- const counterPath = join3(stateDir, "spawn-count.json");
+ const counterPath = join7(stateDir, "spawn-count.json");
const count = readCount(counterPath) + 1;
atomicWriteJson(counterPath, { count });
const limit = fanOutLimit();
@@ -3973,7 +4295,7 @@ function consumeReviewSpawnBudget(payload, plan, stateDir) {
const goal = plan.goals.find((candidate) => candidate.id === plan.activeGoalId) ?? plan.goals.find((candidate) => isFinalRunCompletionCandidate(plan, candidate));
if (goal === undefined)
return null;
- const counterPath = join3(stateDir, "review-spawn-counts.json");
+ const counterPath = join7(stateDir, "review-spawn-counts.json");
const limit = reviewSpawnLimit();
const counts = readCounts(counterPath);
const key = `${agentType}:${goal.id}:a${goal.attempt}`;
@@ -3998,13 +4320,13 @@ function missingGateArtifact(payload, plan) {
const attemptDir = ulwLoopAttemptEvidenceDir(goal.id, goal.attempt, scope);
for (const name of requiredArtifacts) {
const relative = `${attemptDir}/${name}`;
- if (!isNonEmptyFile(join3(payload.cwd, relative)))
+ if (!isNonEmptyFile(join7(payload.cwd, relative)))
return relative;
}
return null;
}
const manualQa = `.omo/evidence/${goal.id}-manual-qa.md`;
- return isNonEmptyFile(join3(payload.cwd, manualQa)) ? null : manualQa;
+ return isNonEmptyFile(join7(payload.cwd, manualQa)) ? null : manualQa;
}
function isGateReviewerSpawn(toolInput) {
const agentType = reviewAgentType(toolInput);
@@ -4051,11 +4373,6 @@ function activeSurfaceReviewerAlias(reviewer) {
}
return reviewer;
}
-function atomicWriteJson(targetPath, data) {
- const tmp = join3(dirname3(targetPath), `.tmp-${randomBytes(6).toString("hex")}`);
- writeFileSync(tmp, JSON.stringify(data));
- renameSync(tmp, targetPath);
-}
function deny(reason) {
return `${JSON.stringify({
hookSpecificOutput: {
@@ -4067,17 +4384,6 @@ function deny(reason) {
})}
`;
}
-function readAdmissionBreaker(sessionId) {
- const dataDir = process.env["PLUGIN_DATA"];
- if (typeof dataDir !== "string")
- return null;
- try {
- const value = JSON.parse(readFileSync5(join3(dataDir, "spawn-breaker", `${sessionId}.json`), "utf8"));
- return typeof value.reason === "string" ? value.reason : "capacity limit";
- } catch {
- return null;
- }
-}
function fanOutLimit() {
const raw = process.env["OMO_SPAWN_FANOUT_LIMIT"];
if (raw === undefined)
@@ -4092,45 +4398,9 @@ function reviewSpawnLimit() {
const parsed = Number.parseInt(raw, 10);
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_REVIEW_SPAWN_LIMIT;
}
-function isNonEmptyFile(path) {
- try {
- return existsSync6(path) && statSync3(path).size > 0;
- } catch (error) {
- if (error instanceof Error)
- return false;
- throw error;
- }
-}
-function readCount(counterPath) {
- try {
- const parsed = JSON.parse(readFileSync5(counterPath, "utf8"));
- return typeof parsed["count"] === "number" && parsed["count"] >= 0 ? parsed["count"] : 0;
- } catch (error) {
- if (error instanceof Error)
- return 0;
- throw error;
- }
-}
-function readCounts(counterPath) {
- try {
- const parsed = JSON.parse(readFileSync5(counterPath, "utf8"));
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
- return {};
- const counts = {};
- for (const [key, value] of Object.entries(parsed)) {
- if (typeof value === "number" && value >= 0)
- counts[key] = value;
- }
- return counts;
- } catch (error) {
- if (error instanceof Error)
- return {};
- throw error;
- }
-}
-function readPlan(goalsPath) {
+function readPlan(repoRoot, sessionId) {
try {
- return JSON.parse(readFileSync5(goalsPath, "utf8"));
+ return readUlwLoopPlanSync(repoRoot, { sessionId });
} catch (error) {
if (error instanceof Error)
return null;
@@ -4139,8 +4409,8 @@ function readPlan(goalsPath) {
}
// components/ulw-loop/src/stop-resume-hook.ts
-import { existsSync as existsSync7, readFileSync as readFileSync6, writeFileSync as writeFileSync2 } from "node:fs";
-import { isAbsolute as isAbsolute2, join as join4, resolve as resolve4, sep as sep2 } from "node:path";
+import { existsSync as existsSync7, readFileSync as readFileSync7, writeFileSync as writeFileSync3 } from "node:fs";
+import { isAbsolute as isAbsolute2, join as join8, resolve as resolve4, sep as sep2 } from "node:path";
var RESUME_CAP = 2;
var CONTEXT_PRESSURE_MARKERS2 = [
"context compacted",
@@ -4161,7 +4431,7 @@ function runStopResumeHook(input) {
return "";
const scope = { sessionId: payload.session_id };
const stateDir = ulwLoopDir(payload.cwd, scope);
- const plan = readPlan2(join4(stateDir, "goals.json"));
+ const plan = readPlan2(payload.cwd, payload.session_id);
if (plan === null || plan.aggregateCompletion?.status === "complete")
return "";
const goal = resumableGoal(plan);
@@ -4207,7 +4477,7 @@ function consumeResumeBudgetLocked(lockPath, stateDir, goalId) {
}
}
function consumeResumeBudget(stateDir, goalId) {
- const ledgerLineCount = countLedgerLines(join4(stateDir, "ledger.jsonl"));
+ const ledgerLineCount = readLedgerAt(stateDir).length;
const counterPath = resolve4(stateDir, `auto-resume-${goalId}.json`);
const stuckPath = resolve4(stateDir, `auto-resume-${goalId}.stuck`);
if (!isInsideDir(stateDir, counterPath) || !isInsideDir(stateDir, stuckPath))
@@ -4215,11 +4485,11 @@ function consumeResumeBudget(stateDir, goalId) {
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
+ writeFileSync3(stuckPath, `no ledger progress after ${count} resumes
`);
return false;
}
- writeFileSync2(counterPath, JSON.stringify({ count: count + 1, ledgerLineCount }));
+ writeFileSync3(counterPath, JSON.stringify({ count: count + 1, ledgerLineCount }));
return true;
}
function isInsideDir(dir, candidate) {
@@ -4238,30 +4508,20 @@ function renderResumeDirective(plan, goal, sessionId) {
].join(`
`);
}
-function readPlan2(goalsPath) {
+function readPlan2(repoRoot, sessionId) {
try {
- return JSON.parse(readFileSync6(goalsPath, "utf8"));
+ return readUlwLoopPlanSync(repoRoot, { sessionId });
} catch (error) {
if (error instanceof Error)
return null;
throw error;
}
}
-function countLedgerLines(ledgerPath) {
- try {
- return readFileSync6(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(readFileSync6(counterPath, "utf8"));
+ const parsed = JSON.parse(readFileSync7(counterPath, "utf8"));
if (typeof parsed["count"] !== "number" || typeof parsed["ledgerLineCount"] !== "number")
return null;
return { count: parsed["count"], ledgerLineCount: parsed["ledgerLineCount"] };
@@ -4273,7 +4533,7 @@ function readCounter(counterPath) {
}
function boulderContinuationWillFire(cwd, sessionId) {
try {
- const raw = JSON.parse(readFileSync6(join4(cwd, ".omo", "boulder.json"), "utf8"));
+ const raw = JSON.parse(readFileSync7(join8(cwd, ".omo", "boulder.json"), "utf8"));
const works = raw["works"];
const entries = typeof works === "object" && works !== null ? Object.values(works) : [raw];
return entries.some((work) => {
@@ -4292,7 +4552,7 @@ function boulderContinuationWillFire(cwd, sessionId) {
}
function transcriptShowsContextPressure(transcriptPath) {
try {
- const transcript = readFileSync6(transcriptPath, "utf8").toLowerCase();
+ const transcript = readFileSync7(transcriptPath, "utf8").toLowerCase();
return CONTEXT_PRESSURE_MARKERS2.some((marker) => transcript.includes(marker));
} catch (error) {
if (error instanceof Error)
@@ -4304,12 +4564,12 @@ function boulderPlanHasChecklist(cwd, entry) {
const activePlan = entry["active_plan"];
if (typeof activePlan !== "string" || activePlan.trim().length === 0)
return false;
- const planPath = isAbsolute2(activePlan) ? activePlan : join4(cwd, activePlan);
+ const planPath = isAbsolute2(activePlan) ? activePlan : join8(cwd, activePlan);
const worktree = entry["worktree_path"];
- const candidates = typeof worktree === "string" && worktree.trim().length > 0 && !isAbsolute2(activePlan) ? [join4(isAbsolute2(worktree) ? worktree : join4(cwd, worktree), activePlan), planPath] : [planPath];
+ const candidates = typeof worktree === "string" && worktree.trim().length > 0 && !isAbsolute2(activePlan) ? [join8(isAbsolute2(worktree) ? worktree : join8(cwd, worktree), activePlan), planPath] : [planPath];
for (const candidate of candidates) {
try {
- return readFileSync6(candidate, "utf8").split(/\r?\n/).some((line) => line.startsWith("- [ ] ") || line.startsWith("- [x] ") || line.startsWith("- [X] "));
+ return readFileSync7(candidate, "utf8").split(/\r?\n/).some((line) => line.startsWith("- [ ] ") || line.startsWith("- [x] ") || line.startsWith("- [X] "));
} catch (error) {
if (!(error instanceof Error))
throw error;
diff --git a/plugins/omo/components/ulw-loop/dist/domain-types.d.ts b/plugins/omo/components/ulw-loop/dist/domain-types.d.ts
index 0ec876a6..899a4c91 100644
--- a/plugins/omo/components/ulw-loop/dist/domain-types.d.ts
+++ b/plugins/omo/components/ulw-loop/dist/domain-types.d.ts
@@ -50,6 +50,9 @@ export interface UlwLoopValidationBatch {
}
export interface UlwLoopPlan {
version: 1;
+ revision?: number;
+ brief?: string;
+ ledgerResetRevision?: number;
evidenceLayoutVersion?: 2;
createdAt: string;
updatedAt: string;
@@ -136,6 +139,8 @@ export interface UlwLoopQualityGateSenpi extends UlwLoopQualityGateCommon {
}
export type UlwLoopQualityGate = UlwLoopQualityGateLazycodex | UlwLoopQualityGateSenpi;
export interface UlwLoopLedgerEntry {
+ revision?: number;
+ id?: string;
at: string;
kind: UlwLoopLedgerEventKind;
goalId?: string;
diff --git a/plugins/omo/components/ulw-loop/dist/evidence.js b/plugins/omo/components/ulw-loop/dist/evidence.js
index b771c2bc..1f892cbe 100644
--- a/plugins/omo/components/ulw-loop/dist/evidence.js
+++ b/plugins/omo/components/ulw-loop/dist/evidence.js
@@ -1,5 +1,6 @@
import { essentialCriteriaOf, hasAllCriteriaPass, hasEssentialCriteriaPass } from "./goal-status.js";
-import { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";
+import { commit } from "./plan-commit.js";
+import { readUlwLoopPlan, withUlwLoopMutationLock } from "./plan-io.js";
import { iso, UlwLoopError } from "./types.js";
function ulwLoopFail(message, code, details) {
throw new UlwLoopError(message, code, { details });
@@ -48,7 +49,6 @@ export async function recordEvidence(repoRoot, args, scope) {
criterion.notes = args.notes;
goal.updatedAt = capturedAt;
plan.updatedAt = capturedAt;
- await writePlan(repoRoot, plan, scope);
const ledgerEntry = {
at: capturedAt,
kind,
@@ -60,7 +60,7 @@ export async function recordEvidence(repoRoot, args, scope) {
before: { status: prevStatus },
after: { goalId: goal.id, criterionId: criterion.id, status: args.status, evidence, capturedAt, prevStatus },
};
- await appendLedger(repoRoot, ledgerEntry, scope);
+ await commit(repoRoot, scope, { plan, entries: [ledgerEntry] });
return { plan, goal, criterion, ledgerEntry };
});
}
@@ -83,15 +83,19 @@ export async function markCriteriaPendingResetForGoal(repoRoot, goalId, scope) {
}
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);
+ await commit(repoRoot, scope, {
+ plan,
+ entries: [
+ {
+ at: now,
+ kind: "criteria_revised",
+ goalId,
+ message: `Reset ${goal.successCriteria.length} criteria to pending.`,
+ before,
+ after: { resetCount: goal.successCriteria.length },
+ },
+ ],
+ });
return { plan, resetCount: goal.successCriteria.length };
});
}
diff --git a/plugins/omo/components/ulw-loop/dist/ledger.d.ts b/plugins/omo/components/ulw-loop/dist/ledger.d.ts
new file mode 100644
index 00000000..35187a03
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/dist/ledger.d.ts
@@ -0,0 +1,4 @@
+import { type UlwLoopScope } from "./paths.js";
+import type { UlwLoopLedgerEntry } from "./types.js";
+export declare function readLedgerAt(dir: string): UlwLoopLedgerEntry[];
+export declare function readLedger(repoRoot: string, scope?: UlwLoopScope): UlwLoopLedgerEntry[];
diff --git a/plugins/omo/components/ulw-loop/dist/ledger.js b/plugins/omo/components/ulw-loop/dist/ledger.js
new file mode 100644
index 00000000..4ad89ff2
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/dist/ledger.js
@@ -0,0 +1,34 @@
+import { join } from "node:path";
+import { ulwLoopDir } from "./paths.js";
+import { readOptional, readRecords, reconcilePlan } from "./plan-log.js";
+export function readLedgerAt(dir) {
+ const entries = new Map();
+ const lines = (readOptional(join(dir, "ledger.jsonl")) ?? "").split(/\r?\n/);
+ for (const [index, line] of lines.entries()) {
+ if (line.trim().length === 0)
+ continue;
+ try {
+ const entry = JSON.parse(line);
+ entry.revision ??= 0;
+ entry.id ??= `legacy-${index + 1}`;
+ entries.set(entry.id, entry);
+ }
+ catch (error) {
+ if (!(error instanceof SyntaxError))
+ throw error;
+ }
+ }
+ for (const record of readRecords(dir))
+ for (const [seq, entry] of record.ledger.entries()) {
+ const id = entry.id ?? `${record.revision}-${seq}`;
+ entries.set(id, { ...entry, revision: record.revision, id });
+ }
+ const reset = reconcilePlan(dir)?.ledgerResetRevision ?? 0;
+ const sequence = (entry) => Number(entry.id?.split("-").at(-1) ?? 0);
+ return [...entries.values()]
+ .filter((entry) => (entry.revision ?? 0) >= reset)
+ .sort((a, b) => (a.revision ?? 0) - (b.revision ?? 0) || sequence(a) - sequence(b));
+}
+export function readLedger(repoRoot, scope) {
+ return readLedgerAt(ulwLoopDir(repoRoot, scope));
+}
diff --git a/plugins/omo/components/ulw-loop/dist/plan-commit.d.ts b/plugins/omo/components/ulw-loop/dist/plan-commit.d.ts
new file mode 100644
index 00000000..39f152b2
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/dist/plan-commit.d.ts
@@ -0,0 +1,19 @@
+import { type UlwLoopScope } from "./paths.js";
+import { type UlwLoopLedgerEntry, type UlwLoopPlan } from "./types.js";
+interface CommitHooks {
+ readonly beforeMutation?: () => void | Promise<void>;
+ readonly beforeCommit?: () => void | Promise<void>;
+ readonly afterCommit?: () => void | Promise<void>;
+ readonly link?: (source: string, destination: string) => void;
+ readonly writeView?: (path: string, content: string) => Promise<void>;
+}
+export declare function withCommitHooks<T>(value: CommitHooks, fn: () => Promise<T>): Promise<T>;
+export declare function beforePlanMutation(): Promise<void>;
+export declare function writeViewFile(path: string, content: string): Promise<void>;
+export declare function commit(repoRoot: string, scope: UlwLoopScope | undefined, mutation: {
+ readonly plan: UlwLoopPlan;
+ readonly entries: readonly UlwLoopLedgerEntry[];
+}): Promise<void>;
+export declare function materializeSync(dir: string): void;
+export declare function materialize(dir: string): Promise<void>;
+export {};
diff --git a/plugins/omo/components/ulw-loop/dist/plan-commit.js b/plugins/omo/components/ulw-loop/dist/plan-commit.js
new file mode 100644
index 00000000..f882df2a
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/dist/plan-commit.js
@@ -0,0 +1,107 @@
+import { AsyncLocalStorage } from "node:async_hooks";
+import { randomUUID } from "node:crypto";
+import { linkSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { rename, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { readLedgerAt } from "./ledger.js";
+import { ulwLoopDir, ulwLoopStateLockPath } from "./paths.js";
+import { assertStateLockOwned, migrationEntries } from "./plan-io.js";
+import { hasCode, readOptional, readRecords, reconcilePlan } from "./plan-log.js";
+import { UlwLoopError } from "./types.js";
+const hooks = new AsyncLocalStorage();
+export function withCommitHooks(value, fn) {
+ return hooks.run(value, fn);
+}
+export async function beforePlanMutation() {
+ await hooks.getStore()?.beforeMutation?.();
+}
+export async function writeViewFile(path, content) {
+ await (hooks.getStore()?.writeView ?? writeFile)(path, content);
+}
+// link is the sole commit point; no copy fallback (Node copyFile is not atomic).
+// A resumed zombie can publish first, but never overwrite an existing revision.
+// Logical audit order is (revision, sequence), not materialization completion time.
+export async function commit(repoRoot, scope, mutation) {
+ const { plan } = mutation;
+ const dir = ulwLoopDir(repoRoot, scope);
+ assertStateLockOwned(ulwLoopStateLockPath(repoRoot, scope));
+ await hooks.getStore()?.beforeCommit?.();
+ const next = (plan.revision ?? 0) + 1;
+ const brief = plan.brief ?? readOptional(join(dir, "brief.md")) ?? "";
+ const entries = [...migrationEntries(plan), ...mutation.entries].map((entry, seq) => ({
+ ...entry,
+ revision: next,
+ id: `${next}-${seq}`,
+ }));
+ const record = {
+ version: 1,
+ revision: next,
+ plan: { ...plan, revision: next, brief },
+ ledger: entries,
+ };
+ mkdirSync(join(dir, "revisions"), { recursive: true });
+ mkdirSync(join(dir, "tmp"), { recursive: true });
+ const temp = join(dir, "tmp", `${process.pid}-${randomUUID()}.json`);
+ try {
+ writeFileSync(temp, `${JSON.stringify(record)}\n`, { flag: "wx" });
+ try {
+ (hooks.getStore()?.link ?? linkSync)(temp, join(dir, "revisions", `${String(next).padStart(8, "0")}.json`));
+ }
+ catch (error) {
+ if (hasCode(error, "EEXIST"))
+ throw new UlwLoopError("Another writer published the read revision.", "ULW_LOOP_PUBLISH_CONFLICT", {
+ cause: error,
+ });
+ if (["EPERM", "ENOTSUP", "EXDEV"].some((code) => hasCode(error, code)))
+ throw new UlwLoopError("Immutable ulw-loop publication requires atomic hard links.", "ULW_LOOP_PUBLISH_UNSUPPORTED_FS", { cause: error });
+ throw error;
+ }
+ }
+ finally {
+ rmSync(temp, { force: true });
+ }
+ plan.revision = next;
+ plan.brief = brief;
+ for (const [index, entry] of mutation.entries.entries())
+ Object.assign(entry, entries[index + entries.length - mutation.entries.length]);
+ await hooks.getStore()?.afterCommit?.();
+ await materialize(dir);
+}
+function viewContents(dir) {
+ const plan = reconcilePlan(dir);
+ if (plan === undefined || readRecords(dir).length === 0)
+ return [];
+ const ledger = readLedgerAt(dir);
+ const views = [
+ ["goals.json", `${JSON.stringify(plan, null, 2)}\n`],
+ ["ledger.jsonl", ledger.length === 0 ? "" : `${ledger.map((entry) => JSON.stringify(entry)).join("\n")}\n`],
+ ["brief.md", plan.brief ?? readOptional(join(dir, "brief.md")) ?? ""],
+ ];
+ return views.filter(([name, content]) => readOptional(join(dir, name)) !== content);
+}
+export function materializeSync(dir) {
+ for (const [name, content] of viewContents(dir)) {
+ mkdirSync(join(dir, "tmp"), { recursive: true });
+ const temp = join(dir, "tmp", `${process.pid}-${randomUUID()}-${name}`);
+ try {
+ writeFileSync(temp, content, { flag: "wx" });
+ renameSync(temp, join(dir, name));
+ }
+ finally {
+ rmSync(temp, { force: true });
+ }
+ }
+}
+export async function materialize(dir) {
+ for (const [name, content] of viewContents(dir)) {
+ mkdirSync(join(dir, "tmp"), { recursive: true });
+ const temp = join(dir, "tmp", `${process.pid}-${randomUUID()}-${name}`);
+ try {
+ await writeViewFile(temp, content);
+ await rename(temp, join(dir, name));
+ }
+ finally {
+ rmSync(temp, { force: true });
+ }
+ }
+}
diff --git a/plugins/omo/components/ulw-loop/dist/plan-crud.d.ts b/plugins/omo/components/ulw-loop/dist/plan-crud.d.ts
index f6d9861b..25644414 100644
--- a/plugins/omo/components/ulw-loop/dist/plan-crud.d.ts
+++ b/plugins/omo/components/ulw-loop/dist/plan-crud.d.ts
@@ -1,4 +1,5 @@
import { type UlwLoopScope } from "./paths.js";
+import type { UlwLoopToolkitSurface } from "./surface.js";
import type { UlwLoopCodexGoalMode, UlwLoopItem, UlwLoopPlan } from "./types.js";
export { deriveGoalCandidates, seedDefaultSuccessCriteria } from "./plan-goal-factory.js";
export type UlwLoopPlanSummary = {
@@ -24,7 +25,7 @@ export declare function createUlwLoopPlan(repoRoot: string, args: {
codexGoalMode?: UlwLoopCodexGoalMode;
force?: boolean;
validationBatchesJson?: string;
-}, scope?: UlwLoopScope): Promise<UlwLoopPlan>;
+}, scope?: UlwLoopScope, surface?: UlwLoopToolkitSurface): Promise<UlwLoopPlan>;
export declare function addUlwLoopGoal(repoRoot: string, args: {
title: string;
objective: string;
diff --git a/plugins/omo/components/ulw-loop/dist/plan-crud.js b/plugins/omo/components/ulw-loop/dist/plan-crud.js
index 4d985453..e2435d39 100644
--- a/plugins/omo/components/ulw-loop/dist/plan-crud.js
+++ b/plugins/omo/components/ulw-loop/dist/plan-crud.js
@@ -1,9 +1,8 @@
-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 { ulwLoopBriefRelativePath, ulwLoopGoalsRelativePath, ulwLoopLedgerRelativePath, } from "./paths.js";
+import { beforePlanMutation, commit } from "./plan-commit.js";
import { appendGoalToPlan, deriveGoalCandidates, makeGoal } from "./plan-goal-factory.js";
-import { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";
+import { planExists, readUlwLoopPlan, withUlwLoopMutationLock } from "./plan-io.js";
import { iso, UlwLoopError } from "./types.js";
import { parseValidationBatches } from "./validation-batch.js";
export { deriveGoalCandidates, seedDefaultSuccessCriteria } from "./plan-goal-factory.js";
@@ -22,18 +21,30 @@ function clearGoalBlockerFields(goal) {
])
delete goal[key];
}
-export async function createUlwLoopPlan(repoRoot, args, scope) {
+export async function createUlwLoopPlan(repoRoot, args, scope, surface = "lazycodex") {
return withUlwLoopMutationLock(repoRoot, scope, async () => {
- if (!args.force && existsSync(ulwLoopGoalsPath(repoRoot, scope))) {
- const existing = await readUlwLoopPlan(repoRoot, scope);
+ let existing;
+ if (planExists(repoRoot, scope)) {
+ try {
+ existing = await readUlwLoopPlan(repoRoot, scope);
+ }
+ catch (error) {
+ if (!args.force)
+ throw error;
+ }
+ }
+ if (!args.force && existing !== undefined) {
if (isUlwLoopDone(existing))
- throw completedPlanExistsError(scope);
+ throw completedPlanExistsError(scope, surface);
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,
+ revision: existing?.revision ?? 0,
+ ledgerResetRevision: (existing?.revision ?? 0) + 1,
+ brief: args.brief.endsWith("\n") ? args.brief : `${args.brief}\n`,
evidenceLayoutVersion: 2,
createdAt: now,
updatedAt: now,
@@ -48,19 +59,25 @@ export async function createUlwLoopPlan(repoRoot, args, scope) {
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);
+ await beforePlanMutation();
+ await commit(repoRoot, scope, {
+ plan,
+ entries: [{ at: now, kind: "plan_created", message: `${goals.length} goal(s) created` }],
+ });
return plan;
});
}
-function completedPlanExistsError(scope) {
+function completedPlanExistsError(scope, surface) {
return new UlwLoopError([
`Existing ulw-loop aggregate is already complete at ${ulwLoopGoalsRelativePath(scope)}.`,
- "Start a new run with `omo-agent-toolkit ulw-loop create-goals --session-id <new-id> ...` to isolate fresh state.",
- "Use --force only when you intentionally want to overwrite the completed evidence.",
+ ...(surface === "omo-senpi"
+ ? [
+ "Start a new run under a fresh session id (a new senpi session) or call agentToolkit.createGoals({ brief, force: true }) to recreate.",
+ ]
+ : [
+ "Start a new run with `omo-agent-toolkit 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) {
@@ -68,8 +85,10 @@ export async function addUlwLoopGoal(repoRoot, args, scope) {
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);
+ await commit(repoRoot, scope, {
+ plan,
+ entries: [{ at: now, kind: "goal_added", goalId: goal.id, status: goal.status, message: goal.title }],
+ });
return { plan, goal };
});
}
@@ -82,17 +101,18 @@ export async function startNextUlwLoop(repoRoot, args = {}, scope) {
const existing = plan.goals.find((goal) => goal.status === "in_progress" && isScheduleEligible(goal));
if (existing)
return { plan, goal: existing, resumed: true };
+ const entries = [];
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, {
+ entries.push({
at: now,
kind: "goal_retried",
goalId: next.id,
status: "pending",
...(next.failureReason ? { message: next.failureReason } : {}),
- }, scope);
+ });
}
if (!next)
return { done: true, plan };
@@ -103,8 +123,14 @@ export async function startNextUlwLoop(repoRoot, args = {}, scope) {
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);
+ entries.push({
+ at: now,
+ kind: "goal_started",
+ goalId: next.id,
+ status: next.status,
+ message: `Attempt ${next.attempt}`,
+ });
+ await commit(repoRoot, scope, { plan, entries });
return { plan, goal: next, resumed: false };
});
}
diff --git a/plugins/omo/components/ulw-loop/dist/plan-io.d.ts b/plugins/omo/components/ulw-loop/dist/plan-io.d.ts
index db6dbc4a..4b527f61 100644
--- a/plugins/omo/components/ulw-loop/dist/plan-io.d.ts
+++ b/plugins/omo/components/ulw-loop/dist/plan-io.d.ts
@@ -1,16 +1,18 @@
import { type UlwLoopScope } from "./paths.js";
-import type { UlwLoopLedgerEntry, UlwLoopPlan } from "./types.js";
+import { type StateLockOptions } from "./state-lock.js";
+import { type UlwLoopLedgerEntry, type UlwLoopPlan } from "./types.js";
+export declare function readLedger(repoRoot: string, scope?: UlwLoopScope): UlwLoopLedgerEntry[];
+export { planExists } from "./plan-log.js";
+export declare function withMutationLockOptions<T>(options: StateLockOptions, fn: () => Promise<T>): Promise<T>;
+export declare function assertStateLockOwned(lockPath: string): void;
+export declare function migrationEntries(plan: UlwLoopPlan): readonly UlwLoopLedgerEntry[];
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 withUlwLoopMutationLock<T>(repoRoot: string, scope: UlwLoopScope | undefined, fn: () => Promise<T>, options?: StateLockOptions): Promise<T>;
+export declare function readUlwLoopPlanSync(repoRoot: string, scope?: UlwLoopScope): UlwLoopPlan;
export declare function readUlwLoopPlan(repoRoot: string, scope?: UlwLoopScope): Promise<UlwLoopPlan>;
export declare function listUlwLoopSessionIds(repoRoot: string): readonly string[];
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.js
index 726a2668..7d4f0d13 100644
--- a/plugins/omo/components/ulw-loop/dist/plan-io.js
+++ b/plugins/omo/components/ulw-loop/dist/plan-io.js
@@ -1,46 +1,88 @@
import { AsyncLocalStorage } from "node:async_hooks";
-import { createReadStream, readdirSync } from "node:fs";
-import { appendFile, mkdir, readFile, rename, writeFile } from "node:fs/promises";
-import { createInterface } from "node:readline";
+import { readdirSync } from "node:fs";
import { aggregateCodexObjectiveForScope } from "./goal-status.js";
-import { repoRelative, ulwLoopDir, ulwLoopGoalsPath, ulwLoopLedgerPath, ulwLoopRelativeDir, ulwLoopStateLockPath, } from "./paths.js";
-import { planMissingRecovery } from "./plan-missing-recovery.js";
+import { readLedger as reconcileLedger } from "./ledger.js";
+import { repoRelative, ulwLoopDir, ulwLoopGoalsPath, ulwLoopRelativeDir, ulwLoopStateLockPath, } from "./paths.js";
+import { commit, materialize, materializeSync } from "./plan-commit.js";
+import { readOptional, reconcilePlan } from "./plan-log.js";
+import { planMissingError } from "./plan-missing-recovery.js";
import { withStateLock } from "./state-lock.js";
-import { iso, ULW_LOOP_DIR, ULW_LOOP_GOALS, ULW_LOOP_LEDGER, UlwLoopError } from "./types.js";
+import { iso, ULW_LOOP_DIR, ULW_LOOP_GOALS, ULW_LOOP_LEDGER, UlwLoopError, } from "./types.js";
+export function readLedger(repoRoot, scope) {
+ const lockPath = ulwLoopStateLockPath(repoRoot, scope);
+ if (heldLocks.getStore()?.has(lockPath)) {
+ assertStateLockOwned(lockPath);
+ materializeSync(ulwLoopDir(repoRoot, scope));
+ }
+ return reconcileLedger(repoRoot, scope);
+}
+export { planExists } from "./plan-log.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();
-// Tracks which state dirs the CURRENT async continuation holds, so a read nested
-// inside a locked mutation can tell itself apart from an unlocked read elsewhere
-// in the same process.
const heldLocks = new AsyncLocalStorage();
-function hasCode(error, code) {
- return error instanceof Error && "code" in error && error.code === code;
+const lockOptions = new AsyncLocalStorage();
+export function withMutationLockOptions(options, fn) {
+ return lockOptions.run(options, fn);
}
-function isLegacyEnumeratedAggregateObjective(objective) {
- return objective === LEGACY_OBJECTIVE || Boolean(objective?.startsWith(LEGACY_OBJECTIVE_PREFIX));
+function tokenAt(lockPath) {
+ const raw = readOptional(lockPath);
+ if (raw === undefined)
+ return undefined;
+ try {
+ const record = JSON.parse(raw);
+ return typeof record === "object" && record !== null && "token" in record && typeof record.token === "string"
+ ? record.token
+ : undefined;
+ }
+ catch (error) {
+ if (error instanceof SyntaxError)
+ return undefined;
+ throw error;
+ }
}
-function isSteeringKind(value) {
- return (value === "steering_accepted" ||
- value === "steering_rejected" ||
- value === "criteria_revised" ||
- value === "batch_updated");
+export function assertStateLockOwned(lockPath) {
+ const context = heldLocks.getStore()?.get(lockPath);
+ if (context === undefined)
+ return;
+ if (tokenAt(lockPath) !== context.token)
+ throw new UlwLoopError("The ulw-loop mutation lock changed owners.", "ULW_LOOP_LOCK_LOST");
+}
+export function migrationEntries(plan) {
+ for (const context of heldLocks.getStore()?.values() ?? []) {
+ const entries = context.migrations.get(plan.goalsPath);
+ if (entries !== undefined) {
+ context.migrations.delete(plan.goalsPath);
+ return entries;
+ }
+ }
+ return [];
}
-export async function withUlwLoopMutationLock(repoRoot, scopeOrFn, maybeFn) {
+export async function withUlwLoopMutationLock(repoRoot, scopeOrFn, maybeFn, options = {}) {
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 lockPath = ulwLoopStateLockPath(repoRoot, scope);
- // The promise chain orders callers inside this process; the file lock is what
- // excludes every other process (each CLI invocation) touching the same state dir.
- const locked = () => withStateLock(lockPath, () => heldLocks.run(new Set([...(heldLocks.getStore() ?? []), lockKey]), fn));
+ const locked = () => withStateLock(lockPath, async (token) => {
+ return heldLocks.run(new Map([...(heldLocks.getStore() ?? []), [lockPath, { token, migrations: new Map() }]]), async () => {
+ for (let attempt = 0;; attempt += 1) {
+ try {
+ return await fn();
+ }
+ catch (error) {
+ if (!(error instanceof UlwLoopError) || error.code !== "ULW_LOOP_PUBLISH_CONFLICT")
+ throw error;
+ assertStateLockOwned(lockPath);
+ if (attempt !== 0)
+ throw error;
+ }
+ }
+ });
+ }, { ...lockOptions.getStore(), ...options });
const prior = locks.get(lockKey) ?? Promise.resolve(undefined);
const run = prior.then(locked, locked);
- // 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(() => {
@@ -49,47 +91,40 @@ export async function withUlwLoopMutationLock(repoRoot, scopeOrFn, maybeFn) {
});
return run;
}
-export async function readUlwLoopPlan(repoRoot, scope) {
+export function readUlwLoopPlanSync(repoRoot, scope) {
const path = ulwLoopGoalsPath(repoRoot, scope);
- let raw;
- try {
- raw = await readFile(path, "utf8");
- }
- catch (error) {
- if (!hasCode(error, "ENOENT"))
- throw error;
- const recovery = planMissingRecovery(listUlwLoopSessionIds(repoRoot));
- throw new UlwLoopError(`No ulw-loop plan found at ${repoRelative(path, repoRoot)}.\n${recovery.message}`, "ULW_LOOP_PLAN_MISSING", { cause: error, ...(recovery.details === undefined ? {} : { details: recovery.details }) });
- }
- const parsed = JSON.parse(raw);
- if (parsed.version !== 1 || !Array.isArray(parsed.goals)) {
+ const parsed = reconcilePlan(ulwLoopDir(repoRoot, scope));
+ if (parsed === undefined)
+ throw planMissingError(repoRelative(path, repoRoot), listUlwLoopSessionIds(repoRoot));
+ 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)) {
- if (!(heldLocks.getStore()?.has(`${repoRoot}\0${ulwLoopRelativeDir(scope)}`) ?? false)) {
- // A read path (status/criteria) must not mutate state: mutating here runs
- // unlocked and a second reader could write a partially-migrated plan.
- throw new UlwLoopError(`The ulw-loop plan at ${repoRelative(path, repoRoot)} carries a legacy enumerated aggregate objective that must be migrated before reads continue. Run any state-mutating ulw-loop command once (e.g. \`record-evidence\`, \`steer\`, \`checkpoint\`) to migrate it under the state lock, then retry.`, "ULW_LOOP_MIGRATION_REQUIRED");
- }
- const now = iso();
+ previousObjective !== undefined &&
+ (previousObjective === LEGACY_OBJECTIVE || previousObjective.startsWith(LEGACY_OBJECTIVE_PREFIX))) {
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);
+ heldLocks
+ .getStore()
+ ?.get(ulwLoopStateLockPath(repoRoot, scope))
+ ?.migrations.set(parsed.goalsPath, [
+ {
+ at: iso(),
+ kind: "aggregate_objective_migrated",
+ before: { codexObjective: previousObjective },
+ after: { codexObjective: parsed.codexObjective },
+ },
+ ]);
}
return parsed;
}
-// Session dirs are the only recovery hint that matters when a plan or a scope is
-// missing: the caller is almost always meant to target one of these siblings.
+export async function readUlwLoopPlan(repoRoot, scope) {
+ if (heldLocks.getStore()?.has(ulwLoopStateLockPath(repoRoot, scope))) {
+ assertStateLockOwned(ulwLoopStateLockPath(repoRoot, scope));
+ await materialize(ulwLoopDir(repoRoot, scope));
+ }
+ return readUlwLoopPlanSync(repoRoot, scope);
+}
export function listUlwLoopSessionIds(repoRoot) {
try {
return readdirSync(ulwLoopDir(repoRoot), { withFileTypes: true })
@@ -102,72 +137,28 @@ export function listUlwLoopSessionIds(repoRoot) {
}
}
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);
+ await commit(repoRoot, scope, { plan, entries: [] });
}
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");
+ if (entries.length > 0)
+ await commit(repoRoot, scope, { plan: await readUlwLoopPlan(repoRoot, scope), entries });
}
-/**
- * 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();
- }
+function isSteeringKind(value) {
+ return (value === "steering_accepted" ||
+ value === "steering_rejected" ||
+ value === "criteria_revised" ||
+ value === "batch_updated");
}
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;
+ return readLedger(repoRoot, scope).filter((entry) => isSteeringKind(entry.kind));
}
-/**
- * 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 ||
+ return readLedger(repoRoot, scope).find((entry) => isSteeringKind(entry.kind) &&
+ entry.steering?.invariant.accepted === true &&
+ (entry.idempotencyKey === key ||
entry.steering.idempotencyKey === key ||
- entry.steering.promptSignature === key)
- return entry;
- }
- return undefined;
+ entry.steering.promptSignature === key));
}
diff --git a/plugins/omo/components/ulw-loop/dist/plan-log.d.ts b/plugins/omo/components/ulw-loop/dist/plan-log.d.ts
new file mode 100644
index 00000000..9c2e09b0
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/dist/plan-log.d.ts
@@ -0,0 +1,15 @@
+import { type UlwLoopScope } from "./paths.js";
+import type { UlwLoopLedgerEntry, UlwLoopPlan } from "./types.js";
+export interface PlanCommitRecord {
+ readonly version: 1;
+ readonly revision: number;
+ readonly plan: UlwLoopPlan;
+ readonly ledger: readonly UlwLoopLedgerEntry[];
+}
+export declare function hasCode(error: unknown, code: string): boolean;
+export declare function readOptional(path: string): string | undefined;
+export declare function logNames(dir: string): string[];
+export declare function readRecords(dir: string): PlanCommitRecord[];
+export declare function readNewestRecord(dir: string): PlanCommitRecord | undefined;
+export declare function reconcilePlan(dir: string): UlwLoopPlan | undefined;
+export declare function planExists(repoRoot: string, scope?: UlwLoopScope): boolean;
diff --git a/plugins/omo/components/ulw-loop/dist/plan-log.js b/plugins/omo/components/ulw-loop/dist/plan-log.js
new file mode 100644
index 00000000..5eb5d92c
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/dist/plan-log.js
@@ -0,0 +1,86 @@
+import { existsSync, readdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { ulwLoopDir } from "./paths.js";
+export function hasCode(error, code) {
+ return error instanceof Error && "code" in error && error.code === code;
+}
+export function readOptional(path) {
+ try {
+ return readFileSync(path, "utf8");
+ }
+ catch (error) {
+ if (hasCode(error, "ENOENT"))
+ return undefined;
+ throw error;
+ }
+}
+export function logNames(dir) {
+ try {
+ return readdirSync(join(dir, "revisions"))
+ .filter((name) => /^\d{8,}\.json$/.test(name))
+ .sort();
+ }
+ catch (error) {
+ if (hasCode(error, "ENOENT"))
+ return [];
+ throw error;
+ }
+}
+function readRecord(dir, name) {
+ try {
+ const record = JSON.parse(readFileSync(join(dir, "revisions", name), "utf8"));
+ return record.version === 1 &&
+ Number.isInteger(record.revision) &&
+ record.plan?.version === 1 &&
+ Array.isArray(record.plan.goals) &&
+ Array.isArray(record.ledger)
+ ? record
+ : undefined;
+ }
+ catch (error) {
+ if (!(error instanceof SyntaxError))
+ throw error;
+ return undefined;
+ }
+}
+// Only the audit trail needs every record; plan reads use readNewestRecord.
+export function readRecords(dir) {
+ const records = [];
+ for (const name of logNames(dir)) {
+ const record = readRecord(dir, name);
+ if (record !== undefined)
+ records.push(record);
+ }
+ return records.sort((a, b) => a.revision - b.revision);
+}
+// Every ulw-loop status probe reads the plan, each record embeds a full plan copy, and records are never
+// deleted - so a plan read parses the newest record only, newest first, and stops there. Names are ordered
+// by their parsed revision because a wider zero-padding would break lexicographic order.
+export function readNewestRecord(dir) {
+ const names = logNames(dir).sort((a, b) => Number.parseInt(b, 10) - Number.parseInt(a, 10));
+ for (const name of names) {
+ const record = readRecord(dir, name);
+ if (record !== undefined)
+ return record;
+ }
+ return undefined;
+}
+export function reconcilePlan(dir) {
+ const raw = readOptional(join(dir, "goals.json"));
+ let cached;
+ if (raw !== undefined) {
+ try {
+ cached = JSON.parse(raw);
+ }
+ catch (error) {
+ if (!(error instanceof SyntaxError))
+ throw error;
+ }
+ }
+ const latest = readNewestRecord(dir);
+ return latest !== undefined && latest.revision >= (cached?.revision ?? 0) ? latest.plan : cached;
+}
+export function planExists(repoRoot, scope) {
+ const dir = ulwLoopDir(repoRoot, scope);
+ return existsSync(join(dir, "goals.json")) || logNames(dir).length > 0;
+}
diff --git a/plugins/omo/components/ulw-loop/dist/plan-missing-recovery.d.ts b/plugins/omo/components/ulw-loop/dist/plan-missing-recovery.d.ts
index 23dd0376..38303dd3 100644
--- a/plugins/omo/components/ulw-loop/dist/plan-missing-recovery.d.ts
+++ b/plugins/omo/components/ulw-loop/dist/plan-missing-recovery.d.ts
@@ -1,4 +1,7 @@
+import { UlwLoopError } from "./runtime.js";
+import type { UlwLoopToolkitSurface } from "./surface.js";
export declare const ULW_LOOP_CREATE_GOALS_COMMAND = "omo-agent-toolkit ulw-loop create-goals --brief \"<brief>\" --json";
+export declare function createGoalsAction(surface: UlwLoopToolkitSurface): string;
export interface PlanMissingRecovery {
readonly message: string;
readonly details?: {
@@ -9,6 +12,7 @@ export interface PlanMissingRecovery {
* A missing plan is either "never bootstrapped" or "bootstrapped under a different
* session id"; the recovery text has to answer both without the caller guessing.
*/
-export declare function planMissingRecovery(existingSessionIds: readonly string[]): PlanMissingRecovery;
+export declare function planMissingRecovery(existingSessionIds: readonly string[], surface?: UlwLoopToolkitSurface): PlanMissingRecovery;
+export declare function planMissingError(planPath: string, existingSessionIds: readonly string[], surface?: UlwLoopToolkitSurface): UlwLoopError;
export declare function sessionScopeRequiredMessage(flag: string, existingSessionIds: readonly string[]): string;
export declare function sessionIdRequiredMessage(flag: string): string;
diff --git a/plugins/omo/components/ulw-loop/dist/plan-missing-recovery.js b/plugins/omo/components/ulw-loop/dist/plan-missing-recovery.js
index cb31353a..7992be4d 100644
--- a/plugins/omo/components/ulw-loop/dist/plan-missing-recovery.js
+++ b/plugins/omo/components/ulw-loop/dist/plan-missing-recovery.js
@@ -1,15 +1,27 @@
+import { UlwLoopError } from "./runtime.js";
export const ULW_LOOP_CREATE_GOALS_COMMAND = 'omo-agent-toolkit ulw-loop create-goals --brief "<brief>" --json';
+export function createGoalsAction(surface) {
+ return surface === "omo-senpi" ? 'agentToolkit.createGoals({ brief: "<brief>" })' : ULW_LOOP_CREATE_GOALS_COMMAND;
+}
/**
* A missing plan is either "never bootstrapped" or "bootstrapped under a different
* session id"; the recovery text has to answer both without the caller guessing.
*/
-export function planMissingRecovery(existingSessionIds) {
- const lines = [`Recovery: bootstrap the plan with \`${ULW_LOOP_CREATE_GOALS_COMMAND}\`.`];
+export function planMissingRecovery(existingSessionIds, surface = "lazycodex") {
+ const lines = [`Recovery: bootstrap the plan with \`${createGoalsAction(surface)}\`.`];
if (existingSessionIds.length === 0)
return { message: lines.join("\n") };
- lines.push(`Existing ulw-loop session ids under .omo/ulw-loop/: ${existingSessionIds.join(", ")}. Re-run with \`--session-id <id>\` to target one of them.`);
+ lines.push(surface === "omo-senpi"
+ ? `Existing ulw-loop session ids under .omo/ulw-loop/: ${existingSessionIds.join(", ")}. The SDK is bound to the current session; resume the owning session to target its plan.`
+ : `Existing ulw-loop session ids under .omo/ulw-loop/: ${existingSessionIds.join(", ")}. Re-run with \`--session-id <id>\` to target one of them.`);
return { message: lines.join("\n"), details: { existingSessionIds } };
}
+export function planMissingError(planPath, existingSessionIds, surface = "lazycodex") {
+ const recovery = planMissingRecovery(existingSessionIds, surface);
+ return new UlwLoopError(`No ulw-loop plan found at ${planPath}.\n${recovery.message}`, "ULW_LOOP_PLAN_MISSING", {
+ ...(recovery.details === undefined ? {} : { details: recovery.details }),
+ });
+}
export function sessionScopeRequiredMessage(flag, existingSessionIds) {
const lines = [
"No ulw-loop session scope: neither the session env (OMO_ULW_LOOP_SESSION_ID / CODEX_SESSION_ID / CODEX_THREAD_ID / PI_SESSION_ID) nor the flag names this run, and the shared .omo/ulw-loop root is never used implicitly because every session in this directory would read and overwrite it.",
diff --git a/plugins/omo/components/ulw-loop/dist/review-blockers.js b/plugins/omo/components/ulw-loop/dist/review-blockers.js
index b6ba7301..8ebaf3f2 100644
--- a/plugins/omo/components/ulw-loop/dist/review-blockers.js
+++ b/plugins/omo/components/ulw-loop/dist/review-blockers.js
@@ -1,8 +1,9 @@
// biome-ignore-all format: compact port must stay within the requested pure LOC budget.
import { CodexGoalSnapshotError, formatCodexGoalReconciliation, readCodexGoalSnapshotInput, reconcileCodexGoalSnapshot, } from "./codex-goal-snapshot.js";
import { compatibleCodexObjectives, expectedCodexObjective, isFinalRunCompletionCandidate } from "./goal-status.js";
+import { commit } from "./plan-commit.js";
import { seedDefaultSuccessCriteria } from "./plan-crud.js";
-import { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";
+import { readUlwLoopPlan, withUlwLoopMutationLock } 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) {
@@ -64,9 +65,7 @@ export async function recordFinalReviewBlockers(repoRoot, args, scope) {
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);
+ await commit(repoRoot, scope, { plan, entries: ledgerEntries });
return {
plan,
blockedGoal: goal,
diff --git a/plugins/omo/components/ulw-loop/dist/sdk/factory.js b/plugins/omo/components/ulw-loop/dist/sdk/factory.js
index a3f82531..f1ac443f 100644
--- a/plugins/omo/components/ulw-loop/dist/sdk/factory.js
+++ b/plugins/omo/components/ulw-loop/dist/sdk/factory.js
@@ -1,9 +1,10 @@
import { checkpointUlwLoop } from "../checkpoint.js";
import { checkpointTemplate } from "../checkpoint-template.js";
import { recordEvidence } from "../evidence.js";
-import { ulwLoopAttemptEvidenceDir } from "../paths.js";
+import { normalizeUlwLoopSessionId, ulwLoopAttemptEvidenceDir, ulwLoopGoalsRelativePath, } from "../paths.js";
import { addUlwLoopGoal, createUlwLoopPlan, startNextUlwLoop, summarizeUlwLoopPlan } from "../plan-crud.js";
-import { readUlwLoopPlan } from "../plan-io.js";
+import { listUlwLoopSessionIds, readUlwLoopPlan } from "../plan-io.js";
+import { planMissingError } from "../plan-missing-recovery.js";
import { recordFinalReviewBlockers } from "../review-blockers.js";
import { UlwLoopError } from "../runtime.js";
import { statusNextActions } from "../status-next-actions.js";
@@ -24,8 +25,12 @@ function validateCodexGoalJson(raw) {
function validateContext(context) {
if (!context.cwd.trim())
throw new UlwLoopError("cwd is required.", "ULW_LOOP_CWD_REQUIRED");
- if (!context.sessionId.trim())
+ const sessionId = context.sessionId.trim();
+ if (!sessionId)
throw new UlwLoopError("ULW_LOOP_SESSION_ID_REQUIRED: sessionId is required.", "ULW_LOOP_SESSION_ID_REQUIRED");
+ const normalizedSessionId = normalizeUlwLoopSessionId(sessionId);
+ if (normalizedSessionId === null || /(?:^|[\\/])\.\.(?:[\\/]|$)/.test(sessionId))
+ throw new UlwLoopError("ULW_LOOP_SESSION_ID_INVALID: sessionId normalizes to null.", "ULW_LOOP_SESSION_ID_INVALID");
if (context.surface !== "omo-senpi" && context.surface !== "lazycodex")
throw new UlwLoopError("surface must be omo-senpi or lazycodex.", "ULW_LOOP_SURFACE_INVALID");
}
@@ -73,6 +78,8 @@ export function createAgentToolkit(context, deps = {}) {
return await notify(operation, { ok: true, operation, result, nextActions });
}
catch (error) {
+ if (error instanceof UlwLoopError && error.code === "ULW_LOOP_PLAN_MISSING" && context.surface === "omo-senpi")
+ return notify(operation, failure(operation, planMissingError(ulwLoopGoalsRelativePath(scope), listUlwLoopSessionIds(context.cwd), context.surface)));
const response = caught(operation, error instanceof Error ? error : new Error("ULW_LOOP_ERROR"));
return notify(operation, response);
}
@@ -107,14 +114,14 @@ export function createAgentToolkit(context, deps = {}) {
}
},
help: () => invoke("help", async () => ULW_LOOP_MANIFEST),
- createGoals: (args) => invoke("create-goals", () => createUlwLoopPlan(context.cwd, args, scope)),
+ createGoals: (args) => invoke("create-goals", () => createUlwLoopPlan(context.cwd, args, scope, context.surface)),
status: () => invoke("status", async () => {
const plan = await readUlwLoopPlan(context.cwd, scope);
const active = plan.goals.find((goal) => goal.id === plan.activeGoalId);
return {
plan,
summary: summarizeUlwLoopPlan(plan),
- nextActions: statusNextActions(plan),
+ nextActions: statusNextActions(plan, context.surface),
// Attempt directories are an evidence-layout v2 concept; a v1 plan must not advertise one.
...(active === undefined || plan.evidenceLayoutVersion !== 2
? {}
diff --git a/plugins/omo/components/ulw-loop/dist/spawn-budget-io.d.ts b/plugins/omo/components/ulw-loop/dist/spawn-budget-io.d.ts
new file mode 100644
index 00000000..d442abfd
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/dist/spawn-budget-io.d.ts
@@ -0,0 +1,5 @@
+export declare function readAdmissionBreaker(sessionId: string): string | null;
+export declare function atomicWriteJson(targetPath: string, data: unknown): void;
+export declare function isNonEmptyFile(path: string): boolean;
+export declare function readCount(counterPath: string): number;
+export declare function readCounts(counterPath: string): Record<string, number>;
diff --git a/plugins/omo/components/ulw-loop/dist/spawn-budget-io.js b/plugins/omo/components/ulw-loop/dist/spawn-budget-io.js
new file mode 100644
index 00000000..1c2de000
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/dist/spawn-budget-io.js
@@ -0,0 +1,67 @@
+import { randomBytes } from "node:crypto";
+import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+export function readAdmissionBreaker(sessionId) {
+ const dataDir = process.env["PLUGIN_DATA"];
+ if (typeof dataDir !== "string")
+ return null;
+ try {
+ const value = JSON.parse(readFileSync(join(dataDir, "spawn-breaker", `${sessionId}.json`), "utf8"));
+ return typeof value === "object" && value !== null && "reason" in value && typeof value.reason === "string"
+ ? value.reason
+ : "capacity limit";
+ }
+ catch {
+ return null;
+ }
+}
+// These hook budget files are not plan/audit state and remain outside the log.
+export function atomicWriteJson(targetPath, data) {
+ const tmp = join(dirname(targetPath), `.tmp-${randomBytes(6).toString("hex")}`);
+ writeFileSync(tmp, JSON.stringify(data));
+ renameSync(tmp, targetPath);
+}
+export function isNonEmptyFile(path) {
+ try {
+ return existsSync(path) && statSync(path).size > 0;
+ }
+ catch (error) {
+ if (error instanceof Error)
+ return false;
+ throw error;
+ }
+}
+export function readCount(counterPath) {
+ try {
+ const parsed = JSON.parse(readFileSync(counterPath, "utf8"));
+ return typeof parsed === "object" &&
+ parsed !== null &&
+ "count" in parsed &&
+ typeof parsed.count === "number" &&
+ parsed.count >= 0
+ ? parsed.count
+ : 0;
+ }
+ catch (error) {
+ if (error instanceof Error)
+ return 0;
+ throw error;
+ }
+}
+export function readCounts(counterPath) {
+ try {
+ const parsed = JSON.parse(readFileSync(counterPath, "utf8"));
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
+ return {};
+ const counts = {};
+ for (const [key, value] of Object.entries(parsed))
+ if (typeof value === "number" && value >= 0)
+ counts[key] = value;
+ return counts;
+ }
+ catch (error) {
+ if (error instanceof Error)
+ return {};
+ throw error;
+ }
+}
diff --git a/plugins/omo/components/ulw-loop/dist/spawn-guard.js b/plugins/omo/components/ulw-loop/dist/spawn-guard.js
index 44407510..d2eb9e53 100644
--- a/plugins/omo/components/ulw-loop/dist/spawn-guard.js
+++ b/plugins/omo/components/ulw-loop/dist/spawn-guard.js
@@ -1,9 +1,10 @@
-import { randomBytes } from "node:crypto";
-import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
-import { dirname, join } from "node:path";
+import { mkdirSync } from "node:fs";
+import { join } from "node:path";
import { parsePreToolUsePayload } from "./codex-hook.js";
import { isFinalRunCompletionCandidate } from "./goal-status.js";
import { ulwLoopAttemptEvidenceDir, ulwLoopDir, ulwLoopStateLockPath } from "./paths.js";
+import { readUlwLoopPlanSync } from "./plan-io.js";
+import { atomicWriteJson, isNonEmptyFile, readAdmissionBreaker, readCount, readCounts } from "./spawn-budget-io.js";
import { spawnRoleDenial } from "./spawn-role-guard.js";
import { isStateLockTimeout, withStateLockSync } from "./state-lock.js";
import { GATE_REVIEWER_AGENT_NAMES, REVIEWER_ROLES_BY_SURFACE, resolveToolkitSurface, reviewerRolesFor, } from "./surface.js";
@@ -43,7 +44,7 @@ export function applySpawnBudgetGuards(payload, options = {}) {
return deny(`Subagent admission failed earlier in this session (${breaker}). Do not spawn more workers or reviewers; report the capacity block and wait for the user.`);
const scope = { sessionId: payload.session_id };
const stateDir = ulwLoopDir(payload.cwd, scope);
- const plan = readPlan(join(stateDir, "goals.json"));
+ const plan = readPlan(payload.cwd, payload.session_id);
if (plan === null)
return "";
const lockOptions = options.lockTimeoutMs === undefined ? {} : { timeoutMs: options.lockTimeoutMs };
@@ -133,6 +134,7 @@ function peekFanOutBudget(stateDir) {
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.`;
}
+// Hook budget counters are exempt from plan/audit commits.
// 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) {
@@ -239,11 +241,6 @@ function activeSurfaceReviewerAlias(reviewer) {
}
return reviewer;
}
-function atomicWriteJson(targetPath, data) {
- const tmp = join(dirname(targetPath), `.tmp-${randomBytes(6).toString("hex")}`);
- writeFileSync(tmp, JSON.stringify(data));
- renameSync(tmp, targetPath);
-}
function deny(reason) {
return `${JSON.stringify({
hookSpecificOutput: {
@@ -254,18 +251,6 @@ function deny(reason) {
},
})}\n`;
}
-function readAdmissionBreaker(sessionId) {
- const dataDir = process.env["PLUGIN_DATA"];
- if (typeof dataDir !== "string")
- return null;
- try {
- const value = JSON.parse(readFileSync(join(dataDir, "spawn-breaker", `${sessionId}.json`), "utf8"));
- return typeof value.reason === "string" ? value.reason : "capacity limit";
- }
- catch {
- return null;
- }
-}
function fanOutLimit() {
const raw = process.env["OMO_SPAWN_FANOUT_LIMIT"];
if (raw === undefined)
@@ -280,48 +265,9 @@ function reviewSpawnLimit() {
const parsed = Number.parseInt(raw, 10);
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_REVIEW_SPAWN_LIMIT;
}
-function isNonEmptyFile(path) {
- try {
- return existsSync(path) && statSync(path).size > 0;
- }
- 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 readCounts(counterPath) {
- try {
- const parsed = JSON.parse(readFileSync(counterPath, "utf8"));
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
- return {};
- const counts = {};
- for (const [key, value] of Object.entries(parsed)) {
- if (typeof value === "number" && value >= 0)
- counts[key] = value;
- }
- return counts;
- }
- catch (error) {
- if (error instanceof Error)
- return {};
- throw error;
- }
-}
-function readPlan(goalsPath) {
+function readPlan(repoRoot, sessionId) {
try {
- return JSON.parse(readFileSync(goalsPath, "utf8"));
+ return readUlwLoopPlanSync(repoRoot, { sessionId });
}
catch (error) {
if (error instanceof Error)
diff --git a/plugins/omo/components/ulw-loop/dist/state-lock.d.ts b/plugins/omo/components/ulw-loop/dist/state-lock.d.ts
index 8be01bbe..c80362ef 100644
--- a/plugins/omo/components/ulw-loop/dist/state-lock.d.ts
+++ b/plugins/omo/components/ulw-loop/dist/state-lock.d.ts
@@ -1,9 +1,19 @@
import { UlwLoopError } from "./types.js";
export declare const ULW_LOOP_LOCK_TIMEOUT_CODE = "ULW_LOOP_LOCK_TIMEOUT";
+export interface StateLockClock {
+ readonly now: () => number;
+ readonly schedule: (fn: () => void, ms: number) => {
+ unref(): void;
+ cancel(): void;
+ };
+}
export interface StateLockOptions {
readonly timeoutMs?: number;
readonly staleMs?: number;
+ readonly leaseMs?: number;
+ readonly heartbeatMs?: number;
+ readonly clock?: StateLockClock;
}
-export declare function withStateLock<T>(lockPath: string, fn: () => Promise<T>, options?: StateLockOptions): Promise<T>;
+export declare function withStateLock<T>(lockPath: string, fn: (token: string) => Promise<T>, options?: StateLockOptions): Promise<T>;
export declare function withStateLockSync<T>(lockPath: string, fn: () => T, options?: StateLockOptions): T;
export declare function isStateLockTimeout(error: unknown): error is UlwLoopError;
diff --git a/plugins/omo/components/ulw-loop/dist/state-lock.js b/plugins/omo/components/ulw-loop/dist/state-lock.js
index b8f7331f..cc546118 100644
--- a/plugins/omo/components/ulw-loop/dist/state-lock.js
+++ b/plugins/omo/components/ulw-loop/dist/state-lock.js
@@ -1,89 +1,121 @@
import { randomUUID } from "node:crypto";
-import { closeSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeSync } from "node:fs";
+import { closeSync, ftruncateSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeSync } from "node:fs";
import { dirname } from "node:path";
-import { setTimeout as sleep } from "node:timers/promises";
import { UlwLoopError } from "./types.js";
-// Cross-process exclusive lock for one ulw-loop state directory. Every CLI
-// invocation is its own process, so the in-process promise chain in plan-io
-// serializes nothing across them; this file-level lock is what makes the
-// read-modify-write of goals.json (and the counters next to it) atomic.
-//
-// Protocol: the lock is a file created with O_EXCL whose body records the
-// owner (pid + a per-acquisition token). A waiter reclaims it only when the
-// owner is provably gone (pid dead) or the body never became a record within
-// `staleMs` (a creator that died mid-write); a live owner is never reclaimed by
-// age alone, because overlapping two bodies is exactly the lost update this lock
-// exists to prevent. Waiters back off and fail closed at `timeoutMs`. Release
-// unlinks only a lock that still carries the releaser's own token.
+// O_EXCL establishes ownership. Async holders keep the fd open and refresh a
+// lease through that fd, never through the pathname: a reclaimed inode is invisible.
+// Sync/legacy holders are lease-less and only dead pids retire their records.
+// Expiry permits overlapping bodies; immutable revision publication fences them.
+// Reclaim's reread/unlink is not atomic. On Windows an open inode may not unlink:
+// treat that refusal as a live owner and fail closed. Release checks its token.
export const ULW_LOOP_LOCK_TIMEOUT_CODE = "ULW_LOOP_LOCK_TIMEOUT";
const DEFAULT_TIMEOUT_MS = 10_000;
const DEFAULT_STALE_MS = 60_000;
-const MIN_DELAY_MS = 5;
-const MAX_DELAY_MS = 100;
+const DEFAULT_LEASE_MS = 30_000;
const SLEEP_CELL = new Int32Array(new SharedArrayBuffer(4));
+const systemClock = {
+ now: Date.now,
+ schedule(fn, ms) {
+ const timer = setTimeout(fn, ms);
+ return {
+ unref: () => {
+ timer.unref();
+ },
+ cancel: () => clearTimeout(timer),
+ };
+ },
+};
export async function withStateLock(lockPath, fn, options = {}) {
- const token = await acquireAsync(lockPath, options);
+ const holder = await acquireAsync(lockPath, options);
+ const clock = options.clock ?? systemClock;
+ let timer;
+ let heartbeatError;
+ const beat = () => {
+ try {
+ holder.record.leaseUntil = clock.now() + (options.leaseMs ?? DEFAULT_LEASE_MS);
+ writeRecord(holder);
+ schedule();
+ }
+ catch (error) {
+ heartbeatError = error;
+ }
+ };
+ const schedule = () => {
+ if (options.heartbeatMs === 0)
+ return;
+ timer = clock.schedule(beat, options.heartbeatMs ?? (options.leaseMs ?? DEFAULT_LEASE_MS) / 3);
+ timer.unref();
+ };
+ schedule();
try {
- return await fn();
+ const result = await fn(holder.record.token);
+ if (heartbeatError !== undefined)
+ throw heartbeatError;
+ return result;
}
finally {
- release(lockPath, token);
+ timer?.cancel();
+ closeSync(holder.fd);
+ release(lockPath, holder.record.token);
}
}
export function withStateLockSync(lockPath, fn, options = {}) {
- const token = acquireSync(lockPath, options);
+ const holder = acquireSync(lockPath, options);
try {
return fn();
}
finally {
- release(lockPath, token);
+ closeSync(holder.fd);
+ release(lockPath, holder.record.token);
}
}
export function isStateLockTimeout(error) {
return error instanceof UlwLoopError && error.code === ULW_LOOP_LOCK_TIMEOUT_CODE;
}
async function acquireAsync(lockPath, options) {
- const deadline = Date.now() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
- const staleMs = options.staleMs ?? DEFAULT_STALE_MS;
+ const clock = options.clock ?? systemClock;
+ const deadline = clock.now() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
mkdirSync(dirname(lockPath), { recursive: true });
for (let attempt = 0;;) {
- const outcome = attemptOnce(lockPath, staleMs);
+ const outcome = attemptOnce(lockPath, options, clock.now(), options.leaseMs ?? DEFAULT_LEASE_MS);
if (outcome.kind === "acquired")
- return outcome.token;
+ return outcome.holder;
if (outcome.kind === "retry")
continue;
- if (Date.now() >= deadline)
- throw lockTimeout(lockPath, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
- await sleep(backoffMs(attempt));
+ if (clock.now() >= deadline)
+ throw lockTimeout(lockPath, options);
+ await new Promise((resolve) => clock.schedule(resolve, backoffMs(attempt)));
attempt += 1;
}
}
function acquireSync(lockPath, options) {
const deadline = Date.now() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
- const staleMs = options.staleMs ?? DEFAULT_STALE_MS;
mkdirSync(dirname(lockPath), { recursive: true });
for (let attempt = 0;;) {
- const outcome = attemptOnce(lockPath, staleMs);
+ const outcome = attemptOnce(lockPath, options, Date.now());
if (outcome.kind === "acquired")
- return outcome.token;
+ return outcome.holder;
if (outcome.kind === "retry")
continue;
if (Date.now() >= deadline)
- throw lockTimeout(lockPath, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
+ throw lockTimeout(lockPath, options);
Atomics.wait(SLEEP_CELL, 0, 0, backoffMs(attempt));
attempt += 1;
}
}
-// EINTR surfaces raw from macOS fs syscalls under some runtimes; it is a retry, never a verdict.
-function attemptOnce(lockPath, staleMs) {
+function attemptOnce(lockPath, options, now, leaseMs) {
try {
- const token = tryCreate(lockPath);
- if (token !== null)
- return { kind: "acquired", token };
- const snapshot = readSnapshot(lockPath);
+ const holder = tryCreate(lockPath, now, leaseMs);
+ if (holder !== null)
+ return { kind: "acquired", holder };
+ const snapshot = readSnapshot(lockPath, now);
if (snapshot === null)
return { kind: "retry" };
- if (isStale(snapshot, staleMs) && reclaim(lockPath, snapshot.raw))
+ const record = snapshot.record;
+ const stale = record === null
+ ? snapshot.ageMs > (options.staleMs ?? DEFAULT_STALE_MS)
+ : !isProcessAlive(record.pid) || (record.leaseUntil !== undefined && now > record.leaseUntil);
+ if (stale && reclaim(lockPath, snapshot.raw))
return { kind: "retry" };
return { kind: "wait" };
}
@@ -93,7 +125,18 @@ function attemptOnce(lockPath, staleMs) {
throw error;
}
}
-function tryCreate(lockPath) {
+function writeRecord(holder) {
+ const buf = Buffer.from(JSON.stringify(holder.record));
+ ftruncateSync(holder.fd, 0);
+ let offset = 0;
+ while (offset < buf.length) {
+ const written = writeSync(holder.fd, buf, offset, buf.length - offset, offset);
+ if (written === 0)
+ throw new Error("State lock write made no progress.");
+ offset += written;
+ }
+}
+function tryCreate(lockPath, now, leaseMs) {
let fd;
try {
fd = openSync(lockPath, "wx");
@@ -103,30 +146,33 @@ function tryCreate(lockPath) {
return null;
throw error;
}
- const record = { pid: process.pid, createdAt: new Date().toISOString(), token: randomUUID() };
+ const record = {
+ pid: process.pid,
+ createdAt: new Date(now).toISOString(),
+ token: randomUUID(),
+ ...(leaseMs === undefined ? {} : { leaseUntil: now + leaseMs }),
+ };
+ const holder = { fd, record };
try {
- writeSync(fd, JSON.stringify(record));
+ writeRecord(holder);
}
catch (error) {
closeSync(fd);
- // A failed write (e.g. EINTR) must not leave a partial lock the owner never recorded;
- // otherwise later readers see a young ownerless lock and only age can retire it.
try {
unlinkSync(lockPath);
}
- catch {
- // another process already reclaimed the partial file; leave it alone
+ catch (cleanup) {
+ if (!hasCode(cleanup, "ENOENT"))
+ throw cleanup;
}
throw error;
}
- closeSync(fd);
- return record.token;
+ return holder;
}
-function readSnapshot(lockPath) {
+function readSnapshot(lockPath, now) {
try {
const raw = readFileSync(lockPath, "utf8");
- const ageMs = Date.now() - statSync(lockPath).mtimeMs;
- return { raw, record: parseRecord(raw), ageMs };
+ return { raw, record: parseRecord(raw), ageMs: now - statSync(lockPath).mtimeMs };
}
catch (error) {
if (hasCode(error, "ENOENT"))
@@ -136,18 +182,21 @@ function readSnapshot(lockPath) {
}
function parseRecord(raw) {
try {
- const parsed = JSON.parse(raw);
- if (typeof parsed !== "object" || parsed === null)
+ const record = JSON.parse(raw);
+ if (typeof record !== "object" || record === null)
+ return null;
+ if (!("pid" in record) || typeof record.pid !== "number" || !Number.isInteger(record.pid) || record.pid <= 0)
return null;
- const record = parsed;
- const pid = record["pid"];
- const createdAt = record["createdAt"];
- const token = record["token"];
- if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0 || typeof createdAt !== "string")
+ if (!("createdAt" in record) || typeof record.createdAt !== "string")
return null;
- if (typeof token !== "string" || token.length === 0)
+ if (!("token" in record) || typeof record.token !== "string" || record.token.length === 0)
return null;
- return { pid, createdAt, token };
+ return {
+ pid: record.pid,
+ createdAt: record.createdAt,
+ token: record.token,
+ ...("leaseUntil" in record && typeof record.leaseUntil === "number" ? { leaseUntil: record.leaseUntil } : {}),
+ };
}
catch (error) {
if (error instanceof SyntaxError)
@@ -155,14 +204,6 @@ function parseRecord(raw) {
throw error;
}
}
-// A body that is not a record is a lock mid-write (or a foreign/legacy file); only
-// age retires it. A parsable record is stale only when its owner is dead: a live
-// owner running past staleMs is slow, not gone, and the waiter fails closed instead.
-function isStale(snapshot, staleMs) {
- if (snapshot.record === null)
- return snapshot.ageMs > staleMs;
- return !isProcessAlive(snapshot.record.pid);
-}
function isProcessAlive(pid) {
try {
process.kill(pid, 0);
@@ -176,10 +217,8 @@ function isProcessAlive(pid) {
throw error;
}
}
-// Re-read right before unlinking so a lock that changed hands since the stale
-// verdict (a sibling waiter reclaimed and re-acquired it) is left alone.
function reclaim(lockPath, expectedRaw) {
- const current = readSnapshot(lockPath);
+ const current = readSnapshot(lockPath, Date.now());
if (current === null)
return true;
if (current.raw !== expectedRaw)
@@ -188,16 +227,15 @@ function reclaim(lockPath, expectedRaw) {
unlinkSync(lockPath);
}
catch (error) {
+ if (hasCode(error, "EPERM") || hasCode(error, "EACCES"))
+ return false;
if (!hasCode(error, "ENOENT"))
throw error;
}
return true;
}
-// Only the acquisition that wrote this token may unlink: if the file now carries
-// another token, a waiter has legitimately taken over and its lock must stand.
function release(lockPath, token) {
- const current = readSnapshot(lockPath);
- if (current === null || current.record?.token !== token)
+ if (readSnapshot(lockPath, Date.now())?.record?.token !== token)
return;
try {
unlinkSync(lockPath);
@@ -208,19 +246,13 @@ function release(lockPath, token) {
}
}
function backoffMs(attempt) {
- const exponential = Math.min(MAX_DELAY_MS, MIN_DELAY_MS * 2 ** attempt);
- return exponential + Math.random() * MIN_DELAY_MS;
-}
-function lockTimeout(lockPath, timeoutMs) {
- const holder = readSnapshot(lockPath)?.record;
- const owner = holder === undefined || holder === null ? "another process" : `pid ${holder.pid}`;
- return new UlwLoopError(`ulw-loop state lock ${lockPath} is held by ${owner} for more than ${timeoutMs}ms; retry once that process finishes, or delete the lock file if that process is gone.`, ULW_LOOP_LOCK_TIMEOUT_CODE, {
- details: {
- lockPath,
- timeoutMs,
- ...(holder === undefined || holder === null ? {} : { holderPid: holder.pid }),
- },
- });
+ return Math.min(100, 5 * 2 ** attempt) + Math.random() * 5;
+}
+function lockTimeout(lockPath, options) {
+ const holder = readSnapshot(lockPath, Date.now())?.record;
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ const owner = holder == null ? "another process" : `pid ${holder.pid}`;
+ return new UlwLoopError(`ulw-loop state lock ${lockPath} is held by ${owner} for more than ${timeoutMs}ms. The lock owner is still alive. If a JS eval kernel was interrupted while writing, wait for its lease to expire (${options.leaseMs ?? DEFAULT_LEASE_MS} ms) or restart the owning senpi process; never delete a lock owned by a live process.`, ULW_LOOP_LOCK_TIMEOUT_CODE, { details: { lockPath, timeoutMs, ...(holder == null ? {} : { holderPid: holder.pid }) } });
}
function hasCode(error, code) {
return error instanceof Error && "code" in error && error.code === code;
diff --git a/plugins/omo/components/ulw-loop/dist/status-next-actions.d.ts b/plugins/omo/components/ulw-loop/dist/status-next-actions.d.ts
index b6a61a97..36e8d4e3 100644
--- a/plugins/omo/components/ulw-loop/dist/status-next-actions.d.ts
+++ b/plugins/omo/components/ulw-loop/dist/status-next-actions.d.ts
@@ -1,6 +1,7 @@
+import type { UlwLoopToolkitSurface } from "./surface.js";
import type { UlwLoopPlan } from "./types.js";
/**
- * `status --json` is the one call every agent already makes between steps, so it is
+ * Status is the one call every agent already makes between steps, so it is
* also the cheapest place to answer "what now?" without a second round trip.
*/
-export declare function statusNextActions(plan: UlwLoopPlan): readonly string[];
+export declare function statusNextActions(plan: UlwLoopPlan, surface?: UlwLoopToolkitSurface): readonly string[];
diff --git a/plugins/omo/components/ulw-loop/dist/status-next-actions.js b/plugins/omo/components/ulw-loop/dist/status-next-actions.js
index 10f0cc1e..6a1b11b4 100644
--- a/plugins/omo/components/ulw-loop/dist/status-next-actions.js
+++ b/plugins/omo/components/ulw-loop/dist/status-next-actions.js
@@ -1,33 +1,41 @@
import { hasAllCriteriaPass, isFinalRunCompletionCandidate } from "./goal-status.js";
-import { ULW_LOOP_CREATE_GOALS_COMMAND } from "./plan-missing-recovery.js";
+import { createGoalsAction } from "./plan-missing-recovery.js";
/**
- * `status --json` is the one call every agent already makes between steps, so it is
+ * Status is the one call every agent already makes between steps, so it is
* also the cheapest place to answer "what now?" without a second round trip.
*/
-export function statusNextActions(plan) {
+export function statusNextActions(plan, surface = "lazycodex") {
const actions = [];
const active = plan.goals.find((goal) => goal.id === plan.activeGoalId);
if (plan.goals.length === 0)
- actions.push(`No goals yet: bootstrap with \`${ULW_LOOP_CREATE_GOALS_COMMAND}\`.`);
+ actions.push(`No goals yet: bootstrap with \`${createGoalsAction(surface)}\`.`);
else if (active !== undefined)
- actions.push(...activeGoalActions(plan, active));
+ actions.push(...activeGoalActions(plan, active, surface));
for (const goal of plan.goals.filter((candidate) => candidate.status === "review_blocked"))
- actions.push(`${goal.id} is review_blocked: capture the reviewer verdict with \`omo-agent-toolkit ulw-loop record-review-blockers --goal-id ${goal.id} --title "<title>" --objective "<objective>" --evidence "<verdict>" --codex-goal-json '<get_goal json>'\`.`);
+ actions.push(surface === "omo-senpi"
+ ? `${goal.id} is review_blocked: capture the reviewer verdict with \`agentToolkit.recordReviewBlockers({ goalId: "${goal.id}", title: "<title>", objective: "<objective>", evidence: "<verdict>" })\`.`
+ : `${goal.id} is review_blocked: capture the reviewer verdict with \`omo-agent-toolkit ulw-loop record-review-blockers --goal-id ${goal.id} --title "<title>" --objective "<objective>" --evidence "<verdict>" --codex-goal-json '<get_goal json>'\`.`);
if (plan.evidenceLayoutVersion !== 2 || active === undefined)
actions.push("plan is evidence-layout v1; artifacts go under .omo/evidence/");
return actions;
}
-function activeGoalActions(plan, active) {
+function activeGoalActions(plan, active, surface) {
const unresolved = active.successCriteria.filter((criterion) => criterion.status !== "pass");
if (unresolved.length > 0)
return [
- `${active.id} has ${unresolved.length} unresolved criterion(s) (${unresolved.map((criterion) => criterion.id).join(", ")}): record proof with \`omo-agent-toolkit ulw-loop record-evidence --goal-id ${active.id} --criterion-id <id> --status pass --evidence "<observable proof>"\`.`,
+ surface === "omo-senpi"
+ ? `${active.id} has ${unresolved.length} unresolved criterion(s) (${unresolved.map((criterion) => criterion.id).join(", ")}): record proof with \`agentToolkit.recordEvidence({ goalId: "${active.id}", criterionId: "<id>", status: "pass", evidence: "<observable proof>" })\`.`
+ : `${active.id} has ${unresolved.length} unresolved criterion(s) (${unresolved.map((criterion) => criterion.id).join(", ")}): record proof with \`omo-agent-toolkit ulw-loop record-evidence --goal-id ${active.id} --criterion-id <id> --status pass --evidence "<observable proof>"\`.`,
];
if (hasAllCriteriaPass(active) && isFinalRunCompletionCandidate(plan, active))
return [
- `${active.id} passes every criterion and is the final story: update_goal complete, then checkpoint --print-template to build the final quality gate. Use status --json's currentAttemptDir for all quality-gate artifacts.`,
+ surface === "omo-senpi"
+ ? `${active.id} passes every criterion and is the final story: complete the driver goal, then call \`agentToolkit.checkpoint({ goalId: "${active.id}", printTemplate: true })\` to build the final quality gate. Use status().result.currentAttemptDir for all quality-gate artifacts.`
+ : `${active.id} passes every criterion and is the final story: update_goal complete, then checkpoint --print-template to build the final quality gate. Use status --json's currentAttemptDir for all quality-gate artifacts.`,
];
return [
- `${active.id} passes every criterion: close it with \`omo-agent-toolkit ulw-loop checkpoint --goal-id ${active.id} --status complete --evidence "<proof>" --codex-goal-json '<get_goal json>'\`. Put quality-gate artifacts under the currentAttemptDir shown by status --json.`,
+ surface === "omo-senpi"
+ ? `${active.id} passes every criterion: close it with \`agentToolkit.checkpoint({ goalId: "${active.id}", status: "complete", evidence: "<proof>" })\`. Put quality-gate artifacts under status().result.currentAttemptDir.`
+ : `${active.id} passes every criterion: close it with \`omo-agent-toolkit ulw-loop checkpoint --goal-id ${active.id} --status complete --evidence "<proof>" --codex-goal-json '<get_goal json>'\`. Put quality-gate artifacts under the currentAttemptDir shown by status --json.`,
];
}
diff --git a/plugins/omo/components/ulw-loop/dist/steering-batch.js b/plugins/omo/components/ulw-loop/dist/steering-batch.js
index e9870b82..2658d3be 100644
--- a/plugins/omo/components/ulw-loop/dist/steering-batch.js
+++ b/plugins/omo/components/ulw-loop/dist/steering-batch.js
@@ -1,4 +1,5 @@
-import { appendLedger, appendLedgerEntries, findAcceptedSteeringLedgerEntry, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";
+import { commit } from "./plan-commit.js";
+import { findAcceptedSteeringLedgerEntry, readUlwLoopPlan, withUlwLoopMutationLock } from "./plan-io.js";
import { applySteeringMutation, validateUlwLoopSteeringProposal } from "./steering.js";
import { buildSteeringPlanSnapshot, changedGoalIdsBetween } from "./steering-snapshot.js";
import { iso } from "./types.js";
@@ -10,7 +11,7 @@ export async function steerUlwLoopBatch(repoRoot, proposals, scope) {
const failed = prepared.results.find((item) => !item.accepted);
if (failed !== undefined) {
const entry = rejectedLedgerEntry(prepared.results);
- await appendLedger(repoRoot, entry, scope);
+ await commit(repoRoot, scope, { plan, entries: [entry] });
return rejected(plan, prepared.results, failed.rejectedReasons);
}
let next = plan;
@@ -19,10 +20,9 @@ export async function steerUlwLoopBatch(repoRoot, proposals, scope) {
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);
+ await commit(repoRoot, scope, { plan: next, entries: batchEntry === null ? entries : [...entries, batchEntry] });
}
return { plan: next, accepted: true, results: prepared.results, rejectedReasons: [] };
});
diff --git a/plugins/omo/components/ulw-loop/dist/steering.js b/plugins/omo/components/ulw-loop/dist/steering.js
index 9682879b..3cc2707f 100644
--- a/plugins/omo/components/ulw-loop/dist/steering.js
+++ b/plugins/omo/components/ulw-loop/dist/steering.js
@@ -1,6 +1,7 @@
// 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 { commit } from "./plan-commit.js";
+import { findAcceptedSteeringLedgerEntry, readUlwLoopPlan, withUlwLoopMutationLock } 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";
@@ -223,11 +224,10 @@ export async function steerUlwLoop(repoRoot, proposal, scope) {
}
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);
+ const entries = [ledgerEntry(proposal, finalAudit, at)];
if (batchEntry !== null)
- await appendLedger(repoRoot, batchEntry, scope);
+ entries.push(batchEntry);
+ await commit(repoRoot, scope, { plan: next, entries });
return { plan: next, accepted, audit: finalAudit, rejectedReasons: audit.invariant.rejectedReasons, deduped: false };
});
}
diff --git a/plugins/omo/components/ulw-loop/dist/stop-resume-hook.js b/plugins/omo/components/ulw-loop/dist/stop-resume-hook.js
index 24ae2448..0d1bcfe3 100644
--- a/plugins/omo/components/ulw-loop/dist/stop-resume-hook.js
+++ b/plugins/omo/components/ulw-loop/dist/stop-resume-hook.js
@@ -1,6 +1,8 @@
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { isAbsolute, join, resolve, sep } from "node:path";
+import { readLedgerAt } from "./ledger.js";
import { normalizeUlwLoopSessionId, ulwLoopDir, ulwLoopStateLockPath } from "./paths.js";
+import { readUlwLoopPlanSync } from "./plan-io.js";
import { isStateLockTimeout, withStateLockSync } from "./state-lock.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
@@ -27,7 +29,7 @@ export function runStopResumeHook(input) {
return "";
const scope = { sessionId: payload.session_id };
const stateDir = ulwLoopDir(payload.cwd, scope);
- const plan = readPlan(join(stateDir, "goals.json"));
+ const plan = readPlan(payload.cwd, payload.session_id);
if (plan === null || plan.aggregateCompletion?.status === "complete")
return "";
const goal = resumableGoal(plan);
@@ -76,11 +78,10 @@ function consumeResumeBudgetLocked(lockPath, stateDir, goalId) {
throw error;
}
}
-// 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.
+// Hook budget counters are exempt from plan/audit commits. Count reconciled
+// entries, not cache lines: a writer dying after link still made progress.
function consumeResumeBudget(stateDir, goalId) {
- const ledgerLineCount = countLedgerLines(join(stateDir, "ledger.jsonl"));
+ const ledgerLineCount = readLedgerAt(stateDir).length;
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
@@ -111,9 +112,9 @@ function renderResumeDirective(plan, goal, sessionId) {
"If the loop is genuinely blocked on the user, checkpoint the goal as blocked with the reason instead.",
].join("\n");
}
-function readPlan(goalsPath) {
+function readPlan(repoRoot, sessionId) {
try {
- return JSON.parse(readFileSync(goalsPath, "utf8"));
+ return readUlwLoopPlanSync(repoRoot, { sessionId });
}
catch (error) {
if (error instanceof Error)
@@ -121,16 +122,6 @@ function readPlan(goalsPath) {
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))
diff --git a/plugins/omo/components/ulw-loop/hooks/hooks.json b/plugins/omo/components/ulw-loop/hooks/hooks.json
index 2748c3ed..650f63a1 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 5.0.0-beta.62) Checking Ulw-Loop Steering"
+ "statusMessage": "(OmO 5.0.0-beta.63) Checking Ulw-Loop Steering"
}
]
}
@@ -20,7 +20,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use-spawn",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.62) Recording Spawn Admission"
+ "statusMessage": "(OmO 5.0.0-beta.63) Recording Spawn Admission"
}
]
}
@@ -33,7 +33,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.62) Enforcing Unlimited Ulw-Loop Budget"
+ "statusMessage": "(OmO 5.0.0-beta.63) Enforcing Unlimited Ulw-Loop Budget"
}
]
},
@@ -44,7 +44,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use-spawn",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.62) Guarding Ulw-Loop Spawns"
+ "statusMessage": "(OmO 5.0.0-beta.63) Guarding Ulw-Loop Spawns"
}
]
}
@@ -56,7 +56,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook stop",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.62) Checking Ulw-Loop Resume"
+ "statusMessage": "(OmO 5.0.0-beta.63) Checking Ulw-Loop Resume"
}
]
}
diff --git a/plugins/omo/components/ulw-loop/package.json b/plugins/omo/components/ulw-loop/package.json
index d31e97ba..3454dc4a 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": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"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.md
index 83213a07..89cda675 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
@@ -20,7 +20,7 @@ Run each criterion's real-surface proof yourself through the channel that faithf
1. **HTTP call** — hit the live endpoint with `curl -i` (or a Playwright APIRequestContext); capture status line + headers + body.
2. **Terminal / TUI** - prove it through the xterm.js web terminal; tmux `send-keys` is fine for a boot smoke, but NEVER `tmux capture-pane` for color/layout/CJK evidence (it degrades truecolor).
-3. **Browser use** — in Codex, use `browser:control-in-app-browser` first when available and the scenario does not need an authenticated or persistent user browser profile. Otherwise use Chrome to drive the REAL page; if unavailable, use agent-browser. Capture action log + screenshot path. Never downgrade a browser-facing criterion.
+3. **Browser use** — in Codex, prefer `browser:control-in-app-browser`. Otherwise, or for Chrome semantics, stealth, trace, or auth, WRITE a `playwright-core` script and run it from js eval against local Chrome (`channel: "chrome"`; persistent context on a CLONED profile, never the live one). Capture action log + screenshot path. Never downgrade a browser-facing criterion.
4. **Computer use** — for desktop/GUI apps, drive the running app via OS automation (computer-use, AppleScript, xdotool, etc.); capture action log + screenshot.
For TUI visual QA (mandatory when a PR or review must inspect the terminal screen),
@@ -165,7 +165,7 @@ Loop per goal. Cap at 5 cycles per goal. Cap identical same-criterion failures a
4. INTEGRATE + CRITICAL SELF-QA + GIT CHECKPOINT (EVERY WORKER RETURN): do NOT trust the worker's report. Read the diff yourself, re-run its tests, and run LSP diagnostics on the changed files. Treat "done" as a claim to disprove. If the diff drifts, the test is hollow, or evidence is missing, RESPAWN the worker with the specific failure context. Once the work unit is verified, use `git-master` before staging: inspect recent repository commits and touched-path history to infer commit language, Conventional Commit scope, message shape, and unit size. Stage only that unit's files and commit in the observed style; do not carry verified work forward into a later omnibus commit. If no git-tracked files changed or committing is unsafe, record the no-commit reason as evidence. Forward every finding/learning to subsequent workers.
5. EXECUTE-AS-SCENARIO: ACTUALLY run the Manual-QA scenario the criterion named (channel table above). Run it yourself for the orchestrator check; for heavier flows dispatch a dedicated QA execution worker (`lazycodex-worker-medium` by default; `lazycodex-worker-high` when the QA flow itself is hard) whose ONLY job is to drive the channel and write the artifact to the named evidence path. If the scenario FAILS, respawn the implementing worker with the captured failure — do not hand-patch around it.
6. CAPTURE: collect the observable artifact path: transcript, stdout, screenshot, assertion, status+body, diff, or parsed dump. No artifact written at the evidence path — not done; record BLOCKED and respawn QA.
-7. CLEAN (PAIRED, NEVER SKIP): tear down every runtime artifact step 5 spawned BEFORE recording — server PIDs (`kill`, verify `kill -0` fails), `tmux` sessions (`tmux kill-session -t ulw-qa-<criterion>`; confirm `tmux ls`), browser / Playwright contexts (`.close()`), containers (`docker rm -f`), bound ports (`lsof -i :<port>` empty), temp sockets / files / dirs (`rm -rf` the `mktemp` paths), QA-only env vars, AND close every finished worker (v1 `close_agent`; on V2 finished workers end on their own — `interrupt_agent` any still running). Register each teardown as its own todo the moment the QA spawns the resource (scripts, tmux assets, browsers / agent-browser sessions, PIDs, ports) so none is forgotten. Embed a one-line cleanup receipt in the evidence string, e.g. `cleanup: killed 12345; tmux kill-session ulw-qa-foo; rm -rf /tmp/ulw.aB12cD; interrupt_agent w-3`. Missing receipt → record BLOCKED, not PASS.
+7. CLEAN (PAIRED, NEVER SKIP): tear down every runtime artifact step 5 spawned BEFORE recording — server PIDs (`kill`, verify `kill -0` fails), `tmux` sessions (`tmux kill-session -t ulw-qa-<criterion>`; confirm `tmux ls`), browser / Playwright contexts (`.close()`), containers (`docker rm -f`), bound ports (`lsof -i :<port>` empty), temp sockets / files / dirs (`rm -rf` the `mktemp` paths), QA-only env vars, AND close every finished worker (v1 `close_agent`; on V2 finished workers end on their own — `interrupt_agent` any still running). Register each teardown as its own todo the moment the QA spawns the resource (scripts, tmux assets, browser contexts, PIDs, ports) so none is forgotten. Embed a one-line cleanup receipt in the evidence string, e.g. `cleanup: killed 12345; tmux kill-session ulw-qa-foo; rm -rf /tmp/ulw.aB12cD; interrupt_agent w-3`. Missing receipt → record BLOCKED, not PASS.
8. RECORD one result immediately from the artifact you just wrote — never from memory or a later turn — stamping the capture tree `$(git rev-parse --short "HEAD^{tree}")` into the evidence:
- PASS: `omo-agent-toolkit ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status pass --evidence "<observable> @tree:<short-tree> | <cleanup receipt>" --json`
- FAIL: `omo-agent-toolkit ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status fail --evidence "<observable> @tree:<short-tree> | <cleanup receipt>" --notes "<diagnosis>" --json`
diff --git a/plugins/omo/components/ulw-loop/src/checkpoint.ts b/plugins/omo/components/ulw-loop/src/checkpoint.ts
index aa9dcdd1..f9efb8b4 100644
--- a/plugins/omo/components/ulw-loop/src/checkpoint.ts
+++ b/plugins/omo/components/ulw-loop/src/checkpoint.ts
@@ -10,7 +10,8 @@ import { requireAllCriteriaPass, requireAllPlanCriteriaPass, requireEssentialCri
import { codexGoalMode, 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 { commit } from "./plan-commit.js";
+import { readUlwLoopPlan, withUlwLoopMutationLock } from "./plan-io.js";
import {
classifyExternalAuthorizationBlocker,
clearGoalBlockerFields,
@@ -226,11 +227,11 @@ export async function checkpointUlwLoop(
if (aggregateCompletion !== undefined) plan.aggregateCompletion = aggregateCompletion;
if (aggregateCompletion !== undefined) nextActions = [...nextActions, 'aggregate complete — now update_goal({status:"complete"})'];
plan.updatedAt = now;
- await writePlan(repoRoot, plan, scope);
const ledgerEntry = buildLedger(now, args, goal, qualityGate, codexGoal, aggregateCompletion);
- await appendLedger(repoRoot, ledgerEntry, scope);
+ const entries = [ledgerEntry];
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);
+ if (closedBatch !== undefined) entries.push({ at: now, kind: "batch_closed", goalId: goal.id, message: closedBatch.batchId });
+ await commit(repoRoot, scope, { plan, entries });
return aggregateCompletion === undefined
? { plan, goal, ledgerEntry, nextActions, warnings }
: { plan, goal, ledgerEntry, aggregateCompletion, nextActions, warnings };
diff --git a/plugins/omo/components/ulw-loop/src/domain-types.ts b/plugins/omo/components/ulw-loop/src/domain-types.ts
index 6a7b1356..5f39255c 100644
--- a/plugins/omo/components/ulw-loop/src/domain-types.ts
+++ b/plugins/omo/components/ulw-loop/src/domain-types.ts
@@ -63,6 +63,9 @@ export interface UlwLoopValidationBatch {
export interface UlwLoopPlan {
version: 1;
+ revision?: number;
+ brief?: string;
+ ledgerResetRevision?: number;
evidenceLayoutVersion?: 2;
createdAt: string;
updatedAt: string;
@@ -158,6 +161,8 @@ export interface UlwLoopQualityGateSenpi extends UlwLoopQualityGateCommon {
export type UlwLoopQualityGate = UlwLoopQualityGateLazycodex | UlwLoopQualityGateSenpi;
export interface UlwLoopLedgerEntry {
+ revision?: number;
+ id?: string;
at: string;
kind: UlwLoopLedgerEventKind;
goalId?: string;
diff --git a/plugins/omo/components/ulw-loop/src/evidence.ts b/plugins/omo/components/ulw-loop/src/evidence.ts
index 1ad3fb61..36cbb378 100644
--- a/plugins/omo/components/ulw-loop/src/evidence.ts
+++ b/plugins/omo/components/ulw-loop/src/evidence.ts
@@ -1,6 +1,7 @@
import { essentialCriteriaOf, hasAllCriteriaPass, hasEssentialCriteriaPass } from "./goal-status.js";
import type { UlwLoopScope } from "./paths.js";
-import { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";
+import { commit } from "./plan-commit.js";
+import { readUlwLoopPlan, withUlwLoopMutationLock } from "./plan-io.js";
import type { UlwLoopItem, UlwLoopLedgerEntry, UlwLoopPlan, UlwLoopSuccessCriterion } from "./types.js";
import { iso, UlwLoopError } from "./types.js";
@@ -75,7 +76,6 @@ export async function recordEvidence(
if (args.notes !== undefined) criterion.notes = args.notes;
goal.updatedAt = capturedAt;
plan.updatedAt = capturedAt;
- await writePlan(repoRoot, plan, scope);
const ledgerEntry: UlwLoopLedgerEntry = {
at: capturedAt,
kind,
@@ -87,7 +87,7 @@ export async function recordEvidence(
before: { status: prevStatus },
after: { goalId: goal.id, criterionId: criterion.id, status: args.status, evidence, capturedAt, prevStatus },
};
- await appendLedger(repoRoot, ledgerEntry, scope);
+ await commit(repoRoot, scope, { plan, entries: [ledgerEntry] });
return { plan, goal, criterion, ledgerEntry };
});
}
@@ -115,19 +115,19 @@ export async function markCriteriaPendingResetForGoal(
}
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,
- );
+ await commit(repoRoot, scope, {
+ plan,
+ entries: [
+ {
+ at: now,
+ kind: "criteria_revised",
+ goalId,
+ message: `Reset ${goal.successCriteria.length} criteria to pending.`,
+ before,
+ after: { resetCount: goal.successCriteria.length },
+ },
+ ],
+ });
return { plan, resetCount: goal.successCriteria.length };
});
}
diff --git a/plugins/omo/components/ulw-loop/src/ledger.ts b/plugins/omo/components/ulw-loop/src/ledger.ts
new file mode 100644
index 00000000..692957cb
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/src/ledger.ts
@@ -0,0 +1,33 @@
+import { join } from "node:path";
+import { type UlwLoopScope, ulwLoopDir } from "./paths.js";
+import { readOptional, readRecords, reconcilePlan } from "./plan-log.js";
+import type { UlwLoopLedgerEntry } from "./types.js";
+
+export function readLedgerAt(dir: string): UlwLoopLedgerEntry[] {
+ const entries = new Map<string, UlwLoopLedgerEntry>();
+ const lines = (readOptional(join(dir, "ledger.jsonl")) ?? "").split(/\r?\n/);
+ for (const [index, line] of lines.entries()) {
+ if (line.trim().length === 0) continue;
+ try {
+ const entry: UlwLoopLedgerEntry = JSON.parse(line);
+ entry.revision ??= 0;
+ entry.id ??= `legacy-${index + 1}`;
+ entries.set(entry.id, entry);
+ } catch (error) {
+ if (!(error instanceof SyntaxError)) throw error;
+ }
+ }
+ for (const record of readRecords(dir))
+ for (const [seq, entry] of record.ledger.entries()) {
+ const id = entry.id ?? `${record.revision}-${seq}`;
+ entries.set(id, { ...entry, revision: record.revision, id });
+ }
+ const reset = reconcilePlan(dir)?.ledgerResetRevision ?? 0;
+ const sequence = (entry: UlwLoopLedgerEntry) => Number(entry.id?.split("-").at(-1) ?? 0);
+ return [...entries.values()]
+ .filter((entry) => (entry.revision ?? 0) >= reset)
+ .sort((a, b) => (a.revision ?? 0) - (b.revision ?? 0) || sequence(a) - sequence(b));
+}
+export function readLedger(repoRoot: string, scope?: UlwLoopScope): UlwLoopLedgerEntry[] {
+ return readLedgerAt(ulwLoopDir(repoRoot, scope));
+}
diff --git a/plugins/omo/components/ulw-loop/src/plan-commit.ts b/plugins/omo/components/ulw-loop/src/plan-commit.ts
new file mode 100644
index 00000000..70b6eda0
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/src/plan-commit.ts
@@ -0,0 +1,124 @@
+import { AsyncLocalStorage } from "node:async_hooks";
+import { randomUUID } from "node:crypto";
+import { linkSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { rename, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { readLedgerAt } from "./ledger.js";
+import { type UlwLoopScope, ulwLoopDir, ulwLoopStateLockPath } from "./paths.js";
+import { assertStateLockOwned, migrationEntries } from "./plan-io.js";
+import { hasCode, type PlanCommitRecord, readOptional, readRecords, reconcilePlan } from "./plan-log.js";
+import { UlwLoopError, type UlwLoopLedgerEntry, type UlwLoopPlan } from "./types.js";
+
+interface CommitHooks {
+ readonly beforeMutation?: () => void | Promise<void>;
+ readonly beforeCommit?: () => void | Promise<void>;
+ readonly afterCommit?: () => void | Promise<void>;
+ readonly link?: (source: string, destination: string) => void;
+ readonly writeView?: (path: string, content: string) => Promise<void>;
+}
+const hooks = new AsyncLocalStorage<CommitHooks>();
+export function withCommitHooks<T>(value: CommitHooks, fn: () => Promise<T>): Promise<T> {
+ return hooks.run(value, fn);
+}
+
+export async function beforePlanMutation(): Promise<void> {
+ await hooks.getStore()?.beforeMutation?.();
+}
+export async function writeViewFile(path: string, content: string): Promise<void> {
+ await (hooks.getStore()?.writeView ?? writeFile)(path, content);
+}
+
+// link is the sole commit point; no copy fallback (Node copyFile is not atomic).
+// A resumed zombie can publish first, but never overwrite an existing revision.
+// Logical audit order is (revision, sequence), not materialization completion time.
+export async function commit(
+ repoRoot: string,
+ scope: UlwLoopScope | undefined,
+ mutation: {
+ readonly plan: UlwLoopPlan;
+ readonly entries: readonly UlwLoopLedgerEntry[];
+ },
+): Promise<void> {
+ const { plan } = mutation;
+ const dir = ulwLoopDir(repoRoot, scope);
+ assertStateLockOwned(ulwLoopStateLockPath(repoRoot, scope));
+ await hooks.getStore()?.beforeCommit?.();
+ const next = (plan.revision ?? 0) + 1;
+ const brief = plan.brief ?? readOptional(join(dir, "brief.md")) ?? "";
+ const entries = [...migrationEntries(plan), ...mutation.entries].map((entry, seq) => ({
+ ...entry,
+ revision: next,
+ id: `${next}-${seq}`,
+ }));
+ const record: PlanCommitRecord = {
+ version: 1,
+ revision: next,
+ plan: { ...plan, revision: next, brief },
+ ledger: entries,
+ };
+ mkdirSync(join(dir, "revisions"), { recursive: true });
+ mkdirSync(join(dir, "tmp"), { recursive: true });
+ const temp = join(dir, "tmp", `${process.pid}-${randomUUID()}.json`);
+ try {
+ writeFileSync(temp, `${JSON.stringify(record)}\n`, { flag: "wx" });
+ try {
+ (hooks.getStore()?.link ?? linkSync)(temp, join(dir, "revisions", `${String(next).padStart(8, "0")}.json`));
+ } catch (error) {
+ if (hasCode(error, "EEXIST"))
+ throw new UlwLoopError("Another writer published the read revision.", "ULW_LOOP_PUBLISH_CONFLICT", {
+ cause: error,
+ });
+ if (["EPERM", "ENOTSUP", "EXDEV"].some((code) => hasCode(error, code)))
+ throw new UlwLoopError(
+ "Immutable ulw-loop publication requires atomic hard links.",
+ "ULW_LOOP_PUBLISH_UNSUPPORTED_FS",
+ { cause: error },
+ );
+ throw error;
+ }
+ } finally {
+ rmSync(temp, { force: true });
+ }
+ plan.revision = next;
+ plan.brief = brief;
+ for (const [index, entry] of mutation.entries.entries())
+ Object.assign(entry, entries[index + entries.length - mutation.entries.length]);
+ await hooks.getStore()?.afterCommit?.();
+ await materialize(dir);
+}
+
+function viewContents(dir: string): [string, string][] {
+ const plan = reconcilePlan(dir);
+ if (plan === undefined || readRecords(dir).length === 0) return [];
+ const ledger = readLedgerAt(dir);
+ const views: [string, string][] = [
+ ["goals.json", `${JSON.stringify(plan, null, 2)}\n`],
+ ["ledger.jsonl", ledger.length === 0 ? "" : `${ledger.map((entry) => JSON.stringify(entry)).join("\n")}\n`],
+ ["brief.md", plan.brief ?? readOptional(join(dir, "brief.md")) ?? ""],
+ ];
+ return views.filter(([name, content]) => readOptional(join(dir, name)) !== content);
+}
+export function materializeSync(dir: string): void {
+ for (const [name, content] of viewContents(dir)) {
+ mkdirSync(join(dir, "tmp"), { recursive: true });
+ const temp = join(dir, "tmp", `${process.pid}-${randomUUID()}-${name}`);
+ try {
+ writeFileSync(temp, content, { flag: "wx" });
+ renameSync(temp, join(dir, name));
+ } finally {
+ rmSync(temp, { force: true });
+ }
+ }
+}
+export async function materialize(dir: string): Promise<void> {
+ for (const [name, content] of viewContents(dir)) {
+ mkdirSync(join(dir, "tmp"), { recursive: true });
+ const temp = join(dir, "tmp", `${process.pid}-${randomUUID()}-${name}`);
+ try {
+ await writeViewFile(temp, content);
+ await rename(temp, join(dir, name));
+ } finally {
+ rmSync(temp, { force: true });
+ }
+ }
+}
diff --git a/plugins/omo/components/ulw-loop/src/plan-crud.ts b/plugins/omo/components/ulw-loop/src/plan-crud.ts
index 97de8734..dcc9e10b 100644
--- a/plugins/omo/components/ulw-loop/src/plan-crud.ts
+++ b/plugins/omo/components/ulw-loop/src/plan-crud.ts
@@ -1,20 +1,21 @@
-import { existsSync } from "node:fs";
-import { mkdir, writeFile } from "node:fs/promises";
-
import { aggregateCodexObjectiveForScope, isUlwLoopDone } from "./goal-status.js";
import {
type UlwLoopScope,
- ulwLoopBriefPath,
ulwLoopBriefRelativePath,
- ulwLoopDir,
- ulwLoopGoalsPath,
ulwLoopGoalsRelativePath,
- ulwLoopLedgerPath,
ulwLoopLedgerRelativePath,
} from "./paths.js";
+import { beforePlanMutation, commit } from "./plan-commit.js";
import { appendGoalToPlan, deriveGoalCandidates, makeGoal } from "./plan-goal-factory.js";
-import { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";
-import type { UlwLoopCodexGoalMode, UlwLoopItem, UlwLoopPlan, UlwLoopSuccessCriterion } from "./types.js";
+import { planExists, readUlwLoopPlan, withUlwLoopMutationLock } from "./plan-io.js";
+import type { UlwLoopToolkitSurface } from "./surface.js";
+import type {
+ UlwLoopCodexGoalMode,
+ UlwLoopItem,
+ UlwLoopLedgerEntry,
+ UlwLoopPlan,
+ UlwLoopSuccessCriterion,
+} from "./types.js";
import { iso, UlwLoopError } from "./types.js";
import { parseValidationBatches } from "./validation-batch.js";
@@ -60,11 +61,19 @@ export async function createUlwLoopPlan(
repoRoot: string,
args: { brief: string; codexGoalMode?: UlwLoopCodexGoalMode; force?: boolean; validationBatchesJson?: string },
scope?: UlwLoopScope,
+ surface: UlwLoopToolkitSurface = "lazycodex",
): Promise<UlwLoopPlan> {
return withUlwLoopMutationLock(repoRoot, scope, async () => {
- if (!args.force && existsSync(ulwLoopGoalsPath(repoRoot, scope))) {
- const existing = await readUlwLoopPlan(repoRoot, scope);
- if (isUlwLoopDone(existing)) throw completedPlanExistsError(scope);
+ let existing: UlwLoopPlan | undefined;
+ if (planExists(repoRoot, scope)) {
+ try {
+ existing = await readUlwLoopPlan(repoRoot, scope);
+ } catch (error) {
+ if (!args.force) throw error;
+ }
+ }
+ if (!args.force && existing !== undefined) {
+ if (isUlwLoopDone(existing)) throw completedPlanExistsError(scope, surface);
throw new UlwLoopError(
`Refusing to overwrite existing ${ulwLoopGoalsRelativePath(scope)}; pass --force to recreate it.`,
"ULW_LOOP_PLAN_EXISTS",
@@ -76,6 +85,9 @@ export async function createUlwLoopPlan(
);
const plan: UlwLoopPlan = {
version: 1,
+ revision: existing?.revision ?? 0,
+ ledgerResetRevision: (existing?.revision ?? 0) + 1,
+ brief: args.brief.endsWith("\n") ? args.brief : `${args.brief}\n`,
evidenceLayoutVersion: 2,
createdAt: now,
updatedAt: now,
@@ -88,29 +100,27 @@ export async function createUlwLoopPlan(
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,
- );
+ await beforePlanMutation();
+ await commit(repoRoot, scope, {
+ plan,
+ entries: [{ at: now, kind: "plan_created", message: `${goals.length} goal(s) created` }],
+ });
return plan;
});
}
-function completedPlanExistsError(scope?: UlwLoopScope): UlwLoopError {
+function completedPlanExistsError(scope: UlwLoopScope | undefined, surface: UlwLoopToolkitSurface): UlwLoopError {
return new UlwLoopError(
[
`Existing ulw-loop aggregate is already complete at ${ulwLoopGoalsRelativePath(scope)}.`,
- "Start a new run with `omo-agent-toolkit ulw-loop create-goals --session-id <new-id> ...` to isolate fresh state.",
- "Use --force only when you intentionally want to overwrite the completed evidence.",
+ ...(surface === "omo-senpi"
+ ? [
+ "Start a new run under a fresh session id (a new senpi session) or call agentToolkit.createGoals({ brief, force: true }) to recreate.",
+ ]
+ : [
+ "Start a new run with `omo-agent-toolkit 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",
);
@@ -125,12 +135,10 @@ export async function addUlwLoopGoal(
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,
- );
+ await commit(repoRoot, scope, {
+ plan,
+ entries: [{ at: now, kind: "goal_added", goalId: goal.id, status: goal.status, message: goal.title }],
+ });
return { plan, goal };
});
}
@@ -146,21 +154,18 @@ export async function startNextUlwLoop(
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 };
+ const entries: UlwLoopLedgerEntry[] = [];
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,
- );
+ entries.push({
+ at: now,
+ kind: "goal_retried",
+ goalId: next.id,
+ status: "pending",
+ ...(next.failureReason ? { message: next.failureReason } : {}),
+ });
}
if (!next) return { done: true, plan };
next.status = "in_progress";
@@ -170,12 +175,14 @@ export async function startNextUlwLoop(
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,
- );
+ entries.push({
+ at: now,
+ kind: "goal_started",
+ goalId: next.id,
+ status: next.status,
+ message: `Attempt ${next.attempt}`,
+ });
+ await commit(repoRoot, scope, { plan, entries });
return { plan, goal: next, resumed: false };
});
}
diff --git a/plugins/omo/components/ulw-loop/src/plan-io.ts b/plugins/omo/components/ulw-loop/src/plan-io.ts
index 6bd45ad3..e70db6ad 100644
--- a/plugins/omo/components/ulw-loop/src/plan-io.ts
+++ b/plugins/omo/components/ulw-loop/src/plan-io.ts
@@ -1,74 +1,122 @@
import { AsyncLocalStorage } from "node:async_hooks";
-import { createReadStream, readdirSync } from "node:fs";
-import { appendFile, mkdir, readFile, rename, writeFile } from "node:fs/promises";
-import { createInterface } from "node:readline";
-
+import { readdirSync } from "node:fs";
import { aggregateCodexObjectiveForScope } from "./goal-status.js";
+import { readLedger as reconcileLedger } from "./ledger.js";
import {
repoRelative,
type UlwLoopScope,
ulwLoopDir,
ulwLoopGoalsPath,
- ulwLoopLedgerPath,
ulwLoopRelativeDir,
ulwLoopStateLockPath,
} from "./paths.js";
-import { planMissingRecovery } from "./plan-missing-recovery.js";
-import { withStateLock } from "./state-lock.js";
-import type { UlwLoopLedgerEntry, UlwLoopPlan } from "./types.js";
-import { iso, ULW_LOOP_DIR, ULW_LOOP_GOALS, ULW_LOOP_LEDGER, UlwLoopError } from "./types.js";
+import { commit, materialize, materializeSync } from "./plan-commit.js";
+import { readOptional, reconcilePlan } from "./plan-log.js";
+import { planMissingError } from "./plan-missing-recovery.js";
+import { type StateLockOptions, withStateLock } from "./state-lock.js";
+import {
+ iso,
+ ULW_LOOP_DIR,
+ ULW_LOOP_GOALS,
+ ULW_LOOP_LEDGER,
+ UlwLoopError,
+ type UlwLoopLedgerEntry,
+ type UlwLoopPlan,
+} from "./types.js";
+
+export function readLedger(repoRoot: string, scope?: UlwLoopScope): UlwLoopLedgerEntry[] {
+ const lockPath = ulwLoopStateLockPath(repoRoot, scope);
+ if (heldLocks.getStore()?.has(lockPath)) {
+ assertStateLockOwned(lockPath);
+ materializeSync(ulwLoopDir(repoRoot, scope));
+ }
+ return reconcileLedger(repoRoot, scope);
+}
+export { planExists } from "./plan-log.js";
const LEGACY_OBJECTIVE_PREFIX = `Complete all ulw-loop stories in ${ULW_LOOP_DIR}/${ULW_LOOP_GOALS}: `;
const LEGACY_OBJECTIVE = `Complete all ulw-loop stories listed in ${ULW_LOOP_DIR}/${ULW_LOOP_GOALS}. Use ${ULW_LOOP_DIR}/${ULW_LOOP_LEDGER} as the durable audit trail.`;
const locks = new Map<string, Promise<undefined>>();
-// Tracks which state dirs the CURRENT async continuation holds, so a read nested
-// inside a locked mutation can tell itself apart from an unlocked read elsewhere
-// in the same process.
-const heldLocks = new AsyncLocalStorage<ReadonlySet<string>>();
-
-function hasCode(error: unknown, code: string): boolean {
- return error instanceof Error && "code" in error && error.code === code;
+interface LockContext {
+ readonly token: string;
+ readonly migrations: Map<string, UlwLoopLedgerEntry[]>;
}
-
-function isLegacyEnumeratedAggregateObjective(objective: string | undefined): objective is string {
- return objective === LEGACY_OBJECTIVE || Boolean(objective?.startsWith(LEGACY_OBJECTIVE_PREFIX));
+const heldLocks = new AsyncLocalStorage<ReadonlyMap<string, LockContext>>();
+const lockOptions = new AsyncLocalStorage<StateLockOptions>();
+export function withMutationLockOptions<T>(options: StateLockOptions, fn: () => Promise<T>): Promise<T> {
+ return lockOptions.run(options, fn);
}
-
-function isSteeringKind(value: unknown): value is UlwLoopLedgerEntry["kind"] {
- return (
- value === "steering_accepted" ||
- value === "steering_rejected" ||
- value === "criteria_revised" ||
- value === "batch_updated"
- );
+function tokenAt(lockPath: string): string | undefined {
+ const raw = readOptional(lockPath);
+ if (raw === undefined) return undefined;
+ try {
+ const record: unknown = JSON.parse(raw);
+ return typeof record === "object" && record !== null && "token" in record && typeof record.token === "string"
+ ? record.token
+ : undefined;
+ } catch (error) {
+ if (error instanceof SyntaxError) return undefined;
+ throw error;
+ }
+}
+export function assertStateLockOwned(lockPath: string): void {
+ const context = heldLocks.getStore()?.get(lockPath);
+ if (context === undefined) return;
+ if (tokenAt(lockPath) !== context.token)
+ throw new UlwLoopError("The ulw-loop mutation lock changed owners.", "ULW_LOOP_LOCK_LOST");
+}
+export function migrationEntries(plan: UlwLoopPlan): readonly UlwLoopLedgerEntry[] {
+ for (const context of heldLocks.getStore()?.values() ?? []) {
+ const entries = context.migrations.get(plan.goalsPath);
+ if (entries !== undefined) {
+ context.migrations.delete(plan.goalsPath);
+ return entries;
+ }
+ }
+ return [];
}
-
export async function withUlwLoopMutationLock<T>(repoRoot: string, fn: () => Promise<T>): Promise<T>;
export async function withUlwLoopMutationLock<T>(
repoRoot: string,
scope: UlwLoopScope | undefined,
fn: () => Promise<T>,
+ options?: StateLockOptions,
): Promise<T>;
export async function withUlwLoopMutationLock<T>(
repoRoot: string,
scopeOrFn: UlwLoopScope | (() => Promise<T>) | undefined,
maybeFn?: () => Promise<T>,
+ options: StateLockOptions = {},
): Promise<T> {
const scope = typeof scopeOrFn === "function" ? undefined : scopeOrFn;
const fn = typeof scopeOrFn === "function" ? scopeOrFn : maybeFn;
if (fn === undefined) throw new UlwLoopError("Missing ulw-loop mutation body.", "ULW_LOOP_LOCK_BODY_MISSING");
const lockKey = `${repoRoot}\0${ulwLoopRelativeDir(scope)}`;
const lockPath = ulwLoopStateLockPath(repoRoot, scope);
- // The promise chain orders callers inside this process; the file lock is what
- // excludes every other process (each CLI invocation) touching the same state dir.
- const locked = (): Promise<T> =>
- withStateLock(lockPath, () => heldLocks.run(new Set([...(heldLocks.getStore() ?? []), lockKey]), fn));
+ const locked = () =>
+ withStateLock(
+ lockPath,
+ async (token) => {
+ return heldLocks.run(
+ new Map([...(heldLocks.getStore() ?? []), [lockPath, { token, migrations: new Map() }]]),
+ async () => {
+ for (let attempt = 0; ; attempt += 1) {
+ try {
+ return await fn();
+ } catch (error) {
+ if (!(error instanceof UlwLoopError) || error.code !== "ULW_LOOP_PUBLISH_CONFLICT") throw error;
+ assertStateLockOwned(lockPath);
+ if (attempt !== 0) throw error;
+ }
+ }
+ },
+ );
+ },
+ { ...lockOptions.getStore(), ...options },
+ );
const prior = locks.get(lockKey) ?? Promise.resolve(undefined);
const run = prior.then(locked, locked);
- // 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: Promise<undefined> = run.then(
+ const gate = run.then(
() => undefined,
() => undefined,
);
@@ -78,60 +126,41 @@ export async function withUlwLoopMutationLock<T>(
});
return run;
}
-
-export async function readUlwLoopPlan(repoRoot: string, scope?: UlwLoopScope): Promise<UlwLoopPlan> {
+export function readUlwLoopPlanSync(repoRoot: string, scope?: UlwLoopScope): UlwLoopPlan {
const path = ulwLoopGoalsPath(repoRoot, scope);
- let raw: string;
- try {
- raw = await readFile(path, "utf8");
- } catch (error) {
- if (!hasCode(error, "ENOENT")) throw error;
- const recovery = planMissingRecovery(listUlwLoopSessionIds(repoRoot));
- throw new UlwLoopError(
- `No ulw-loop plan found at ${repoRelative(path, repoRoot)}.\n${recovery.message}`,
- "ULW_LOOP_PLAN_MISSING",
- { cause: error, ...(recovery.details === undefined ? {} : { details: recovery.details }) },
- );
- }
- const parsed: UlwLoopPlan = JSON.parse(raw);
- if (parsed.version !== 1 || !Array.isArray(parsed.goals)) {
+ const parsed = reconcilePlan(ulwLoopDir(repoRoot, scope));
+ if (parsed === undefined) throw planMissingError(repoRelative(path, repoRoot), listUlwLoopSessionIds(repoRoot));
+ 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)
+ previousObjective !== undefined &&
+ (previousObjective === LEGACY_OBJECTIVE || previousObjective.startsWith(LEGACY_OBJECTIVE_PREFIX))
) {
- if (!(heldLocks.getStore()?.has(`${repoRoot}\0${ulwLoopRelativeDir(scope)}`) ?? false)) {
- // A read path (status/criteria) must not mutate state: mutating here runs
- // unlocked and a second reader could write a partially-migrated plan.
- throw new UlwLoopError(
- `The ulw-loop plan at ${repoRelative(path, repoRoot)} carries a legacy enumerated aggregate objective that must be migrated before reads continue. Run any state-mutating ulw-loop command once (e.g. \`record-evidence\`, \`steer\`, \`checkpoint\`) to migrate it under the state lock, then retry.`,
- "ULW_LOOP_MIGRATION_REQUIRED",
- );
- }
- 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,
- );
+ heldLocks
+ .getStore()
+ ?.get(ulwLoopStateLockPath(repoRoot, scope))
+ ?.migrations.set(parsed.goalsPath, [
+ {
+ at: iso(),
+ kind: "aggregate_objective_migrated",
+ before: { codexObjective: previousObjective },
+ after: { codexObjective: parsed.codexObjective },
+ },
+ ]);
}
return parsed;
}
-
-// Session dirs are the only recovery hint that matters when a plan or a scope is
-// missing: the caller is almost always meant to target one of these siblings.
+export async function readUlwLoopPlan(repoRoot: string, scope?: UlwLoopScope): Promise<UlwLoopPlan> {
+ if (heldLocks.getStore()?.has(ulwLoopStateLockPath(repoRoot, scope))) {
+ assertStateLockOwned(ulwLoopStateLockPath(repoRoot, scope));
+ await materialize(ulwLoopDir(repoRoot, scope));
+ }
+ return readUlwLoopPlanSync(repoRoot, scope);
+}
export function listUlwLoopSessionIds(repoRoot: string): readonly string[] {
try {
return readdirSync(ulwLoopDir(repoRoot), { withFileTypes: true })
@@ -142,84 +171,41 @@ export function listUlwLoopSessionIds(repoRoot: string): readonly string[] {
return [];
}
}
-
export async function writePlan(repoRoot: string, plan: UlwLoopPlan, scope?: UlwLoopScope): Promise<void> {
- await mkdir(ulwLoopDir(repoRoot, scope), { recursive: true });
- const path = ulwLoopGoalsPath(repoRoot, scope);
- const tmpPath = `${path}.${process.pid}.${Date.now()}.tmp`;
- await writeFile(tmpPath, `${JSON.stringify(plan, null, 2)}\n`, "utf8");
- await rename(tmpPath, path);
+ await commit(repoRoot, scope, { plan, entries: [] });
}
-
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),
- `${entries.map((entry) => JSON.stringify(entry)).join("\n")}\n`,
- "utf8",
- );
+ if (entries.length > 0) await commit(repoRoot, scope, { plan: await readUlwLoopPlan(repoRoot, scope), entries });
}
-
-/**
- * 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: string, scope?: UlwLoopScope): AsyncGenerator<string> {
- 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();
- }
+function isSteeringKind(value: unknown): boolean {
+ return (
+ value === "steering_accepted" ||
+ value === "steering_rejected" ||
+ value === "criteria_revised" ||
+ value === "batch_updated"
+ );
}
-
export async function readSteeringLedgerEntries(repoRoot: string, scope?: UlwLoopScope): Promise<UlwLoopLedgerEntry[]> {
- const entries: UlwLoopLedgerEntry[] = [];
- for await (const line of ledgerLines(repoRoot, scope)) {
- const entry: UlwLoopLedgerEntry = JSON.parse(line);
- if (isSteeringKind(entry.kind)) entries.push(entry);
- }
- return entries;
+ return readLedger(repoRoot, scope).filter((entry) => isSteeringKind(entry.kind));
}
-
-/**
- * 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: string,
key: string,
scope?: UlwLoopScope,
): Promise<UlwLoopLedgerEntry | undefined> {
- const probe = JSON.stringify(key);
- for await (const line of ledgerLines(repoRoot, scope)) {
- if (!line.includes(probe)) continue;
- const entry: UlwLoopLedgerEntry = 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;
+ return readLedger(repoRoot, scope).find(
+ (entry) =>
+ isSteeringKind(entry.kind) &&
+ entry.steering?.invariant.accepted === true &&
+ (entry.idempotencyKey === key ||
+ entry.steering.idempotencyKey === key ||
+ entry.steering.promptSignature === key),
+ );
}
diff --git a/plugins/omo/components/ulw-loop/src/plan-log.ts b/plugins/omo/components/ulw-loop/src/plan-log.ts
new file mode 100644
index 00000000..5a020526
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/src/plan-log.ts
@@ -0,0 +1,84 @@
+import { existsSync, readdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { type UlwLoopScope, ulwLoopDir } from "./paths.js";
+import type { UlwLoopLedgerEntry, UlwLoopPlan } from "./types.js";
+
+export interface PlanCommitRecord {
+ readonly version: 1;
+ readonly revision: number;
+ readonly plan: UlwLoopPlan;
+ readonly ledger: readonly UlwLoopLedgerEntry[];
+}
+export function hasCode(error: unknown, code: string): boolean {
+ return error instanceof Error && "code" in error && error.code === code;
+}
+export function readOptional(path: string): string | undefined {
+ try {
+ return readFileSync(path, "utf8");
+ } catch (error) {
+ if (hasCode(error, "ENOENT")) return undefined;
+ throw error;
+ }
+}
+export function logNames(dir: string): string[] {
+ try {
+ return readdirSync(join(dir, "revisions"))
+ .filter((name) => /^\d{8,}\.json$/.test(name))
+ .sort();
+ } catch (error) {
+ if (hasCode(error, "ENOENT")) return [];
+ throw error;
+ }
+}
+function readRecord(dir: string, name: string): PlanCommitRecord | undefined {
+ try {
+ const record: PlanCommitRecord = JSON.parse(readFileSync(join(dir, "revisions", name), "utf8"));
+ return record.version === 1 &&
+ Number.isInteger(record.revision) &&
+ record.plan?.version === 1 &&
+ Array.isArray(record.plan.goals) &&
+ Array.isArray(record.ledger)
+ ? record
+ : undefined;
+ } catch (error) {
+ if (!(error instanceof SyntaxError)) throw error;
+ return undefined;
+ }
+}
+// Only the audit trail needs every record; plan reads use readNewestRecord.
+export function readRecords(dir: string): PlanCommitRecord[] {
+ const records: PlanCommitRecord[] = [];
+ for (const name of logNames(dir)) {
+ const record = readRecord(dir, name);
+ if (record !== undefined) records.push(record);
+ }
+ return records.sort((a, b) => a.revision - b.revision);
+}
+// Every ulw-loop status probe reads the plan, each record embeds a full plan copy, and records are never
+// deleted - so a plan read parses the newest record only, newest first, and stops there. Names are ordered
+// by their parsed revision because a wider zero-padding would break lexicographic order.
+export function readNewestRecord(dir: string): PlanCommitRecord | undefined {
+ const names = logNames(dir).sort((a, b) => Number.parseInt(b, 10) - Number.parseInt(a, 10));
+ for (const name of names) {
+ const record = readRecord(dir, name);
+ if (record !== undefined) return record;
+ }
+ return undefined;
+}
+export function reconcilePlan(dir: string): UlwLoopPlan | undefined {
+ const raw = readOptional(join(dir, "goals.json"));
+ let cached: UlwLoopPlan | undefined;
+ if (raw !== undefined) {
+ try {
+ cached = JSON.parse(raw);
+ } catch (error) {
+ if (!(error instanceof SyntaxError)) throw error;
+ }
+ }
+ const latest = readNewestRecord(dir);
+ return latest !== undefined && latest.revision >= (cached?.revision ?? 0) ? latest.plan : cached;
+}
+export function planExists(repoRoot: string, scope?: UlwLoopScope): boolean {
+ const dir = ulwLoopDir(repoRoot, scope);
+ return existsSync(join(dir, "goals.json")) || logNames(dir).length > 0;
+}
diff --git a/plugins/omo/components/ulw-loop/src/plan-missing-recovery.ts b/plugins/omo/components/ulw-loop/src/plan-missing-recovery.ts
index 45354424..1ee78be9 100644
--- a/plugins/omo/components/ulw-loop/src/plan-missing-recovery.ts
+++ b/plugins/omo/components/ulw-loop/src/plan-missing-recovery.ts
@@ -1,5 +1,12 @@
+import { UlwLoopError } from "./runtime.js";
+import type { UlwLoopToolkitSurface } from "./surface.js";
+
export const ULW_LOOP_CREATE_GOALS_COMMAND = 'omo-agent-toolkit ulw-loop create-goals --brief "<brief>" --json';
+export function createGoalsAction(surface: UlwLoopToolkitSurface): string {
+ return surface === "omo-senpi" ? 'agentToolkit.createGoals({ brief: "<brief>" })' : ULW_LOOP_CREATE_GOALS_COMMAND;
+}
+
export interface PlanMissingRecovery {
readonly message: string;
readonly details?: { readonly existingSessionIds: readonly string[] };
@@ -9,15 +16,31 @@ export interface PlanMissingRecovery {
* A missing plan is either "never bootstrapped" or "bootstrapped under a different
* session id"; the recovery text has to answer both without the caller guessing.
*/
-export function planMissingRecovery(existingSessionIds: readonly string[]): PlanMissingRecovery {
- const lines = [`Recovery: bootstrap the plan with \`${ULW_LOOP_CREATE_GOALS_COMMAND}\`.`];
+export function planMissingRecovery(
+ existingSessionIds: readonly string[],
+ surface: UlwLoopToolkitSurface = "lazycodex",
+): PlanMissingRecovery {
+ const lines = [`Recovery: bootstrap the plan with \`${createGoalsAction(surface)}\`.`];
if (existingSessionIds.length === 0) return { message: lines.join("\n") };
lines.push(
- `Existing ulw-loop session ids under .omo/ulw-loop/: ${existingSessionIds.join(", ")}. Re-run with \`--session-id <id>\` to target one of them.`,
+ surface === "omo-senpi"
+ ? `Existing ulw-loop session ids under .omo/ulw-loop/: ${existingSessionIds.join(", ")}. The SDK is bound to the current session; resume the owning session to target its plan.`
+ : `Existing ulw-loop session ids under .omo/ulw-loop/: ${existingSessionIds.join(", ")}. Re-run with \`--session-id <id>\` to target one of them.`,
);
return { message: lines.join("\n"), details: { existingSessionIds } };
}
+export function planMissingError(
+ planPath: string,
+ existingSessionIds: readonly string[],
+ surface: UlwLoopToolkitSurface = "lazycodex",
+): UlwLoopError {
+ const recovery = planMissingRecovery(existingSessionIds, surface);
+ return new UlwLoopError(`No ulw-loop plan found at ${planPath}.\n${recovery.message}`, "ULW_LOOP_PLAN_MISSING", {
+ ...(recovery.details === undefined ? {} : { details: recovery.details }),
+ });
+}
+
export function sessionScopeRequiredMessage(flag: string, existingSessionIds: readonly string[]): string {
const lines = [
"No ulw-loop session scope: neither the session env (OMO_ULW_LOOP_SESSION_ID / CODEX_SESSION_ID / CODEX_THREAD_ID / PI_SESSION_ID) nor the flag names this run, and the shared .omo/ulw-loop root is never used implicitly because every session in this directory would read and overwrite it.",
diff --git a/plugins/omo/components/ulw-loop/src/review-blockers.ts b/plugins/omo/components/ulw-loop/src/review-blockers.ts
index b9348a1e..0e2aa107 100644
--- a/plugins/omo/components/ulw-loop/src/review-blockers.ts
+++ b/plugins/omo/components/ulw-loop/src/review-blockers.ts
@@ -8,8 +8,9 @@ import {
} from "./codex-goal-snapshot.js";
import { compatibleCodexObjectives, expectedCodexObjective, isFinalRunCompletionCandidate } from "./goal-status.js";
import type { UlwLoopScope } from "./paths.js";
+import { commit } from "./plan-commit.js";
import { seedDefaultSuccessCriteria } from "./plan-crud.js";
-import { appendLedger, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";
+import { readUlwLoopPlan, withUlwLoopMutationLock } from "./plan-io.js";
import type { UlwLoopItem, UlwLoopLedgerEntry, UlwLoopPlan } from "./types.js";
import { iso, UlwLoopError } from "./types.js";
@@ -88,8 +89,7 @@ export async function recordFinalReviewBlockers(
const summaryEntry: UlwLoopLedgerEntry = { at: now, kind: "goal_review_blocked", goalId: goal.id, status: goal.status, evidence: args.evidence, codexGoal, message: `Review blockers recorded; appended ${newGoal.id}.` };
Reflect.set(summaryEntry, "kind", "blocker_recorded");
const ledgerEntries = [blockedEntry, addedEntry, summaryEntry];
- await writePlan(repoRoot, plan, scope);
- for (const entry of ledgerEntries) await appendLedger(repoRoot, entry, scope);
+ await commit(repoRoot, scope, { plan, entries: ledgerEntries });
return {
plan,
blockedGoal: goal,
diff --git a/plugins/omo/components/ulw-loop/src/sdk/factory.ts b/plugins/omo/components/ulw-loop/src/sdk/factory.ts
index f0d1a73a..17aa0e72 100644
--- a/plugins/omo/components/ulw-loop/src/sdk/factory.ts
+++ b/plugins/omo/components/ulw-loop/src/sdk/factory.ts
@@ -1,9 +1,15 @@
import { checkpointUlwLoop } from "../checkpoint.js";
import { checkpointTemplate } from "../checkpoint-template.js";
import { recordEvidence } from "../evidence.js";
-import { type UlwLoopScope, ulwLoopAttemptEvidenceDir } from "../paths.js";
+import {
+ normalizeUlwLoopSessionId,
+ type UlwLoopScope,
+ ulwLoopAttemptEvidenceDir,
+ ulwLoopGoalsRelativePath,
+} from "../paths.js";
import { addUlwLoopGoal, createUlwLoopPlan, startNextUlwLoop, summarizeUlwLoopPlan } from "../plan-crud.js";
-import { readUlwLoopPlan } from "../plan-io.js";
+import { listUlwLoopSessionIds, readUlwLoopPlan } from "../plan-io.js";
+import { planMissingError } from "../plan-missing-recovery.js";
import { recordFinalReviewBlockers } from "../review-blockers.js";
import { UlwLoopError } from "../runtime.js";
import { statusNextActions } from "../status-next-actions.js";
@@ -41,8 +47,15 @@ function validateCodexGoalJson(raw: string | undefined): void {
function validateContext(context: ToolkitContext): void {
if (!context.cwd.trim()) throw new UlwLoopError("cwd is required.", "ULW_LOOP_CWD_REQUIRED");
- if (!context.sessionId.trim())
+ const sessionId = context.sessionId.trim();
+ if (!sessionId)
throw new UlwLoopError("ULW_LOOP_SESSION_ID_REQUIRED: sessionId is required.", "ULW_LOOP_SESSION_ID_REQUIRED");
+ const normalizedSessionId = normalizeUlwLoopSessionId(sessionId);
+ if (normalizedSessionId === null || /(?:^|[\\/])\.\.(?:[\\/]|$)/.test(sessionId))
+ throw new UlwLoopError(
+ "ULW_LOOP_SESSION_ID_INVALID: sessionId normalizes to null.",
+ "ULW_LOOP_SESSION_ID_INVALID",
+ );
if (context.surface !== "omo-senpi" && context.surface !== "lazycodex")
throw new UlwLoopError("surface must be omo-senpi or lazycodex.", "ULW_LOOP_SURFACE_INVALID");
}
@@ -106,6 +119,18 @@ export function createAgentToolkit(context: ToolkitContext, deps: AgentToolkitDe
const nextActions = typeof result === "object" && result !== null ? nextActionsFrom(result) : [];
return await notify(operation, { ok: true, operation, result, nextActions });
} catch (error) {
+ if (error instanceof UlwLoopError && error.code === "ULW_LOOP_PLAN_MISSING" && context.surface === "omo-senpi")
+ return notify(
+ operation,
+ failure(
+ operation,
+ planMissingError(
+ ulwLoopGoalsRelativePath(scope),
+ listUlwLoopSessionIds(context.cwd),
+ context.surface,
+ ),
+ ),
+ );
const response = caught(operation, error instanceof Error ? error : new Error("ULW_LOOP_ERROR"));
return notify(operation, response);
}
@@ -143,7 +168,7 @@ export function createAgentToolkit(context: ToolkitContext, deps: AgentToolkitDe
}
},
help: () => invoke("help", async () => ULW_LOOP_MANIFEST),
- createGoals: (args) => invoke("create-goals", () => createUlwLoopPlan(context.cwd, args, scope)),
+ createGoals: (args) => invoke("create-goals", () => createUlwLoopPlan(context.cwd, args, scope, context.surface)),
status: () =>
invoke("status", async () => {
const plan = await readUlwLoopPlan(context.cwd, scope);
@@ -151,7 +176,7 @@ export function createAgentToolkit(context: ToolkitContext, deps: AgentToolkitDe
return {
plan,
summary: summarizeUlwLoopPlan(plan),
- nextActions: statusNextActions(plan),
+ nextActions: statusNextActions(plan, context.surface),
// Attempt directories are an evidence-layout v2 concept; a v1 plan must not advertise one.
...(active === undefined || plan.evidenceLayoutVersion !== 2
? {}
diff --git a/plugins/omo/components/ulw-loop/src/spawn-budget-io.ts b/plugins/omo/components/ulw-loop/src/spawn-budget-io.ts
new file mode 100644
index 00000000..6bb50322
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/src/spawn-budget-io.ts
@@ -0,0 +1,59 @@
+import { randomBytes } from "node:crypto";
+import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+
+export function readAdmissionBreaker(sessionId: string): string | null {
+ const dataDir = process.env["PLUGIN_DATA"];
+ if (typeof dataDir !== "string") return null;
+ try {
+ const value: unknown = JSON.parse(readFileSync(join(dataDir, "spawn-breaker", `${sessionId}.json`), "utf8"));
+ return typeof value === "object" && value !== null && "reason" in value && typeof value.reason === "string"
+ ? value.reason
+ : "capacity limit";
+ } catch {
+ return null;
+ }
+}
+
+// These hook budget files are not plan/audit state and remain outside the log.
+export function atomicWriteJson(targetPath: string, data: unknown): void {
+ const tmp = join(dirname(targetPath), `.tmp-${randomBytes(6).toString("hex")}`);
+ writeFileSync(tmp, JSON.stringify(data));
+ renameSync(tmp, targetPath);
+}
+export function isNonEmptyFile(path: string): boolean {
+ try {
+ return existsSync(path) && statSync(path).size > 0;
+ } catch (error) {
+ if (error instanceof Error) return false;
+ throw error;
+ }
+}
+export function readCount(counterPath: string): number {
+ try {
+ const parsed: unknown = JSON.parse(readFileSync(counterPath, "utf8"));
+ return typeof parsed === "object" &&
+ parsed !== null &&
+ "count" in parsed &&
+ typeof parsed.count === "number" &&
+ parsed.count >= 0
+ ? parsed.count
+ : 0;
+ } catch (error) {
+ if (error instanceof Error) return 0;
+ throw error;
+ }
+}
+export function readCounts(counterPath: string): Record<string, number> {
+ try {
+ const parsed: unknown = JSON.parse(readFileSync(counterPath, "utf8"));
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
+ const counts: Record<string, number> = {};
+ for (const [key, value] of Object.entries(parsed))
+ if (typeof value === "number" && value >= 0) counts[key] = value;
+ return counts;
+ } catch (error) {
+ if (error instanceof Error) return {};
+ throw error;
+ }
+}
diff --git a/plugins/omo/components/ulw-loop/src/spawn-guard.ts b/plugins/omo/components/ulw-loop/src/spawn-guard.ts
index bdac27e4..57407b90 100644
--- a/plugins/omo/components/ulw-loop/src/spawn-guard.ts
+++ b/plugins/omo/components/ulw-loop/src/spawn-guard.ts
@@ -1,11 +1,12 @@
-import { randomBytes } from "node:crypto";
-import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
-import { dirname, join } from "node:path";
+import { mkdirSync } from "node:fs";
+import { join } from "node:path";
import type { PreToolUsePayload } from "./codex-hook.js";
import { parsePreToolUsePayload } from "./codex-hook.js";
import { isFinalRunCompletionCandidate } from "./goal-status.js";
import { ulwLoopAttemptEvidenceDir, ulwLoopDir, ulwLoopStateLockPath } from "./paths.js";
+import { readUlwLoopPlanSync } from "./plan-io.js";
+import { atomicWriteJson, isNonEmptyFile, readAdmissionBreaker, readCount, readCounts } from "./spawn-budget-io.js";
import { spawnRoleDenial } from "./spawn-role-guard.js";
import { isStateLockTimeout, type StateLockOptions, withStateLockSync } from "./state-lock.js";
import {
@@ -57,7 +58,7 @@ export function applySpawnBudgetGuards(payload: PreToolUsePayload, options: Spaw
);
const scope = { sessionId: payload.session_id } as const;
const stateDir = ulwLoopDir(payload.cwd, scope);
- const plan = readPlan(join(stateDir, "goals.json"));
+ const plan = readPlan(payload.cwd, payload.session_id);
if (plan === null) return "";
const lockOptions: StateLockOptions =
options.lockTimeoutMs === undefined ? {} : { timeoutMs: options.lockTimeoutMs };
@@ -148,6 +149,7 @@ function peekFanOutBudget(stateDir: string): string | 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.`;
}
+// Hook budget counters are exempt from plan/audit commits.
// 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: string): string | null {
@@ -245,12 +247,6 @@ function activeSurfaceReviewerAlias(reviewer: string): string {
return reviewer;
}
-function atomicWriteJson(targetPath: string, data: unknown): void {
- const tmp = join(dirname(targetPath), `.tmp-${randomBytes(6).toString("hex")}`);
- writeFileSync(tmp, JSON.stringify(data));
- renameSync(tmp, targetPath);
-}
-
function deny(reason: string): string {
return `${JSON.stringify({
hookSpecificOutput: {
@@ -262,19 +258,6 @@ function deny(reason: string): string {
})}\n`;
}
-function readAdmissionBreaker(sessionId: string): string | null {
- const dataDir = process.env["PLUGIN_DATA"];
- if (typeof dataDir !== "string") return null;
- try {
- const value = JSON.parse(readFileSync(join(dataDir, "spawn-breaker", `${sessionId}.json`), "utf8")) as {
- reason?: unknown;
- };
- return typeof value.reason === "string" ? value.reason : "capacity limit";
- } catch {
- return null;
- }
-}
-
function fanOutLimit(): number {
const raw = process.env["OMO_SPAWN_FANOUT_LIMIT"];
if (raw === undefined) return DEFAULT_FANOUT_LIMIT;
@@ -289,43 +272,9 @@ function reviewSpawnLimit(): number {
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_REVIEW_SPAWN_LIMIT;
}
-function isNonEmptyFile(path: string): boolean {
- try {
- return existsSync(path) && statSync(path).size > 0;
- } catch (error) {
- if (error instanceof Error) return false;
- throw error;
- }
-}
-
-function readCount(counterPath: string): number {
- try {
- const parsed = JSON.parse(readFileSync(counterPath, "utf8")) as Record<string, unknown>;
- return typeof parsed["count"] === "number" && parsed["count"] >= 0 ? parsed["count"] : 0;
- } catch (error) {
- if (error instanceof Error) return 0;
- throw error;
- }
-}
-
-function readCounts(counterPath: string): Record<string, number> {
- try {
- const parsed: unknown = JSON.parse(readFileSync(counterPath, "utf8"));
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
- const counts: Record<string, number> = {};
- for (const [key, value] of Object.entries(parsed)) {
- if (typeof value === "number" && value >= 0) counts[key] = value;
- }
- return counts;
- } catch (error) {
- if (error instanceof Error) return {};
- throw error;
- }
-}
-
-function readPlan(goalsPath: string): UlwLoopPlan | null {
+function readPlan(repoRoot: string, sessionId: string): UlwLoopPlan | null {
try {
- return JSON.parse(readFileSync(goalsPath, "utf8")) as UlwLoopPlan;
+ return readUlwLoopPlanSync(repoRoot, { sessionId });
} catch (error) {
if (error instanceof Error) return null;
throw error;
diff --git a/plugins/omo/components/ulw-loop/src/state-lock.ts b/plugins/omo/components/ulw-loop/src/state-lock.ts
index 8b5b914e..30adea3e 100644
--- a/plugins/omo/components/ulw-loop/src/state-lock.ts
+++ b/plugins/omo/components/ulw-loop/src/state-lock.ts
@@ -1,120 +1,159 @@
import { randomUUID } from "node:crypto";
-import { closeSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeSync } from "node:fs";
+import { closeSync, ftruncateSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeSync } from "node:fs";
import { dirname } from "node:path";
-import { setTimeout as sleep } from "node:timers/promises";
-
import { UlwLoopError } from "./types.js";
-// Cross-process exclusive lock for one ulw-loop state directory. Every CLI
-// invocation is its own process, so the in-process promise chain in plan-io
-// serializes nothing across them; this file-level lock is what makes the
-// read-modify-write of goals.json (and the counters next to it) atomic.
-//
-// Protocol: the lock is a file created with O_EXCL whose body records the
-// owner (pid + a per-acquisition token). A waiter reclaims it only when the
-// owner is provably gone (pid dead) or the body never became a record within
-// `staleMs` (a creator that died mid-write); a live owner is never reclaimed by
-// age alone, because overlapping two bodies is exactly the lost update this lock
-// exists to prevent. Waiters back off and fail closed at `timeoutMs`. Release
-// unlinks only a lock that still carries the releaser's own token.
-
+// O_EXCL establishes ownership. Async holders keep the fd open and refresh a
+// lease through that fd, never through the pathname: a reclaimed inode is invisible.
+// Sync/legacy holders are lease-less and only dead pids retire their records.
+// Expiry permits overlapping bodies; immutable revision publication fences them.
+// Reclaim's reread/unlink is not atomic. On Windows an open inode may not unlink:
+// treat that refusal as a live owner and fail closed. Release checks its token.
export const ULW_LOOP_LOCK_TIMEOUT_CODE = "ULW_LOOP_LOCK_TIMEOUT";
-
+export interface StateLockClock {
+ readonly now: () => number;
+ readonly schedule: (fn: () => void, ms: number) => { unref(): void; cancel(): void };
+}
export interface StateLockOptions {
readonly timeoutMs?: number;
readonly staleMs?: number;
+ readonly leaseMs?: number;
+ readonly heartbeatMs?: number;
+ readonly clock?: StateLockClock;
}
-
interface LockRecord {
readonly pid: number;
readonly createdAt: string;
readonly token: string;
+ leaseUntil?: number;
+}
+interface Holder {
+ readonly fd: number;
+ readonly record: LockRecord;
}
-
interface LockSnapshot {
readonly raw: string;
readonly record: LockRecord | null;
readonly ageMs: number;
}
-
-type AttemptOutcome = { readonly kind: "acquired"; readonly token: string } | { readonly kind: "retry" | "wait" };
-
+type AttemptOutcome = { readonly kind: "acquired"; readonly holder: Holder } | { readonly kind: "retry" | "wait" };
const DEFAULT_TIMEOUT_MS = 10_000;
const DEFAULT_STALE_MS = 60_000;
-const MIN_DELAY_MS = 5;
-const MAX_DELAY_MS = 100;
+const DEFAULT_LEASE_MS = 30_000;
const SLEEP_CELL = new Int32Array(new SharedArrayBuffer(4));
+const systemClock: StateLockClock = {
+ now: Date.now,
+ schedule(fn, ms) {
+ const timer = setTimeout(fn, ms);
+ return {
+ unref: () => {
+ timer.unref();
+ },
+ cancel: () => clearTimeout(timer),
+ };
+ },
+};
export async function withStateLock<T>(
lockPath: string,
- fn: () => Promise<T>,
+ fn: (token: string) => Promise<T>,
options: StateLockOptions = {},
): Promise<T> {
- const token = await acquireAsync(lockPath, options);
+ const holder = await acquireAsync(lockPath, options);
+ const clock = options.clock ?? systemClock;
+ let timer: ReturnType<StateLockClock["schedule"]> | undefined;
+ let heartbeatError: unknown;
+ const beat = () => {
+ try {
+ holder.record.leaseUntil = clock.now() + (options.leaseMs ?? DEFAULT_LEASE_MS);
+ writeRecord(holder);
+ schedule();
+ } catch (error) {
+ heartbeatError = error;
+ }
+ };
+ const schedule = () => {
+ if (options.heartbeatMs === 0) return;
+ timer = clock.schedule(beat, options.heartbeatMs ?? (options.leaseMs ?? DEFAULT_LEASE_MS) / 3);
+ timer.unref();
+ };
+ schedule();
try {
- return await fn();
+ const result = await fn(holder.record.token);
+ if (heartbeatError !== undefined) throw heartbeatError;
+ return result;
} finally {
- release(lockPath, token);
+ timer?.cancel();
+ closeSync(holder.fd);
+ release(lockPath, holder.record.token);
}
}
-
export function withStateLockSync<T>(lockPath: string, fn: () => T, options: StateLockOptions = {}): T {
- const token = acquireSync(lockPath, options);
+ const holder = acquireSync(lockPath, options);
try {
return fn();
} finally {
- release(lockPath, token);
+ closeSync(holder.fd);
+ release(lockPath, holder.record.token);
}
}
-
export function isStateLockTimeout(error: unknown): error is UlwLoopError {
return error instanceof UlwLoopError && error.code === ULW_LOOP_LOCK_TIMEOUT_CODE;
}
-
-async function acquireAsync(lockPath: string, options: StateLockOptions): Promise<string> {
- const deadline = Date.now() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
- const staleMs = options.staleMs ?? DEFAULT_STALE_MS;
+async function acquireAsync(lockPath: string, options: StateLockOptions): Promise<Holder> {
+ const clock = options.clock ?? systemClock;
+ const deadline = clock.now() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
mkdirSync(dirname(lockPath), { recursive: true });
for (let attempt = 0; ; ) {
- const outcome = attemptOnce(lockPath, staleMs);
- if (outcome.kind === "acquired") return outcome.token;
+ const outcome = attemptOnce(lockPath, options, clock.now(), options.leaseMs ?? DEFAULT_LEASE_MS);
+ if (outcome.kind === "acquired") return outcome.holder;
if (outcome.kind === "retry") continue;
- if (Date.now() >= deadline) throw lockTimeout(lockPath, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
- await sleep(backoffMs(attempt));
+ if (clock.now() >= deadline) throw lockTimeout(lockPath, options);
+ await new Promise<void>((resolve) => clock.schedule(resolve, backoffMs(attempt)));
attempt += 1;
}
}
-
-function acquireSync(lockPath: string, options: StateLockOptions): string {
+function acquireSync(lockPath: string, options: StateLockOptions): Holder {
const deadline = Date.now() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
- const staleMs = options.staleMs ?? DEFAULT_STALE_MS;
mkdirSync(dirname(lockPath), { recursive: true });
for (let attempt = 0; ; ) {
- const outcome = attemptOnce(lockPath, staleMs);
- if (outcome.kind === "acquired") return outcome.token;
+ const outcome = attemptOnce(lockPath, options, Date.now());
+ if (outcome.kind === "acquired") return outcome.holder;
if (outcome.kind === "retry") continue;
- if (Date.now() >= deadline) throw lockTimeout(lockPath, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
+ if (Date.now() >= deadline) throw lockTimeout(lockPath, options);
Atomics.wait(SLEEP_CELL, 0, 0, backoffMs(attempt));
attempt += 1;
}
}
-
-// EINTR surfaces raw from macOS fs syscalls under some runtimes; it is a retry, never a verdict.
-function attemptOnce(lockPath: string, staleMs: number): AttemptOutcome {
+function attemptOnce(lockPath: string, options: StateLockOptions, now: number, leaseMs?: number): AttemptOutcome {
try {
- const token = tryCreate(lockPath);
- if (token !== null) return { kind: "acquired", token };
- const snapshot = readSnapshot(lockPath);
+ const holder = tryCreate(lockPath, now, leaseMs);
+ if (holder !== null) return { kind: "acquired", holder };
+ const snapshot = readSnapshot(lockPath, now);
if (snapshot === null) return { kind: "retry" };
- if (isStale(snapshot, staleMs) && reclaim(lockPath, snapshot.raw)) return { kind: "retry" };
+ const record = snapshot.record;
+ const stale =
+ record === null
+ ? snapshot.ageMs > (options.staleMs ?? DEFAULT_STALE_MS)
+ : !isProcessAlive(record.pid) || (record.leaseUntil !== undefined && now > record.leaseUntil);
+ if (stale && reclaim(lockPath, snapshot.raw)) return { kind: "retry" };
return { kind: "wait" };
} catch (error) {
if (hasCode(error, "EINTR")) return { kind: "wait" };
throw error;
}
}
-
-function tryCreate(lockPath: string): string | null {
+function writeRecord(holder: Holder): void {
+ const buf = Buffer.from(JSON.stringify(holder.record));
+ ftruncateSync(holder.fd, 0);
+ let offset = 0;
+ while (offset < buf.length) {
+ const written = writeSync(holder.fd, buf, offset, buf.length - offset, offset);
+ if (written === 0) throw new Error("State lock write made no progress.");
+ offset += written;
+ }
+}
+function tryCreate(lockPath: string, now: number, leaseMs?: number): Holder | null {
let fd: number;
try {
fd = openSync(lockPath, "wx");
@@ -122,60 +161,54 @@ function tryCreate(lockPath: string): string | null {
if (hasCode(error, "EEXIST")) return null;
throw error;
}
- const record: LockRecord = { pid: process.pid, createdAt: new Date().toISOString(), token: randomUUID() };
+ const record: LockRecord = {
+ pid: process.pid,
+ createdAt: new Date(now).toISOString(),
+ token: randomUUID(),
+ ...(leaseMs === undefined ? {} : { leaseUntil: now + leaseMs }),
+ };
+ const holder = { fd, record };
try {
- writeSync(fd, JSON.stringify(record));
+ writeRecord(holder);
} catch (error) {
closeSync(fd);
- // A failed write (e.g. EINTR) must not leave a partial lock the owner never recorded;
- // otherwise later readers see a young ownerless lock and only age can retire it.
try {
unlinkSync(lockPath);
- } catch {
- // another process already reclaimed the partial file; leave it alone
+ } catch (cleanup) {
+ if (!hasCode(cleanup, "ENOENT")) throw cleanup;
}
throw error;
}
- closeSync(fd);
- return record.token;
+ return holder;
}
-
-function readSnapshot(lockPath: string): LockSnapshot | null {
+function readSnapshot(lockPath: string, now: number): LockSnapshot | null {
try {
const raw = readFileSync(lockPath, "utf8");
- const ageMs = Date.now() - statSync(lockPath).mtimeMs;
- return { raw, record: parseRecord(raw), ageMs };
+ return { raw, record: parseRecord(raw), ageMs: now - statSync(lockPath).mtimeMs };
} catch (error) {
if (hasCode(error, "ENOENT")) return null;
throw error;
}
}
-
function parseRecord(raw: string): LockRecord | null {
try {
- const parsed: unknown = JSON.parse(raw);
- if (typeof parsed !== "object" || parsed === null) return null;
- const record = parsed as Record<string, unknown>;
- const pid = record["pid"];
- const createdAt = record["createdAt"];
- const token = record["token"];
- if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0 || typeof createdAt !== "string") return null;
- if (typeof token !== "string" || token.length === 0) return null;
- return { pid, createdAt, token };
+ const record: unknown = JSON.parse(raw);
+ if (typeof record !== "object" || record === null) return null;
+ if (!("pid" in record) || typeof record.pid !== "number" || !Number.isInteger(record.pid) || record.pid <= 0)
+ return null;
+ if (!("createdAt" in record) || typeof record.createdAt !== "string") return null;
+ if (!("token" in record) || typeof record.token !== "string" || record.token.length === 0) return null;
+ return {
+ pid: record.pid,
+ createdAt: record.createdAt,
+ token: record.token,
+ ...("leaseUntil" in record && typeof record.leaseUntil === "number" ? { leaseUntil: record.leaseUntil } : {}),
+ };
} catch (error) {
if (error instanceof SyntaxError) return null;
throw error;
}
}
-
-// A body that is not a record is a lock mid-write (or a foreign/legacy file); only
-// age retires it. A parsable record is stale only when its owner is dead: a live
-// owner running past staleMs is slow, not gone, and the waiter fails closed instead.
-function isStale(snapshot: LockSnapshot, staleMs: number): boolean {
- if (snapshot.record === null) return snapshot.ageMs > staleMs;
- return !isProcessAlive(snapshot.record.pid);
-}
-
function isProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0);
@@ -186,54 +219,39 @@ function isProcessAlive(pid: number): boolean {
throw error;
}
}
-
-// Re-read right before unlinking so a lock that changed hands since the stale
-// verdict (a sibling waiter reclaimed and re-acquired it) is left alone.
function reclaim(lockPath: string, expectedRaw: string): boolean {
- const current = readSnapshot(lockPath);
+ const current = readSnapshot(lockPath, Date.now());
if (current === null) return true;
if (current.raw !== expectedRaw) return false;
try {
unlinkSync(lockPath);
} catch (error) {
+ if (hasCode(error, "EPERM") || hasCode(error, "EACCES")) return false;
if (!hasCode(error, "ENOENT")) throw error;
}
return true;
}
-
-// Only the acquisition that wrote this token may unlink: if the file now carries
-// another token, a waiter has legitimately taken over and its lock must stand.
function release(lockPath: string, token: string): void {
- const current = readSnapshot(lockPath);
- if (current === null || current.record?.token !== token) return;
+ if (readSnapshot(lockPath, Date.now())?.record?.token !== token) return;
try {
unlinkSync(lockPath);
} catch (error) {
if (!hasCode(error, "ENOENT")) throw error;
}
}
-
function backoffMs(attempt: number): number {
- const exponential = Math.min(MAX_DELAY_MS, MIN_DELAY_MS * 2 ** attempt);
- return exponential + Math.random() * MIN_DELAY_MS;
+ return Math.min(100, 5 * 2 ** attempt) + Math.random() * 5;
}
-
-function lockTimeout(lockPath: string, timeoutMs: number): UlwLoopError {
- const holder = readSnapshot(lockPath)?.record;
- const owner = holder === undefined || holder === null ? "another process" : `pid ${holder.pid}`;
+function lockTimeout(lockPath: string, options: StateLockOptions): UlwLoopError {
+ const holder = readSnapshot(lockPath, Date.now())?.record;
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ const owner = holder == null ? "another process" : `pid ${holder.pid}`;
return new UlwLoopError(
- `ulw-loop state lock ${lockPath} is held by ${owner} for more than ${timeoutMs}ms; retry once that process finishes, or delete the lock file if that process is gone.`,
+ `ulw-loop state lock ${lockPath} is held by ${owner} for more than ${timeoutMs}ms. The lock owner is still alive. If a JS eval kernel was interrupted while writing, wait for its lease to expire (${options.leaseMs ?? DEFAULT_LEASE_MS} ms) or restart the owning senpi process; never delete a lock owned by a live process.`,
ULW_LOOP_LOCK_TIMEOUT_CODE,
- {
- details: {
- lockPath,
- timeoutMs,
- ...(holder === undefined || holder === null ? {} : { holderPid: holder.pid }),
- },
- },
+ { details: { lockPath, timeoutMs, ...(holder == null ? {} : { holderPid: holder.pid }) } },
);
}
-
function hasCode(error: unknown, code: string): boolean {
return error instanceof Error && "code" in error && error.code === code;
}
diff --git a/plugins/omo/components/ulw-loop/src/status-next-actions.ts b/plugins/omo/components/ulw-loop/src/status-next-actions.ts
index d720c75f..432d895c 100644
--- a/plugins/omo/components/ulw-loop/src/status-next-actions.ts
+++ b/plugins/omo/components/ulw-loop/src/status-next-actions.ts
@@ -1,36 +1,45 @@
import { hasAllCriteriaPass, isFinalRunCompletionCandidate } from "./goal-status.js";
-import { ULW_LOOP_CREATE_GOALS_COMMAND } from "./plan-missing-recovery.js";
+import { createGoalsAction } from "./plan-missing-recovery.js";
+import type { UlwLoopToolkitSurface } from "./surface.js";
import type { UlwLoopItem, UlwLoopPlan } from "./types.js";
/**
- * `status --json` is the one call every agent already makes between steps, so it is
+ * Status is the one call every agent already makes between steps, so it is
* also the cheapest place to answer "what now?" without a second round trip.
*/
-export function statusNextActions(plan: UlwLoopPlan): readonly string[] {
+export function statusNextActions(plan: UlwLoopPlan, surface: UlwLoopToolkitSurface = "lazycodex"): readonly string[] {
const actions: string[] = [];
const active = plan.goals.find((goal) => goal.id === plan.activeGoalId);
- if (plan.goals.length === 0) actions.push(`No goals yet: bootstrap with \`${ULW_LOOP_CREATE_GOALS_COMMAND}\`.`);
- else if (active !== undefined) actions.push(...activeGoalActions(plan, active));
+ if (plan.goals.length === 0) actions.push(`No goals yet: bootstrap with \`${createGoalsAction(surface)}\`.`);
+ else if (active !== undefined) actions.push(...activeGoalActions(plan, active, surface));
for (const goal of plan.goals.filter((candidate) => candidate.status === "review_blocked"))
actions.push(
- `${goal.id} is review_blocked: capture the reviewer verdict with \`omo-agent-toolkit ulw-loop record-review-blockers --goal-id ${goal.id} --title "<title>" --objective "<objective>" --evidence "<verdict>" --codex-goal-json '<get_goal json>'\`.`,
+ surface === "omo-senpi"
+ ? `${goal.id} is review_blocked: capture the reviewer verdict with \`agentToolkit.recordReviewBlockers({ goalId: "${goal.id}", title: "<title>", objective: "<objective>", evidence: "<verdict>" })\`.`
+ : `${goal.id} is review_blocked: capture the reviewer verdict with \`omo-agent-toolkit ulw-loop record-review-blockers --goal-id ${goal.id} --title "<title>" --objective "<objective>" --evidence "<verdict>" --codex-goal-json '<get_goal json>'\`.`,
);
if (plan.evidenceLayoutVersion !== 2 || active === undefined)
actions.push("plan is evidence-layout v1; artifacts go under .omo/evidence/");
return actions;
}
-function activeGoalActions(plan: UlwLoopPlan, active: UlwLoopItem): readonly string[] {
+function activeGoalActions(plan: UlwLoopPlan, active: UlwLoopItem, surface: UlwLoopToolkitSurface): readonly string[] {
const unresolved = active.successCriteria.filter((criterion) => criterion.status !== "pass");
if (unresolved.length > 0)
return [
- `${active.id} has ${unresolved.length} unresolved criterion(s) (${unresolved.map((criterion) => criterion.id).join(", ")}): record proof with \`omo-agent-toolkit ulw-loop record-evidence --goal-id ${active.id} --criterion-id <id> --status pass --evidence "<observable proof>"\`.`,
+ surface === "omo-senpi"
+ ? `${active.id} has ${unresolved.length} unresolved criterion(s) (${unresolved.map((criterion) => criterion.id).join(", ")}): record proof with \`agentToolkit.recordEvidence({ goalId: "${active.id}", criterionId: "<id>", status: "pass", evidence: "<observable proof>" })\`.`
+ : `${active.id} has ${unresolved.length} unresolved criterion(s) (${unresolved.map((criterion) => criterion.id).join(", ")}): record proof with \`omo-agent-toolkit ulw-loop record-evidence --goal-id ${active.id} --criterion-id <id> --status pass --evidence "<observable proof>"\`.`,
];
if (hasAllCriteriaPass(active) && isFinalRunCompletionCandidate(plan, active))
return [
- `${active.id} passes every criterion and is the final story: update_goal complete, then checkpoint --print-template to build the final quality gate. Use status --json's currentAttemptDir for all quality-gate artifacts.`,
+ surface === "omo-senpi"
+ ? `${active.id} passes every criterion and is the final story: complete the driver goal, then call \`agentToolkit.checkpoint({ goalId: "${active.id}", printTemplate: true })\` to build the final quality gate. Use status().result.currentAttemptDir for all quality-gate artifacts.`
+ : `${active.id} passes every criterion and is the final story: update_goal complete, then checkpoint --print-template to build the final quality gate. Use status --json's currentAttemptDir for all quality-gate artifacts.`,
];
return [
- `${active.id} passes every criterion: close it with \`omo-agent-toolkit ulw-loop checkpoint --goal-id ${active.id} --status complete --evidence "<proof>" --codex-goal-json '<get_goal json>'\`. Put quality-gate artifacts under the currentAttemptDir shown by status --json.`,
+ surface === "omo-senpi"
+ ? `${active.id} passes every criterion: close it with \`agentToolkit.checkpoint({ goalId: "${active.id}", status: "complete", evidence: "<proof>" })\`. Put quality-gate artifacts under status().result.currentAttemptDir.`
+ : `${active.id} passes every criterion: close it with \`omo-agent-toolkit ulw-loop checkpoint --goal-id ${active.id} --status complete --evidence "<proof>" --codex-goal-json '<get_goal json>'\`. Put quality-gate artifacts under the currentAttemptDir shown by status --json.`,
];
}
diff --git a/plugins/omo/components/ulw-loop/src/steering-batch.ts b/plugins/omo/components/ulw-loop/src/steering-batch.ts
index 1711da36..16aaca64 100644
--- a/plugins/omo/components/ulw-loop/src/steering-batch.ts
+++ b/plugins/omo/components/ulw-loop/src/steering-batch.ts
@@ -1,6 +1,7 @@
// 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 { commit } from "./plan-commit.js";
+import { findAcceptedSteeringLedgerEntry, readUlwLoopPlan, withUlwLoopMutationLock } 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";
@@ -43,17 +44,16 @@ export async function steerUlwLoopBatch(
const failed = prepared.results.find((item) => !item.accepted);
if (failed !== undefined) {
const entry = rejectedLedgerEntry(prepared.results);
- await appendLedger(repoRoot, entry, scope);
+ await commit(repoRoot, scope, { plan, entries: [entry] });
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);
+ await commit(repoRoot, scope, { plan: next, entries: batchEntry === null ? entries : [...entries, batchEntry] });
}
return { plan: next, accepted: true, results: prepared.results, rejectedReasons: [] };
});
diff --git a/plugins/omo/components/ulw-loop/src/steering.ts b/plugins/omo/components/ulw-loop/src/steering.ts
index 7b1e3a47..0734ce8d 100644
--- a/plugins/omo/components/ulw-loop/src/steering.ts
+++ b/plugins/omo/components/ulw-loop/src/steering.ts
@@ -1,7 +1,8 @@
// biome-ignore-all format: compact steering module must stay below the 240 pure-LOC budget
import { isUlwLoopDone } from "./goal-status.js";
import type { UlwLoopScope } from "./paths.js";
-import { appendLedger, findAcceptedSteeringLedgerEntry, readUlwLoopPlan, withUlwLoopMutationLock, writePlan } from "./plan-io.js";
+import { commit } from "./plan-commit.js";
+import { findAcceptedSteeringLedgerEntry, readUlwLoopPlan, withUlwLoopMutationLock } from "./plan-io.js";
import { makeGoal, reviseCriterion, reviseWording, splitOrBlock } from "./steering-mutations.js";
import { buildSteeringPlanSnapshot, changedGoalIdsBetween } from "./steering-snapshot.js";
import type {
@@ -209,9 +210,9 @@ export async function steerUlwLoop(repoRoot: string, proposal: UlwLoopSteeringPr
}
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);
+ const entries = [ledgerEntry(proposal, finalAudit, at)];
+ if (batchEntry !== null) entries.push(batchEntry);
+ await commit(repoRoot, scope, { plan: next, entries });
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.ts
index 80ea224e..366dc4a0 100644
--- a/plugins/omo/components/ulw-loop/src/stop-resume-hook.ts
+++ b/plugins/omo/components/ulw-loop/src/stop-resume-hook.ts
@@ -1,7 +1,9 @@
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { isAbsolute, join, resolve, sep } from "node:path";
+import { readLedgerAt } from "./ledger.js";
import { normalizeUlwLoopSessionId, ulwLoopDir, ulwLoopStateLockPath } from "./paths.js";
+import { readUlwLoopPlanSync } from "./plan-io.js";
import { isStateLockTimeout, withStateLockSync } from "./state-lock.js";
import type { UlwLoopItem, UlwLoopPlan } from "./types.js";
@@ -37,7 +39,7 @@ export function runStopResumeHook(input: unknown): string {
if (boulderContinuationWillFire(payload.cwd, payload.session_id)) return "";
const scope = { sessionId: payload.session_id } as const;
const stateDir = ulwLoopDir(payload.cwd, scope);
- const plan = readPlan(join(stateDir, "goals.json"));
+ const plan = readPlan(payload.cwd, payload.session_id);
if (plan === null || plan.aggregateCompletion?.status === "complete") return "";
const goal = resumableGoal(plan);
if (goal === undefined) return "";
@@ -81,11 +83,10 @@ function consumeResumeBudgetLocked(lockPath: string, stateDir: string, goalId: s
}
}
-// 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.
+// Hook budget counters are exempt from plan/audit commits. Count reconciled
+// entries, not cache lines: a writer dying after link still made progress.
function consumeResumeBudget(stateDir: string, goalId: string): boolean {
- const ledgerLineCount = countLedgerLines(join(stateDir, "ledger.jsonl"));
+ const ledgerLineCount = readLedgerAt(stateDir).length;
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
@@ -119,24 +120,15 @@ function renderResumeDirective(plan: UlwLoopPlan, goal: UlwLoopItem, sessionId:
].join("\n");
}
-function readPlan(goalsPath: string): UlwLoopPlan | null {
+function readPlan(repoRoot: string, sessionId: string): UlwLoopPlan | null {
try {
- return JSON.parse(readFileSync(goalsPath, "utf8")) as UlwLoopPlan;
+ return readUlwLoopPlanSync(repoRoot, { sessionId });
} catch (error) {
if (error instanceof Error) return null;
throw error;
}
}
-function countLedgerLines(ledgerPath: string): number {
- try {
- return readFileSync(ledgerPath, "utf8").split("\n").filter(Boolean).length;
- } catch (error) {
- if (error instanceof Error) return 0;
- throw error;
- }
-}
-
function readCounter(counterPath: string): { count: number; ledgerLineCount: number } | null {
try {
if (!existsSync(counterPath)) return null;
diff --git a/plugins/omo/components/ulw-loop/test/fixtures/barrier.ts b/plugins/omo/components/ulw-loop/test/fixtures/barrier.ts
new file mode 100644
index 00000000..9381363a
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/test/fixtures/barrier.ts
@@ -0,0 +1,13 @@
+export function barrier() {
+ let resolve: () => void = () => {
+ throw new Error("barrier not initialized");
+ };
+ const promise = new Promise<void>((done, reject) => {
+ const timeout = setTimeout(() => reject(new Error("barrier timed out")), 5_000);
+ resolve = () => {
+ clearTimeout(timeout);
+ done();
+ };
+ });
+ return { promise, resolve };
+}
diff --git a/plugins/omo/components/ulw-loop/test/fixtures/commit-child.ts b/plugins/omo/components/ulw-loop/test/fixtures/commit-child.ts
new file mode 100644
index 00000000..e474f967
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/test/fixtures/commit-child.ts
@@ -0,0 +1,65 @@
+import { fork } from "node:child_process";
+import { join } from "node:path";
+
+const running = new Set<ReturnType<typeof childWriter>>();
+export async function cleanupWriters(): Promise<void> {
+ await Promise.all(
+ [...running].map(async (writer) => {
+ writer.child.kill("SIGKILL");
+ await writer.exited;
+ }),
+ );
+}
+export function childWriter(rootPath: string, mode: string, now = Date.now()) {
+ const child = fork(join(import.meta.dirname, "commit-writer.ts"), [rootPath, mode, String(now)], {
+ execPath: "bun",
+ execArgv: [],
+ stdio: ["ignore", "inherit", "inherit", "ipc"],
+ });
+ const pending = new Map<string, { resolve: () => void; reject: (error: Error) => void }>();
+ const seen = new Set<string>();
+ child.on("message", (message) => {
+ if (typeof message !== "string") return;
+ seen.add(message);
+ pending.get(message)?.resolve();
+ });
+ const exited = new Promise<number | null>((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ child.kill("SIGKILL");
+ reject(new Error("child exit timed out"));
+ }, 15_000);
+ child.once("error", (error) => {
+ clearTimeout(timeout);
+ reject(error);
+ });
+ child.once("exit", (code) => {
+ clearTimeout(timeout);
+ running.delete(writer);
+ resolve(code);
+ for (const [name, waiter] of pending)
+ if (!seen.has(name)) waiter.reject(new Error(`child exited before ${name}: ${code}`));
+ });
+ });
+ const writer = {
+ child,
+ exited,
+ wait(name: string) {
+ if (seen.has(name)) return Promise.resolve();
+ return new Promise<void>((resolve, reject) => {
+ const timeout = setTimeout(() => reject(new Error(`IPC timeout: ${name}`)), 10_000);
+ pending.set(name, {
+ resolve: () => {
+ clearTimeout(timeout);
+ resolve();
+ },
+ reject: (error) => {
+ clearTimeout(timeout);
+ reject(error);
+ },
+ });
+ });
+ },
+ };
+ running.add(writer);
+ return writer;
+}
diff --git a/plugins/omo/components/ulw-loop/test/fixtures/commit-cli-qa.mjs b/plugins/omo/components/ulw-loop/test/fixtures/commit-cli-qa.mjs
new file mode 100644
index 00000000..29125c34
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/test/fixtures/commit-cli-qa.mjs
@@ -0,0 +1,76 @@
+import assert from "node:assert/strict";
+import { fork, spawnSync } from "node:child_process";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { withCommitHooks } from "../../dist/plan-commit.js";
+import { commit } from "../../dist/plan-commit.js";
+import { readLedger, readUlwLoopPlan, withUlwLoopMutationLock } from "../../dist/plan-io.js";
+const cli = resolve("dist/cli.js");
+const root = mkdtempSync(join(tmpdir(), "ulw-cli-qa-"));
+const legacyRoot = mkdtempSync(join(tmpdir(), "ulw-legacy-qa-"));
+const scope = { sessionId: "commit-log" };
+const dir = join(root, ".omo", "ulw-loop", scope.sessionId);
+const json = (path) => JSON.parse(readFileSync(path, "utf8"));
+function run(cwd, ...args) {
+ const argv = [...args, "--session-id", scope.sessionId, "--json"];
+ const result = spawnSync(process.execPath, [cli, ...argv], { cwd, encoding: "utf8", timeout: 15_000, env: { ...process.env, PI_SESSION_ID: "", CODEX_SESSION_ID: "", CODEX_THREAD_ID: "", OMO_ULW_LOOP_SESSION_ID: "" } });
+ console.log(`command=${process.execPath} ${cli} ${argv.map((arg) => JSON.stringify(arg)).join(" ")} cwd=${cwd}\n${result.stdout}${result.stderr}\nexit=${result.status}`);
+ assert.equal(result.status, 0);
+ return JSON.parse(result.stdout);
+}
+try {
+ run(root, "create-goals", "--brief", "Build durable state");
+ const original = json(join(dir, "goals.json"));
+ assert.equal(run(root, "status").plan.revision, 1);
+ rmSync(join(dir, "goals.json"));
+ assert.equal(run(root, "status").plan.revision, 1);
+ assert.equal(existsSync(join(dir, "goals.json")), false);
+ const goal = original.goals[0];
+ run(root, "record-evidence", "--goal-id", goal.id, "--criterion-id", goal.successCriteria[0].id, "--status", "pass", "--evidence", "Observed real CLI publication");
+ assert.equal(json(join(dir, "revisions", "00000002.json")).ledger[0].kind, "evidence_captured");
+ assert.equal(json(join(dir, "goals.json")).revision, 2);
+ console.log("QA=PASS log-only status is read-only; CLI evidence repairs and commits plan plus audit");
+ const clock = { now: () => 0, schedule: () => { throw new Error("Unexpected scheduler use"); } };
+ await assert.rejects(withCommitHooks({ beforeCommit: async () => {
+ const child = fork(resolve("test/fixtures/commit-writer.ts"), [root, "write", "201"], { execPath: "bun", execArgv: [], stdio: ["ignore", "inherit", "inherit", "ipc"] });
+ const exit = await new Promise((done, reject) => {
+ const timeout = setTimeout(() => { child.kill("SIGKILL"); reject(new Error("writer B timed out")); }, 10_000);
+ child.once("error", (error) => { clearTimeout(timeout); reject(error); });
+ child.once("exit", (code) => { clearTimeout(timeout); done(code); });
+ });
+ assert.equal(exit, 0);
+ } }, () => withUlwLoopMutationLock(root, scope, async () => {
+ const plan = await readUlwLoopPlan(root, scope);
+ plan.brief = "zombie";
+ await commit(root, scope, { plan, entries: [{ at: "A", kind: "goal_added", message: "A" }] });
+ }, { clock, leaseMs: 200, heartbeatMs: 0 })), { code: "ULW_LOOP_LOCK_LOST" });
+ assert.equal(readLedger(root, scope).at(-1).message, "B");
+ assert.equal(readLedger(root, scope).some((entry) => entry.message === "A"), false);
+ assert.deepEqual(readdirSync(join(dir, "revisions")), ["00000001.json", "00000002.json", "00000003.json"]);
+ console.log(`QA=PASS real fork zombie fencing ULW_LOOP_LOCK_LOST record=${JSON.stringify(json(join(dir, "revisions", "00000003.json")))}`);
+ run(root, "create-goals", "--brief", "Replacement brief", "--force");
+ const recreated = json(join(dir, "goals.json"));
+ assert.equal(recreated.revision, 4);
+ assert.equal(recreated.ledgerResetRevision, 4);
+ assert.equal(readFileSync(join(dir, "brief.md"), "utf8"), recreated.brief);
+ assert.equal(readLedger(root, scope).length, 1);
+ console.log("QA=PASS force recreation retains revision history and resets the logical audit");
+ const legacyDir = join(legacyRoot, ".omo", "ulw-loop", scope.sessionId);
+ mkdirSync(legacyDir, { recursive: true });
+ delete original.revision; delete original.brief; delete original.ledgerResetRevision;
+ writeFileSync(join(legacyDir, "goals.json"), JSON.stringify(original));
+ writeFileSync(join(legacyDir, "brief.md"), "Legacy brief\n");
+ writeFileSync(join(legacyDir, "ledger.jsonl"), '{"at":"legacy","kind":"goal_started"}\n');
+ assert.equal(run(legacyRoot, "status").plan.revision ?? 0, 0);
+ assert.equal(existsSync(join(legacyDir, "revisions")), false);
+ run(legacyRoot, "add-goal", "--title", "Extra", "--objective", "Verify legacy hydration");
+ assert.equal(json(join(legacyDir, "revisions", "00000001.json")).plan.brief, "Legacy brief\n");
+ assert.equal(readLedger(legacyRoot, scope)[0].id, "legacy-1");
+ console.log("QA=PASS legacy CLI status and first commit preserve brief and legacy audit");
+} finally {
+ rmSync(root, { recursive: true, force: true });
+ rmSync(legacyRoot, { recursive: true, force: true });
+ assert.equal(existsSync(root) || existsSync(legacyRoot), false);
+ console.log(`cleanup=REMOVED ${root} ${legacyRoot}; real home directories not accessed by this driver`);
+}
diff --git a/plugins/omo/components/ulw-loop/test/fixtures/commit-crash.ts b/plugins/omo/components/ulw-loop/test/fixtures/commit-crash.ts
new file mode 100644
index 00000000..cc90aada
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/test/fixtures/commit-crash.ts
@@ -0,0 +1,23 @@
+import { mkdirSync, writeFileSync } from "node:fs";
+import { rm } from "node:fs/promises";
+import { join } from "node:path";
+import { type UlwLoopScope, ulwLoopDir } from "../../src/paths.js";
+import { createUlwLoopPlan } from "../../src/plan-crud.js";
+
+export async function seedCrash(root: string, scope: UlwLoopScope, first: boolean) {
+ const dir = ulwLoopDir(root, scope);
+ const plan = await createUlwLoopPlan(root, { brief: "original" }, scope);
+ const next = { ...plan, revision: (plan.revision ?? 0) + 1, brief: "committed\n", codexObjective: "committed" };
+ mkdirSync(join(dir, "revisions"), { recursive: true });
+ writeFileSync(
+ join(dir, "revisions", `${String(next.revision).padStart(8, "0")}.json`),
+ JSON.stringify({
+ version: 1,
+ revision: next.revision,
+ plan: next,
+ ledger: [{ at: "now", kind: "goal_added", revision: next.revision, id: `${next.revision}-0` }],
+ }),
+ );
+ if (first) await rm(join(dir, "goals.json"));
+ return next;
+}
diff --git a/plugins/omo/components/ulw-loop/test/fixtures/commit-mutations.mjs b/plugins/omo/components/ulw-loop/test/fixtures/commit-mutations.mjs
new file mode 100644
index 00000000..296a525a
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/test/fixtures/commit-mutations.mjs
@@ -0,0 +1,58 @@
+// Run only in an isolated remote test checkout. Each mutant is restored before the next.
+import { createHash } from "node:crypto";
+import { readFileSync, writeFileSync } from "node:fs";
+import { spawnSync } from "node:child_process";
+
+function replace(source, before, after) {
+ if (source.split(before).length !== 2) throw new Error(`Mutation anchor is not unique: ${before}`);
+ return source.replace(before, after);
+}
+const publication = '(hooks.getStore()?.link ?? linkSync)(temp, join(dir, "revisions", `${String(next).padStart(8, "0")}.json`));';
+const logTest = "test/plan-commit-log.test.ts";
+const recoveryTest = "test/plan-commit-recovery.test.ts";
+const mutations = [
+ { name: "heartbeat-no-refresh", file: "src/state-lock.ts", test: "test/state-lock.test.ts", pattern: "\\(3\\)", change: (s) => replace(s, "holder.record.leaseUntil = clock.now()", "holder.record.leaseUntil ??= clock.now()") },
+ { name: "heartbeat-by-path", file: "src/state-lock.ts", test: "test/state-lock.test.ts", pattern: "\\(2\\)", change: (s) => 'import { writeFileSync } from "node:fs";\n' + replace(s, "writeRecord(holder);\n\t\t\tschedule();", "writeFileSync(lockPath, JSON.stringify(holder.record));\n\t\t\tschedule();") },
+ { name: "rename-over-goals", file: "src/plan-commit.ts", test: logTest, pattern: "B wins write", change: (s) => replace(s, publication, `if (next === 1) { ${publication} } else { writeFileSync(temp, JSON.stringify(record.plan)); renameSync(temp, join(dir, "goals.json")); }`) },
+ { name: "delete-published-record", file: "src/plan-commit.ts", test: logTest, pattern: "B wins write", change: (s) => replace(s, "await materialize(dir);", 'await materialize(dir);\n if (next > 1) rmSync(join(dir, "revisions", `${String(next).padStart(8, "0")}.json`));') },
+ { name: "next-from-directory", file: "src/plan-commit.ts", test: logTest, pattern: "\\(6\\)", change: (s) => replace(s, "const next = (plan.revision ?? 0) + 1;", "const next = Math.max(plan.revision ?? 0, ...readRecords(dir).map((record) => record.revision)) + 1;") },
+ { name: "no-holder-retry", file: "src/plan-io.ts", test: logTest, pattern: "\\(6\\)", change: (s) => replace(s, "if (attempt !== 0) throw error;", "throw error;") },
+ { name: "no-plan-reconciliation", file: "src/plan-log.ts", test: logTest, pattern: "\\(7a\\)", change: (s) => replace(s, "const latest = readNewestRecord(dir);", "const latest = cached === undefined ? readNewestRecord(dir) : undefined;") },
+ { name: "no-ledger-reconciliation", file: "src/ledger.ts", test: logTest, pattern: "\\(7a\\)", change: (s) => replace(s, "for (const record of readRecords(dir))", "for (const record of [])") },
+ { name: "cache-only-existence", file: "src/plan-log.ts", test: recoveryTest, pattern: "\\(7b\\)", change: (s) => replace(s, 'return existsSync(join(dir, "goals.json")) || logNames(dir).length > 0;', 'return existsSync(join(dir, "goals.json"));') },
+ { name: "in-place-ledger-append", file: "src/plan-commit.ts", test: logTest, pattern: "\\(7c\\)", change: (s) => {
+ const start = s.indexOf("export async function materialize(dir:");
+ if (start < 0) throw new Error("materializer not found");
+ const body = replace(s.slice(start), 'const temp = join(dir, "tmp", `${process.pid}-${randomUUID()}-${name}`);', 'const temp = name === "ledger.jsonl" && readRecords(dir).length > 1 ? join(dir, name) : join(dir, "tmp", `${process.pid}-${randomUUID()}-${name}`);');
+ return 'import { appendFile } from "node:fs/promises";\n' + s.slice(0, start) + replace(body, 'await writeViewFile(temp, content);', 'if (name === "ledger.jsonl" && readRecords(dir).length > 1) await (hooks.getStore()?.writeView ?? appendFile)(temp, content); else await writeViewFile(temp, content);');
+ } },
+ { name: "brief-before-publication", file: "src/plan-crud.ts", test: recoveryTest, pattern: "\\(9\\)", change: (s) => replace(replace(s, 'import { beforePlanMutation, commit }', 'import { beforePlanMutation, commit, writeViewFile }'), "await beforePlanMutation();", 'await beforePlanMutation();\n await writeViewFile(`${repoRoot}/${plan.briefPath}`, plan.brief ?? "");') },
+ { name: "steering-audit-outside-record", file: "src/steering.ts", test: logTest, pattern: "\\(11\\)", change: (s) => replace(s, "await commit(repoRoot, scope, { plan: next, entries });", 'await commit(repoRoot, scope, { plan: next, entries: [] });\n await (await import("node:fs/promises")).appendFile(`${repoRoot}/${next.ledgerPath}`, entries.map((entry) => JSON.stringify(entry)).join("\\n") + "\\n");') },
+ { name: "copy-fallback", file: "src/plan-commit.ts", test: logTest, pattern: "\\(12\\)", change: (s) => 'import { copyFileSync } from "node:fs";\n' + replace(s, publication, `try { ${publication} } catch (error) { if (hasCode(error, "EPERM")) copyFileSync(temp, join(dir, "revisions", \`\${String(next).padStart(8, "0")}.json\`)); else throw error; }`) },
+];
+const digest = (content) => createHash("sha256").update(content).digest("hex");
+let failures = 0;
+for (const mutation of mutations) {
+ const original = readFileSync(mutation.file, "utf8");
+ console.log(`\n## MUTATION ${mutation.name}\nfile=${mutation.file}\nbefore_sha256=${digest(original)}`);
+ try {
+ writeFileSync(mutation.file, mutation.change(original));
+ const args = ["run", "test", "--", mutation.test, "-t", mutation.pattern];
+ console.log(`command=bun ${args.map((arg) => JSON.stringify(arg)).join(" ")}`);
+ const result = spawnSync("bun", args, { encoding: "utf8", timeout: 60_000 });
+ const output = `${result.stdout ?? ""}${result.stderr ?? ""}`;
+ console.log(output);
+ console.log(`mutation_exit=${result.status}`);
+ if (result.status !== 1 || !/[1-9]\d* failed/.test(output.replace(/\x1b\[[0-9;]*m/g, "")) || !output.includes("AssertionError")) {
+ failures += 1;
+ console.log(`PROOF=FAILED ${mutation.name}`);
+ } else console.log(`PROOF=RED ${mutation.name}`);
+ } finally {
+ writeFileSync(mutation.file, original);
+ const restored = readFileSync(mutation.file, "utf8");
+ if (restored !== original) throw new Error(`Failed to restore ${mutation.file}`);
+ console.log(`restored_sha256=${digest(restored)} cleanup=RESTORED`);
+ }
+}
+console.log(`mutation_proofs=${mutations.length} failed_proofs=${failures}`);
+process.exitCode = failures === 0 ? 0 : 1;
diff --git a/plugins/omo/components/ulw-loop/test/fixtures/commit-writer.ts b/plugins/omo/components/ulw-loop/test/fixtures/commit-writer.ts
new file mode 100644
index 00000000..3c8ff4aa
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/test/fixtures/commit-writer.ts
@@ -0,0 +1,65 @@
+import { writeFile } from "node:fs/promises";
+import { commit, withCommitHooks } from "../../src/plan-commit.js";
+import { createUlwLoopPlan } from "../../src/plan-crud.js";
+import { readUlwLoopPlan, withMutationLockOptions, withUlwLoopMutationLock } from "../../src/plan-io.js";
+import { steerUlwLoop } from "../../src/steering.js";
+import { leaseClock } from "./lease-clock.js";
+
+const root = process.argv[2];
+const mode = process.argv[3];
+if (root === undefined) throw new Error("root required");
+const scope = { sessionId: "commit-log" };
+function barrier(name: string): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const timeout = setTimeout(() => reject(new Error(`barrier timed out: ${name}`)), 10_000);
+ process.once("message", () => {
+ clearTimeout(timeout);
+ resolve();
+ });
+ process.send?.(name);
+ });
+}
+let calls = 0;
+await withMutationLockOptions({ clock: leaseClock(Number(process.argv[4])), heartbeatMs: 0, timeoutMs: 0 }, () =>
+ withCommitHooks(
+ {
+ beforeCommit: async () => {
+ calls += 1;
+ if (mode === "mirror" && calls === 1) await barrier("before");
+ },
+ afterCommit: async () => {
+ if (mode === "accepted" || mode === "rejected") await barrier("linked");
+ },
+ writeView: async (path, content) => {
+ if (mode === "partial" && path.endsWith("ledger.jsonl")) {
+ await writeFile(path, content.slice(0, Math.max(1, Math.floor(content.length / 2))));
+ await barrier("partial");
+ }
+ await writeFile(path, content);
+ },
+ },
+ async () => {
+ if (mode === "force") await createUlwLoopPlan(root, { brief: "B\n", force: true }, scope);
+ else if (mode === "accepted" || mode === "rejected")
+ await steerUlwLoop(
+ root,
+ {
+ kind: "annotate_ledger",
+ source: "cli",
+ evidence: mode === "rejected" ? "" : "observed",
+ rationale: "audit",
+ idempotencyKey: "crash-key",
+ },
+ scope,
+ );
+ else
+ await withUlwLoopMutationLock(root, scope, async () => {
+ const plan = await readUlwLoopPlan(root, scope);
+ plan.codexObjective = `${plan.codexObjective}|B`;
+ await commit(root, scope, { plan, entries: [{ at: "B", kind: "goal_added", message: "B" }] });
+ });
+ },
+ ),
+);
+process.send?.("done");
+process.disconnect?.();
diff --git a/plugins/omo/components/ulw-loop/test/fixtures/lease-clock.ts b/plugins/omo/components/ulw-loop/test/fixtures/lease-clock.ts
new file mode 100644
index 00000000..96947784
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/test/fixtures/lease-clock.ts
@@ -0,0 +1,23 @@
+export function leaseClock(initial = 0) {
+ let now = initial;
+ const tasks = new Set<{ at: number; fn: () => void }>();
+ return {
+ now: () => now,
+ schedule(fn: () => void, ms: number) {
+ const task = { at: now + ms, fn };
+ tasks.add(task);
+ return { unref() {}, cancel: () => tasks.delete(task) };
+ },
+ advance(ms: number) {
+ const end = now + ms;
+ for (;;) {
+ const next = [...tasks].filter((task) => task.at <= end).sort((a, b) => a.at - b.at)[0];
+ if (next === undefined) break;
+ now = next.at;
+ tasks.delete(next);
+ next.fn();
+ }
+ now = end;
+ },
+ };
+}
diff --git a/plugins/omo/components/ulw-loop/test/plan-commit-log.test.ts b/plugins/omo/components/ulw-loop/test/plan-commit-log.test.ts
new file mode 100644
index 00000000..c825a001
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/test/plan-commit-log.test.ts
@@ -0,0 +1,252 @@
+import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { ulwLoopDir } from "../src/paths.js";
+import { createUlwLoopPlan } from "../src/plan-crud.js";
+import * as io from "../src/plan-io.js";
+import { childWriter, cleanupWriters } from "./fixtures/commit-child.js";
+import { seedCrash } from "./fixtures/commit-crash.js";
+import { leaseClock } from "./fixtures/lease-clock.js";
+
+let root: string;
+let dir: string;
+const scope = { sessionId: "commit-log" };
+beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), "ulw-commit-"));
+ dir = ulwLoopDir(root, scope);
+});
+afterEach(async () => {
+ await cleanupWriters();
+ await rm(root, { recursive: true, force: true });
+});
+function snapshot() {
+ return Object.fromEntries(
+ ["goals.json", "ledger.jsonl", "brief.md"].map((name) => [
+ name,
+ existsSync(join(dir, name)) ? readFileSync(join(dir, name), "utf8") : null,
+ ]),
+ );
+}
+
+describe("#given an immutable plan and audit log", () => {
+ it("#when (7a) a writer dies after publishing #then reads reconcile without writes and locked reads repair views", async () => {
+ const next = await seedCrash(root, scope, false);
+ const before = snapshot();
+ expect(await io.readUlwLoopPlan(root, scope)).toEqual(next);
+ expect(io.readLedger(root, scope).at(-1)?.id).toBe(`${next.revision}-0`);
+ expect(snapshot()).toEqual(before);
+ await io.withUlwLoopMutationLock(root, scope, () => io.readUlwLoopPlan(root, scope));
+ expect(JSON.parse(readFileSync(join(dir, "goals.json"), "utf8"))).toEqual(next);
+ expect(readFileSync(join(dir, "brief.md"), "utf8")).toBe(next.brief);
+ });
+ it("#when (7b) first creation has no goals cache #then existence and reads use the log", async () => {
+ const next = await seedCrash(root, scope, true);
+ expect(io.planExists(root, scope)).toBe(true);
+ expect(await io.readUlwLoopPlan(root, scope)).toEqual(next);
+ });
+ it("#when (8) a legacy plan first commits #then revision zero and legacy ledger and brief survive", async () => {
+ const plan = await createUlwLoopPlan(root, { brief: "legacy" }, scope);
+ delete plan.revision;
+ delete plan.brief;
+ delete plan.ledgerResetRevision;
+ await rm(join(dir, "revisions"), { recursive: true, force: true });
+ writeFileSync(join(dir, "goals.json"), JSON.stringify(plan));
+ writeFileSync(join(dir, "ledger.jsonl"), '{"at":"legacy","kind":"goal_started"}\n{"torn":');
+ expect(io.readLedger(root, scope)[0]).toMatchObject({ revision: 0, id: "legacy-1" });
+ const { commit } = await import("../src/plan-commit.js");
+ await io.withUlwLoopMutationLock(root, scope, async () => {
+ const legacy = await io.readUlwLoopPlan(root, scope);
+ await commit(root, scope, { plan: legacy, entries: [] });
+ });
+ expect(readdirSync(join(dir, "revisions"))).toEqual(["00000001.json"]);
+ expect(io.readLedger(root, scope)[0]?.id).toBe("legacy-1");
+ expect(readFileSync(join(dir, "brief.md"), "utf8")).toBe("legacy\n");
+ });
+ it("#when (9) force recreation succeeds #then the reset is a new revision with filtered views", async () => {
+ const first = await createUlwLoopPlan(root, { brief: "old" }, scope);
+ const next = await createUlwLoopPlan(root, { brief: "new", force: true }, scope);
+ expect(next.revision).toBe((first.revision ?? 0) + 1);
+ expect(next.ledgerResetRevision).toBe(next.revision);
+ expect(io.readLedger(root, scope)).toHaveLength(1);
+ expect(readFileSync(join(dir, "brief.md"), "utf8")).toBe(next.brief);
+ expect(readdirSync(join(dir, "revisions"))).toHaveLength(2);
+ });
+ it("#when (12) hard links are unsupported #then publication fails closed without a record or view changes", async () => {
+ await createUlwLoopPlan(root, { brief: "old" }, scope);
+ const before = snapshot();
+ const { withCommitHooks, commit } = await import("../src/plan-commit.js");
+ await expect(
+ withCommitHooks(
+ {
+ link: () => {
+ throw Object.assign(new Error("unsupported"), { code: "EPERM" });
+ },
+ },
+ () =>
+ io.withUlwLoopMutationLock(root, scope, async () => {
+ const plan = await io.readUlwLoopPlan(root, scope);
+ plan.brief = "forbidden";
+ await commit(root, scope, { plan, entries: [] });
+ }),
+ ),
+ ).rejects.toMatchObject({ code: "ULW_LOOP_PUBLISH_UNSUPPORTED_FS" });
+ expect(snapshot()).toEqual(before);
+ expect(readdirSync(join(dir, "revisions"))).toHaveLength(1);
+ });
+});
+
+describe("#given paused writers in separate processes", () => {
+ it.each(["write", "force"])(
+ "#when (5)/(9) B wins %s after A's precheck #then A loses without publishing or changing views",
+ async (mode) => {
+ await createUlwLoopPlan(root, { brief: "initial" }, scope);
+ const { withCommitHooks, commit } = await import("../src/plan-commit.js");
+ let successor: ReturnType<typeof snapshot> | undefined;
+ let writes = 0;
+ const clock = leaseClock();
+ await expect(
+ withCommitHooks(
+ {
+ beforeCommit: async () => {
+ clock.advance(201);
+ const writer = childWriter(root, mode, clock.now());
+ expect(await writer.exited).toBe(0);
+ successor = snapshot();
+ },
+ writeView: async () => {
+ writes += 1;
+ throw new Error("loser wrote a view");
+ },
+ },
+ () =>
+ io.withUlwLoopMutationLock(
+ root,
+ scope,
+ async () => {
+ const plan = await io.readUlwLoopPlan(root, scope);
+ plan.brief = "A\n";
+ await commit(root, scope, { plan, entries: [{ at: "A", kind: "goal_added", message: "A" }] });
+ },
+ { clock, leaseMs: 200, heartbeatMs: 0 },
+ ),
+ ),
+ ).rejects.toMatchObject({ code: "ULW_LOOP_LOCK_LOST" });
+ expect(writes).toBe(0);
+ expect(snapshot()).toEqual(successor);
+ const published = JSON.parse(readFileSync(join(dir, "revisions", "00000002.json"), "utf8"));
+ expect(published.plan).toEqual(await io.readUlwLoopPlan(root, scope));
+ expect(published.ledger).toHaveLength(1);
+ expect(io.readLedger(root, scope).at(-1)).toEqual(published.ledger[0]);
+ expect(published.ledger[0].kind).toBe(mode === "force" ? "plan_created" : "goal_added");
+ expect(io.readLedger(root, scope).some((entry) => entry.message === "A")).toBe(false);
+ expect(readdirSync(join(dir, "revisions"))).toEqual(["00000001.json", "00000002.json"]);
+ },
+ );
+ it("#when (6) A wins before the valid holder B #then B retries once from A's revision", async () => {
+ await createUlwLoopPlan(root, { brief: "initial" }, scope);
+ const { withCommitHooks, commit } = await import("../src/plan-commit.js");
+ let writer: ReturnType<typeof childWriter> | undefined;
+ const clock = leaseClock();
+ await withCommitHooks(
+ {
+ beforeCommit: async () => {
+ clock.advance(201);
+ writer = childWriter(root, "mirror", clock.now());
+ await writer.wait("before");
+ },
+ },
+ () =>
+ io.withUlwLoopMutationLock(
+ root,
+ scope,
+ async () => {
+ const plan = await io.readUlwLoopPlan(root, scope);
+ plan.codexObjective = "A";
+ await commit(root, scope, { plan, entries: [{ at: "A", kind: "goal_added", message: "A" }] });
+ },
+ { clock, leaseMs: 200, heartbeatMs: 0 },
+ ),
+ );
+ if (writer === undefined) throw new Error("B not started");
+ writer.child.send("resume");
+ expect(await writer.exited).toBe(0);
+ expect((await io.readUlwLoopPlan(root, scope)).codexObjective).toBe("A|B");
+ expect(
+ io
+ .readLedger(root, scope)
+ .slice(-2)
+ .map((entry) => entry.message),
+ ).toEqual(["A", "B"]);
+ expect(readdirSync(join(dir, "revisions"))).toHaveLength(3);
+ });
+ it("#when (7c) a child dies after an acknowledged partial temp write #then every public view remains complete", async () => {
+ await createUlwLoopPlan(root, { brief: "initial" }, scope);
+ const before = snapshot();
+ const writer = childWriter(root, "partial");
+ await writer.wait("partial");
+ writer.child.kill("SIGKILL");
+ await writer.exited;
+ const after = snapshot();
+ const published = JSON.parse(readFileSync(join(dir, "revisions", "00000002.json"), "utf8"));
+ expect([before["goals.json"], `${JSON.stringify(published.plan, null, 2)}\n`]).toContain(after["goals.json"]);
+ expect([before["brief.md"], published.plan.brief]).toContain(after["brief.md"]);
+ expect(after["ledger.jsonl"]).toBe(before["ledger.jsonl"]);
+ for (const line of readFileSync(join(dir, "ledger.jsonl"), "utf8").trim().split("\n"))
+ expect(() => JSON.parse(line)).not.toThrow();
+ expect(io.readLedger(root, scope).at(-1)?.message).toBe("B");
+ });
+ it.each(["accepted", "rejected"])(
+ "#when (11) %s steering dies after link #then its audit survives and accepted retries dedupe",
+ async (mode) => {
+ const original = await createUlwLoopPlan(root, { brief: "initial" }, scope);
+ const writer = childWriter(root, mode);
+ await writer.wait("linked");
+ writer.child.kill("SIGKILL");
+ await writer.exited;
+ expect(io.readLedger(root, scope).at(-1)?.kind).toBe(`steering_${mode}`);
+ const prior = await io.findAcceptedSteeringLedgerEntry(root, "crash-key", scope);
+ if (mode === "rejected") {
+ expect(prior).toBeUndefined();
+ expect(await io.readUlwLoopPlan(root, scope)).toEqual({ ...original, revision: 2 });
+ } else {
+ const { steerUlwLoop } = await import("../src/steering.js");
+ const result = await steerUlwLoop(
+ root,
+ {
+ kind: "annotate_ledger",
+ source: "cli",
+ evidence: "observed",
+ rationale: "audit",
+ idempotencyKey: "crash-key",
+ },
+ scope,
+ );
+ expect(result.deduped).toBe(true);
+ expect(io.readLedger(root, scope)).toHaveLength(2);
+ expect(readdirSync(join(dir, "revisions"))).toHaveLength(2);
+ }
+ },
+ );
+ it("#when (10) retry fails before commit #then no goal_retried audit escapes", async () => {
+ const { startNextUlwLoop } = await import("../src/plan-crud.js");
+ const plan = await createUlwLoopPlan(root, { brief: "initial" }, scope);
+ const { commit, withCommitHooks } = await import("../src/plan-commit.js");
+ for (const goal of plan.goals) goal.status = "failed";
+ await commit(root, scope, { plan, entries: [] });
+ const before = snapshot();
+ await expect(
+ withCommitHooks(
+ {
+ beforeCommit: () => {
+ throw new Error("stop before commit");
+ },
+ },
+ () => startNextUlwLoop(root, { retryFailed: true }, scope),
+ ),
+ ).rejects.toThrow("stop before commit");
+ expect(snapshot()).toEqual(before);
+ expect(io.readLedger(root, scope).some((entry) => entry.kind === "goal_retried")).toBe(false);
+ });
+});
diff --git a/plugins/omo/components/ulw-loop/test/plan-commit-recovery.test.ts b/plugins/omo/components/ulw-loop/test/plan-commit-recovery.test.ts
new file mode 100644
index 00000000..fdd04b70
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/test/plan-commit-recovery.test.ts
@@ -0,0 +1,190 @@
+import { readdirSync, readFileSync } from "node:fs";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { PreToolUsePayload } from "../src/codex-hook.js";
+import { ulwLoopDir } from "../src/paths.js";
+import { commit, materialize, withCommitHooks } from "../src/plan-commit.js";
+import { createUlwLoopPlan } from "../src/plan-crud.js";
+import {
+ planExists,
+ readLedger,
+ readUlwLoopPlan,
+ withMutationLockOptions,
+ withUlwLoopMutationLock,
+} from "../src/plan-io.js";
+import { applySpawnBudgetGuards } from "../src/spawn-guard.js";
+import { runStopResumeHook } from "../src/stop-resume-hook.js";
+import { childWriter, cleanupWriters } from "./fixtures/commit-child.js";
+import { leaseClock } from "./fixtures/lease-clock.js";
+
+let root: string;
+let dir: string;
+const scope = { sessionId: "commit-log" };
+beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), "ulw-recovery-"));
+ dir = ulwLoopDir(root, scope);
+});
+afterEach(async () => {
+ await cleanupWriters();
+ vi.unstubAllEnvs();
+ await rm(root, { recursive: true, force: true });
+});
+function signal() {
+ let resolve: () => void = () => {
+ throw new Error("signal not initialized");
+ };
+ const promise = new Promise<void>((done, reject) => {
+ const timeout = setTimeout(() => reject(new Error("signal timed out")), 5_000);
+ resolve = () => {
+ clearTimeout(timeout);
+ done();
+ };
+ });
+ return { promise, resolve };
+}
+function views() {
+ return ["goals.json", "ledger.jsonl", "brief.md"].map((name) => readFileSync(join(dir, name), "utf8"));
+}
+describe("#given crash recovery through public surfaces", () => {
+ it("#when (7b) only revision one exists #then both hooks and existence gates use it", async () => {
+ const plan = await createUlwLoopPlan(root, { brief: "unfinished" }, scope);
+ for (const name of ["goals.json", "ledger.jsonl", "brief.md"]) await rm(join(dir, name));
+ expect(readdirSync(join(dir, "revisions"))).toEqual(["00000001.json"]);
+ expect(planExists(root, scope)).toBe(true);
+ expect((await readUlwLoopPlan(root, scope)).revision).toBe(1);
+ const payload = {
+ session_id: scope.sessionId,
+ turn_id: "turn",
+ cwd: root,
+ model: "test",
+ permission_mode: "default",
+ };
+ const stop = {
+ ...payload,
+ hook_event_name: "Stop",
+ transcript_path: join(root, "transcript"),
+ stop_hook_active: false,
+ };
+ expect(JSON.parse(runStopResumeHook(stop)).decision).toBe("block");
+ expect(JSON.parse(readFileSync(join(dir, `auto-resume-${plan.goals[0]?.id}.json`), "utf8")).ledgerLineCount).toBe(
+ 1,
+ );
+ vi.stubEnv("OMO_SPAWN_FANOUT_LIMIT", "1");
+ vi.stubEnv("PLUGIN_DATA", join(root, "plugin-data"));
+ const spawn: PreToolUsePayload = {
+ ...payload,
+ hook_event_name: "PreToolUse",
+ transcript_path: null,
+ tool_name: "spawn_agent",
+ tool_use_id: "tool",
+ tool_input: {},
+ };
+ expect(applySpawnBudgetGuards(spawn)).toBe("");
+ expect(JSON.parse(applySpawnBudgetGuards(spawn)).hookSpecificOutput.permissionDecision).toBe("deny");
+ });
+ it("#when (7c) two materializers overlap #then every public inode is complete even if a view regresses", async () => {
+ const plan = await createUlwLoopPlan(root, { brief: "old" }, scope);
+ const old = views();
+ await withCommitHooks(
+ {
+ afterCommit: () => {
+ throw new Error("crash");
+ },
+ },
+ () =>
+ commit(root, scope, {
+ plan: { ...plan, brief: "middle\n" },
+ entries: [{ at: "middle", kind: "goal_added" }],
+ }),
+ ).catch((error: unknown) => {
+ expect(error).toBeInstanceOf(Error);
+ });
+ const middleViews = [
+ `${JSON.stringify(await readUlwLoopPlan(root, scope), null, 2)}\n`,
+ `${readLedger(root, scope)
+ .map((entry) => JSON.stringify(entry))
+ .join("\n")}\n`,
+ "middle\n",
+ ];
+ const partial = signal();
+ const resume = signal();
+ const first = withCommitHooks(
+ {
+ writeView: async (path, content) => {
+ if (path.endsWith("ledger.jsonl")) {
+ await writeFile(path, content.slice(0, 5));
+ partial.resolve();
+ await resume.promise;
+ }
+ await writeFile(path, content);
+ },
+ },
+ () => materialize(dir),
+ );
+ await partial.promise;
+ expect(readFileSync(join(dir, "ledger.jsonl"), "utf8")).toBe(old[1]);
+ const latest = await readUlwLoopPlan(root, scope);
+ await commit(root, scope, { plan: { ...latest, brief: "new\n" }, entries: [{ at: "new", kind: "goal_added" }] });
+ const newViews = views();
+ resume.resolve();
+ await first;
+ const final = views();
+ expect(() => JSON.parse(final[0] ?? "")).not.toThrow();
+ for (const line of (final[1] ?? "").trim().split("\n")) expect(() => JSON.parse(line)).not.toThrow();
+ for (const [index, content] of final.entries()) expect([middleViews[index], newViews[index]]).toContain(content);
+ expect(
+ readLedger(root, scope)
+ .map((entry) => entry.at)
+ .slice(-2),
+ ).toEqual(["middle", "new"]);
+ });
+ it("#when (9) a force-recreator loses before its first possible view write #then its successor stays untouched", async () => {
+ await createUlwLoopPlan(root, { brief: "old" }, scope);
+ let successor: string[] = [];
+ let writes = 0;
+ const clock = leaseClock();
+ await expect(
+ withCommitHooks(
+ {
+ beforeMutation: async () => {
+ clock.advance(201);
+ const writer = childWriter(root, "force", clock.now());
+ expect(await writer.exited).toBe(0);
+ successor = views();
+ },
+ writeView: async (path, content) => {
+ writes += 1;
+ await writeFile(path, content);
+ },
+ },
+ () =>
+ withMutationLockOptions({ clock, leaseMs: 200, heartbeatMs: 0 }, () =>
+ createUlwLoopPlan(root, { brief: "A", force: true }, scope),
+ ),
+ ),
+ ).rejects.toMatchObject({ code: "ULW_LOOP_LOCK_LOST" });
+ expect(writes).toBe(0);
+ expect(views()).toEqual(successor);
+ expect(readLedger(root, scope)).toHaveLength(1);
+ });
+ it("#when a locked ledger-only read follows a crash #then all views are repaired without another revision", async () => {
+ const plan = await createUlwLoopPlan(root, { brief: "old" }, scope);
+ await expect(
+ withCommitHooks(
+ {
+ afterCommit: () => {
+ throw new Error("crash");
+ },
+ },
+ () => commit(root, scope, { plan: { ...plan, brief: "new\n" }, entries: [] }),
+ ),
+ ).rejects.toThrow("crash");
+ await withUlwLoopMutationLock(root, scope, async () => {
+ expect(readLedger(root, scope)).toHaveLength(1);
+ });
+ expect(readFileSync(join(dir, "brief.md"), "utf8")).toBe("new\n");
+ expect(readdirSync(join(dir, "revisions"))).toHaveLength(2);
+ });
+});
diff --git a/plugins/omo/components/ulw-loop/test/plan-io.test.ts b/plugins/omo/components/ulw-loop/test/plan-io.test.ts
index 85b9bb4d..acf308a3 100644
--- a/plugins/omo/components/ulw-loop/test/plan-io.test.ts
+++ b/plugins/omo/components/ulw-loop/test/plan-io.test.ts
@@ -2,7 +2,6 @@ import { existsSync } from "node:fs";
import { appendFile, copyFile, mkdir, mkdtemp, readdir, readFile, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { setImmediate as tick } from "node:timers/promises";
import { beforeEach, describe, expect, it } from "vitest";
import { ulwLoopDir, ulwLoopGoalsPath, ulwLoopLedgerPath } from "../src/paths.js";
import {
@@ -15,6 +14,7 @@ import {
} from "../src/plan-io.js";
import type { UlwLoopItem, UlwLoopLedgerEntry, UlwLoopPlan, UlwLoopSteeringAudit } from "../src/types.js";
import { UlwLoopError } from "../src/types.js";
+import { barrier } from "./fixtures/barrier.js";
const NOW = "2026-05-23T00:00:00.000Z";
const STABLE_OBJECTIVE =
@@ -97,6 +97,12 @@ async function makeRepo(): Promise<string> {
return mkdtemp(join(tmpdir(), "ug-io-"));
}
+async function makeLedgerRepo(): Promise<string> {
+ const root = await makeRepo();
+ await writePlan(root, makePlan());
+ return root;
+}
+
async function writeRawPlan(repoRoot: string, plan: UlwLoopPlan): Promise<void> {
await mkdir(ulwLoopDir(repoRoot), { recursive: true });
await writeFile(ulwLoopGoalsPath(repoRoot), `${JSON.stringify(plan, null, 2)}\n`, "utf8");
@@ -136,13 +142,17 @@ describe("readUlwLoopPlan", () => {
expect(plan.goals[0]?.successCriteria).toHaveLength(3);
});
- it("migrates legacy aggregate objective on read + writes aggregate_objective_migrated ledger entry + retains alias", async () => {
+ it("migrates legacy aggregate objective in memory and folds its audit into the enclosing commit", async () => {
// given
const legacyObjective = "Complete all ulw-loop stories in .omo/ulw-loop/goals.json: G001 Build auth service";
await writeRawPlan(repoRoot, makePlan({ codexObjective: legacyObjective }));
// when: read inside the mutation lock, the way every mutating command does
- const plan = await withUlwLoopMutationLock(repoRoot, () => readUlwLoopPlan(repoRoot));
+ const plan = await withUlwLoopMutationLock(repoRoot, async () => {
+ const migrated = await readUlwLoopPlan(repoRoot);
+ await writePlan(repoRoot, migrated);
+ return migrated;
+ });
// then
expect(plan.codexObjective).toBe(STABLE_OBJECTIVE);
@@ -157,22 +167,17 @@ describe("readUlwLoopPlan", () => {
});
});
- it("readUlwLoopPlan refuses to migrate a legacy aggregate plan outside the mutation lock (no unlocked write on a read path)", async () => {
+ it("readUlwLoopPlan migrates a legacy aggregate plan in memory outside the mutation lock without writing", async () => {
// given: the same legacy plan, but the read is not wrapped in withUlwLoopMutationLock
const legacyObjective = "Complete all ulw-loop stories in .omo/ulw-loop/goals.json: G001 Build auth service";
await writeRawPlan(repoRoot, makePlan({ codexObjective: legacyObjective }));
// when
- let caught: unknown;
- try {
- await readUlwLoopPlan(repoRoot);
- } catch (error) {
- caught = error;
- }
-
- // then: it refuses with a recovery hint and writes nothing
- expect(caught).toBeInstanceOf(UlwLoopError);
- expect((caught as UlwLoopError).code).toBe("ULW_LOOP_MIGRATION_REQUIRED");
+ const migrated = await readUlwLoopPlan(repoRoot);
+
+ // then: only the returned shape changes
+ expect(migrated.codexObjective).toBe(STABLE_OBJECTIVE);
+ expect(migrated.codexObjectiveAliases).toContain(legacyObjective);
const persisted = JSON.parse(await readFile(ulwLoopGoalsPath(repoRoot), "utf8"));
expect(persisted.codexObjective).toBe(legacyObjective);
expect(existsSync(ulwLoopLedgerPath(repoRoot))).toBe(false);
@@ -211,7 +216,8 @@ describe("writePlan", () => {
await writePlan(repoRoot, makePlan({ codexObjective: "first" }));
// when
- await writePlan(repoRoot, makePlan({ codexObjective: "second" }));
+ const current = await readUlwLoopPlan(repoRoot);
+ await writePlan(repoRoot, { ...current, codexObjective: "second" });
// then
expect(JSON.parse(await readFile(ulwLoopGoalsPath(repoRoot), "utf8"))).toMatchObject({
@@ -223,7 +229,7 @@ describe("writePlan", () => {
describe("appendLedger", () => {
it("appends a single JSONL line to ledger.jsonl", async () => {
// given
- const repoRoot = await makeRepo();
+ const repoRoot = await makeLedgerRepo();
const ledgerEntry = entry("goal_started");
// when
@@ -236,6 +242,7 @@ describe("appendLedger", () => {
it("creates ledger.jsonl if missing", async () => {
// given
const repoRoot = await makeRepo();
+ await writeRawPlan(repoRoot, makePlan());
// when
await appendLedger(repoRoot, entry("goal_completed"));
@@ -246,7 +253,7 @@ describe("appendLedger", () => {
it("preserves prior entries", async () => {
// given
- const repoRoot = await makeRepo();
+ const repoRoot = await makeLedgerRepo();
const first = entry("goal_started");
const second = entry("goal_completed");
@@ -262,7 +269,7 @@ describe("appendLedger", () => {
describe("readSteeringLedgerEntries", () => {
it("returns only steering-related event kinds", async () => {
// given
- const repoRoot = await makeRepo();
+ const repoRoot = await makeLedgerRepo();
await appendLedger(repoRoot, entry("steering_accepted"));
await appendLedger(repoRoot, entry("goal_started"));
await appendLedger(repoRoot, entry("steering_rejected"));
@@ -297,7 +304,7 @@ describe("findAcceptedSteeringLedgerEntry", () => {
],
] as const)("finds an accepted entry by %s", async (_name, target) => {
// given
- const repoRoot = await makeRepo();
+ const repoRoot = await makeLedgerRepo();
await appendLedger(repoRoot, steeringEntry("steering_accepted", steeringAudit({ idempotencyKey: "other-key" })));
await appendLedger(repoRoot, target);
@@ -310,7 +317,7 @@ describe("findAcceptedSteeringLedgerEntry", () => {
it("skips a rejected entry carrying the same key", async () => {
// given
- const repoRoot = await makeRepo();
+ const repoRoot = await makeLedgerRepo();
await appendLedger(
repoRoot,
steeringEntry("steering_rejected", rejectedSteeringAudit({ idempotencyKey: "needle-key" })),
@@ -322,7 +329,7 @@ describe("findAcceptedSteeringLedgerEntry", () => {
it("returns the accepted entry even when a rejected one with the same key precedes it", async () => {
// given
- const repoRoot = await makeRepo();
+ const repoRoot = await makeLedgerRepo();
const accepted = steeringEntry("steering_accepted", steeringAudit({ idempotencyKey: "needle-key" }));
await appendLedger(
repoRoot,
@@ -344,7 +351,7 @@ describe("findAcceptedSteeringLedgerEntry", () => {
it("ignores the key when it only appears in non-steering entries", async () => {
// given
- const repoRoot = await makeRepo();
+ const repoRoot = await makeLedgerRepo();
await appendLedger(repoRoot, { at: NOW, kind: "goal_completed", goalId: "G001", idempotencyKey: "needle-key" });
await appendLedger(repoRoot, { at: NOW, kind: "evidence_captured", goalId: "G001", evidence: "needle-key" });
@@ -354,7 +361,7 @@ describe("findAcceptedSteeringLedgerEntry", () => {
it("ignores an accepted entry whose key only appears in evidence text", async () => {
// given
- const repoRoot = await makeRepo();
+ const repoRoot = await makeLedgerRepo();
await appendLedger(repoRoot, steeringEntry("steering_accepted", steeringAudit({ evidence: "needle-key" })));
// when/then
@@ -440,13 +447,13 @@ describe("withUlwLoopMutationLock", () => {
const body = async (): Promise<void> => {
active += 1;
maxActive = Math.max(maxActive, active);
- await tick();
+ await Promise.resolve();
active -= 1;
};
// when
await Promise.all([1, 2, 3].map(() => withUlwLoopMutationLock(repoRoot, body)));
- await tick();
+ await Promise.resolve();
await Promise.all([1, 2].map(() => withUlwLoopMutationLock(repoRoot, body)));
// then
@@ -457,7 +464,8 @@ describe("withUlwLoopMutationLock", () => {
// given
const repoRoot = await makeRepo();
const events: string[] = [];
- let releaseSecond = false;
+ const releaseSecond = barrier();
+ const enteredSecond = barrier();
// when
const first = withUlwLoopMutationLock(repoRoot, async () => {
@@ -465,15 +473,16 @@ describe("withUlwLoopMutationLock", () => {
});
const second = withUlwLoopMutationLock(repoRoot, async () => {
events.push("second:start");
- while (!releaseSecond) await tick();
+ enteredSecond.resolve();
+ await releaseSecond.promise;
events.push("second:end");
});
await first;
- await tick();
+ await enteredSecond.promise;
const third = withUlwLoopMutationLock(repoRoot, async () => {
events.push("third");
});
- releaseSecond = true;
+ releaseSecond.resolve();
await Promise.all([second, third]);
// then
@@ -485,18 +494,21 @@ describe("withUlwLoopMutationLock", () => {
const rootA = await makeRepo();
const rootB = await makeRepo();
const events: string[] = [];
- let releaseA = false;
+ const releaseA = barrier();
+ const enteredA = barrier();
// when
const held = withUlwLoopMutationLock(rootA, async () => {
events.push("a:start");
- while (!releaseA) await tick();
+ enteredA.resolve();
+ await releaseA.promise;
events.push("a:end");
});
+ await enteredA.promise;
await withUlwLoopMutationLock(rootB, async () => {
events.push("b");
});
- releaseA = true;
+ releaseA.resolve();
await held;
// then
@@ -508,21 +520,24 @@ describe("withUlwLoopMutationLock", () => {
const repoRoot = await makeRepo();
const scoped = { sessionId: "session-a" };
const events: string[] = [];
- let releaseScoped = false;
+ const releaseScoped = barrier();
+ const enteredScoped = barrier();
// when
const heldScoped = withUlwLoopMutationLock(repoRoot, scoped, async () => {
events.push("scoped-1:start");
- while (!releaseScoped) await tick();
+ enteredScoped.resolve();
+ await releaseScoped.promise;
events.push("scoped-1:end");
});
+ await enteredScoped.promise;
const queuedScoped = withUlwLoopMutationLock(repoRoot, scoped, async () => {
events.push("scoped-2");
});
await withUlwLoopMutationLock(repoRoot, async () => {
events.push("root-scope");
});
- releaseScoped = true;
+ releaseScoped.resolve();
await Promise.all([heldScoped, queuedScoped]);
// then
diff --git a/plugins/omo/components/ulw-loop/test/plan-log-newest.test.ts b/plugins/omo/components/ulw-loop/test/plan-log-newest.test.ts
new file mode 100644
index 00000000..d97e83df
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/test/plan-log-newest.test.ts
@@ -0,0 +1,72 @@
+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { ulwLoopDir } from "../src/paths.js";
+import { createUlwLoopPlan } from "../src/plan-crud.js";
+import { readNewestRecord, readRecords, reconcilePlan } from "../src/plan-log.js";
+import type { UlwLoopPlan } from "../src/types.js";
+
+let root: string;
+let dir: string;
+let base: UlwLoopPlan;
+const scope = { sessionId: "newest-record" };
+beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), "ulw-newest-"));
+ dir = ulwLoopDir(root, scope);
+ base = await createUlwLoopPlan(root, { brief: "initial" }, scope);
+});
+afterEach(async () => {
+ await rm(root, { recursive: true, force: true });
+});
+// The names are deliberately mixed-width: lexicographically "000000010.json" sorts BEFORE "00000009.json",
+// so only numeric ordering of the parsed revision picks revision 10 as the newest record.
+function seedRecord(name: string, revision: number, brief: string): UlwLoopPlan {
+ const plan: UlwLoopPlan = { ...base, revision, brief };
+ mkdirSync(join(dir, "revisions"), { recursive: true });
+ writeFileSync(
+ join(dir, "revisions", name),
+ `${JSON.stringify({ version: 1, revision, plan, ledger: [{ at: "now", kind: "goal_added", revision, id: `${revision}-0` }] })}\n`,
+ );
+ return plan;
+}
+
+describe("#given a commit log whose newest record is the only one a plan read needs", () => {
+ it("#when the newest record is valid #then it wins over older records and a stale goals cache", async () => {
+ seedRecord("00000009.json", 9, "nine");
+ const newest = seedRecord("000000010.json", 10, "ten");
+
+ expect(base.revision).toBe(1);
+ expect(readNewestRecord(dir)?.revision).toBe(10);
+ expect(reconcilePlan(dir)).toEqual(newest);
+ });
+ it("#when the newest record is corrupt #then the newest valid older record wins", () => {
+ const older = seedRecord("00000009.json", 9, "nine");
+ writeFileSync(join(dir, "revisions", "000000010.json"), "{not json");
+
+ expect(readNewestRecord(dir)?.revision).toBe(9);
+ expect(reconcilePlan(dir)).toEqual(older);
+ });
+ it("#when an OLDER record is unreadable for a non-syntax reason #then the read stops at the newest record", () => {
+ const newest = seedRecord("000000010.json", 10, "ten");
+ rmSync(join(dir, "revisions", "00000001.json"));
+ mkdirSync(join(dir, "revisions", "00000001.json"));
+
+ expect(reconcilePlan(dir)).toEqual(newest);
+ expect(readNewestRecord(dir)).toEqual({
+ version: 1,
+ revision: 10,
+ plan: newest,
+ ledger: [{ at: "now", kind: "goal_added", revision: 10, id: "10-0" }],
+ });
+ expect(() => readRecords(dir)).toThrow(/EISDIR/);
+ });
+ it("#when the NEWEST record is unreadable for a non-syntax reason #then the error propagates", () => {
+ seedRecord("00000009.json", 9, "nine");
+ mkdirSync(join(dir, "revisions", "000000010.json"));
+
+ expect(() => readNewestRecord(dir)).toThrow(/EISDIR/);
+ expect(() => reconcilePlan(dir)).toThrow(/EISDIR/);
+ });
+});
diff --git a/plugins/omo/components/ulw-loop/test/sdk-completed-plan.test.ts b/plugins/omo/components/ulw-loop/test/sdk-completed-plan.test.ts
new file mode 100644
index 00000000..d7fd71a7
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/test/sdk-completed-plan.test.ts
@@ -0,0 +1,43 @@
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { commit } from "../src/plan-commit.js";
+import { readUlwLoopPlan, withUlwLoopMutationLock } from "../src/plan-io.js";
+import { createAgentToolkit } from "../src/sdk.js";
+import type { UlwLoopToolkitSurface } from "../src/surface.js";
+
+const directories: string[] = [];
+afterEach(async () => {
+ for (const directory of directories.splice(0)) await rm(directory, { recursive: true, force: true });
+});
+
+const surfaces: UlwLoopToolkitSurface[] = ["lazycodex", "omo-senpi"];
+describe.each(surfaces)("#given a completed plan on %s", (surface) => {
+ it("#when createGoals is called #then it rejects without overwriting, unless explicitly forced", async () => {
+ const cwd = await mkdtemp(join(tmpdir(), "sdk-completed-plan-"));
+ directories.push(cwd);
+ const scope = { sessionId: "completed-plan" };
+ const toolkit = createAgentToolkit({ cwd, ...scope, surface });
+ expect((await toolkit.createGoals({ brief: "- original" })).ok).toBe(true);
+ await withUlwLoopMutationLock(cwd, scope, async () => {
+ const plan = await readUlwLoopPlan(cwd, scope);
+ for (const goal of plan.goals) goal.status = "complete";
+ await commit(cwd, scope, { plan, entries: [] });
+ });
+ const before = await readUlwLoopPlan(cwd, scope);
+ const response = await toolkit.createGoals({ brief: "- replacement" });
+ expect(response).toMatchObject({ ok: false, error: { code: "ULW_LOOP_PLAN_EXISTS_COMPLETE" } });
+ if (response.ok) throw new Error("expected createGoals to fail");
+ if (surface === "omo-senpi") {
+ expect(response.error.message).toMatch(/agentToolkit\.createGoals\(/);
+ expect(response.error.message).not.toMatch(/omo-agent-toolkit ulw-loop/);
+ } else {
+ expect(response.error.message).toMatch(/omo-agent-toolkit ulw-loop create-goals/);
+ expect(response.error.message).not.toMatch(/agentToolkit\./);
+ }
+ expect(await readUlwLoopPlan(cwd, scope)).toEqual(before);
+ expect((await toolkit.createGoals({ brief: "- replacement", force: true })).ok).toBe(true);
+ expect((await readUlwLoopPlan(cwd, scope)).goals[0]?.id).toBe("G001-replacement");
+ });
+});
diff --git a/plugins/omo/components/ulw-loop/test/sdk-session-context.test.ts b/plugins/omo/components/ulw-loop/test/sdk-session-context.test.ts
index a5832429..b3fcb88e 100644
--- a/plugins/omo/components/ulw-loop/test/sdk-session-context.test.ts
+++ b/plugins/omo/components/ulw-loop/test/sdk-session-context.test.ts
@@ -72,6 +72,27 @@ async function seedSession(
}
describe("agent toolkit session context", () => {
+ describe("#given a session id that normalizes to null", () => {
+ it("#when an omo-senpi SDK context is created #then it rejects without creating session state", async () => {
+ const cwd = await makeWorkdir();
+
+ expect(() => createAgentToolkit({ cwd, sessionId: "../../x", surface: "omo-senpi" })).toThrowError(
+ expect.objectContaining({ code: "ULW_LOOP_SESSION_ID_INVALID" }),
+ );
+ expect(existsSync(join(cwd, ".omo", "ulw-loop"))).toBe(false);
+ });
+ });
+
+ describe("#given a blank session id", () => {
+ it("#when an SDK context is created #then it reports the required-id error", async () => {
+ const cwd = await makeWorkdir();
+
+ expect(() => createAgentToolkit({ cwd, sessionId: " ", surface: "omo-senpi" })).toThrowError(
+ expect.objectContaining({ code: "ULW_LOOP_SESSION_ID_REQUIRED" }),
+ );
+ });
+ });
+
describe("#given a plan written under session A", () => {
it("#when session B reads through its own context #then the read fails closed instead of borrowing A", async () => {
const cwd = await makeWorkdir();
diff --git a/plugins/omo/components/ulw-loop/test/state-lock.test.ts b/plugins/omo/components/ulw-loop/test/state-lock.test.ts
index e102f6dd..a57b1f3f 100644
--- a/plugins/omo/components/ulw-loop/test/state-lock.test.ts
+++ b/plugins/omo/components/ulw-loop/test/state-lock.test.ts
@@ -80,6 +80,98 @@ function ownerPid(): number {
return record.pid;
}
+function manualClock() {
+ let now = Date.now();
+ const tasks = new Set<{ at: number; fn: () => void }>();
+ return {
+ now: () => now,
+ schedule(fn: () => void, ms: number) {
+ const task = { at: now + ms, fn };
+ tasks.add(task);
+ return { unref() {}, cancel: () => tasks.delete(task) };
+ },
+ advance(ms: number) {
+ const end = now + ms;
+ for (;;) {
+ const next = [...tasks].filter((task) => task.at <= end).sort((a, b) => a.at - b.at)[0];
+ if (next === undefined) break;
+ now = next.at;
+ tasks.delete(next);
+ next.fn();
+ }
+ now = end;
+ },
+ };
+}
+
+describe("#given lease-based ownership", () => {
+ it("#when (1) a live owner's lease expired #then an async waiter reclaims it", async () => {
+ const clock = manualClock();
+ mkdirSync(join(workDir, ".omo", "ulw-loop", "s1"), { recursive: true });
+ await writeFile(
+ lockPath,
+ JSON.stringify({
+ pid: process.pid,
+ token: "expired",
+ createdAt: new Date().toISOString(),
+ leaseUntil: clock.now() - 1,
+ }),
+ );
+ await expect(withStateLock(lockPath, async () => "acquired", { clock, leaseMs: 90, timeoutMs: 0 })).resolves.toBe(
+ "acquired",
+ );
+ });
+
+ it("#when (2) reclaimed while owner alive #then its heartbeat never overwrites or recreates the successor path", async () => {
+ const clock = manualClock();
+ await withStateLock(
+ lockPath,
+ async () => {
+ const initial = JSON.parse(readFileSync(lockPath, "utf8"));
+ expect(initial.leaseUntil).toBe(clock.now() + 90);
+ await withStateLock(
+ lockPath,
+ async () => {
+ const successor = readFileSync(lockPath, "utf8");
+ clock.advance(30);
+ expect(readFileSync(lockPath, "utf8")).toBe(successor);
+ },
+ { leaseMs: 900, heartbeatMs: 0, timeoutMs: 0, clock: { ...clock, now: () => clock.now() + 91 } },
+ );
+ clock.advance(30);
+ expect(existsSync(lockPath)).toBe(false);
+ },
+ { clock, leaseMs: 90 },
+ );
+ });
+
+ it("#when (3) the clock passes the original lease #then a refreshing holder cannot be reclaimed", async () => {
+ const clock = manualClock();
+ await withStateLock(
+ lockPath,
+ async () => {
+ clock.advance(120);
+ await expect(withStateLock(lockPath, async () => "stolen", { clock, timeoutMs: 0 })).rejects.toMatchObject({
+ code: ULW_LOOP_LOCK_TIMEOUT_CODE,
+ });
+ },
+ { clock, leaseMs: 90 },
+ );
+ });
+
+ it("#when acquisition hands off to its body #then ownership uses the acquired token rather than rereading a successor", async () => {
+ await withStateLock(lockPath, async (token: string) => {
+ expect(token).toBe(JSON.parse(readFileSync(lockPath, "utf8")).token);
+ });
+ });
+
+ it("#when (4) a synchronous holder runs #then it writes a lease-less record", () => {
+ withStateLockSync(lockPath, () => {
+ expect(JSON.parse(readFileSync(lockPath, "utf8"))).not.toHaveProperty("leaseUntil");
+ });
+ });
+});
+
describe("withStateLock", () => {
describe("#given a lock held by another live process", () => {
it("#when acquiring #then it waits for that process to release before running the body", async () => {
diff --git a/plugins/omo/components/ulw-loop/test/status-next-actions-surface.test.ts b/plugins/omo/components/ulw-loop/test/status-next-actions-surface.test.ts
new file mode 100644
index 00000000..debf7f92
--- /dev/null
+++ b/plugins/omo/components/ulw-loop/test/status-next-actions-surface.test.ts
@@ -0,0 +1,133 @@
+import { mkdir, mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { runInNewContext } from "node:vm";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { ulwLoopDir } from "../src/paths.js";
+import { writePlan } from "../src/plan-io.js";
+import {
+ type CheckpointArgs,
+ type CreateGoalsArgs,
+ createAgentToolkit,
+ type RecordEvidenceArgs,
+ type RecordReviewBlockersArgs,
+ type ToolkitSurface,
+} from "../src/sdk.js";
+import type { UlwLoopPlan } from "../src/types.js";
+import { criterion, goal, plan } from "./fixtures/checkpoint-builders.js";
+
+const scope = { sessionId: "surface-test" };
+const surfaces: ToolkitSurface[] = ["omo-senpi", "lazycodex"];
+let cwd: string;
+
+beforeEach(async () => {
+ cwd = await mkdtemp(join(tmpdir(), "ulw-surface-"));
+});
+afterEach(async () => {
+ await rm(cwd, { recursive: true, force: true });
+});
+
+interface Scenario {
+ readonly name: string;
+ readonly plan: UlwLoopPlan;
+ readonly method: string;
+ readonly args:
+ | CreateGoalsArgs
+ | RecordEvidenceArgs
+ | CheckpointArgs
+ | Omit<RecordReviewBlockersArgs, "codexGoalJson">;
+ readonly cli: string;
+}
+
+const scenarios: Scenario[] = [
+ {
+ name: "no goals",
+ plan: plan([]),
+ method: "createGoals",
+ args: { brief: "<brief>" },
+ cli: 'omo-agent-toolkit ulw-loop create-goals --brief "<brief>" --json',
+ },
+ {
+ name: "unresolved criteria",
+ plan: plan([goal({ successCriteria: [criterion("C001", "pass"), criterion("C002", "pending")] })]),
+ method: "recordEvidence",
+ args: { goalId: "G001", criterionId: "<id>", status: "pass", evidence: "<observable proof>" },
+ cli: 'omo-agent-toolkit ulw-loop record-evidence --goal-id G001 --criterion-id <id> --status pass --evidence "<observable proof>"',
+ },
+ {
+ name: "a passing non-final goal",
+ plan: plan([goal(), goal({ id: "G002", status: "pending" })]),
+ method: "checkpoint",
+ args: { goalId: "G001", status: "complete", evidence: "<proof>" },
+ cli: "omo-agent-toolkit ulw-loop checkpoint --goal-id G001 --status complete --evidence \"<proof>\" --codex-goal-json '<get_goal json>'",
+ },
+ {
+ name: "a passing final goal",
+ plan: plan([goal()]),
+ method: "checkpoint",
+ args: { goalId: "G001", printTemplate: true },
+ cli: "checkpoint --print-template",
+ },
+ {
+ name: "a review-blocked goal",
+ plan: plan([goal({ status: "review_blocked" })]),
+ method: "recordReviewBlockers",
+ args: { goalId: "G001", title: "<title>", objective: "<objective>", evidence: "<verdict>" },
+ cli: 'omo-agent-toolkit ulw-loop record-review-blockers --goal-id G001 --title "<title>" --objective "<objective>" --evidence "<verdict>" --codex-goal-json \'<get_goal json>\'',
+ },
+];
+
+function sdkArgs(text: string, method: string): unknown {
+ const snippet = text.match(new RegExp(`agentToolkit\\.${method}\\([^\x60]*\\)`))?.[0];
+ expect(snippet).toBeDefined();
+ if (snippet === undefined) throw new Error(`Missing SDK call: ${method}`);
+ return runInNewContext(snippet, { agentToolkit: { [method]: (args: unknown) => args } });
+}
+
+for (const surface of surfaces) {
+ describe(`#given the ${surface} SDK surface`, () => {
+ it.each(scenarios)("#when status reads $name #then its action uses the calling surface", async (scenario) => {
+ await mkdir(ulwLoopDir(cwd, scope), { recursive: true });
+ await writePlan(cwd, { ...scenario.plan, evidenceLayoutVersion: 2 }, scope);
+ const response = await createAgentToolkit({ cwd, ...scope, surface }).status();
+ if (!response.ok) throw new Error(response.error.message);
+
+ expect(response.nextActions).toEqual(response.result.nextActions);
+ const actions = response.nextActions.join("\n");
+ if (surface === "lazycodex") {
+ expect(actions).toContain(scenario.cli);
+ expect(actions).not.toContain("agentToolkit.");
+ return;
+ }
+ expect(actions).not.toMatch(/omo-agent-toolkit|status --json|codexGoalJson|--codex-goal-json|update_goal/);
+ expect(sdkArgs(actions, scenario.method)).toEqual(scenario.args);
+ if (scenario.method === "checkpoint") expect(actions).toContain("status().result.currentAttemptDir");
+ });
+
+ for (const siblings of [false, true]) {
+ it.each(["status", "completeGoals"])(
+ `#when %s has no plan and siblings=${siblings} #then recovery uses the calling surface`,
+ async (method) => {
+ if (siblings) await mkdir(ulwLoopDir(cwd, { sessionId: "other-session" }), { recursive: true });
+ const toolkit = createAgentToolkit({ cwd, ...scope, surface });
+ const response = await (method === "status" ? toolkit.status() : toolkit.completeGoals());
+ if (response.ok) throw new Error("Expected a missing-plan failure");
+
+ expect(response.error.code).toBe("ULW_LOOP_PLAN_MISSING");
+ if (surface === "lazycodex") {
+ expect(response.error.message).toContain(
+ 'omo-agent-toolkit ulw-loop create-goals --brief "<brief>" --json',
+ );
+ if (siblings) expect(response.error.message).toContain("--session-id <id>");
+ } else {
+ expect(response.error.message).not.toMatch(/omo-agent-toolkit|--session-id/);
+ expect(sdkArgs(response.error.message, "createGoals")).toEqual({ brief: "<brief>" });
+ }
+ if (siblings)
+ expect(response.error.details?.["existingSessionIds"]?.split(",")).toContain("other-session");
+ },
+ );
+ }
+ });
+}
diff --git a/plugins/omo/components/ulw-loop/test/steering-batch.test.ts b/plugins/omo/components/ulw-loop/test/steering-batch.test.ts
index 050b3fec..9b268309 100644
--- a/plugins/omo/components/ulw-loop/test/steering-batch.test.ts
+++ b/plugins/omo/components/ulw-loop/test/steering-batch.test.ts
@@ -9,11 +9,11 @@ import { readSteeringLedgerEntries, readUlwLoopPlan, writePlan } from "../src/pl
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 publishCalls = vi.hoisted(() => vi.fn());
+vi.mock("node:fs", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("node:fs")>();
+ publishCalls.mockImplementation(actual.linkSync);
+ return { ...actual, linkSync: publishCalls };
});
const NOW = "2026-05-23T00:00:00.000Z";
@@ -78,12 +78,12 @@ describe("steerUlwLoopBatch", () => {
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 before = 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)).toEqual({ ...before, revision: (before.revision ?? 0) + 1 });
expect((await readUlwLoopPlan(repo)).goals).toHaveLength(2);
const entries = await readSteeringLedgerEntries(repo);
expect(entries.filter((entry) => entry.kind === "steering_accepted")).toHaveLength(0);
@@ -120,13 +120,13 @@ describe("steerUlwLoopBatch", () => {
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 () => {
+ it("#given mixed fresh and deduped proposals #when accepted and replayed #then one publication 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();
+ publishCalls.mockClear();
const revise = { ...proposal({ kind: "revise_criterion", targetGoalId: "G001", criterionId: "C001", idempotencyKey: "revise-c1" }), scenario: "new" } satisfies CliSteeringProposal;
const batch = [
@@ -138,15 +138,15 @@ describe("steerUlwLoopBatch", () => {
expect(result.accepted).toBe(true);
expect(result.results.map((item) => item.deduped)).toEqual([true, false, false]);
- expect(appendFileCalls).toHaveBeenCalledTimes(1);
+ expect(publishCalls).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();
+ publishCalls.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();
+ expect(publishCalls).not.toHaveBeenCalled();
});
});
diff --git a/plugins/omo/components/ulw-loop/test/steering.test.ts b/plugins/omo/components/ulw-loop/test/steering.test.ts
index 478d1d32..4837bc84 100644
--- a/plugins/omo/components/ulw-loop/test/steering.test.ts
+++ b/plugins/omo/components/ulw-loop/test/steering.test.ts
@@ -250,7 +250,10 @@ describe("steerUlwLoop", () => {
const repoRoot = await repoWithPlan(seed);
const result = await steerUlwLoop(repoRoot, steering({ kind: "annotate_ledger" }));
expect(result.plan.goals).toEqual(seed.goals);
- expect(await readFile(ulwLoopGoalsPath(repoRoot), "utf8")).toBe(`${JSON.stringify(seed, null, 2)}\n`);
+ expect(JSON.parse(await readFile(ulwLoopGoalsPath(repoRoot), "utf8"))).toEqual({
+ ...seed,
+ revision: (seed.revision ?? 0) + 1,
+ });
});
it("mark_blocked_superseded with children: supersede + replace", async () => {
diff --git a/plugins/omo/dist/cli-node/index.js b/plugins/omo/dist/cli-node/index.js
index 2998b23f..67dc0ec7 100755
--- a/plugins/omo/dist/cli-node/index.js
+++ b/plugins/omo/dist/cli-node/index.js
@@ -65,7 +65,7 @@ var package_default;
var init_package = __esm(() => {
package_default = {
name: "oh-my-opencode",
- version: "5.0.0-beta.62",
+ version: "5.0.0-beta.63",
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",
@@ -97,8 +97,6 @@ var init_package = __esm(() => {
"packages/omo-codex",
"packages/omo-senpi",
"packages/senpi-task",
- "packages/pi-goal",
- "packages/pi-webfetch",
"packages/omo-opencode",
"packages/omo-native"
],
@@ -200,7 +198,7 @@ var init_package = __esm(() => {
prepublishOnly: "bun run clean && bun run build:lsp-tools-mcp && bun run build:lsp-daemon && bun run build",
"test:model-capabilities": "bun test --timeout 20000 packages/model-core/src/model-capability-aliases.test.ts packages/model-core/src/model-capability-guardrails.test.ts packages/model-core/src/model-capabilities.test.ts packages/omo-opencode/src/cli/doctor/checks/model-resolution.test.ts --bail",
typecheck: "tsgo --noEmit && bun run typecheck:script && bun run typecheck:packages",
- "typecheck:packages": "tsgo --noEmit -p packages/rules-engine/tsconfig.json && tsgo --noEmit -p packages/delegate-core/tsconfig.json && tsgo --noEmit -p packages/mcp-stdio-core/tsconfig.json && tsgo --noEmit -p packages/mcp-client-core/tsconfig.json && tsgo --noEmit -p packages/git-bash-mcp/tsconfig.json && tsgo --noEmit -p packages/ast-grep-mcp/tsconfig.json && tsgo --noEmit -p packages/lsp-core/tsconfig.json && tsgo --noEmit -p packages/utils/tsconfig.json && tsgo --noEmit -p packages/model-core/tsconfig.json && tsgo --noEmit -p packages/omo-config-core/tsconfig.json && tsgo --noEmit -p packages/prompts-core/tsconfig.json && tsgo --noEmit -p packages/comment-checker-core/tsconfig.json && tsgo --noEmit -p packages/hashline-core/tsconfig.json && tsgo --noEmit -p packages/tmux-core/tsconfig.json && tsgo --noEmit -p packages/team-core/tsconfig.json && tsgo --noEmit -p packages/openclaw-core/tsconfig.json && tsgo --noEmit -p packages/boulder-state/tsconfig.json && tsgo --noEmit -p packages/memory-core/tsconfig.json && tsgo --noEmit -p packages/telemetry-core/tsconfig.json && tsgo --noEmit -p packages/claude-code-compat-core/tsconfig.json && tsgo --noEmit -p packages/skills-loader-core/tsconfig.json && tsgo --noEmit -p packages/agents-md-core/tsconfig.json && tsgo --noEmit -p packages/omo-codex/plugin/shared/tsconfig.json && tsgo --noEmit -p packages/omo-codex/tsconfig.json && tsgo --noEmit -p packages/omo-senpi/tsconfig.json && tsgo --noEmit -p packages/senpi-task/tsconfig.json && tsgo --noEmit -p packages/pi-goal/tsconfig.json && tsgo --noEmit -p packages/pi-webfetch/tsconfig.json && tsgo --noEmit -p packages/omo-opencode/tsconfig.json && tsgo --noEmit -p packages/omo-native/tsconfig.json",
+ "typecheck:packages": "tsgo --noEmit -p packages/rules-engine/tsconfig.json && tsgo --noEmit -p packages/delegate-core/tsconfig.json && tsgo --noEmit -p packages/mcp-stdio-core/tsconfig.json && tsgo --noEmit -p packages/mcp-client-core/tsconfig.json && tsgo --noEmit -p packages/git-bash-mcp/tsconfig.json && tsgo --noEmit -p packages/ast-grep-mcp/tsconfig.json && tsgo --noEmit -p packages/lsp-core/tsconfig.json && tsgo --noEmit -p packages/utils/tsconfig.json && tsgo --noEmit -p packages/model-core/tsconfig.json && tsgo --noEmit -p packages/omo-config-core/tsconfig.json && tsgo --noEmit -p packages/prompts-core/tsconfig.json && tsgo --noEmit -p packages/comment-checker-core/tsconfig.json && tsgo --noEmit -p packages/hashline-core/tsconfig.json && tsgo --noEmit -p packages/tmux-core/tsconfig.json && tsgo --noEmit -p packages/team-core/tsconfig.json && tsgo --noEmit -p packages/openclaw-core/tsconfig.json && tsgo --noEmit -p packages/boulder-state/tsconfig.json && tsgo --noEmit -p packages/memory-core/tsconfig.json && tsgo --noEmit -p packages/telemetry-core/tsconfig.json && tsgo --noEmit -p packages/claude-code-compat-core/tsconfig.json && tsgo --noEmit -p packages/skills-loader-core/tsconfig.json && tsgo --noEmit -p packages/agents-md-core/tsconfig.json && tsgo --noEmit -p packages/omo-codex/plugin/shared/tsconfig.json && tsgo --noEmit -p packages/omo-codex/tsconfig.json && tsgo --noEmit -p packages/omo-senpi/tsconfig.json && tsgo --noEmit -p packages/senpi-task/tsconfig.json && tsgo --noEmit -p packages/omo-opencode/tsconfig.json && tsgo --noEmit -p packages/omo-native/tsconfig.json",
"typecheck:script": "tsgo --noEmit -p script/tsconfig.json",
test: "bun test --timeout 20000",
"changelog:section": "bun script/changelog-section.ts",
@@ -232,7 +230,6 @@ var init_package = __esm(() => {
homepage: "https://github.com/code-yeongyu/oh-my-openagent#readme",
dependencies: {
"@clack/prompts": "^1.7.0",
- "@code-yeongyu/comment-checker": "^0.8.0",
"@modelcontextprotocol/sdk": "^1.30.0",
"@opencode-ai/plugin": "1.18.22",
"@opencode-ai/sdk": "1.18.22",
@@ -250,7 +247,7 @@ var init_package = __esm(() => {
zod: "^4.4.3"
},
devDependencies: {
- "@code-yeongyu/senpi": "2026.9.13",
+ "@code-yeongyu/senpi": "2026.9.15-2",
"@oh-my-opencode/agents-md-core": "workspace:*",
"@oh-my-opencode/ast-grep-mcp": "workspace:*",
"@oh-my-opencode/boulder-state": "workspace:*",
@@ -269,8 +266,6 @@ var init_package = __esm(() => {
"@oh-my-opencode/omo-opencode": "workspace:*",
"@oh-my-opencode/omo-senpi": "workspace:*",
"@oh-my-opencode/openclaw-core": "workspace:*",
- "@oh-my-opencode/pi-goal": "workspace:*",
- "@oh-my-opencode/pi-webfetch": "workspace:*",
"@oh-my-opencode/prompts-core": "workspace:*",
"@oh-my-opencode/rules-engine": "workspace:*",
"@oh-my-opencode/senpi-task": "workspace:*",
@@ -291,18 +286,18 @@ var init_package = __esm(() => {
typescript: "^7.0.2"
},
optionalDependencies: {
- "oh-my-opencode-darwin-arm64": "5.0.0-beta.62",
- "oh-my-opencode-darwin-x64": "5.0.0-beta.62",
- "oh-my-opencode-darwin-x64-baseline": "5.0.0-beta.62",
- "oh-my-opencode-linux-arm64": "5.0.0-beta.62",
- "oh-my-opencode-linux-arm64-musl": "5.0.0-beta.62",
- "oh-my-opencode-linux-x64": "5.0.0-beta.62",
- "oh-my-opencode-linux-x64-baseline": "5.0.0-beta.62",
- "oh-my-opencode-linux-x64-musl": "5.0.0-beta.62",
- "oh-my-opencode-linux-x64-musl-baseline": "5.0.0-beta.62",
- "oh-my-opencode-windows-arm64": "5.0.0-beta.62",
- "oh-my-opencode-windows-x64": "5.0.0-beta.62",
- "oh-my-opencode-windows-x64-baseline": "5.0.0-beta.62"
+ "oh-my-opencode-darwin-arm64": "5.0.0-beta.63",
+ "oh-my-opencode-darwin-x64": "5.0.0-beta.63",
+ "oh-my-opencode-darwin-x64-baseline": "5.0.0-beta.63",
+ "oh-my-opencode-linux-arm64": "5.0.0-beta.63",
+ "oh-my-opencode-linux-arm64-musl": "5.0.0-beta.63",
+ "oh-my-opencode-linux-x64": "5.0.0-beta.63",
+ "oh-my-opencode-linux-x64-baseline": "5.0.0-beta.63",
+ "oh-my-opencode-linux-x64-musl": "5.0.0-beta.63",
+ "oh-my-opencode-linux-x64-musl-baseline": "5.0.0-beta.63",
+ "oh-my-opencode-windows-arm64": "5.0.0-beta.63",
+ "oh-my-opencode-windows-x64": "5.0.0-beta.63",
+ "oh-my-opencode-windows-x64-baseline": "5.0.0-beta.63"
},
overrides: {
"@earendil-works/pi-agent-core": "0.84.2",
@@ -316,9 +311,7 @@ var init_package = __esm(() => {
"path-to-regexp": "^8.4.2",
"@types/node": "26.2.0"
},
- trustedDependencies: [
- "@code-yeongyu/comment-checker"
- ]
+ trustedDependencies: []
};
});
@@ -7151,15 +7144,20 @@ var init_agent_model_requirements = __esm(() => {
},
metis: {
fallbackChain: [
+ {
+ providers: ["anthropic", "github-copilot", "opencode"],
+ model: "claude-fable-5-1",
+ variant: "max"
+ },
{
providers: ["anthropic", "github-copilot", "opencode"],
model: "claude-opus-5",
- variant: "high"
+ variant: "max"
},
{
providers: ["opencode-go", "kimi-for-coding", "moonshotai", "opencode"],
model: "kimi-k3",
- variant: "low"
+ variant: "max"
}
]
},
@@ -73013,6 +73011,7 @@ var init_task = __esm(() => {
model_concurrency: record(string2(), number2().int().nonnegative()).optional(),
max_depth: number2().int().nonnegative().default(1),
residency_max_children: ResidencyMaxChildrenInputSchema.default(8),
+ resident_idle_timeout_ms: number2().int().positive().max(Number.MAX_SAFE_INTEGER).default(900000),
ttl_ms: number2().int().positive().default(86400000),
state_dir: string2().optional(),
reattach_on_reconcile: boolean2().optional(),
@@ -73057,6 +73056,7 @@ var init_task = __esm(() => {
model_concurrency: record(string2(), number2().int().nonnegative()).optional(),
max_depth: number2().int().nonnegative().optional(),
residency_max_children: ResidencyMaxChildrenInputSchema.optional(),
+ resident_idle_timeout_ms: number2().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
ttl_ms: number2().int().positive().optional(),
state_dir: string2().optional(),
reattach_on_reconcile: boolean2().optional(),
@@ -84621,7 +84621,7 @@ var package_default2;
var init_package2 = __esm(() => {
package_default2 = {
name: "@oh-my-opencode/omo-codex",
- version: "5.0.0-beta.62",
+ version: "5.0.0-beta.63",
type: "module",
private: true,
description: "Codex harness adapter for oh-my-openagent. Vendored Codex plugin namespace (omo) + TypeScript installer + telemetry.",
@@ -93624,7 +93624,6 @@ var REQUIRED_PLUGIN_ARTIFACTS = [
join60("extensions", "omo.js"),
join60("extensions", "omo-task.js"),
join60("extensions", "omo-member.js"),
- join60("extensions", "omo-agent-toolkit.js"),
join60("extensions", "memory-run-supervisor.mjs"),
...PERSONA_ASSET_FILES.map((filename) => join60("extensions", filename)),
join60("skills", "ast-grep", "SKILL.md"),
@@ -93646,6 +93645,7 @@ var REQUIRED_PLUGIN_ARTIFACTS = [
join60("skills", "ulw-research", "SKILL.md"),
join60("skills", "visual-qa", "SKILL.md"),
join60("skills-conditional", "x-search", "SKILL.md"),
+ join60("runtime", "agent-toolkit-sdk", "sdk.js"),
join60("runtime", "ast-grep-mcp", "cli.js"),
join60("runtime", "lsp-daemon", "dist", "cli.js"),
join60("runtime", "lsp-daemon", "dist", "index.js"),
@@ -96978,7 +96978,6 @@ var BuiltinAgentNameSchema = _enum([
]);
var BuiltinSkillNameSchema = _enum([
"playwright",
- "agent-browser",
"dev-browser",
"frontend",
"git-master",
@@ -97141,10 +97140,11 @@ var BackgroundTaskConfigSchema = object({
init_zod();
var BrowserAutomationProviderSchema = _enum([
"playwright",
- "agent-browser",
"dev-browser",
"playwright-cli"
-]);
+], {
+ error: (issue) => `Browser provider ${JSON.stringify(issue.input)} is no longer supported; use the built-in browser path: Bun.WebView / playwright-core scripts`
+});
var BrowserAutomationConfigSchema = object({
provider: BrowserAutomationProviderSchema.default("playwright"),
playwright_mcp_args: array(string2()).optional()
@@ -100352,7 +100352,6 @@ var defaultDeps5 = {
readConfigFile: (path) => readFileSync31(path, "utf-8"),
parseConfigContent: (content) => parseJsonc(content)
};
-var BUN_POSTINSTALL_HELPER_PACKAGE_NAME = "@code-yeongyu/comment-checker";
function isConfigValid(configPath, deps) {
if (!configPath)
return true;
@@ -100473,7 +100472,7 @@ async function checkSystem(deps = defaultDeps5) {
description: `Loaded ${systemInfo.loadedVersion}, latest ${latestVersion}.`,
fix: `Update: cd "${loadedInfo.cacheDir}" && bun add ${loadedPackageName}@${installTag}
` + `If Bun reports blocked postinstalls, inspect them: cd "${loadedInfo.cacheDir}" && bun pm untrusted
-` + `Then trust only OMO-related packages from that list: cd "${loadedInfo.cacheDir}" && bun pm trust ${loadedPackageName} ${BUN_POSTINSTALL_HELPER_PACKAGE_NAME}`,
+` + `Then trust only OMO-related packages from that list: cd "${loadedInfo.cacheDir}" && bun pm trust ${loadedPackageName}`,
severity: "warning",
affects: ["plugin features"]
});
@@ -100940,6 +100939,35 @@ async function checkConfig() {
};
}
+// packages/omo-opencode/src/cli/doctor/checks/browser-provider.ts
+async function checkBrowserProvider() {
+ const chain = loadOmoOpenCodeConfigChain(process.cwd());
+ const issues = [];
+ for (const view of chain.views) {
+ const browserConfig = view.config.browser_automation_engine;
+ if (browserConfig === undefined)
+ continue;
+ const result = BrowserAutomationConfigSchema.safeParse(browserConfig);
+ if (result.success)
+ continue;
+ for (const issue of result.error.issues) {
+ const path = ["browser_automation_engine", ...issue.path].join(".");
+ issues.push({
+ title: "Invalid browser provider configuration",
+ description: `${view.path}: ${path}: ${issue.message}`,
+ severity: "error",
+ affects: [path]
+ });
+ }
+ }
+ return {
+ name: "Browser Provider",
+ status: issues.length > 0 ? "fail" : "pass",
+ message: issues.length > 0 ? "Browser provider configuration requires migration" : "Browser provider configuration is valid",
+ issues
+ };
+}
+
// packages/omo-opencode/src/cli/doctor/checks/deprecated-reasoning-keys.ts
init_src4();
init_main();
@@ -101035,11 +101063,11 @@ import { homedir as homedir19 } from "node:os";
import { dirname as dirname31, join as join81 } from "node:path";
// packages/omo-opencode/src/hooks/comment-checker/downloader.ts
-import { join as join80 } from "path";
-import { homedir as homedir18, tmpdir as tmpdir4 } from "os";
init_binary_downloader();
init_logger2();
init_plugin_identity();
+import { join as join80 } from "path";
+import { homedir as homedir18, tmpdir as tmpdir4 } from "os";
var DEBUG = process.env.COMMENT_CHECKER_DEBUG === "1";
var DEBUG_FILE = join80(tmpdir4(), "comment-checker-debug.log");
function getCacheDir2() {
@@ -101597,7 +101625,7 @@ function buildToolIssues(summary) {
issues.push({
title: "Comment checker unavailable",
description: "Comment checker binary is not installed.",
- fix: "Install @code-yeongyu/comment-checker",
+ fix: "The hook downloads its pinned GitHub release automatically on first use. Allow access to github.com and restart OpenCode to retry.",
severity: "warning",
affects: ["comment-checker hook"]
});
@@ -102505,6 +102533,7 @@ function parseRuntimeTargetPath(wrapper) {
// packages/omo-opencode/src/cli/doctor/checks/index.ts
function getAllCheckDefinitions() {
return [
+ { id: "browser-provider", name: "Browser Provider", check: checkBrowserProvider },
{
id: CHECK_IDS.SYSTEM,
name: CHECK_NAMES[CHECK_IDS.SYSTEM],
diff --git a/plugins/omo/dist/cli/index.js b/plugins/omo/dist/cli/index.js
index c155d2b1..09bf1888 100755
--- a/plugins/omo/dist/cli/index.js
+++ b/plugins/omo/dist/cli/index.js
@@ -64,7 +64,7 @@ var package_default;
var init_package = __esm(() => {
package_default = {
name: "oh-my-opencode",
- version: "5.0.0-beta.62",
+ version: "5.0.0-beta.63",
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",
@@ -96,8 +96,6 @@ var init_package = __esm(() => {
"packages/omo-codex",
"packages/omo-senpi",
"packages/senpi-task",
- "packages/pi-goal",
- "packages/pi-webfetch",
"packages/omo-opencode",
"packages/omo-native"
],
@@ -199,7 +197,7 @@ var init_package = __esm(() => {
prepublishOnly: "bun run clean && bun run build:lsp-tools-mcp && bun run build:lsp-daemon && bun run build",
"test:model-capabilities": "bun test --timeout 20000 packages/model-core/src/model-capability-aliases.test.ts packages/model-core/src/model-capability-guardrails.test.ts packages/model-core/src/model-capabilities.test.ts packages/omo-opencode/src/cli/doctor/checks/model-resolution.test.ts --bail",
typecheck: "tsgo --noEmit && bun run typecheck:script && bun run typecheck:packages",
- "typecheck:packages": "tsgo --noEmit -p packages/rules-engine/tsconfig.json && tsgo --noEmit -p packages/delegate-core/tsconfig.json && tsgo --noEmit -p packages/mcp-stdio-core/tsconfig.json && tsgo --noEmit -p packages/mcp-client-core/tsconfig.json && tsgo --noEmit -p packages/git-bash-mcp/tsconfig.json && tsgo --noEmit -p packages/ast-grep-mcp/tsconfig.json && tsgo --noEmit -p packages/lsp-core/tsconfig.json && tsgo --noEmit -p packages/utils/tsconfig.json && tsgo --noEmit -p packages/model-core/tsconfig.json && tsgo --noEmit -p packages/omo-config-core/tsconfig.json && tsgo --noEmit -p packages/prompts-core/tsconfig.json && tsgo --noEmit -p packages/comment-checker-core/tsconfig.json && tsgo --noEmit -p packages/hashline-core/tsconfig.json && tsgo --noEmit -p packages/tmux-core/tsconfig.json && tsgo --noEmit -p packages/team-core/tsconfig.json && tsgo --noEmit -p packages/openclaw-core/tsconfig.json && tsgo --noEmit -p packages/boulder-state/tsconfig.json && tsgo --noEmit -p packages/memory-core/tsconfig.json && tsgo --noEmit -p packages/telemetry-core/tsconfig.json && tsgo --noEmit -p packages/claude-code-compat-core/tsconfig.json && tsgo --noEmit -p packages/skills-loader-core/tsconfig.json && tsgo --noEmit -p packages/agents-md-core/tsconfig.json && tsgo --noEmit -p packages/omo-codex/plugin/shared/tsconfig.json && tsgo --noEmit -p packages/omo-codex/tsconfig.json && tsgo --noEmit -p packages/omo-senpi/tsconfig.json && tsgo --noEmit -p packages/senpi-task/tsconfig.json && tsgo --noEmit -p packages/pi-goal/tsconfig.json && tsgo --noEmit -p packages/pi-webfetch/tsconfig.json && tsgo --noEmit -p packages/omo-opencode/tsconfig.json && tsgo --noEmit -p packages/omo-native/tsconfig.json",
+ "typecheck:packages": "tsgo --noEmit -p packages/rules-engine/tsconfig.json && tsgo --noEmit -p packages/delegate-core/tsconfig.json && tsgo --noEmit -p packages/mcp-stdio-core/tsconfig.json && tsgo --noEmit -p packages/mcp-client-core/tsconfig.json && tsgo --noEmit -p packages/git-bash-mcp/tsconfig.json && tsgo --noEmit -p packages/ast-grep-mcp/tsconfig.json && tsgo --noEmit -p packages/lsp-core/tsconfig.json && tsgo --noEmit -p packages/utils/tsconfig.json && tsgo --noEmit -p packages/model-core/tsconfig.json && tsgo --noEmit -p packages/omo-config-core/tsconfig.json && tsgo --noEmit -p packages/prompts-core/tsconfig.json && tsgo --noEmit -p packages/comment-checker-core/tsconfig.json && tsgo --noEmit -p packages/hashline-core/tsconfig.json && tsgo --noEmit -p packages/tmux-core/tsconfig.json && tsgo --noEmit -p packages/team-core/tsconfig.json && tsgo --noEmit -p packages/openclaw-core/tsconfig.json && tsgo --noEmit -p packages/boulder-state/tsconfig.json && tsgo --noEmit -p packages/memory-core/tsconfig.json && tsgo --noEmit -p packages/telemetry-core/tsconfig.json && tsgo --noEmit -p packages/claude-code-compat-core/tsconfig.json && tsgo --noEmit -p packages/skills-loader-core/tsconfig.json && tsgo --noEmit -p packages/agents-md-core/tsconfig.json && tsgo --noEmit -p packages/omo-codex/plugin/shared/tsconfig.json && tsgo --noEmit -p packages/omo-codex/tsconfig.json && tsgo --noEmit -p packages/omo-senpi/tsconfig.json && tsgo --noEmit -p packages/senpi-task/tsconfig.json && tsgo --noEmit -p packages/omo-opencode/tsconfig.json && tsgo --noEmit -p packages/omo-native/tsconfig.json",
"typecheck:script": "tsgo --noEmit -p script/tsconfig.json",
test: "bun test --timeout 20000",
"changelog:section": "bun script/changelog-section.ts",
@@ -231,7 +229,6 @@ var init_package = __esm(() => {
homepage: "https://github.com/code-yeongyu/oh-my-openagent#readme",
dependencies: {
"@clack/prompts": "^1.7.0",
- "@code-yeongyu/comment-checker": "^0.8.0",
"@modelcontextprotocol/sdk": "^1.30.0",
"@opencode-ai/plugin": "1.18.22",
"@opencode-ai/sdk": "1.18.22",
@@ -249,7 +246,7 @@ var init_package = __esm(() => {
zod: "^4.4.3"
},
devDependencies: {
- "@code-yeongyu/senpi": "2026.9.13",
+ "@code-yeongyu/senpi": "2026.9.15-2",
"@oh-my-opencode/agents-md-core": "workspace:*",
"@oh-my-opencode/ast-grep-mcp": "workspace:*",
"@oh-my-opencode/boulder-state": "workspace:*",
@@ -268,8 +265,6 @@ var init_package = __esm(() => {
"@oh-my-opencode/omo-opencode": "workspace:*",
"@oh-my-opencode/omo-senpi": "workspace:*",
"@oh-my-opencode/openclaw-core": "workspace:*",
- "@oh-my-opencode/pi-goal": "workspace:*",
- "@oh-my-opencode/pi-webfetch": "workspace:*",
"@oh-my-opencode/prompts-core": "workspace:*",
"@oh-my-opencode/rules-engine": "workspace:*",
"@oh-my-opencode/senpi-task": "workspace:*",
@@ -290,18 +285,18 @@ var init_package = __esm(() => {
typescript: "^7.0.2"
},
optionalDependencies: {
- "oh-my-opencode-darwin-arm64": "5.0.0-beta.62",
- "oh-my-opencode-darwin-x64": "5.0.0-beta.62",
- "oh-my-opencode-darwin-x64-baseline": "5.0.0-beta.62",
- "oh-my-opencode-linux-arm64": "5.0.0-beta.62",
- "oh-my-opencode-linux-arm64-musl": "5.0.0-beta.62",
- "oh-my-opencode-linux-x64": "5.0.0-beta.62",
- "oh-my-opencode-linux-x64-baseline": "5.0.0-beta.62",
- "oh-my-opencode-linux-x64-musl": "5.0.0-beta.62",
- "oh-my-opencode-linux-x64-musl-baseline": "5.0.0-beta.62",
- "oh-my-opencode-windows-arm64": "5.0.0-beta.62",
- "oh-my-opencode-windows-x64": "5.0.0-beta.62",
- "oh-my-opencode-windows-x64-baseline": "5.0.0-beta.62"
+ "oh-my-opencode-darwin-arm64": "5.0.0-beta.63",
+ "oh-my-opencode-darwin-x64": "5.0.0-beta.63",
+ "oh-my-opencode-darwin-x64-baseline": "5.0.0-beta.63",
+ "oh-my-opencode-linux-arm64": "5.0.0-beta.63",
+ "oh-my-opencode-linux-arm64-musl": "5.0.0-beta.63",
+ "oh-my-opencode-linux-x64": "5.0.0-beta.63",
+ "oh-my-opencode-linux-x64-baseline": "5.0.0-beta.63",
+ "oh-my-opencode-linux-x64-musl": "5.0.0-beta.63",
+ "oh-my-opencode-linux-x64-musl-baseline": "5.0.0-beta.63",
+ "oh-my-opencode-windows-arm64": "5.0.0-beta.63",
+ "oh-my-opencode-windows-x64": "5.0.0-beta.63",
+ "oh-my-opencode-windows-x64-baseline": "5.0.0-beta.63"
},
overrides: {
"@earendil-works/pi-agent-core": "0.84.2",
@@ -315,9 +310,7 @@ var init_package = __esm(() => {
"path-to-regexp": "^8.4.2",
"@types/node": "26.2.0"
},
- trustedDependencies: [
- "@code-yeongyu/comment-checker"
- ]
+ trustedDependencies: []
};
});
@@ -7150,15 +7143,20 @@ var init_agent_model_requirements = __esm(() => {
},
metis: {
fallbackChain: [
+ {
+ providers: ["anthropic", "github-copilot", "opencode"],
+ model: "claude-fable-5-1",
+ variant: "max"
+ },
{
providers: ["anthropic", "github-copilot", "opencode"],
model: "claude-opus-5",
- variant: "high"
+ variant: "max"
},
{
providers: ["opencode-go", "kimi-for-coding", "moonshotai", "opencode"],
model: "kimi-k3",
- variant: "low"
+ variant: "max"
}
]
},
@@ -72934,6 +72932,7 @@ var init_task = __esm(() => {
model_concurrency: record(string2(), number2().int().nonnegative()).optional(),
max_depth: number2().int().nonnegative().default(1),
residency_max_children: ResidencyMaxChildrenInputSchema.default(8),
+ resident_idle_timeout_ms: number2().int().positive().max(Number.MAX_SAFE_INTEGER).default(900000),
ttl_ms: number2().int().positive().default(86400000),
state_dir: string2().optional(),
reattach_on_reconcile: boolean2().optional(),
@@ -72978,6 +72977,7 @@ var init_task = __esm(() => {
model_concurrency: record(string2(), number2().int().nonnegative()).optional(),
max_depth: number2().int().nonnegative().optional(),
residency_max_children: ResidencyMaxChildrenInputSchema.optional(),
+ resident_idle_timeout_ms: number2().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
ttl_ms: number2().int().positive().optional(),
state_dir: string2().optional(),
reattach_on_reconcile: boolean2().optional(),
@@ -84542,7 +84542,7 @@ var package_default2;
var init_package2 = __esm(() => {
package_default2 = {
name: "@oh-my-opencode/omo-codex",
- version: "5.0.0-beta.62",
+ version: "5.0.0-beta.63",
type: "module",
private: true,
description: "Codex harness adapter for oh-my-openagent. Vendored Codex plugin namespace (omo) + TypeScript installer + telemetry.",
@@ -93545,7 +93545,6 @@ var REQUIRED_PLUGIN_ARTIFACTS = [
join60("extensions", "omo.js"),
join60("extensions", "omo-task.js"),
join60("extensions", "omo-member.js"),
- join60("extensions", "omo-agent-toolkit.js"),
join60("extensions", "memory-run-supervisor.mjs"),
...PERSONA_ASSET_FILES.map((filename) => join60("extensions", filename)),
join60("skills", "ast-grep", "SKILL.md"),
@@ -93567,6 +93566,7 @@ var REQUIRED_PLUGIN_ARTIFACTS = [
join60("skills", "ulw-research", "SKILL.md"),
join60("skills", "visual-qa", "SKILL.md"),
join60("skills-conditional", "x-search", "SKILL.md"),
+ join60("runtime", "agent-toolkit-sdk", "sdk.js"),
join60("runtime", "ast-grep-mcp", "cli.js"),
join60("runtime", "lsp-daemon", "dist", "cli.js"),
join60("runtime", "lsp-daemon", "dist", "index.js"),
@@ -96899,7 +96899,6 @@ var BuiltinAgentNameSchema = _enum([
]);
var BuiltinSkillNameSchema = _enum([
"playwright",
- "agent-browser",
"dev-browser",
"frontend",
"git-master",
@@ -97062,10 +97061,11 @@ var BackgroundTaskConfigSchema = object({
init_zod();
var BrowserAutomationProviderSchema = _enum([
"playwright",
- "agent-browser",
"dev-browser",
"playwright-cli"
-]);
+], {
+ error: (issue) => `Browser provider ${JSON.stringify(issue.input)} is no longer supported; use the built-in browser path: Bun.WebView / playwright-core scripts`
+});
var BrowserAutomationConfigSchema = object({
provider: BrowserAutomationProviderSchema.default("playwright"),
playwright_mcp_args: array(string2()).optional()
@@ -100273,7 +100273,6 @@ var defaultDeps5 = {
readConfigFile: (path) => readFileSync31(path, "utf-8"),
parseConfigContent: (content) => parseJsonc(content)
};
-var BUN_POSTINSTALL_HELPER_PACKAGE_NAME = "@code-yeongyu/comment-checker";
function isConfigValid(configPath, deps) {
if (!configPath)
return true;
@@ -100394,7 +100393,7 @@ async function checkSystem(deps = defaultDeps5) {
description: `Loaded ${systemInfo.loadedVersion}, latest ${latestVersion}.`,
fix: `Update: cd "${loadedInfo.cacheDir}" && bun add ${loadedPackageName}@${installTag}
` + `If Bun reports blocked postinstalls, inspect them: cd "${loadedInfo.cacheDir}" && bun pm untrusted
-` + `Then trust only OMO-related packages from that list: cd "${loadedInfo.cacheDir}" && bun pm trust ${loadedPackageName} ${BUN_POSTINSTALL_HELPER_PACKAGE_NAME}`,
+` + `Then trust only OMO-related packages from that list: cd "${loadedInfo.cacheDir}" && bun pm trust ${loadedPackageName}`,
severity: "warning",
affects: ["plugin features"]
});
@@ -100861,6 +100860,35 @@ async function checkConfig() {
};
}
+// packages/omo-opencode/src/cli/doctor/checks/browser-provider.ts
+async function checkBrowserProvider() {
+ const chain = loadOmoOpenCodeConfigChain(process.cwd());
+ const issues = [];
+ for (const view of chain.views) {
+ const browserConfig = view.config.browser_automation_engine;
+ if (browserConfig === undefined)
+ continue;
+ const result = BrowserAutomationConfigSchema.safeParse(browserConfig);
+ if (result.success)
+ continue;
+ for (const issue of result.error.issues) {
+ const path = ["browser_automation_engine", ...issue.path].join(".");
+ issues.push({
+ title: "Invalid browser provider configuration",
+ description: `${view.path}: ${path}: ${issue.message}`,
+ severity: "error",
+ affects: [path]
+ });
+ }
+ }
+ return {
+ name: "Browser Provider",
+ status: issues.length > 0 ? "fail" : "pass",
+ message: issues.length > 0 ? "Browser provider configuration requires migration" : "Browser provider configuration is valid",
+ issues
+ };
+}
+
// packages/omo-opencode/src/cli/doctor/checks/deprecated-reasoning-keys.ts
init_src4();
init_main();
@@ -100956,11 +100984,11 @@ import { homedir as homedir19 } from "os";
import { dirname as dirname31, join as join81 } from "path";
// packages/omo-opencode/src/hooks/comment-checker/downloader.ts
-import { join as join80 } from "path";
-import { homedir as homedir18, tmpdir as tmpdir4 } from "os";
init_binary_downloader();
init_logger2();
init_plugin_identity();
+import { join as join80 } from "path";
+import { homedir as homedir18, tmpdir as tmpdir4 } from "os";
var DEBUG = process.env.COMMENT_CHECKER_DEBUG === "1";
var DEBUG_FILE = join80(tmpdir4(), "comment-checker-debug.log");
function getCacheDir2() {
@@ -101518,7 +101546,7 @@ function buildToolIssues(summary) {
issues.push({
title: "Comment checker unavailable",
description: "Comment checker binary is not installed.",
- fix: "Install @code-yeongyu/comment-checker",
+ fix: "The hook downloads its pinned GitHub release automatically on first use. Allow access to github.com and restart OpenCode to retry.",
severity: "warning",
affects: ["comment-checker hook"]
});
@@ -102426,6 +102454,7 @@ function parseRuntimeTargetPath(wrapper) {
// packages/omo-opencode/src/cli/doctor/checks/index.ts
function getAllCheckDefinitions() {
return [
+ { id: "browser-provider", name: "Browser Provider", check: checkBrowserProvider },
{
id: CHECK_IDS.SYSTEM,
name: CHECK_NAMES[CHECK_IDS.SYSTEM],
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.json
index a644c04a..3a225909 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 5.0.0-beta.62) Resetting Git Bash MCP Reminder",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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.json
index 4514e12f..e8edb0bc 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 5.0.0-beta.62) Resetting LSP Diagnostics Cache",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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.json
index 33104403..0580b5fa 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 5.0.0-beta.62) Resetting Project Rule Cache",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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-comments.json b/plugins/omo/hooks/post-tool-use-checking-comments.json
index 91bd8b90..aabf8f38 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 5.0.0-beta.62) Checking Comments",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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.json
index 534ea792..a1ff73b4 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 5.0.0-beta.62) Checking LSP Diagnostics",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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.json
index abff39a9..6a9b0ed1 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 5.0.0-beta.62) Checking Thread Title Hygiene",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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.json
index a97cff24..3ffec820 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 5.0.0-beta.62) Matching Project Rules",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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/post-tool-use-recording-spawn-admission.json b/plugins/omo/hooks/post-tool-use-recording-spawn-admission.json
index 67e94de9..89f7c86b 100644
--- a/plugins/omo/hooks/post-tool-use-recording-spawn-admission.json
+++ b/plugins/omo/hooks/post-tool-use-recording-spawn-admission.json
@@ -8,7 +8,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook post-tool-use-spawn",
"timeout": 5,
- "statusMessage": "(OmO 5.0.0-beta.62) Recording Spawn Admission",
+ "statusMessage": "(OmO 5.0.0-beta.63) Recording Spawn Admission",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook post-tool-use-spawn"
}
]
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.json
index 2e247b2f..00578ef4 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 5.0.0-beta.62) Enforcing Unlimited Goal Budget",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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.json
index c26eba4b..b292b53f 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 5.0.0-beta.62) Guarding Ulw-Loop Spawns",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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.json
index 850d2034..a58868c1 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 5.0.0-beta.62) Recommending Git Bash MCP",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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.json
index 0089721b..54e2632d 100644
--- a/plugins/omo/hooks/session-start-checking-auto-update.json
+++ b/plugins/omo/hooks/session-start-checking-auto-update.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/scripts/auto-update.mjs\" hook session-start",
"timeout": 15,
- "statusMessage": "(OmO 5.0.0-beta.62) Checking Auto Update",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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.json
index 1f87fda6..dbd59590 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 5.0.0-beta.62) Checking Bootstrap Provisioning"
+ "statusMessage": "(OmO 5.0.0-beta.63) Checking Bootstrap Provisioning"
}
]
}
diff --git a/plugins/omo/hooks/session-start-loading-project-rules.json b/plugins/omo/hooks/session-start-loading-project-rules.json
index c0328fc0..ccce7932 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 5.0.0-beta.62) Loading Project Rules",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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.json
index d1071e7a..97483cc7 100644
--- a/plugins/omo/hooks/session-start-recording-session-telemetry.json
+++ b/plugins/omo/hooks/session-start-recording-session-telemetry.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/telemetry/dist/cli.js\" hook session-start",
"timeout": 15,
- "statusMessage": "(OmO 5.0.0-beta.62) Recording Session Telemetry",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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-ulw-execute-continuation.json b/plugins/omo/hooks/stop-checking-ulw-execute-continuation.json
index 6ede9e7d..36db922f 100644
--- a/plugins/omo/hooks/stop-checking-ulw-execute-continuation.json
+++ b/plugins/omo/hooks/stop-checking-ulw-execute-continuation.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/ulw-execute-continuation/dist/cli.js\" hook stop",
"timeout": 10,
- "statusMessage": "(OmO 5.0.0-beta.62) Checking Ulw-Execute Continuation",
+ "statusMessage": "(OmO 5.0.0-beta.63) Checking Ulw-Execute Continuation",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-execute-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.json
index 34479f4d..2e122c52 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 5.0.0-beta.62) Checking Ulw-Loop Resume",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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-verifying-lazycodex-executor-evidence.json b/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json
index 64024e32..344803a7 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 5.0.0-beta.62) Verifying LazyCodex Executor Evidence",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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.json
index 2c59c568..a8d65bb0 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 5.0.0-beta.62) Checking Ultrawork Trigger",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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.json
index 2c8fb922..0b36a604 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 5.0.0-beta.62) Checking Ulw-Loop Steering",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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.json
index e1128d51..44a922ce 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 5.0.0-beta.62) Loading Project Rules",
+ "statusMessage": "(OmO 5.0.0-beta.63) 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.json
index ed04646d..309a2a74 100644
--- a/plugins/omo/package-lock.json
+++ b/plugins/omo/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@sisyphuslabs/omo-codex-plugin",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@sisyphuslabs/omo-codex-plugin",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"workspaces": [
"components/comment-checker",
"components/git-bash",
@@ -90,7 +90,7 @@
},
"components/comment-checker": {
"name": "@code-yeongyu/codex-comment-checker",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"license": "MIT",
"bin": {
"omo-comment-checker": "dist/cli.js"
@@ -111,7 +111,7 @@
},
"components/git-bash": {
"name": "@sisyphuslabs/codex-git-bash-hook",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"bin": {
"omo-git-bash-hook": "dist/cli.js"
},
@@ -125,7 +125,7 @@
},
"components/lazycodex-executor-verify": {
"name": "@code-yeongyu/codex-lazycodex-executor-verify",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"license": "MIT",
"bin": {
"lazycodex-executor-verify": "dist/cli.js"
@@ -142,7 +142,7 @@
},
"components/lsp": {
"name": "@code-yeongyu/codex-lsp",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"license": "MIT",
"dependencies": {
"@code-yeongyu/lsp-daemon": "file:../../../../lsp-daemon",
@@ -163,7 +163,7 @@
},
"components/rules": {
"name": "@code-yeongyu/codex-rules",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"license": "MIT",
"dependencies": {
"picomatch": "^4.0.7"
@@ -185,7 +185,7 @@
},
"components/teammode": {
"name": "@sisyphuslabs/codex-teammode",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"devDependencies": {
"@types/node": "^26.2.0",
"bun-types": "^1.4.2",
@@ -198,7 +198,7 @@
},
"components/telemetry": {
"name": "@code-yeongyu/codex-telemetry",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"license": "MIT",
"bin": {
"omo-telemetry": "dist/cli.js"
@@ -216,7 +216,7 @@
},
"components/ultrawork": {
"name": "@code-yeongyu/codex-ultrawork",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"license": "MIT",
"bin": {
"omo-ultrawork": "dist/cli.js"
@@ -234,7 +234,7 @@
},
"components/ulw-execute-continuation": {
"name": "@code-yeongyu/codex-ulw-execute-continuation",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"license": "MIT",
"bin": {
"omo-ulw-execute-continuation": "dist/cli.js"
@@ -251,7 +251,7 @@
},
"components/ulw-loop": {
"name": "@code-yeongyu/codex-ulw-loop",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"license": "MIT",
"bin": {
"omo-ulw-loop": "dist/cli.js",
diff --git a/plugins/omo/package.json b/plugins/omo/package.json
index a42fa1e8..47001640 100644
--- a/plugins/omo/package.json
+++ b/plugins/omo/package.json
@@ -1,6 +1,6 @@
{
"name": "@sisyphuslabs/omo-codex-plugin",
- "version": "5.0.0-beta.62",
+ "version": "5.0.0-beta.63",
"description": "Aggregate Codex plugin root for OMO components.",
"type": "module",
"packageManager": "[email protected]",
diff --git a/plugins/omo/scripts/sync-skills.d.mts b/plugins/omo/scripts/sync-skills.d.mts
new file mode 100644
index 00000000..1f68959c
--- /dev/null
+++ b/plugins/omo/scripts/sync-skills.d.mts
@@ -0,0 +1,4 @@
+export function getSkillOutputManifest(): Promise<{
+ readonly root: string
+ readonly names: readonly string[]
+}>
diff --git a/plugins/omo/scripts/sync-skills.mjs b/plugins/omo/scripts/sync-skills.mjs
index 8ca1362f..cf76fe7f 100644
--- a/plugins/omo/scripts/sync-skills.mjs
+++ b/plugins/omo/scripts/sync-skills.mjs
@@ -274,6 +274,19 @@ async function adaptSkillForCodex(skillName) {
await writeCodexSkillDisplayMetadata(skillName);
}
+// Read-only inventory shared by generation and shipped-payload validation.
+export async function getSkillOutputManifest() {
+ const sharedSkillEntries = await readdir(sharedSkillsRoot, { withFileTypes: true });
+ const sharedSkillNames = sharedSkillEntries
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => entry.name)
+ .sort();
+ return {
+ root: skillsRoot,
+ names: [...new Set([...componentSkillNames, ...sharedSkillNames])],
+ };
+}
+
async function syncSkills() {
await rm(skillsRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
await mkdir(skillsRoot, { recursive: true });
@@ -292,13 +305,8 @@ async function syncSkills() {
);
await adaptSkillForCodex("ultrawork");
- const sharedSkillEntries = await readdir(sharedSkillsRoot, { withFileTypes: true });
- const sharedSkillNames = sharedSkillEntries
- .filter((entry) => entry.isDirectory())
- .map((entry) => entry.name)
- .sort();
-
- for (const skillName of sharedSkillNames) {
+ const { names } = await getSkillOutputManifest();
+ for (const skillName of names) {
if (componentSkillNames.has(skillName)) continue;
const sharedSkillSource = join(sharedSkillsRoot, skillName);
await cp(sharedSkillSource, join(skillsRoot, skillName), {
diff --git a/plugins/omo/skills/ast-grep/SKILL.md b/plugins/omo/skills/ast-grep/SKILL.md
index 40e395d0..98a112cd 100644
--- a/plugins/omo/skills/ast-grep/SKILL.md
+++ b/plugins/omo/skills/ast-grep/SKILL.md
@@ -11,6 +11,18 @@ This skill ships a Python wrapper at `scripts/ast_grep_helper.py` and platform i
---
+## OmO native: the ast-grep MCP tools (fastest path, no CLI needed)
+
+OmO native also registers a bundled ast-grep MCP server. Its three tools are **deferred**: they are absent from the resident tool list and activate automatically the first time you call them by name — no `tool_search` round trip needed.
+
+- `mcp__ast_grep_search({ pattern, language, paths })` — AST-shape search, the MCP equivalent of `sg run -p`. Prefer this over shelling out to `sg` for one-off lookups: no install, no PATH issues.
+- `mcp__ast_grep_rewrite({ pattern, rewrite, language, paths, apply })` — preview matches (`apply: false`, the default) or apply the rewrite (`apply: true`). Same two-pass discipline as `sg run -r`: preview first, then apply.
+- `mcp__ast_grep_scan({ paths })` — run project YAML rules (`sgconfig.yml`, `rules/`), the MCP equivalent of `sg scan`.
+
+Same pattern language as the CLI: `$VAR` matches one AST node, `$$$VAR` matches zero or more, and the pattern is code, not regex. `paths` accepts a file or directory list; `language` is required for patterns that are ambiguous across languages.
+
+---
+
## When to use this skill
Use it whenever the user's question is about **code structure**, not bytes:
diff --git a/plugins/omo/skills/debugging/references/tools/playwright-cli.md b/plugins/omo/skills/debugging/references/tools/playwright-cli.md
index 7d636715..c5d8865d 100644
--- a/plugins/omo/skills/debugging/references/tools/playwright-cli.md
+++ b/plugins/omo/skills/debugging/references/tools/playwright-cli.md
@@ -1,194 +1,112 @@
-# Playwright CLI — Browser QA That Actually Drives a Browser
+# Browser QA — Scripts from js eval
-**https://playwright.dev/ · https://github.com/microsoft/playwright**
-
-For any browser-served web UI bug, this is the correct tool. Not curl. Not imagination. Not a headless HTTP library. A real browser with a real rendering engine, real JS execution, real cookies, real service workers, real viewport.
-
-**In Phase 8 Manual QA for browser products, using Playwright is not optional.** Curl cannot catch: CSS that breaks at specific viewport widths, hydration mismatches, client-side router bugs, cookie/session interactions, service-worker caching, JS-triggered navigations. All of those are common bug classes. Drive a browser.
-
-> Note: `microsoft/playwright-cli` is the legacy repo; the current tooling lives in `@playwright/test` (npm) and `playwright` (pip), which include the `playwright` CLI. Use those — the legacy `playwright-cli` package is deprecated.
-
----
+A browser UI bug needs a rendered browser, not curl. Use two tiers from the
+js-eval kernel: `new Bun.WebView()` on Bun >= 1.4 for ordinary captures (macOS
+uses WebKit; Linux/Windows need installed Chrome/Chromium/Edge), otherwise a
+written `playwright-core` script against local Chrome. Use the script tier for
+Chrome semantics, stealth, traces, keyboard events, or authenticated profiles.
+In Codex, prefer `browser:control-in-app-browser` for ordinary page control.
## When to reach for Playwright
-| Bug symptom | Use Playwright? |
-|---|---|
-| Form submit produces wrong result | ✅ — Playwright drives the form exactly as a user does |
-| Page blank in prod, fine locally | ✅ — hydration/env differences need a real browser |
-| CSS looks wrong at a specific width | ✅ — use `--viewport-size` |
-| Click doesn't fire / wrong handler | ✅ — Playwright fires real DOM events |
-| Flash of unstyled content / loading glitch | ✅ — use trace viewer to see frames |
-| API returns wrong data | ❌ — use curl, this isn't a browser bug |
-| Backend returns wrong status code | ❌ — use curl |
-| Client hits a URL that returns 500 | ✅ but also ❌ — Playwright shows the call + response + failure effect on UI |
-
----
+Use the script tier for forms, hydration, responsive CSS, cookie/session flows,
+service workers, or client-side navigation. For a backend-only status/body bug,
+use HTTP. WebView is headless, WebKit has no CDP, and `type()` emits no keyboard
+events; choose real Chrome when these distinctions affect the reproduction.
## Install (per-project)
-Playwright installs browser binaries separately from the npm package.
-
-```bash
-# In the project
-npm init playwright@latest # interactive; picks TS/JS + browsers + config
-# Or if Playwright is already a dep:
-npx playwright install # downloads browsers
-npx playwright install chromium # just chromium
-npx playwright install --with-deps # also installs OS deps (Linux)
-```
-
-Python:
-```bash
-pip install playwright
-playwright install
-```
+Reuse installed `playwright-core`. If absent, the user can install the script
+dependency once with `bun add playwright-core`. Chrome must already be installed;
+report an absent executable rather than downloading a managed browser. Write the
+script beside the dependency so normal module resolution works.
----
+For stealth, use the ultimate-browsing reference `references/chrome-stealth.md`:
+its optional plugins are user-installed once in the engine directory and executed
+as a script, not injected into WebView.
## The four things you'll actually use
-### 1. `codegen` — record a session, generate the script
-
-The fastest way to create a repro. Opens a real browser; your clicks / typing become a Playwright script you can paste into a test.
-
-```bash
-npx playwright codegen https://your-app.local
-npx playwright codegen --viewport-size=375,667 https://your-app.local # iPhone SE size
-npx playwright codegen --device="iPhone 14" https://your-app.local
-```
-
-Click / type / navigate in the browser; watch the script build in the side panel. Copy the generated script into your journal as the repro for Phase 8.
-
-### 2. A one-shot Playwright script — reproduce + capture
-
-Usually the Phase 8 QA artifact. Save to `/tmp/debug-repro.spec.ts` (journal it):
-
-```ts
-// /tmp/debug-repro.spec.ts
-import { test, expect } from '@playwright/test';
-
-test('refinement chat shows non-empty response when env var set', async ({ page }) => {
- await page.goto('http://localhost:3000/chat');
- await page.fill('textarea[name="message"]', 'Add a logging step');
- await page.click('button[type=submit]');
-
- // Wait for the response to appear (not just the spinner to disappear)
- const response = page.locator('[data-testid="assistant-reply"]');
- await expect(response).toBeVisible({ timeout: 30_000 });
- await expect(response).not.toBeEmpty();
-
- // Capture evidence
- await page.screenshot({ path: '/tmp/debug-after-fix.png', fullPage: true });
- console.log(await response.textContent());
-});
-```
-
-Run it with tracing enabled for rich post-mortem:
-
-```bash
-npx playwright test /tmp/debug-repro.spec.ts --trace on --headed
-```
-
-### 3. `PWDEBUG=1` — step through the script with Playwright Inspector
-
-```bash
-PWDEBUG=1 npx playwright test /tmp/debug-repro.spec.ts
+### 1. Write a reproduction script
+
+Record the exact URL, inputs, viewport, expected UI state, and output artifact.
+For auth, CLONE the user-data directory and use `launchPersistentContext` on the
+clone. NEVER launch against or clear data from the live profile.
+
+### 2. Reproduce + capture
+
+```js
+// debug-repro.mjs
+import { chromium } from 'playwright-core';
+const [url, pngPath, tracePath] = process.argv.slice(2);
+const browser = await chromium.launch({ channel: 'chrome', headless: true });
+try {
+ const context = await browser.newContext({ viewport: { width: 1280, height: 720 } });
+ await context.tracing.start({ screenshots: true, snapshots: true });
+ try {
+ const page = await context.newPage();
+ page.on('pageerror', error => console.error(error));
+ await page.goto(url, { waitUntil: 'load', timeout: 30000 });
+ // Add the scenario's actions and locator/state assertions here.
+ await page.screenshot({ path: pngPath });
+ console.log(pngPath);
+ } finally {
+ await context.tracing.stop({ path: tracePath });
+ await context.close();
+ }
+} finally {
+ await browser.close();
+}
```
-Opens the Playwright Inspector alongside the browser. You can step through Playwright actions, see the DOM state at each step, and edit selectors on the fly.
-
-Use this when the script doesn't reproduce cleanly and you need to watch it run.
+A screenshot alone is not a reproduction assertion. Use locators for the exact
+observable state; fail the script when that state is absent.
-### 4. `show-trace` — post-mortem on a failed run
+### 3. Run from the js-eval kernel
-```bash
-npx playwright show-trace trace.zip
-# or from the test-results dir:
-npx playwright show-trace test-results/<test-name>/trace.zip
+```js
+const { promisify } = await import('node:util')
+const { execFile } = await import('node:child_process')
+const result = await promisify(execFile)('node', [scriptPath, url, pngPath, tracePath], { timeout: 60000 })
+console.log(result.stdout)
```
-Scrubs through a recorded session: timeline, DOM snapshot at each action, network, console, source. When a test failed on CI but passed locally, this is the single best artifact.
+### 4. Inspect the trace
----
+Retain the trace ZIP for the project's existing trace viewer and inspect the PNG.
+Trace snapshots, network events, and screenshots identify where the UI diverged.
+Keep auth-bearing traces private; do not upload them to public viewers.
## Headless vs headed during debugging
-Always add `--headed` when debugging. Headless browsers sometimes behave subtly differently (font rendering, viewport, media permissions). For QA evidence, run headed and screenshot.
-
-```bash
-npx playwright test --headed
-npx playwright test --headed --project=chromium # pin the browser
-```
-
----
+Use `headless: false` with an available display when reproducing headed-only
+behavior. State which mode produced the evidence; do not claim a headless capture
+proves desktop-browser permissions or window behavior.
## Catching the silent-failure patterns Playwright is good at
-```ts
-// Toast that flashes and disappears
-page.on('console', msg => console.log('[browser console]', msg.type(), msg.text()));
-
-// Unhandled page errors (uncaught exceptions in the page JS)
-page.on('pageerror', err => console.error('[page error]', err));
-
-// Network failures — e.g., backend returned 500 but UI shows nothing
-page.on('response', async resp => {
- if (!resp.ok()) {
- console.warn(`[network ${resp.status()}] ${resp.url()} — ${await resp.text()}`);
- }
-});
-
-// Request that never came back
-page.on('requestfailed', req => {
- console.error('[request failed]', req.url(), req.failure()?.errorText);
-});
-```
-
-Add these listeners to the top of the debug script. They surface a lot of the "UI showed nothing" class of bug.
-
----
+Subscribe before triggering the action: `page.on('pageerror', ...)`,
+`page.on('requestfailed', ...)`, or a bounded `page.waitForResponse(...)` promise.
+Await that specific response/state rather than sleeping or waiting for generic
+network idleness. Propagate failed assertions and process exit codes.
## Viewport and device emulation
-CSS bugs that only appear at specific sizes, or layout bugs on mobile:
-
-```ts
-// At test level
-test.use({ viewport: { width: 375, height: 667 } });
-
-// Per-page
-await page.setViewportSize({ width: 375, height: 667 });
-
-// Predefined devices
-import { devices } from '@playwright/test';
-test.use({ ...devices['iPhone 14'] });
-```
-
----
+Use `page.setViewportSize({ width: 375, height: 667 })` for a narrow capture.
+`devices` comes from `playwright-core`; apply the desired preset when creating
+a context. Match the reference's pixel scale as well as its viewport.
## Gotchas
-- **Wait for state, not for time.** `await page.waitForTimeout(2000)` is flaky. Use `await expect(locator).toBeVisible()` or `page.waitForResponse(urlPattern)`.
-- **Stale selectors re-resolve.** Playwright's locators re-find the element on each action, unlike Puppeteer's handles. Don't over-think it.
-- **Service workers persist across test runs in headed mode.** If you see cached behavior from a previous run, add `await context.clearCookies()` + clear storage before the test.
-- **Installing on CI requires `--with-deps`** on Linux images that lack the browser's shared-library deps.
-- **Parallel tests share a browser process by default**; if one test polls a debugger port, others may interfere. Use `workers: 1` for debugging.
-
----
+- Wait for state, not time: locator visibility or the exact response is the signal.
+- Locators re-resolve after UI changes; stale element handles do not.
+- Fresh task-owned contexts avoid cached state leaking between runs.
+- Auth belongs in a private clone, never the live browser profile.
+- Give every run its own output directory and bounded process lifetime.
## Phase 9 cleanup specifics
-```bash
-# Remove trace files from debug runs
-rm -rf playwright-report/ test-results/ trace.zip
-
-# Remove debug spec files from /tmp
-rm -f /tmp/debug-*.spec.ts
-
-# Remove screenshot captures
-rm -f /tmp/debug-*.png
-
-# If you installed browsers just for this session (rare):
-# Don't remove them — they're useful for future sessions. They live in ~/Library/Caches/ms-playwright (macOS) or ~/.cache/ms-playwright (Linux).
-```
+Close WebView/browser contexts even on failure, stop the fixture server, and remove
+only this run's temporary scripts and profile clone. Preserve requested PNG/trace
+artifacts, then record the cleanup receipt. Do not kill unrelated browsers or
+remove a user's installed Chrome.
diff --git a/plugins/omo/skills/frontend/SKILL.md b/plugins/omo/skills/frontend/SKILL.md
index d583b17f..4bd071bf 100644
--- a/plugins/omo/skills/frontend/SKILL.md
+++ b/plugins/omo/skills/frontend/SKILL.md
@@ -146,7 +146,7 @@ Domains: `product` `style` `typography` `color` `landing` `chart` `ux` `react` `
| Situation | Load |
|---|---|
| Brand/style not among the 70 in `references/design/`, or the user says "Open Design" | `open-design` skill — the local nexu-io/open-design library (137+ design skills, 150+ design systems) |
-| Driving a browser for the Design QA phase | `agent-browser` skill |
+| Driving a browser for the Design QA phase | `visual-qa` skill: Bun.WebView / local-Chrome `playwright-core` scripts from js eval; Codex in-app browser |
| Pure TypeScript/logic work with zero visual surface | `programming` skill alone — this skill adds nothing there |
## Activation
diff --git a/plugins/omo/skills/frontend/references/design/aside.md b/plugins/omo/skills/frontend/references/design/aside.md
index 7462f49c..2fbacca3 100644
--- a/plugins/omo/skills/frontend/references/design/aside.md
+++ b/plugins/omo/skills/frontend/references/design/aside.md
@@ -1,7 +1,7 @@
# Design System Inspired by Aside
> Category: Developer Tools & IDEs
-> AI browser agent. Bright product-app marketing, custom display type, soft squircle controls, agent-browser product framing.
+> AI browser agent. Bright product-app marketing, custom display type, soft squircle controls, browser-product framing.
## Provenance
diff --git a/plugins/omo/skills/frontend/references/design/clone-from-url.md b/plugins/omo/skills/frontend/references/design/clone-from-url.md
index 6188cb18..a1cebb1c 100644
--- a/plugins/omo/skills/frontend/references/design/clone-from-url.md
+++ b/plugins/omo/skills/frontend/references/design/clone-from-url.md
@@ -8,7 +8,7 @@ A `DESIGN.md` whose every token, interaction state, and motion value was read fr
## Phase 1 — Extract the runtime truth (never guess a value)
-Drive a real browser: Codex `browser:control-in-app-browser` first, otherwise the project's `agent-browser` / playwright / dev-browser tooling. Do NOT parse CSS files — minification, CORS, CSS-in-JS, and Tailwind utilities make source unreliable. `getComputedStyle` returns what the browser ACTUALLY rendered, so it is the only source of truth.
+Drive a real browser from js eval: `new Bun.WebView()` on Bun >= 1.4 (macOS default; Linux/Windows need installed Chrome/Chromium/Edge), otherwise write and run a `playwright-core` script against local Chrome (`channel: "chrome"`). Use that script lane for Chrome semantics, stealth, trace, or auth, with persistent contexts on CLONED profiles only. Codex: `browser:control-in-app-browser`. Do NOT parse CSS files — minification, CORS, CSS-in-JS, and Tailwind utilities make source unreliable. `getComputedStyle` returns what the browser ACTUALLY rendered, so it is the only source of truth.
Sweep the page and read, for every meaningful element and every repeated pattern:
diff --git a/plugins/omo/skills/frontend/scripts/perfection/lighthouse-audit.py b/plugins/omo/skills/frontend/scripts/perfection/lighthouse-audit.py
index ca63e62f..10bdb223 100644
--- a/plugins/omo/skills/frontend/scripts/perfection/lighthouse-audit.py
+++ b/plugins/omo/skills/frontend/scripts/perfection/lighthouse-audit.py
@@ -11,8 +11,8 @@
# ─── How to run ───
# 1. Install uv (if not installed):
# curl -LsSf https://astral.sh/uv/install.sh | sh
-# 2. Install Playwright browsers (one-time):
-# uv run --with playwright python -m playwright install chromium
+# 2. Chrome must already be installed locally:
+# The script uses channel="chrome"; it downloads no browser.
# 3. Run:
# uv run lighthouse-audit.py https://example.com
# uv run lighthouse-audit.py https://example.com --desktop-only
diff --git a/plugins/omo/skills/review-work/SKILL.md b/plugins/omo/skills/review-work/SKILL.md
index 18c42dba..1cb402e3 100644
--- a/plugins/omo/skills/review-work/SKILL.md
+++ b/plugins/omo/skills/review-work/SKILL.md
@@ -169,7 +169,7 @@ You are the QA lane. Do not delegate hands-on QA to a sub-agent: the orchestrato
2. **Pick the channel that faithfully exercises the surface** and capture the artifact:
- HTTP: `curl -i` (or an API request context) - status line, headers, body.
- CLI / TUI: a real pty - drive the command and keep the transcript; for color or layout evidence render through a browser-based terminal, never a `tmux capture-pane` dump.
- - Web: the real page in a real browser - the harness's in-process surface (a `Bun.WebView` / `playwright-core` code cell, or Codex's Browser plugin) or the agent-browser CLI - action log plus screenshot.
+ - Web: from js eval, use `new Bun.WebView()` on Bun >= 1.4 (macOS default; Linux/Windows need Chrome/Chromium/Edge). Otherwise, or for Chrome semantics, stealth, trace, or auth, write and run a `playwright-core` script against local Chrome (`channel: "chrome"`; persistent context on a CLONED profile). Codex: `browser:control-in-app-browser`. Capture action log plus screenshot.
- Desktop / GUI: OS-level automation against the running app - action log plus screenshot.
- Library / SDK: a script that imports and exercises the public API - transcript.
- Data-shaped work (migrations, configs, generated files): the resulting artifact itself, diffed or dumped.
diff --git a/plugins/omo/skills/ultimate-browsing/ATTRIBUTION.md b/plugins/omo/skills/ultimate-browsing/ATTRIBUTION.md
index 27664df2..aa4742ce 100644
--- a/plugins/omo/skills/ultimate-browsing/ATTRIBUTION.md
+++ b/plugins/omo/skills/ultimate-browsing/ATTRIBUTION.md
@@ -1,8 +1,7 @@
# ATTRIBUTION / NOTICE
This skill (`ultimate-browsing`, part of `@oh-my-opencode/shared-skills`) ships
-project-original content, one vendored-and-modified upstream engine, plus two
-third-party tools that it installs at runtime (it does NOT vendor their source).
+project-original content and one vendored-and-modified upstream engine.
Each component's provenance, license, and required notices are reproduced below.
---
@@ -50,83 +49,3 @@ license obligation:
These reference platform-native CLIs and public APIs by name (e.g. `xhs`, `yt-dlp`,
`agent-reach`, `mcporter`, Jina Reader, V2EX public API). Those are external tools the
user installs separately; this skill includes none of their source.
-
----
-
-## 3. CloakBrowser (CloakHQ) — Tier-2 stealth Chromium (runtime dependency)
-
-The Tier-2 stealth browser is **CloakBrowser**, installed at runtime via `pip`
-(`pip install cloakbrowser`). No CloakBrowser source is vendored in this repository.
-
-- Source: https://github.com/CloakHQ/CloakBrowser
-- Pinned runtime version: **0.5.7** (documented in `references/chrome-stealth.md`;
- this is a documented version string, not an automated drift check).
-- Wrapper source license: MIT License.
-- Binary license: the compiled CloakBrowser Chromium binary downloaded by
- `cloakbrowser.ensure_binary()` is governed by the separate CloakBrowser
- Binary License:
- https://github.com/CloakHQ/CloakBrowser/blob/main/BINARY-LICENSE.md
-- Redistribution note: this npm package does not redistribute the CloakBrowser
- binary, does not repackage it, and does not include it in `skills/` or
- `dist/skills`. Users who run the Tier-2 setup download the binary directly
- from CloakHQ's official distribution channels and must comply with that
- binary license.
-
-MIT wrapper source license:
-
-```
-MIT License
-
-Copyright (c) 2026 CloakHQ
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-```
-
----
-
-## 4. agent-browser (vercel-labs) — Tier-2 CDP automation CLI (runtime dependency)
-
-The Tier-2 automation CLI is **agent-browser**, installed at runtime via `npm`
-(`bun add -g agent-browser`). No agent-browser source is vendored in this repository.
-
-- Source: https://github.com/vercel-labs/agent-browser
-- Pinned runtime version: **0.34.0** (documented in `references/chrome-stealth.md`;
- documented version string, no automated drift check).
-- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
- these files except in compliance with the License. You may obtain a copy of the
- License at:
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software distributed under
- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the specific language governing
- permissions and limitations under the License.
-
-- **Changes (Apache-2.0 §4(b)):** none. agent-browser is installed unmodified at
- runtime; no agent-browser source file is copied, modified, or redistributed by this
- skill. This skill only documents how to invoke the upstream CLI.
-
-- **NOTICE:** the upstream agent-browser distribution may include a `NOTICE` file. As
- this skill redistributes no agent-browser source, no upstream NOTICE content is
- bundled here; consult the upstream repository for its `NOTICE` file when present.
-
-- **Trademark notice:** "agent-browser" and "Vercel" are referenced by name for
- identification only. No trademark license is granted under the Apache License 2.0
- (Section 6).
diff --git a/plugins/omo/skills/ultimate-browsing/SKILL.md b/plugins/omo/skills/ultimate-browsing/SKILL.md
index 610e66f6..a654674c 100644
--- a/plugins/omo/skills/ultimate-browsing/SKILL.md
+++ b/plugins/omo/skills/ultimate-browsing/SKILL.md
@@ -1,13 +1,13 @@
---
name: ultimate-browsing
-description: "Reaches web pages a plain fetch cannot: renders JS, drives clicks and forms, captures screenshots, holds a login, and gets past WAF blocks through platform-native readers and stealth Chrome. Use for any page work beyond retrieving static text."
+description: "Renders, drives, and screenshots web pages: JS-rendered sources, clicks and forms, persistent logins, WAF-blocked hosts (platform-native readers, stealth Chrome), and the browsing lane of a research run, with screenshots as provenance. Not for plain search or unblocked static fetch."
---
# Ultimate Browsing
Web access for everything a plain fetch cannot finish: a page that renders in JS, a click or a form, a screenshot, a login that must persist across pages, or a host that blocks generic fetchers (WAF / 403 / Cloudflare). Start at the cheapest tier that can do the job and climb only when it cannot:
-**Tier 1 — insane-search** (headless extraction + WAF bypass) -> **Tier 1.5 — agent-reach** (platform-native APIs, esp. Chinese platforms) -> **Tier 2 — a real browser**: 2a a code-driven kernel browser, 2b Chrome stealth (CloakBrowser + agent-browser) when the page fights back.
+**Tier 1 — insane-search** (headless extraction + WAF bypass) -> **Tier 1.5 — agent-reach** (platform-native APIs, esp. Chinese platforms) -> **Tier 2 — a real browser**: 2a Bun.WebView, 2b a local-Chrome `playwright-core` script from js eval for Chrome semantics, stealth, trace, or auth.
## PHASE 0 — ROUTE FIRST (MANDATORY)
@@ -86,33 +86,26 @@ Routing table, per-platform auth (set `TWITTER_*` env vars, `gh auth login`, a t
### Tier 2a — kernel browser (default)
-Drive the page from the code cell you are already in, with no CLI process and no open CDP port. On a Bun >= 1.4 runtime that is `new Bun.WebView()` (`navigate`, `click`, `type`, `evaluate`, `screenshot`, raw `cdp`); elsewhere it is `playwright-core`/`puppeteer-core` against the local Chrome. Snapshots and screenshots come back in-process, so this is the cheapest way to answer "what does the page actually render".
+Use `new Bun.WebView()` from the js-eval kernel on Bun >= 1.4: macOS defaults to system WebKit; Linux/Windows need installed Chrome/Chromium/Edge. WebView is headless, WebKit has no CDP, and `type()` emits no keyboard events. For other kernels or when those differences matter, use 2b.
```js
-await using view = new Bun.WebView({ width: 1280, height: 800 })
-await view.navigate(url)
-const title = await view.evaluate("document.title")
-await view.screenshot({ path: "/tmp/page.png" })
+const view = new Bun.WebView({ width: 1280, height: 800 })
+try {
+ await view.navigate(url)
+ const title = await view.evaluate("document.title")
+ await Bun.write(pngPath, await view.screenshot())
+} finally {
+ view[Symbol.dispose]()
+}
```
-Climb to 2b when the site detects automation (Turnstile, FingerprintJS, "unusual traffic"), when the flow needs a persistent logged-in profile or injected cookies, or when the kernel browser cannot reach the page at all.
+Use 2b for real-Chrome semantics, stealth, trace, authenticated profiles, or a page the kernel browser cannot reach.
### Tier 2b — Chrome stealth (blocked or logged-in pages)
-CloakBrowser is a stealth Chromium with source-level fingerprint patches that passes Cloudflare Turnstile, FingerprintJS, BrowserScan, and 30+ detectors; agent-browser is the CDP automation CLI that drives it. Both are runtime-installed tools (not vendored here). Full setup, version pins, launch flow, cookie login, and cross-platform notes are in [references/chrome-stealth.md](references/chrome-stealth.md).
+WRITE a `playwright-core` script and run it from js eval against installed local Chrome: `chromium.launch({ channel: "chrome" })`, or `launchPersistentContext` on a task-owned profile. For authenticated state, CLONE the user's profile first (`rsync -a <profile>/ <tmp-clone>/`); NEVER launch against or clear cookies/cache/site data from the live profile. Codex: prefer `browser:control-in-app-browser` for ordinary page control.
-NEVER clear cookies, cache, or site data (`Network.clearBrowserCookies`, `Storage.clearCookies`, `chrome.browsingData.remove`, "clear browsing data") on the user's real/main browser profile — it wipes their logged-in state everywhere. If the task needs that profile's login state, clone the profile directory first (`rsync -a <profile>/ <tmp-clone>/`) and launch CloakBrowser / agent-browser with the clone as the user-data-dir; run any clearing on the clone only.
-
-```bash
-# 1. Launch CloakBrowser with CDP on :9242 (see chrome-stealth.md for install + venv).
-# 2. CloakBrowser launches tabless — open the first tab via CDP before any agent-browser command:
-curl -s -X PUT "http://127.0.0.1:9242/json/new?https://example.com"
-# 3. Drive it with agent-browser over CDP:
-agent-browser --cdp 9242 snapshot -i # interactive elements (@eN refs)
-agent-browser --cdp 9242 click @e3
-agent-browser --cdp 9242 screenshot out.png
-agent-browser --cdp 9242 close
-```
+Keep the engine's Playwright templates for script-based extraction. Stealth is optional: the user installs `playwright-extra` + `puppeteer-extra-plugin-stealth` once in the engine directory and the script wraps the `playwright-core` browser type. Setup, persistent-context arguments, screenshots, and cleanup are in [references/chrome-stealth.md](references/chrome-stealth.md). A stealth flag is not proof of access: inspect the rendered result and report challenges that remain.
### Cookie login (cross-platform)
@@ -134,14 +127,11 @@ Cookie export files are written with owner-only `0600` permissions. Do not place
|------|-------------|
| [references/insane-search/README.md](references/insane-search/README.md) | Tier-1 engine harness (R1-R7, Phase 0 API index, no-site-name rule) + its `*.md` deep-dives |
| [references/agent-reach/README.md](references/agent-reach/README.md) | Tier-1.5 routing table, platform auth, per-category `*.md` |
-| [references/chrome-stealth.md](references/chrome-stealth.md) | Tier-2 CloakBrowser + agent-browser install, CDP flow, version pins, cookie login |
+| [references/chrome-stealth.md](references/chrome-stealth.md) | Tier-2 playwright-core scripts, optional stealth setup, cloned profiles, cookie login |
## Environment variables
```bash
-CLOAK_CDP_PORT=9242 # CloakBrowser CDP port (default 9242)
-AGENT_BROWSER_USER_AGENT="..." # override UA to hide HeadlessChrome
-AGENT_BROWSER_HEADED=1 # show the browser window
# agent-reach auth: set the channel-specific env vars from each tool's docs only if you have access
# insane-search needs no env vars — it auto-installs deps on first run
```
@@ -149,9 +139,7 @@ AGENT_BROWSER_HEADED=1 # show the browser window
## Anti-patterns
- Do NOT launch Chrome stealth for plain text extraction — use Tier 1.
-- Do NOT pass an `--init-script` for the webdriver flag — CloakBrowser already patches it at source; the only required override is `--user-agent`.
-- Do NOT run agent-browser before creating the first tab via `curl -X PUT .../json/new` — CloakBrowser launches tabless.
-- Do NOT use vanilla Chrome when stealth is needed — always CloakBrowser.
-- Do NOT forget to `close` the session when done.
+- Use stealth plugins only in an explicitly installed script environment, not injected into WebView.
+- Close every WebView/browser context when done and remove only task-owned profile clones.
- Do NOT inject cookies without reloading the page.
- Do NOT hardcode site domains/selectors into `engine/**` or `waf_profiles.yaml` — runtime hints only (see the no-site-name rule in the insane-search reference).
diff --git a/plugins/omo/skills/ultimate-browsing/engine/AGENTS.md b/plugins/omo/skills/ultimate-browsing/engine/AGENTS.md
index a3801b50..bcc9891f 100644
--- a/plugins/omo/skills/ultimate-browsing/engine/AGENTS.md
+++ b/plugins/omo/skills/ultimate-browsing/engine/AGENTS.md
@@ -65,7 +65,8 @@ is a regression, not an upgrade:
- **De-personalization** — no personal absolute paths, no personal auth token literals,
no personal browser choice; enforced by `depersonalization-gate.test.ts`.
- **Skill-level layering** — the engine is Tier 1 under a router that also owns Tier 1.5
- (agent-reach) and Tier 2 (CloakBrowser + agent-browser). Upstream has no such tiering.
+ (agent-reach) and Tier 2 (Bun.WebView / local-Chrome playwright-core scripts from js eval).
+ Upstream has no such tiering.
### WANT — upstream improvements worth porting forward
diff --git a/plugins/omo/skills/ultimate-browsing/engine/templates/package.json b/plugins/omo/skills/ultimate-browsing/engine/templates/package.json
index 1e4c3dd5..01ab32b1 100644
--- a/plugins/omo/skills/ultimate-browsing/engine/templates/package.json
+++ b/plugins/omo/skills/ultimate-browsing/engine/templates/package.json
@@ -2,9 +2,9 @@
"name": "insane-search-templates",
"version": "0.1.0",
"private": true,
- "description": "Local deps for Playwright real-Chrome templates. npm install && npx playwright install chrome",
+ "description": "Script-only dependencies for local Chrome templates driven from js eval; Chrome must already be installed.",
"dependencies": {
- "playwright": "^1.62.1",
+ "playwright-core": "^1.62.1",
"playwright-extra": "^4.3.6",
"puppeteer-extra-plugin-stealth": "^2.11.2"
}
diff --git a/plugins/omo/skills/ultimate-browsing/engine/templates/playwright_mobile_chrome.js b/plugins/omo/skills/ultimate-browsing/engine/templates/playwright_mobile_chrome.js
index aca07b30..cf030932 100644
--- a/plugins/omo/skills/ultimate-browsing/engine/templates/playwright_mobile_chrome.js
+++ b/plugins/omo/skills/ultimate-browsing/engine/templates/playwright_mobile_chrome.js
@@ -76,11 +76,12 @@ async function main() {
const playwrightExtra = requireOptionalModule('playwright-extra');
const stealthPlugin = playwrightExtra ? requireOptionalModule('puppeteer-extra-plugin-stealth') : null;
if (playwrightExtra && stealthPlugin) {
- ({ chromium, devices } = playwrightExtra);
+ ({ devices } = require('playwright-core'));
+ chromium = playwrightExtra.addExtra(require('playwright-core').chromium);
const stealth = stealthPlugin();
chromium.use(stealth);
} else {
- ({ chromium, devices } = require('playwright'));
+ ({ chromium, devices } = require('playwright-core'));
}
const dev = devices[deviceName];
@@ -94,6 +95,8 @@ async function main() {
try {
ctx = await chromium.launchPersistentContext(profileDir, {
channel: 'chrome',
+ args: ['--disable-blink-features=AutomationControlled'],
+ ignoreDefaultArgs: ['--enable-automation'],
headless,
...dev,
});
diff --git a/plugins/omo/skills/ultimate-browsing/engine/templates/playwright_real_chrome.js b/plugins/omo/skills/ultimate-browsing/engine/templates/playwright_real_chrome.js
index f0825388..3b88d6d5 100644
--- a/plugins/omo/skills/ultimate-browsing/engine/templates/playwright_real_chrome.js
+++ b/plugins/omo/skills/ultimate-browsing/engine/templates/playwright_real_chrome.js
@@ -10,9 +10,9 @@
* NO-SITE-NAME RULE: this file must never branch on specific hostnames.
* All site specifics come from the JSON input (url, waitSelector).
*
- * Dependencies (install once on target machine):
- * npm i -g playwright playwright-extra puppeteer-extra-plugin-stealth
- * npx playwright install chrome # system Chrome binary
+ * User setup: ../../references/chrome-stealth.md (engine-local dependencies).
+ * Chrome must already be installed; optional stealth plugins run only in this script.
+ * Execute this script from js eval; profileDir must be task-owned or a CLONED profile.
*/
const fs = require('fs');
@@ -82,18 +82,20 @@ async function main() {
const playwrightExtra = requireOptionalModule('playwright-extra');
const stealthPlugin = playwrightExtra ? requireOptionalModule('puppeteer-extra-plugin-stealth') : null;
if (playwrightExtra && stealthPlugin) {
- ({ chromium } = playwrightExtra);
+ chromium = playwrightExtra.addExtra(require('playwright-core').chromium);
const stealth = stealthPlugin();
chromium.use(stealth);
} else {
- // Fallback to plain playwright (no stealth). Still uses channel:chrome.
- ({ chromium } = require('playwright'));
+ // Core controls installed Chrome without downloading a managed browser.
+ ({ chromium } = require('playwright-core'));
}
let ctx;
try {
ctx = await chromium.launchPersistentContext(profileDir, {
channel: 'chrome', // real Chrome, not bundled Chromium
+ args: ['--disable-blink-features=AutomationControlled'],
+ ignoreDefaultArgs: ['--enable-automation'],
headless,
viewport,
});
diff --git a/plugins/omo/skills/ultimate-browsing/engine/tests/test_playwright_stealth.py b/plugins/omo/skills/ultimate-browsing/engine/tests/test_playwright_stealth.py
new file mode 100644
index 00000000..171325b3
--- /dev/null
+++ b/plugins/omo/skills/ultimate-browsing/engine/tests/test_playwright_stealth.py
@@ -0,0 +1,86 @@
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import tempfile
+import unittest
+from pathlib import Path
+
+from test_playwright_templates import (
+ TEMPLATE_NAMES,
+ TEMPLATES_DIR,
+ _install_fake_playwright,
+ _write_file,
+)
+
+
+class PlaywrightTemplateStealth(unittest.TestCase):
+ def test_extracts_html_and_closes_wrapped_chrome_when_stealth_is_installed(self) -> None:
+ for template_name in TEMPLATE_NAMES:
+ with self.subTest(template_name=template_name), tempfile.TemporaryDirectory() as tmp:
+ # Given: core has no plugin API; only addExtra supplies a registered wrapper.
+ root = Path(tmp)
+ modules = root / "node_modules"
+ profile = root / "profile"
+ receipt = root / "launch.json"
+ _install_fake_playwright(modules)
+ _write_file(modules / "puppeteer-extra-plugin-stealth/index.js", """
+ module.exports = () => ({ name: 'stealth' });
+ """)
+ _write_file(modules / "playwright-extra/index.js", """
+ const assert = require('node:assert/strict');
+ const fs = require('node:fs');
+ exports.addExtra = (core) => {
+ assert.equal(core, require('playwright-core').chromium);
+ assert.equal(Object.hasOwn(core, 'use'), false);
+ const events = ['wrap'];
+ let registered = false;
+ return {
+ use(plugin) {
+ assert.equal(plugin.name, 'stealth');
+ registered = true;
+ events.push(plugin.name);
+ },
+ async launchPersistentContext(profileDir, options) {
+ assert.equal(registered, true);
+ events.push({ profileDir, channel: options.channel, viewport: options.viewport });
+ const context = await core.launchPersistentContext(profileDir, options);
+ return {
+ ...context,
+ async close() {
+ await context.close();
+ events.push('close');
+ fs.writeFileSync(process.env.STEALTH_RECEIPT, JSON.stringify(events));
+ },
+ };
+ },
+ };
+ };
+ """)
+ script = root / template_name
+ script.write_bytes((TEMPLATES_DIR / template_name).read_bytes())
+ env = {key: value for key, value in os.environ.items() if key != "NODE_PATH"}
+ env["STEALTH_RECEIPT"] = str(receipt)
+
+ # When: the actual bundled entry point consumes its normal stdin protocol.
+ result = subprocess.run(
+ ["node", str(script)],
+ input=json.dumps({"url": "https://example.com/", "profileDir": str(profile), "headless": True}),
+ text=True, capture_output=True, timeout=5, env=env, check=False,
+ )
+
+ # Then: HTML arrives through the registered wrapper and the context is closed.
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout, "<html><article>ok</article></html>")
+ self.assertEqual(result.stderr, "")
+ viewport = {"width": 390, "height": 844} if "mobile" in template_name else {"width": 1366, "height": 900}
+ self.assertEqual(json.loads(receipt.read_text(encoding="utf-8")), [
+ "wrap", "stealth",
+ {"profileDir": str(profile), "channel": "chrome", "viewport": viewport},
+ "close",
+ ])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/plugins/omo/skills/ultimate-browsing/engine/tests/test_playwright_templates.py b/plugins/omo/skills/ultimate-browsing/engine/tests/test_playwright_templates.py
index 6b28a41e..3f038062 100644
--- a/plugins/omo/skills/ultimate-browsing/engine/tests/test_playwright_templates.py
+++ b/plugins/omo/skills/ultimate-browsing/engine/tests/test_playwright_templates.py
@@ -21,7 +21,7 @@ def _write_file(path: Path, content: str) -> None:
def _install_fake_playwright(node_modules: Path) -> None:
_write_file(
- node_modules / "playwright" / "index.js",
+ node_modules / "playwright-core" / "index.js",
"""
const page = {
async goto() {},
@@ -47,7 +47,6 @@ def _install_fake_playwright(node_modules: Path) -> None:
};
exports.chromium = {
- use() {},
async launchPersistentContext() { return context; },
};
exports.devices = {
@@ -78,9 +77,7 @@ def _install_working_playwright_extra(node_modules: Path) -> None:
_write_file(
node_modules / "playwright-extra" / "index.js",
"""
- const playwright = require('playwright');
- exports.chromium = playwright.chromium;
- exports.devices = playwright.devices;
+ exports.addExtra = (browserType) => browserType;
""",
)
@@ -149,7 +146,7 @@ def _run_template(
@unittest.skipUnless(shutil.which("node"), "node is required for Playwright template tests")
class PlaywrightTemplateErrorHandling(unittest.TestCase):
- def test_missing_playwright_extra_warns_and_falls_back_to_plain_playwright(self) -> None:
+ def test_missing_playwright_extra_warns_and_falls_back_to_playwright_core(self) -> None:
for template_name in TEMPLATE_NAMES:
with self.subTest(template_name=template_name):
result = _run_template(
@@ -166,7 +163,7 @@ class PlaywrightTemplateErrorHandling(unittest.TestCase):
self.assertIn("best-effort optional module playwright-extra failed:", result.stderr)
self.assertIn("Cannot find module 'playwright-extra'", result.stderr)
- def test_missing_stealth_plugin_warns_and_falls_back_to_plain_playwright(self) -> None:
+ def test_missing_stealth_plugin_warns_and_falls_back_to_playwright_core(self) -> None:
for template_name in TEMPLATE_NAMES:
with self.subTest(template_name=template_name):
result = _run_template(
diff --git a/plugins/omo/skills/ultimate-browsing/references/chrome-stealth.md b/plugins/omo/skills/ultimate-browsing/references/chrome-stealth.md
index fe8dea41..e0e091c8 100644
--- a/plugins/omo/skills/ultimate-browsing/references/chrome-stealth.md
+++ b/plugins/omo/skills/ultimate-browsing/references/chrome-stealth.md
@@ -1,127 +1,113 @@
-# Tier 2 — Chrome stealth (CloakBrowser + agent-browser)
+# Tier 2 — Chrome stealth through playwright-core scripts
-Real interaction (clicks, forms, screenshots, video, persistent login) for pages that defeat Tier 1/1.5. Two runtime tools, both installed on demand — neither is vendored in this skill:
-
-- **CloakBrowser** (`pip`) — stealth Chromium with source-level C++ fingerprint patches. The Python wrapper source is MIT; the downloaded Chromium binary is covered by CloakBrowser's separate binary license and is not redistributed by this package. Passes Cloudflare Turnstile, FingerprintJS, BrowserScan, and 30+ detectors. Pin **0.5.7**.
-- **agent-browser** (`npm`, Apache-2.0) — native CDP automation CLI that drives CloakBrowser. AX-tree snapshots, `@eN` refs, click/fill/type/scroll, screenshots, video, cookie/state/session management. Pin **0.34.0**.
-
-```
-CloakBrowser (stealth Chromium) <- CDP port 9242 -> agent-browser CLI
- - 57 C++ fingerprint patches - AX-tree snapshots, @eN refs
- - Canvas/WebGL consistency - click / fill / type / scroll
- - navigator.webdriver = false at C++ source - screenshot, video record
- - Humanize mode (mouse curves, timing) - cookie / state / session mgmt
-```
+For real-Chrome semantics, stealth, traces, or authenticated sessions, WRITE a
+script and run it from the js-eval kernel. Use installed local Chrome, not a
+managed browser download. Ordinary macOS captures on a Bun >= 1.4 kernel use
+`new Bun.WebView()`; Linux/Windows WebView needs installed Chrome/Chromium/Edge.
+Codex's ordinary browser surface is `browser:control-in-app-browser`.
## Install (one-time)
-CloakBrowser runs in a dedicated Python venv. Cross-platform: macOS, Linux, and Windows all supported by both tools (use the venv path convention for your OS).
-
-The venv lives at a fixed path so every session reuses one stealth-Chromium download instead of creating a new venv per working directory, and every command below calls its interpreter by absolute path — no `activate` step to forget.
-
-```bash
-# CloakBrowser (MIT wrapper source; separate binary license, pin 0.5.7):
-VENV="$HOME/.agents/cloak-venv" # Windows: %USERPROFILE%\.agents\cloak-venv
-uv venv "$VENV" --python 3.13
-uv pip install --python "$VENV/bin/python" "cloakbrowser==0.5.7"
-"$VENV/bin/python" -c "import cloakbrowser; cloakbrowser.ensure_binary()" # downloads stealth Chromium on first import
+Only the user installs these script dependencies, once in the skill's engine
+directory. Stealth plugins run inside scripts, never inside WebView:
-# agent-browser (Apache-2.0, pin 0.34.0):
-bun add -g [email protected] && agent-browser install
-agent-browser --version # 0.34.0
+```sh
+cd "$SKILL_DIR/engine"
+test -f package.json || cp templates/package.json package.json
```
-Verify CloakBrowser:
-
-```bash
-"$VENV/bin/python" -c "import cloakbrowser; print(cloakbrowser.__version__, cloakbrowser.CHROMIUM_VERSION, cloakbrowser.binary_info()['installed'])"
-# -> 0.5.7 <chromium-version> True
-```
+Chrome must already be installed. The bundled `templates/playwright_real_chrome.js`
+and `templates/playwright_mobile_chrome.js` resolve these dependencies from their
+parent engine directory. Without optional plugins, templates report the fallback
+and use plain `playwright-core`; do not call that fallback stealth.
## Launch + drive
-NEVER clear cookies, cache, or site data (`Network.clearBrowserCookies`, `Storage.clearCookies`, `chrome.browsingData.remove`, "clear browsing data") on the user's real/main browser profile — it wipes their logged-in state everywhere. If you need that profile's login state, clone it first (`rsync -a <profile>/ <tmp-clone>/`) and launch with the clone as the user-data-dir; run any clearing on the clone only.
-
-```bash
-# 1. Launch CloakBrowser with CDP on :9242 (background). cloakbrowser lives only in the venv,
-# so call its interpreter by absolute path — this works in any shell, activated or not:
-"$HOME/.agents/cloak-venv/bin/python" -c "import asyncio,cloakbrowser; asyncio.run(cloakbrowser.launch_async(headless=False, stealth_args=True, args=['--remote-debugging-port=9242']))" &
-
-# 2. CloakBrowser launches tabless -> agent-browser would say "No page found".
-# Open the first tab via CDP before any agent-browser command:
-curl -s -X PUT "http://127.0.0.1:9242/json/new?https://example.com"
-
-# 3. Connect agent-browser. CloakBrowser already patches navigator.webdriver=false at the
-# C++ source, so NO --init-script is required — only --user-agent to hide HeadlessChrome:
-agent-browser --cdp 9242 \
- --user-agent "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.7680.177 Safari/537.36" \
- open https://example.com
-
-# 4. Interact:
-agent-browser --cdp 9242 snapshot -i # interactive elements (@eN refs)
-agent-browser --cdp 9242 click @e3
-agent-browser --cdp 9242 screenshot out.png
-
-# 5. Close when done:
-agent-browser --cdp 9242 close
+Close the source browser before cloning its user-data directory for a consistent
+copy. Preserve its `Local State` alongside the selected profile. Use a private,
+task-owned clone, never the live user-data-dir. NEVER clear the live profile's
+cookies, cache, or site data. For unauthenticated QA, use a fresh task-owned profile.
+
+Write `capture.cjs` in the engine directory. `clonePath`, URL, and output path are
+arguments owned by this QA run; keep cookie values out of argv and logs:
+
+```js
+const { chromium: core } = require('playwright-core');
+const { addExtra } = require('playwright-extra');
+const stealth = require('puppeteer-extra-plugin-stealth');
+const [clonePath, url, pngPath] = process.argv.slice(2);
+const chromium = addExtra(core);
+chromium.use(stealth());
+
+async function capture() {
+ const context = await chromium.launchPersistentContext(clonePath, {
+ channel: 'chrome',
+ headless: true,
+ args: ['--disable-blink-features=AutomationControlled'],
+ ignoreDefaultArgs: ['--enable-automation'],
+ viewport: { width: 1280, height: 720 },
+ });
+ try {
+ const page = await context.newPage();
+ await page.goto(url, { waitUntil: 'load', timeout: 30000 });
+ await page.screenshot({ path: pngPath });
+ console.log(JSON.stringify({ pngPath, webdriver: await page.evaluate(() => navigator.webdriver) }));
+ } finally {
+ await context.close();
+ }
+}
+capture().catch((error) => { console.error(error); process.exitCode = 1; });
```
-agent-browser ships its own always-version-matched usage guide — load it instead of guessing flags:
+Run the script from js eval with a bounded process lifetime:
-```bash
-agent-browser skills get core # core workflows, patterns, troubleshooting
-agent-browser skills get core --full # + full command reference and templates
-agent-browser skills get electron # Electron apps (VS Code, Slack, Discord, Figma, ...)
-agent-browser skills list # everything available on the installed version
+```js
+const { promisify } = await import('node:util')
+const { execFile } = await import('node:child_process')
+const result = await promisify(execFile)('node', [scriptPath, clonePath, url, pngPath], { timeout: 45000 })
+console.log(result.stdout)
```
-## Verify stealth
-
-```bash
-agent-browser --cdp 9242 eval 'navigator.webdriver' # must print false
-```
+For extraction, run a bundled template the same way, supplying its JSON input on
+stdin (`url`, `profileDir: clonePath`, `waitSelector`, `headless`). The template
+returns HTML on stdout. For traces, use `context.tracing.start()` before navigation
+and `context.tracing.stop({ path: tracePath })` before closing. Use `headless: false`
+only with an available display when headed behavior is the criterion.
-Verified 2026-07 with CloakBrowser 0.5.7 + agent-browser 0.34.0: `navigator.webdriver` reads the boolean false with no init-script, bot.sannysoft.com all-green, browserscan.net "Normal" (15/15), nowsecure.nl Turnstile bypassed.
+## Verify stealth
-> **agent-browser 0.33.x behavior note:** the daemon now defaults to a 1-hour idle timeout (saves restore state, closes the browser, exits after 1 h of no commands). Set `AGENT_BROWSER_IDLE_TIMEOUT_MS=0` to restore the old always-persist behavior. External WebSocket stream consumers see latest-wins frame delivery; `record` (CDP) and the dashboard are unaffected.
+Inspect the page, screenshot, and requested content. `navigator.webdriver === false`
+checks one browser property, NOT a promise to pass a detector or challenge.
+Persistent challenge pages or missing content are failures, even if the script
+exits zero. Do not keep retrying or silently swap browser tooling.
## Cookie login (cross-platform)
-`scripts/extract_cookies.py` reads cookies from a local browser profile and optionally injects them into the running CDP session. Profile-path resolution and value decryption are per-OS:
+`scripts/extract_cookies.py` exports local-browser cookies with owner-only `0600`
+permissions. Keep exports private and never commit them. For a persistent context,
+load the exported cookies with `context.addCookies(...)`, then navigate/reload.
+Browser- or device-bound login tokens may not transfer to a clone.
-| OS | Profile location | Cookie value decryption |
-|----|------------------|--------------------------|
-| macOS | `~/Library/Application Support/<app>/` | Keychain (AES-128-CBC, PBKDF2 salt `saltysalt`) |
-| Linux | `~/.config/<app>/` (Chromium), `~/.mozilla/firefox/` (Firefox) | libsecret/SecretService, then PBKDF2 + AES-128-CBC |
-| Windows | `%LOCALAPPDATA%\<app>\User Data\` | DPAPI (`CryptUnprotectData`) + AES-256-GCM (`os_crypt` key) |
-
-```bash
-# Extract to a file:
-mkdir -p ~/.local/state/omo-cookies
-python3 ../scripts/extract_cookies.py --browser chrome --domain youtube.com --output ~/.local/state/omo-cookies/youtube.cookies.json
-# Extract and inject into the running CDP session:
-python3 ../scripts/extract_cookies.py --browser chrome --domain youtube.com --inject --cdp 9242
-```
-
-Cookie export files are written with owner-only `0600` permissions. Do not place live auth cookies in shared temp directories or commit them to a repo. Cookie injection sends values to CDP over stdin rather than argv, so live cookie values do not appear in process listings. Cookies apply on next navigation — reload after injecting. Google services use fingerprint-bound tokens (SIDTS) that may not transfer across browser profiles. Firefox-family profiles store cookies unencrypted; Chromium-family profiles trigger a one-time OS-keyring prompt on macOS/Linux.
+The helper's `--inject --cdp <port>` targets a task-owned local Chrome CDP endpoint,
+which a script can also use via `chromium.connectOverCDP(...)`. Expose CDP on
+loopback only, never against the live profile. Values travel on stdin, not argv.
## Anti-patterns
-- Do NOT launch CloakBrowser for plain text extraction — use Tier 1.
-- Do NOT pass an `--init-script` for the webdriver flag — CloakBrowser already patches it at source; the only required override is `--user-agent`.
-- Do NOT run agent-browser before creating the first tab via `curl -X PUT .../json/new` — CloakBrowser launches tabless.
-- Do NOT use vanilla Chrome when stealth is needed — always CloakBrowser.
-- Do NOT forget to `close` the session when done.
-- Do NOT inject cookies without reloading the page.
+- Plain text extraction does not need a stealth browser: use the extraction lane.
+- Never launch against, clear, or delete the user's live profile.
+- Never claim stealth from successful startup alone; validate rendered content.
+- Never run plugins without explicit user-installed script dependencies.
## Troubleshooting
-```bash
-# Port 9242 already in use (macOS/Linux):
-lsof -ti:9242 | xargs kill -9
-# agent-browser can't connect:
-curl -s http://127.0.0.1:9242/json/version | head -5 # empty -> CloakBrowser not running
-# Update either tool:
-uv pip install --python "$HOME/.agents/cloak-venv/bin/python" --upgrade "cloakbrowser==0.5.7" && "$HOME/.agents/cloak-venv/bin/python" -c "import cloakbrowser; cloakbrowser.ensure_binary()"
-bun add -g [email protected]
-```
+A missing Chrome executable is a prerequisite failure: report it, do not download
+a replacement. Missing plugins require the one-time setup above; module errors
+inside installed plugins are real failures, not optional-dependency misses.
+A locked profile usually means the source was not cloned or another run owns the
+clone. Use a new task-owned clone instead of killing unrelated browsers.
+
+Always close contexts in `finally`, stop the fixture server, and remove only this
+run's clone and temporary scripts. Preserve requested PNG/trace evidence and record
+the cleanup receipt, including failures.
diff --git a/plugins/omo/skills/ultimate-browsing/references/insane-search/README.md b/plugins/omo/skills/ultimate-browsing/references/insane-search/README.md
index b5ab8418..7919925e 100644
--- a/plugins/omo/skills/ultimate-browsing/references/insane-search/README.md
+++ b/plugins/omo/skills/ultimate-browsing/references/insane-search/README.md
@@ -223,11 +223,17 @@ result = fetch(
python3 -c "import curl_cffi, bs4, yaml" 2>/dev/null || pip install curl_cffi beautifulsoup4 pyyaml -q
```
-Playwright 로컬 경로 사용 시 Node가 필요:
+브라우저를 직접 제어할 때는 js eval에서 Bun >= 1.4의 `new Bun.WebView()`를
+사용한다(macOS 기본; Linux/Windows는 설치된 Chrome/Chromium/Edge 필요).
+그 외 또는 Chrome 동작·stealth·trace·인증이 필요하면 `playwright-core` 스크립트를
+작성해 js eval에서 로컬 Chrome(`channel: "chrome"`)으로 실행한다.
+사용자가 엔진 디렉터리에서 한 번 설치할 스크립트 의존성:
```bash
-npm i -g playwright playwright-extra puppeteer-extra-plugin-stealth
-npx playwright install chrome
+cd "$SKILL_DIR/engine"
+test -f package.json || cp templates/package.json package.json
```
+Chrome은 이미 설치되어 있어야 한다. 인증 프로필은 먼저 복제하고 복제본만 사용한다.
## 빠른 참조 — Phase 0 명령어
diff --git a/plugins/omo/skills/ultimate-browsing/references/insane-search/playwright.md b/plugins/omo/skills/ultimate-browsing/references/insane-search/playwright.md
index d8e45103..7c30afe3 100644
--- a/plugins/omo/skills/ultimate-browsing/references/insane-search/playwright.md
+++ b/plugins/omo/skills/ultimate-browsing/references/insane-search/playwright.md
@@ -16,10 +16,10 @@
### 의존성
-```bash
-claude mcp list 2>/dev/null | grep -q playwright && echo "OK" || echo "NOT CONNECTED"
-claude mcp add playwright -- npx @playwright/mcp@latest
-```
+이 항목은 이미 연결된 MCP를 사용하는 엔진 어댑터의 설명이다.
+새 브라우저 세션은 js eval의 Bun.WebView(Bun >= 1.4, macOS 기본;
+Linux/Windows는 설치된 Chrome/Chromium/Edge 필요), 그 외 또는 Chrome 동작·stealth·trace·인증은
+로컬 Chrome을 제어하는 `playwright-core` 스크립트로 실행한다. MCP를 새로 설치하지 않는다.
### 기본 워크플로
@@ -56,11 +56,11 @@ claude mcp add playwright -- npx @playwright/mcp@latest
# Node (시스템 설치)
node -v # v18+ 권장
-# Playwright + stealth 플러그인
-npm i -g playwright playwright-extra puppeteer-extra-plugin-stealth
-
-# 시스템 Chrome 바이너리 (번들 Chromium 아님)
-npx playwright install chrome
+# 사용자가 엔진 디렉터리에서 한 번 설치하는 스크립트 의존성
+cd "$SKILL_DIR/engine"
+test -f package.json || cp templates/package.json package.json
+# Chrome은 이미 시스템에 설치되어 있어야 한다. 브라우저 다운로드 명령은 없다.
```
### 호출 (engine 내부)
@@ -81,7 +81,8 @@ attempt, html = run_playwright_fallback(
### 데스크톱 템플릿 (`playwright_real_chrome.js`)
```js
-const { chromium } = require('playwright-extra');
+const { addExtra } = require('playwright-extra');
+const chromium = addExtra(require('playwright-core').chromium);
const stealth = require('puppeteer-extra-plugin-stealth')();
chromium.use(stealth);
@@ -95,7 +96,9 @@ const ctx = await chromium.launchPersistentContext(profileDir, {
### 모바일 템플릿 (`playwright_mobile_chrome.js`)
```js
-const { chromium, devices } = require('playwright-extra');
+const { devices } = require('playwright-core');
+const { addExtra } = require('playwright-extra');
+const chromium = addExtra(require('playwright-core').chromium);
const iPhone = devices['iPhone 13 Pro'];
const ctx = await chromium.launchPersistentContext(profileDir, {
@@ -126,8 +129,8 @@ const ctx = await chromium.launchPersistentContext(profileDir, {
## 디버깅 팁
-- `profileDir`를 고정 경로로 두면 세션·쿠키가 유지되어 재시도 빠름 (`/tmp/.insane_pw_profile`)
-- Akamai 재시도가 잦으면 `profileDir`를 삭제해 fresh 상태로 리셋
+- 템플릿은 js eval에서 스크립트로 실행한다. `profileDir`는 작업 전용 경로나 사용자 프로필의 복제본만 사용한다.
+- 사용자의 실제 프로필을 실행·초기화·삭제하지 않는다. 작업 종료 시 컨텍스트를 닫고 작업 전용 복제본만 정리한다.
- 실패 시 `result.trace`의 `error` 필드에 Node stderr 200자가 포함됨
## 사이트 예시 (독자 이해용, 코드 분기 근거 아님)
diff --git a/plugins/omo/skills/ultimate-browsing/scripts/extract_cookies.py b/plugins/omo/skills/ultimate-browsing/scripts/extract_cookies.py
index 52f6eeda..c81f73c0 100644
--- a/plugins/omo/skills/ultimate-browsing/scripts/extract_cookies.py
+++ b/plugins/omo/skills/ultimate-browsing/scripts/extract_cookies.py
@@ -4,7 +4,7 @@
The OS-keyring lookup is an injected boundary: cookie_paths resolves profile
paths and cookie_crypto derives keys + decrypts values, both pure and testable
with synthetic fixtures on any OS. This module wires them to a real browser DB
-and the agent-browser CDP session.
+and a local Chrome CDP session controlled by playwright-core scripts.
Usage:
python extract_cookies.py --browser chrome --domain youtube.com --output /tmp/cookies.json
@@ -255,7 +255,7 @@ def inject_cookies(cookies: list[CookieRecord], cdp_port: int) -> None:
if proc.returncode != 0:
raise RuntimeError((proc.stderr or "CDP cookie injection failed").strip())
ok = int((proc.stdout or "0").strip() or "0")
- print(f"Injected {ok}/{len(filtered)} cookies into agent-browser (CDP {cdp_port})")
+ print(f"Injected {ok}/{len(filtered)} cookies into local Chrome (playwright-core CDP {cdp_port})")
def main() -> None:
@@ -263,7 +263,7 @@ def main() -> None:
parser.add_argument("--browser", required=True, choices=sorted(BROWSERS.keys()))
parser.add_argument("--domain", required=True, action="append", dest="domains")
parser.add_argument("--output", help="Write cookies JSON to file")
- parser.add_argument("--inject", action="store_true", help="Inject into agent-browser")
+ parser.add_argument("--inject", action="store_true", help="Inject into the local Chrome CDP endpoint used by a playwright-core script")
parser.add_argument("--cdp", type=int, default=9242, help="CDP port (default 9242)")
args = parser.parse_args()
diff --git a/plugins/omo/skills/ultrawork/SKILL.md b/plugins/omo/skills/ultrawork/SKILL.md
index 17daf277..ff652a1e 100644
--- a/plugins/omo/skills/ultrawork/SKILL.md
+++ b/plugins/omo/skills/ultrawork/SKILL.md
@@ -69,16 +69,17 @@ exercises the surface; capture the artifact.
for color / layout / CJK evidence, which degrades truecolor.
3. Browser use — in Codex, use `browser:control-in-app-browser`
first when available and no authenticated/persistent user browser
- profile is required. Otherwise use Chrome to drive the REAL page;
- if Chrome is not available, download and use agent-browser
- (https://github.com/vercel-labs/agent-browser). Capture action
+ profile is required. Otherwise, or for Chrome semantics, stealth,
+ or trace, WRITE a `playwright-core` script and run it from js eval
+ against local Chrome (`chromium.launch({ channel: "chrome" })` /
+ `launchPersistentContext` on a CLONED profile). Capture action
log + screenshot path. Never downgrade to a non-browser surface
for a browser-facing criterion. NEVER clear cookies, cache, or
site data (`Network.clearBrowserCookies`, `Storage.clearCookies`,
`chrome.browsingData.remove`, "clear browsing data") on the user's
real/main browser profile — it wipes their logged-in state. If you
need that profile's login state, clone it first (`rsync -a
- <profile>/ <tmp-clone>/`) and launch Chrome / agent-browser against
+ <profile>/ <tmp-clone>/`) and launch Chrome against
the clone as the user-data-dir; run any clearing there only.
4. Computer use — when the surface is a desktop/GUI app rather than a
page, drive it via OS-level automation (a computer-use agent,
diff --git a/plugins/omo/skills/ulw-execute/SKILL.md b/plugins/omo/skills/ulw-execute/SKILL.md
index a30ee23c..e7f7c2ea 100644
--- a/plugins/omo/skills/ulw-execute/SKILL.md
+++ b/plugins/omo/skills/ulw-execute/SKILL.md
@@ -169,7 +169,7 @@ Each sub-task message must include:
5. One Manual-QA channel, named with the exact tool and exact invocation (the literal `curl`, `send-keys`, `browser:control-in-app-browser` action, `page.click`, payload, selectors, and the binary observable that decides PASS/FAIL), not "verify it works". A LIGHT checkbox needs one real-surface proof of its deliverable, and auxiliary surfaces (CLI stdout, DB state diff, parsed config dump) are first-class when the surface is CLI- or data-shaped:
- HTTP call: `curl -i` against the live endpoint.
- Terminal / TUI: drive a real pty; `tmux send-keys` is fine for a boot/behavior smoke, but color/layout/CJK evidence goes through the xterm.js web terminal below, NEVER `tmux capture-pane`.
- - Browser use: prefer the harness's in-app browser control when available and the scenario does not need an authenticated or persistent user browser profile; otherwise drive the real page with Chrome, or agent-browser (https://github.com/vercel-labs/agent-browser) when Chrome is unavailable.
+ - Browser use: from js eval, use `new Bun.WebView()` on Bun >= 1.4 (macOS default; Linux/Windows need Chrome/Chromium/Edge). Otherwise, or for Chrome semantics, stealth, trace, or auth, write and run a `playwright-core` script against local Chrome (`channel: "chrome"`; persistent context on a CLONED profile). Codex: `browser:control-in-app-browser` for ordinary page control.
- Computer use: OS-level GUI automation against the running desktop app when the surface is not a page.
- TUI visual evidence: when a TUI claim needs visual QA or PR proof, run `bun script/qa/web-terminal-visual-qa.mjs --command "<cmd>" --input "{Enter}" --evidence-dir <dir>` (real pty rendered through xterm.js in Chrome) and attach `terminal.png` plus `metadata.json`.
6. The adversarial classes that apply to this sub-task (from the 9 ultraqa classes) and how each is probed.
diff --git a/plugins/omo/skills/ulw-loop/references/full-workflow.md b/plugins/omo/skills/ulw-loop/references/full-workflow.md
index 83213a07..89cda675 100644
--- a/plugins/omo/skills/ulw-loop/references/full-workflow.md
+++ b/plugins/omo/skills/ulw-loop/references/full-workflow.md
@@ -20,7 +20,7 @@ Run each criterion's real-surface proof yourself through the channel that faithf
1. **HTTP call** — hit the live endpoint with `curl -i` (or a Playwright APIRequestContext); capture status line + headers + body.
2. **Terminal / TUI** - prove it through the xterm.js web terminal; tmux `send-keys` is fine for a boot smoke, but NEVER `tmux capture-pane` for color/layout/CJK evidence (it degrades truecolor).
-3. **Browser use** — in Codex, use `browser:control-in-app-browser` first when available and the scenario does not need an authenticated or persistent user browser profile. Otherwise use Chrome to drive the REAL page; if unavailable, use agent-browser. Capture action log + screenshot path. Never downgrade a browser-facing criterion.
+3. **Browser use** — in Codex, prefer `browser:control-in-app-browser`. Otherwise, or for Chrome semantics, stealth, trace, or auth, WRITE a `playwright-core` script and run it from js eval against local Chrome (`channel: "chrome"`; persistent context on a CLONED profile, never the live one). Capture action log + screenshot path. Never downgrade a browser-facing criterion.
4. **Computer use** — for desktop/GUI apps, drive the running app via OS automation (computer-use, AppleScript, xdotool, etc.); capture action log + screenshot.
For TUI visual QA (mandatory when a PR or review must inspect the terminal screen),
@@ -165,7 +165,7 @@ Loop per goal. Cap at 5 cycles per goal. Cap identical same-criterion failures a
4. INTEGRATE + CRITICAL SELF-QA + GIT CHECKPOINT (EVERY WORKER RETURN): do NOT trust the worker's report. Read the diff yourself, re-run its tests, and run LSP diagnostics on the changed files. Treat "done" as a claim to disprove. If the diff drifts, the test is hollow, or evidence is missing, RESPAWN the worker with the specific failure context. Once the work unit is verified, use `git-master` before staging: inspect recent repository commits and touched-path history to infer commit language, Conventional Commit scope, message shape, and unit size. Stage only that unit's files and commit in the observed style; do not carry verified work forward into a later omnibus commit. If no git-tracked files changed or committing is unsafe, record the no-commit reason as evidence. Forward every finding/learning to subsequent workers.
5. EXECUTE-AS-SCENARIO: ACTUALLY run the Manual-QA scenario the criterion named (channel table above). Run it yourself for the orchestrator check; for heavier flows dispatch a dedicated QA execution worker (`lazycodex-worker-medium` by default; `lazycodex-worker-high` when the QA flow itself is hard) whose ONLY job is to drive the channel and write the artifact to the named evidence path. If the scenario FAILS, respawn the implementing worker with the captured failure — do not hand-patch around it.
6. CAPTURE: collect the observable artifact path: transcript, stdout, screenshot, assertion, status+body, diff, or parsed dump. No artifact written at the evidence path — not done; record BLOCKED and respawn QA.
-7. CLEAN (PAIRED, NEVER SKIP): tear down every runtime artifact step 5 spawned BEFORE recording — server PIDs (`kill`, verify `kill -0` fails), `tmux` sessions (`tmux kill-session -t ulw-qa-<criterion>`; confirm `tmux ls`), browser / Playwright contexts (`.close()`), containers (`docker rm -f`), bound ports (`lsof -i :<port>` empty), temp sockets / files / dirs (`rm -rf` the `mktemp` paths), QA-only env vars, AND close every finished worker (v1 `close_agent`; on V2 finished workers end on their own — `interrupt_agent` any still running). Register each teardown as its own todo the moment the QA spawns the resource (scripts, tmux assets, browsers / agent-browser sessions, PIDs, ports) so none is forgotten. Embed a one-line cleanup receipt in the evidence string, e.g. `cleanup: killed 12345; tmux kill-session ulw-qa-foo; rm -rf /tmp/ulw.aB12cD; interrupt_agent w-3`. Missing receipt → record BLOCKED, not PASS.
+7. CLEAN (PAIRED, NEVER SKIP): tear down every runtime artifact step 5 spawned BEFORE recording — server PIDs (`kill`, verify `kill -0` fails), `tmux` sessions (`tmux kill-session -t ulw-qa-<criterion>`; confirm `tmux ls`), browser / Playwright contexts (`.close()`), containers (`docker rm -f`), bound ports (`lsof -i :<port>` empty), temp sockets / files / dirs (`rm -rf` the `mktemp` paths), QA-only env vars, AND close every finished worker (v1 `close_agent`; on V2 finished workers end on their own — `interrupt_agent` any still running). Register each teardown as its own todo the moment the QA spawns the resource (scripts, tmux assets, browser contexts, PIDs, ports) so none is forgotten. Embed a one-line cleanup receipt in the evidence string, e.g. `cleanup: killed 12345; tmux kill-session ulw-qa-foo; rm -rf /tmp/ulw.aB12cD; interrupt_agent w-3`. Missing receipt → record BLOCKED, not PASS.
8. RECORD one result immediately from the artifact you just wrote — never from memory or a later turn — stamping the capture tree `$(git rev-parse --short "HEAD^{tree}")` into the evidence:
- PASS: `omo-agent-toolkit ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status pass --evidence "<observable> @tree:<short-tree> | <cleanup receipt>" --json`
- FAIL: `omo-agent-toolkit ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status fail --evidence "<observable> @tree:<short-tree> | <cleanup receipt>" --notes "<diagnosis>" --json`
diff --git a/plugins/omo/skills/ulw-research/SKILL.md b/plugins/omo/skills/ulw-research/SKILL.md
index b36d6934..0863addd 100644
--- a/plugins/omo/skills/ulw-research/SKILL.md
+++ b/plugins/omo/skills/ulw-research/SKILL.md
@@ -177,7 +177,7 @@ Scaling floor — more angles always justify more workers:
| Multi-faceted | 4 | 6 | 2 | 2 | 14 |
| Full due diligence | 4 | 6 | 3 | 2 | 15 |
-The browsing column is BINDING, not advisory: when the brief says `Browsing: yes`, the roster names a browsing-worker angle before the first wave launches, and that worker is spawned in the same turn as the rest of the wave. A run that reaches wave 2 with zero browsing workers on a `Browsing: yes` brief has silently downgraded every source to what plain fetch happened to return.
+The browsing column is BINDING, not advisory: when the brief says `Browsing: yes`, the roster names a browsing-worker angle, armed with the `ultimate-browsing` skill, before the first wave launches, and that worker is spawned in the same turn as the rest of the wave. A run that reaches wave 2 with zero browsing workers on a `Browsing: yes` brief has silently downgraded every source to what plain fetch happened to return.
**Disambiguate before you expand.** When the topic names something that could resolve several ways — a product, a person, a codename, a version — the first wave settles WHICH entity before any worker researches its history, benchmarks, or controversies: canonical name, first-party URL or account, whether it exists in the claimed category, and a confidence line. An unresolved entity never becomes a premise in a later wave's spawn message; that is exactly how a run starts inventing facts about something that does not exist.
@@ -185,7 +185,7 @@ Role protocols — embed the relevant one in each spawn message; every worker ge
- **Codebase (explore), 2-4 workers.** Grep with 3+ keyword variations; structural/AST search; LSP definitions and references; file-name globs; `git log --all -S '<keyword>'` and `--grep` for history including deleted code. Cross-validate hits across tools. Report absolute file paths, patterns with `file:line`, and how findings connect.
- **Web (librarian), 3-6 workers.** At least 10 distinct websearch queries per worker, each with a different operator or angle (see Search craft); fetch the full page for every result that matters — snippets lie. Context7 with 3+ queries per known library. grep.app and `gh search code|repos|issues` for real-world usage. Official docs via sitemap discovery (`<base>/sitemap.xml`), then targeted pages.
-- **Browsing, 1-3 workers on a `Browsing: yes` brief (0 otherwise).** This worker RENDERS pages, it does not re-fetch them: it drives a real browser through whatever the harness provides — the Browser plugin, an agent-browser or playwright skill, or a code-cell browser — and loads the `ultimate-browsing` skill to escalate through its tiers (insane-search engine with its Phase-2.5 archive surrogates, platform-native readers, then Chrome stealth) only when that browser is blocked. Its standing deliverable is a full-page screenshot of every top source plus the rendered text plain fetch could not reach; a worker that returns only fetched text has not done its job. JS-rendered, login-gated, WAF-blocked, and screenshot-bearing sources all belong here rather than in the web lane. **Provenance is part of the claim**: when a source came back with `provenance` of `snapshot` (an archive copy), cite it with its `snapshot_timestamp` and never state it as the current live page; content from a `proxy` route is `untrusted` and needs a second independent route before any claim rests on it. When one blocked territory hides many leads, fan out more browsing subagents in parallel for breadth instead of serializing one worker through them.
+- **Browsing, 1-3 workers on a `Browsing: yes` brief (0 otherwise), every one loaded with the `ultimate-browsing` skill.** The skill owns the routing — the harness's own browser first, then its extraction engine with archive surrogates, platform-native readers, and Chrome stealth as each source demands; the worker owns the deliverable. This worker RENDERS pages, it does not re-fetch them: its standing deliverable is a full-page screenshot of every top source plus the rendered text plain fetch could not reach; a worker that returns only fetched text has not done its job. JS-rendered, login-gated, WAF-blocked, and screenshot-bearing sources all belong here rather than in the web lane. **Provenance is part of the claim**: when a source came back with `provenance` of `snapshot` (an archive copy), cite it with its `snapshot_timestamp` and never state it as the current live page; content from a `proxy` route is `untrusted` and needs a second independent route before any claim rests on it. When one blocked territory hides many leads, fan out more browsing subagents in parallel for breadth instead of serializing one worker through them.
- **Repo deep-dive (librarian), 0-2 workers.** Shallow-clone the most relevant repos to `${TMPDIR:-/tmp}`, pin the HEAD SHA, read core modules, follow call chains, return SHA-pinned permalinks.
Example spawn (codebase axis; librarian, browsing, and repo-dive follow the same contract with their own protocol):
@@ -384,7 +384,7 @@ High-yield combinations: official docs (`site:<docs domain>`), GitHub implementa
| Obeying a surrounding "stop exploring" rule mid-research | Authority section — those rules do not bind this mode |
| Asking a worker to write journal or session files | Workers are read-only; you journal every return |
| Two workers given the same angle | One unique angle per worker, always |
-| A `Browsing: yes` run whose roster carries no browsing worker | The browsing column is binding — name the angle in the brief and spawn it with the first wave, before any lead is chased |
+| A `Browsing: yes` run whose roster carries no browsing worker, or a browsing worker spawned without `ultimate-browsing` | The browsing column is binding — name the angle in the brief and spawn it, armed with the skill, in the first wave before any lead is chased |
| Contested claim settled by judgment | Phase 3 — run code, capture output, verdict |
| Deliverable claims without citations | Every claim cites a source or a verification artifact |
| Guessing the deliverable format instead of asking | The format gate is unconditional: propose PDF+DOCX plus the domain-fitting alternatives and the template, then wait before wave 1 |
diff --git a/plugins/omo/skills/visual-qa/AGENTS.md b/plugins/omo/skills/visual-qa/AGENTS.md
index d291a2a7..faa05c99 100644
--- a/plugins/omo/skills/visual-qa/AGENTS.md
+++ b/plugins/omo/skills/visual-qa/AGENTS.md
@@ -11,7 +11,7 @@ The visual-QA skill's executable core: a zero-dependency Node CLI that produces
```
visual-qa/
├── SKILL.md # reviewer workflow (dual oracle, evidence gates) — the prose contract
-├── references/agent-browser-setup.md
+├── references/browser-setup.md
└── scripts/
├── visual-qa.mjs # SHIPPED RUNTIME: bun-build bundle of cli.ts (+ embedded modules)
├── cli.ts # development source; dispatches image-diff / tui-check
diff --git a/plugins/omo/skills/visual-qa/SKILL.md b/plugins/omo/skills/visual-qa/SKILL.md
index 1adb2ef3..bc92bdaf 100644
--- a/plugins/omo/skills/visual-qa/SKILL.md
+++ b/plugins/omo/skills/visual-qa/SKILL.md
@@ -73,7 +73,7 @@ Before any reviewer sees an image, verify each capture yourself: the file signat
### Web
1. Capture a REFERENCE image: the user's mock/target, generated page snapshot, Figma export, source-site capture, or known-good baseline. Save as PNG. If the user provided overview text or annotations, save them next to the image and treat them as part of the reference packet.
-2. Capture the ACTUAL rendered screenshot at the same viewport size, driving the browser your harness actually has. Where a code cell can reach a browser (`new Bun.WebView()` on a Bun >= 1.4 kernel, otherwise `playwright-core` against the local Chrome), capture in-process: it needs no CLI and returns the PNG path directly. In Codex, `browser:control-in-app-browser` is that in-process surface — use it first unless the page needs an authenticated user browser session. Otherwise use the project's configured browser tooling (the playwright, agent-browser, or dev-browser skill). Save as PNG. If nothing is available, install [agent-browser](https://github.com/vercel-labs/agent-browser) (`bun add -g agent-browser && agent-browser install`) and capture with it — see `$SKILL_DIR/references/agent-browser-setup.md` for the full setup, including how to shoot a fixed-viewport screenshot.
+2. Capture the ACTUAL rendered screenshot at the reference viewport. Use two browser tiers from js eval: (1) `new Bun.WebView()` on Bun >= 1.4 (macOS default; Linux/Windows need installed Chrome/Chromium/Edge); (2) otherwise, or for Chrome semantics, stealth, trace, or authenticated profiles, WRITE a `playwright-core` script and run it from the kernel against local Chrome (`chromium.launch({ channel: "chrome" })` / `launchPersistentContext` on a CLONED profile, never the live one). In Codex, prefer `browser:control-in-app-browser` for ordinary captures. Save PNG and return its path; close the browser context. See `$SKILL_DIR/references/browser-setup.md` for fixed-viewport examples and prerequisites.
3. Run the diff and keep the JSON:
```
diff --git a/plugins/omo/skills/visual-qa/references/agent-browser-setup.md b/plugins/omo/skills/visual-qa/references/agent-browser-setup.md
deleted file mode 100644
index 021114cc..00000000
--- a/plugins/omo/skills/visual-qa/references/agent-browser-setup.md
+++ /dev/null
@@ -1,45 +0,0 @@
-# agent-browser setup (Web capture fallback)
-
-Use this when the project has **no** browser tooling configured or available for the Web
-capture path in Step 2 (no playwright / dev-browser skill, no usable headless browser).
-[agent-browser](https://github.com/vercel-labs/agent-browser) is a standalone CLI that
-drives a real Chromium and can screenshot a page at a fixed viewport — exactly what the
-`image-diff` evidence step needs.
-
-Repo: https://github.com/vercel-labs/agent-browser
-
-## Install
-
-```
-npm install -g agent-browser && agent-browser install
-```
-
-`npm install -g agent-browser` installs the CLI globally; `agent-browser install` downloads the
-managed browser it drives. If Bun is already available, `bun add -g agent-browser && agent-browser install`
-is equivalent, but npm is the default because LazyCodex/Codex installations do not require Bun.
-
-Confirm it is ready and discover the current flags:
-
-```
-agent-browser --help
-```
-
-## Capture a screenshot at a fixed viewport
-
-Set the viewport first, then screenshot — this guarantees the ACTUAL capture matches the
-REFERENCE viewport so `image-diff` compares like-for-like:
-
-```
-agent-browser set viewport 1280 720 # width height (add a third arg, e.g. 2, for retina scale)
-agent-browser screenshot actual.png # add --full for full-page, --screenshot-dir ./shots for a custom dir
-```
-
-Then feed the PNG into the diff exactly as in Step 2:
-
-```
-node "$SKILL_DIR/scripts/visual-qa.mjs" image-diff <reference.png> actual.png
-```
-
-Match the viewport numbers to whatever the reference/mock was captured at; mismatched
-dimensions make `dimensionsMatch` false and inflate `diffRatio`. Run `agent-browser --help`
-for the full command set (navigation, batch, annotate, format/quality flags).
diff --git a/plugins/omo/skills/visual-qa/references/browser-setup.md b/plugins/omo/skills/visual-qa/references/browser-setup.md
new file mode 100644
index 00000000..683aaa79
--- /dev/null
+++ b/plugins/omo/skills/visual-qa/references/browser-setup.md
@@ -0,0 +1,75 @@
+# Browser setup (Web capture)
+
+Use the js-eval kernel for both tiers. In Codex, prefer
+`browser:control-in-app-browser` for ordinary captures.
+
+## Tier 1: Bun.WebView
+
+On a Bun >= 1.4 kernel, `new Bun.WebView()` is the macOS default (system
+WebKit, no browser download). Linux/Windows require `backend: "chrome"`
+and installed Chrome/Chromium/Edge. WebView is headless; WebKit has no CDP,
+and `type()` emits no keyboard events. Use tier 2 when these differences matter.
+
+```js
+// js-eval cell; url and pngPath belong to this QA run.
+const view = new Bun.WebView({ width: 1280, height: 720 })
+try {
+ await view.navigate(url)
+ await Bun.write(pngPath, await view.screenshot())
+ console.log(pngPath)
+} finally {
+ view[Symbol.dispose]()
+}
+```
+
+## Tier 2: playwright-core with local Chrome
+
+For other kernels, real-Chrome semantics, stealth, traces, or authenticated
+profiles, WRITE a script beside the project's installed `playwright-core`
+dependency and execute it from js eval. The user installs `playwright-core`
+once with `bun add playwright-core` if needed; Chrome must already exist.
+No managed browser download is needed.
+
+```js
+// capture.mjs
+import { chromium } from "playwright-core"
+const [url, pngPath] = process.argv.slice(2)
+const browser = await chromium.launch({ channel: "chrome", headless: true })
+try {
+ const page = await browser.newPage({ viewport: { width: 1280, height: 720 }, deviceScaleFactor: 1 })
+ await page.goto(url, { waitUntil: "load", timeout: 30000 })
+ await page.screenshot({ path: pngPath })
+ console.log(pngPath)
+} finally {
+ await browser.close()
+}
+```
+
+Run from the js-eval kernel (also works on a Node kernel):
+
+```js
+const { promisify } = await import("node:util")
+const { execFile } = await import("node:child_process")
+const result = await promisify(execFile)("node", [scriptPath, url, pngPath], { timeout: 45000 })
+console.log(result.stdout)
+```
+
+For auth, CLONE the user-data directory to a private task-owned directory
+and use `chromium.launchPersistentContext(clonePath, { channel: "chrome" })`.
+NEVER launch against or clear cookies/cache/site data from the live profile.
+Close the context and remove only the clone after QA. For script-based stealth,
+read the ultimate-browsing skill's `references/chrome-stealth.md`.
+
+## Capture a screenshot at a fixed viewport
+
+Match CSS viewport AND PNG dimensions: WebKit follows native display scale
+(a 1280x720 viewport can yield 2560x1440 pixels). Use matching reference
+captures or Chrome's `deviceScaleFactor`, not resizing to force a pass.
+Wait for the specific page state, not a sleep, then compare:
+
+```sh
+node "$SKILL_DIR/scripts/visual-qa.mjs" image-diff reference.png actual.png
+```
+
+Inspect `dimensionsMatch` and `diffRatio`, then inspect the image. Close every
+WebView/browser context and the fixture server, even on a failed capture.