Sync third-party marketplace plugins

Constraint: Public skills are published only by explicit administrator action unless they are tracked third-party market sources.
Confidence: high
Scope-risk: narrow
Directive: Keep private/internal skills out of the public marketplace.
Tested: Marketplace validation passed.
This commit is contained in:
KeyInfo Bot
2026-06-11 16:40:38 +08:00
parent 488e2bd620
commit bb633f3f31
40 changed files with 6305 additions and 2 deletions
@@ -219,6 +219,18 @@
"authentication": "ON_INSTALL"
},
"category": "文档处理"
},
{
"name": "oh-my-codex",
"source": {
"source": "local",
"path": "./plugins/oh-my-codex"
},
"policy": {
"installation": "AVAILABLE",
"authentication": "ON_INSTALL"
},
"category": "开发工具"
}
]
}
@@ -0,0 +1,3 @@
{
"apps": {}
}
@@ -0,0 +1,44 @@
{
"name": "oh-my-codex",
"version": "0.18.11",
"description": "oh-my-codex 是 Codex CLI 的多 Agent 编排、结构化工作流、插件级 hooks、MCP 和 HUD 扩展插件。",
"author": {
"name": "Yeachan Heo",
"url": "https://github.com/Yeachan-Heo"
},
"homepage": "https://yeachan-heo.github.io/oh-my-codex",
"repository": "https://github.com/Yeachan-Heo/oh-my-codex.git",
"license": "MIT",
"keywords": [
"codex",
"openai",
"cli",
"agents",
"orchestration",
"multi-agent"
],
"skills": "./skills/",
"mcpServers": "./.mcp.json",
"apps": "./.app.json",
"interface": {
"displayName": "oh-my-codex",
"shortDescription": "为 Codex CLI 提供 OMX 工作流、hooks、MCP 和多 Agent 编排。",
"longDescription": "oh-my-codex 将 OMX 的规划、调试、代码评审、多 Agent 协作、目标执行、质量验证、wiki 和 HUD 工作流打包为 Codex 插件。插件包含官方支持的 plugin-scoped hooks、MCP 配置和多个 workflow skills;完整运行需要用户已安装 oh-my-codex CLI 并完成 omx setup。",
"developerName": "Yeachan Heo",
"category": "开发工具",
"capabilities": [
"Interactive",
"Read",
"Write"
],
"defaultPrompt": [
"使用 oh-my-codex 帮我选择合适的 OMX 工作流。",
"使用 oh-my-codex 帮我规划、执行并验证这个开发任务。"
],
"websiteURL": "https://oh-my-codex.dev",
"privacyPolicyURL": "https://github.com/Yeachan-Heo/oh-my-codex",
"termsOfServiceURL": "https://github.com/Yeachan-Heo/oh-my-codex",
"brandColor": "#111827"
},
"hooks": "./hooks/hooks.json"
}
@@ -0,0 +1,52 @@
{
"mcpServers": {
"omx_state": {
"command": "omx",
"args": [
"mcp-serve",
"state"
],
"enabled": false
},
"omx_memory": {
"command": "omx",
"args": [
"mcp-serve",
"memory"
],
"enabled": false
},
"omx_code_intel": {
"command": "omx",
"args": [
"mcp-serve",
"code-intel"
],
"enabled": false
},
"omx_trace": {
"command": "omx",
"args": [
"mcp-serve",
"trace"
],
"enabled": false
},
"omx_wiki": {
"command": "omx",
"args": [
"mcp-serve",
"wiki"
],
"enabled": false
},
"omx_hermes": {
"command": "omx",
"args": [
"mcp-serve",
"hermes"
],
"enabled": false
}
}
}
@@ -0,0 +1,9 @@
{
"sourceId": "oh-my-codex",
"repo": "https://github.com/Yeachan-Heo/oh-my-codex.git",
"ref": "main",
"commit": "0332e47d2a961f738cf4c52e86cd517eaae4197b",
"adapter": "codex-plugin",
"sourcePath": "plugins/oh-my-codex",
"syncedAt": "2026-06-11T08:39:42Z"
}
@@ -0,0 +1,369 @@
#!/usr/bin/env node
import { spawn } from 'node:child_process';
import { existsSync, readFileSync, realpathSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const hookDir = dirname(fileURLToPath(import.meta.url));
// sync-plugin-mirror verifies this stable marker; runtime behavior is tested separately.
const OMX_PLUGIN_HOOK_LAUNCHER_CONTRACT_MARKER = 'omx-plugin-hook-launcher:v1';
const MAX_WRAPPER_STDIN_BYTES = 1024 * 1024;
const RAW_EVENT_SCAN_BYTES = 64 * 1024;
const CODEX_HOOK_EVENT_NAMES = new Set([
'SessionStart',
'PreToolUse',
'PostToolUse',
'UserPromptSubmit',
'PreCompact',
'PostCompact',
'Stop',
]);
function skipJsonWhitespace(raw, index) {
while (index < raw.length && /\s/.test(raw[index] ?? '')) index += 1;
return index;
}
function readJsonStringLiteral(raw, quoteIndex) {
if (raw[quoteIndex] !== '"') return null;
let value = '';
for (let index = quoteIndex + 1; index < raw.length; index += 1) {
const char = raw[index];
if (char === '"') return { value, endIndex: index + 1 };
if (char !== '\\') {
value += char;
continue;
}
index += 1;
if (index >= raw.length) return null;
const escaped = raw[index];
switch (escaped) {
case '"':
case '\\':
case '/':
value += escaped;
break;
case 'b':
value += '\b';
break;
case 'f':
value += '\f';
break;
case 'n':
value += '\n';
break;
case 'r':
value += '\r';
break;
case 't':
value += '\t';
break;
case 'u': {
const hex = raw.slice(index + 1, index + 5);
if (!/^[0-9a-fA-F]{4}$/.test(hex)) return null;
value += String.fromCharCode(Number.parseInt(hex, 16));
index += 4;
break;
}
default:
return null;
}
}
return null;
}
function extractTopLevelStringField(rawInput, fieldNames) {
const raw = rawInput.slice(0, RAW_EVENT_SCAN_BYTES);
const wanted = new Set(fieldNames);
let depth = 0;
let index = 0;
while (index < raw.length) {
const char = raw[index];
if (char === '"') {
const key = readJsonStringLiteral(raw, index);
if (!key) return null;
index = key.endIndex;
const afterKey = skipJsonWhitespace(raw, index);
if (depth === 1 && raw[afterKey] === ':' && wanted.has(key.value)) {
const valueStart = skipJsonWhitespace(raw, afterKey + 1);
const value = readJsonStringLiteral(raw, valueStart);
return value?.value ?? null;
}
continue;
}
if (char === '{') depth += 1;
else if (char === '}') depth = Math.max(0, depth - 1);
index += 1;
}
return null;
}
function extractTopLevelHookEventName(rawInput) {
const eventName = extractTopLevelStringField(rawInput, ['hook_event_name', 'hookEventName', 'event', 'name']);
return CODEX_HOOK_EVENT_NAMES.has(eventName) ? eventName : null;
}
function detectStopHookInput(input) {
const text = input.toString('utf8');
try {
const parsed = JSON.parse(text);
const eventName = parsed?.hook_event_name ?? parsed?.hookEventName ?? parsed?.event ?? parsed?.name;
return eventName === 'Stop';
} catch {
return extractTopLevelHookEventName(text) === 'Stop';
}
}
async function readBoundedStdin() {
const chunks = [];
let totalBytes = 0;
for await (const rawChunk of process.stdin) {
const chunk = Buffer.isBuffer(rawChunk) ? rawChunk : Buffer.from(rawChunk);
totalBytes += chunk.length;
if (totalBytes > MAX_WRAPPER_STDIN_BYTES) {
const remaining = MAX_WRAPPER_STDIN_BYTES - Buffer.concat(chunks).length;
if (remaining > 0) chunks.push(chunk.subarray(0, remaining));
return { input: Buffer.concat(chunks), oversized: true, totalBytes };
}
chunks.push(chunk);
}
return { input: Buffer.concat(chunks), oversized: false, totalBytes };
}
function stopFallbackOutput(stopReason, detail) {
const reason = 'OMX plugin Stop hook launcher failed before valid native Stop JSON could be produced. Continue once, preserve runtime state, inspect hook launcher diagnostics, and retry.';
return {
decision: 'block',
reason,
stopReason,
systemMessage: detail ? `${reason} Failure: ${detail}` : reason,
};
}
function writeStopFallback(stopReason, detail) {
process.stdout.write(`${JSON.stringify(stopFallbackOutput(stopReason, detail))}\n`);
process.exitCode = 0;
}
function failLauncher(error, isStop, stopReason = 'plugin_stop_hook_launcher_failure') {
const detail = error instanceof Error ? error.message : String(error);
console.error(`[oh-my-codex] ${detail}`);
if (isStop) {
writeStopFallback(stopReason, detail);
return;
}
process.exitCode = 1;
}
function readPinnedLauncher() {
const launcherPath = join(hookDir, 'omx-command.json');
try {
const raw = JSON.parse(readFileSync(launcherPath, 'utf8'));
if (typeof raw.command !== 'string' || raw.command.trim() === '') {
throw new Error('missing non-empty command');
}
const argsPrefix = Array.isArray(raw.argsPrefix) ? raw.argsPrefix : [];
if (!argsPrefix.every((arg) => typeof arg === 'string')) {
throw new Error('argsPrefix must contain only strings');
}
return { command: raw.command, argsPrefix };
} catch (error) {
if (error?.code === 'ENOENT') return null;
throw new Error(`invalid plugin hook launcher ${launcherPath}: ${error.message}`);
}
}
function readConfiguredLauncher() {
if (process.env.OMX_NATIVE_HOOK_COMMAND) {
return { command: process.env.OMX_NATIVE_HOOK_COMMAND, argsPrefix: [] };
}
return readPinnedLauncher() ?? { command: 'omx', argsPrefix: [] };
}
function readJsonFile(path) {
try {
return JSON.parse(readFileSync(path, 'utf8'));
} catch {
return null;
}
}
function isTerminalOutcome(value) {
return ['finish', 'finished', 'complete', 'completed', 'done', 'blocked', 'blocked-on-user', 'blocked_on_user', 'failed', 'fail', 'error', 'cancelled', 'canceled', 'cancel', 'aborted', 'abort', 'userinterlude', 'user-interlude', 'interrupted', 'interrupt', 'askuserquestion', 'ask-user-question', 'askuser', 'question'].includes(String(value ?? '').trim().toLowerCase());
}
function isTerminalRunStateForMode(state, mode) {
if (!state) return false;
const runMode = String(state.mode ?? '').trim();
if (runMode && runMode !== mode) return false;
return isTerminalOutcome(state.outcome)
|| isTerminalOutcome(state.run_outcome)
|| isTerminalOutcome(state.lifecycle_outcome)
|| isTerminalOutcome(state.terminal_outcome);
}
function canonicalPath(path) {
const absolute = resolve(path);
if (!existsSync(absolute)) return absolute;
try {
return typeof realpathSync.native === 'function' ? realpathSync.native(absolute) : realpathSync(absolute);
} catch {
return absolute;
}
}
function sameFilePath(leftPath, rightPath) {
return canonicalPath(leftPath) === canonicalPath(rightPath);
}
function isSessionStateAuthoritativeForCwd(state, cwd) {
if (!isSafeSessionId(state?.session_id)) return false;
const sessionCwd = typeof state.cwd === 'string' ? state.cwd.trim() : '';
return !sessionCwd || sameFilePath(sessionCwd, cwd);
}
function listAuthoritativeStateBaseDirs(cwd) {
if (process.env.OMX_TEAM_STATE_ROOT?.trim()) return [process.env.OMX_TEAM_STATE_ROOT.trim()];
if (process.env.OMX_ROOT?.trim()) return [join(process.env.OMX_ROOT.trim(), '.omx', 'state')];
if (process.env.OMX_STATE_ROOT?.trim()) return [join(process.env.OMX_STATE_ROOT.trim(), '.omx', 'state')];
return [join(cwd, '.omx', 'state')];
}
function isSafeSessionId(sessionId) {
return typeof sessionId === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(sessionId.trim());
}
function readCurrentSessionId(stateBaseDirs, cwd) {
for (const stateDir of stateBaseDirs) {
const session = readJsonFile(join(stateDir, 'session.json'));
if (isSessionStateAuthoritativeForCwd(session, cwd)) return session.session_id.trim();
}
const envSessionId = process.env.OMX_SESSION_ID || process.env.CODEX_SESSION_ID;
return isSafeSessionId(envSessionId) ? envSessionId.trim() : null;
}
function shouldContinueAutopilotState(state) {
if (state?.active !== true) return false;
return !(isTerminalOutcome(state.current_phase)
|| isTerminalOutcome(state.run_outcome)
|| isTerminalOutcome(state.lifecycle_outcome)
|| isTerminalOutcome(state.terminal_outcome)
|| isTerminalOutcome(state.outcome)
|| (typeof state.completed_at === 'string' && state.completed_at.trim() !== ''));
}
function hasActiveAutopilotStateForOversizedStop(input) {
const text = input.toString('utf8');
const cwd = extractTopLevelStringField(text, ['cwd']) || process.cwd();
const stateBaseDirs = listAuthoritativeStateBaseDirs(cwd);
const sessionId = readCurrentSessionId(stateBaseDirs, cwd);
if (!isSafeSessionId(sessionId)) return false;
const sessionDir = join(stateBaseDirs[0], 'sessions', sessionId.trim());
const terminalRunState = readJsonFile(join(sessionDir, 'run-state.json'));
if (isTerminalRunStateForMode(terminalRunState, 'autopilot')) return false;
const sessionState = readJsonFile(join(sessionDir, 'autopilot-state.json'));
return shouldContinueAutopilotState(sessionState);
}
function writeJsonNoop() {
process.stdout.write(`${JSON.stringify({})}\n`);
process.exitCode = 0;
}
async function main() {
const { input, oversized, totalBytes } = await readBoundedStdin();
const isStop = detectStopHookInput(input);
if (oversized) {
const message = `plugin hook stdin exceeded ${MAX_WRAPPER_STDIN_BYTES} bytes before launcher delegation; totalBytes>${totalBytes}`;
if (isStop) {
if (hasActiveAutopilotStateForOversizedStop(input)) {
console.error(`[oh-my-codex] ${message}`);
writeStopFallback('plugin_stop_hook_stdin_oversized_active_workflow', message);
return;
}
writeJsonNoop();
return;
}
console.error(`[oh-my-codex] ${message}`);
process.exitCode = 1;
return;
}
let launcher;
try {
launcher = readConfiguredLauncher();
} catch (error) {
failLauncher(error, isStop);
return;
}
const { command, argsPrefix } = launcher;
const child = spawn(command, [...argsPrefix, 'codex-native-hook'], {
stdio: ['pipe', 'pipe', 'pipe'],
env: process.env,
shell: process.platform === 'win32',
});
let stdoutBytes = 0;
let childSpawnError = null;
let childStdinError = null;
child.stdout.on('data', (chunk) => {
stdoutBytes += Buffer.byteLength(chunk);
process.stdout.write(chunk);
});
child.stderr.pipe(process.stderr);
child.stdin.on('error', (error) => {
childStdinError = error;
});
child.on('error', (error) => {
childSpawnError = error;
});
child.on('close', (code, signal) => {
if (isStop && stdoutBytes === 0) {
if (childSpawnError) {
writeStopFallback('plugin_stop_hook_launcher_spawn_error', `failed to launch ${command} codex-native-hook: ${childSpawnError.message}`);
return;
}
if (signal) {
writeStopFallback('plugin_stop_hook_launcher_signal', `codex-native-hook terminated by ${signal}`);
return;
}
if (code && code !== 0) {
if (childStdinError) {
writeStopFallback('plugin_stop_hook_launcher_stdin_error', `codex-native-hook stdin failed: ${childStdinError.message}`);
return;
}
writeStopFallback('plugin_stop_hook_launcher_exit', `codex-native-hook exited with code ${code}`);
return;
}
writeStopFallback('plugin_stop_hook_launcher_empty_stdout', 'codex-native-hook exited successfully without producing Stop hook JSON');
return;
}
if (childSpawnError) {
console.error(`[oh-my-codex] failed to launch ${command} codex-native-hook: ${childSpawnError.message}`);
process.exitCode = 1;
return;
}
if (signal) {
console.error(`[oh-my-codex] codex-native-hook terminated by ${signal}`);
process.exitCode = 1;
return;
}
process.exitCode = code ?? 0;
});
child.stdin.end(input);
}
main().catch((error) => {
console.error(`[oh-my-codex] plugin hook launcher failed: ${error instanceof Error ? error.message : String(error)}`);
process.exitCode = 1;
});
@@ -0,0 +1,76 @@
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "node \"${PLUGIN_ROOT}/hooks/codex-native-hook.mjs\""
}
],
"matcher": "startup|resume|clear"
}
],
"PreToolUse": [
{
"hooks": [
{
"type": "command",
"command": "node \"${PLUGIN_ROOT}/hooks/codex-native-hook.mjs\""
}
]
}
],
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "node \"${PLUGIN_ROOT}/hooks/codex-native-hook.mjs\""
}
]
}
],
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "node \"${PLUGIN_ROOT}/hooks/codex-native-hook.mjs\""
}
]
}
],
"PreCompact": [
{
"hooks": [
{
"type": "command",
"command": "node \"${PLUGIN_ROOT}/hooks/codex-native-hook.mjs\""
}
]
}
],
"PostCompact": [
{
"hooks": [
{
"type": "command",
"command": "node \"${PLUGIN_ROOT}/hooks/codex-native-hook.mjs\""
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "node \"${PLUGIN_ROOT}/hooks/codex-native-hook.mjs\"",
"timeout": 30
}
]
}
]
}
}
@@ -0,0 +1,148 @@
---
name: ai-slop-cleaner
description: Run an anti-slop cleanup/refactor/deslop workflow
---
# AI Slop Cleaner Skill
Reduce AI-generated slop with a regression-tests-first, smell-by-smell cleanup workflow that preserves behavior and raises signal quality.
## When to Use
Use this skill when:
- A code path works but feels bloated, noisy, repetitive, or over-abstracted
- A user asks to “cleanup”, “refactor”, or “deslop” AI-generated output
- Follow-up implementation left duplicate code, dead code, weak boundaries, missing tests, fallback-like code, or unnecessary wrapper layers
- You need a disciplined cleanup workflow without broad rewrites
## GPT-5.5 Guidance Alignment
- Keep outputs concise and evidence-dense unless risk or the user requests more detail.
- Treat newer user instructions as local workflow updates without discarding earlier non-conflicting constraints.
- Keep using inspection, tests, diagnostics, and verification until the cleanup is grounded.
- Proceed automatically through clear, reversible cleanup steps; ask only when a choice materially changes scope or behavior.
## Scoped File Lists and Ralph Workflow
- This skill can accept a **file list scope** instead of a whole feature area.
- When the caller provides a changed-files list (for example, Ralph session-owned edits), keep the cleanup strictly bounded to those files.
- In the **Ralph workflow**, the mandatory deslop pass should run this skill on Ralph's changed files only, in standard mode unless the caller explicitly requests otherwise.
## Procedure
1. **Lock behavior with regression tests first**
- Identify the behavior that must not change
- Add or run targeted regression tests before editing cleanup candidates
- If behavior is currently untested, create the narrowest test coverage needed first
- For fallback-like code, cover the primary path and any preserved compatibility/fail-safe fallback before cleanup
2. **Create a cleanup plan before code**
- List the specific smells to remove
- Bound the pass to the requested files/scope
- If a file list scope is provided, keep the pass restricted to that changed-files list
- Include fallback findings, classifications, and escalation status in the plan
- Order fixes from safest/highest-signal to riskiest
- Do not start coding until the cleanup plan is explicit
3. **Inventory fallback-like code before editing**
- Search the requested scope for fallback-like detection signals: quick hacks, temporary workaround, temporary fallback, just bypass, just skip, fallback if it fails, swallowed errors, silent defaults, broad compatibility shims, and duplicate alternate execution paths
- Classify each finding before changing it:
- **Masking fallback slop** — hides errors or evidence, bypasses the primary contract, suppresses tests or validation, swallows failures, silently defaults, or adds untested alternate paths
- **Grounded compatibility/fail-safe fallback** — is scoped to an external/version/fail-safe boundary, documents the rationale, preserves failure evidence, and has regression tests for both the primary and fallback behavior
- Prefer root-cause repair, deletion, boundary repair, or explicit failure behavior before preserving fallback paths
- For broad, ambiguous, cross-layer, or architectural fallback-like code, invoke `$ralplan` for consensus resolution before edits
- Recursion guard: when already inside ralplan, ralph, team, or another OMX workflow, do not spawn a nested `$ralplan`; record the finding and attach it to the active ralplan, leader, or plan handoff instead
4. **Categorize issues before editing**
- **Fallback-like code** — masking fallbacks, workaround branches, bypasses, swallowed errors, silent defaults, broad shims, alternate execution paths
- **Duplication** — repeated logic, copy-paste branches, redundant helpers
- **Dead code** — unused code, unreachable branches, stale flags, debug leftovers
- **Needless abstraction** — pass-through wrappers, speculative indirection, single-use helper layers
- **Boundary violations** — hidden coupling, leaky responsibilities, wrong-layer imports or side effects
- **UI/design slop** — review visual outputs as context-sensitive signals, not absolute bans; preserve intentional brand, design-system, accessibility, or product-context exceptions when the rationale is clear
- Korean body text that is too small: challenge 11-12px body copy; Korean body text generally needs 14px or larger unless a dense, accessible system explicitly supports smaller text
- Gratuitous depth: avoid putting box shadows on every logo, surface, card, icon, background, and step block when hierarchy or affordance does not need it
- Repetitive content scaffolding: trim repeated eyebrow + title + description + paragraph stacks, filler explanation text, and generic emoji badges that do not add meaning
- Default AI palettes: question blue/purple defaults such as #3B82F6 when there is no brand, semantic, or system rationale
- Over-perfect grids: avoid reflexive uniform 3-column or 4-column card grids when the product context would benefit from rhythm, asymmetry, carousel cuts, bento composition, or varied emphasis
- Extreme gradients: tone down "AI demo" gradients unless the brand or campaign intentionally calls for that intensity
- **Missing tests** — behavior not locked, weak regression coverage, gaps around edge cases
5. **Execute passes one smell at a time**
- **Fallback-like code resolution gate** — remove masking fallback slop, repair root causes, or escalate ambiguous cases before continuing
- **Pass 1: Dead code deletion**
- **Pass 2: Duplicate removal**
- **Pass 3: Naming/error handling cleanup**
- **Pass 4: Test reinforcement**
- Re-run targeted verification after each pass
- Avoid bundling unrelated refactors into the same edit set
6. **Run quality gates**
- Regression tests stay green
- Lint passes
- Typecheck passes
- Relevant unit/integration tests pass
- Static/security scan passes when available
- Diff stays minimal and scoped
- No new abstractions or dependencies unless explicitly required
7. **Finish with an evidence-dense report**
- Changed files
- Simplifications made
- Fallback findings, classifications, and escalation status
- Tests/diagnostics/build checks run
- UI/design reviewer checklist findings when visual/UI files were in scope
- Remaining risks
- Residual follow-ups or consciously deferred cleanup
## Output Format
```text
AI SLOP CLEANUP REPORT
======================
Scope: [files or feature area]
Behavior Lock: [targeted regression tests added/run]
Cleanup Plan: [bounded smells and order]
Fallback Findings: [none, or finding -> masking fallback slop / grounded compatibility/fail-safe fallback -> escalation status]
UI/Design Findings: [none/N/A, or signal -> action taken/deferred -> intentional exception rationale]
Passes Completed:
- Fallback-like code resolution gate - [root-cause repair, explicit failure behavior, preserved grounded fallback, or ralplan handoff]
1. Pass 1: Dead code deletion - [concise fix]
2. Pass 2: Duplicate removal - [concise fix]
3. Pass 3: Naming/error handling cleanup - [concise fix]
4. Pass 4: Test reinforcement - [concise fix]
Quality Gates:
- Regression tests: PASS/FAIL
- Lint: PASS/FAIL
- Typecheck: PASS/FAIL
- Tests: PASS/FAIL
- Static/security scan: PASS/FAIL or N/A
Changed Files:
- [path] - [simplification]
Fallback Review:
- Findings: [fallback-like findings detected]
- Classification: [masking fallback slop | grounded fallback]
- Escalation Status: [none | raised to leader/ralplan | no escalation]
Remaining Risks:
- [none or short deferred item]
```
## Scenario Examples
**Good:** The user says `continue` after tests already lock behavior and the next smell pass is clear. Continue with the next bounded cleanup pass.
**Good:** The user narrows the scope to a specific file after planning. Keep the regression-tests-first workflow, but apply the new scope locally.
**Bad:** Start rewriting architecture before protecting behavior with tests.
**Bad:** Collapse multiple smell categories into one large refactor with no intermediate verification.
**Bad:** Keep a `fallback if it fails` branch that silently defaults after a swallowed error instead of fixing the root cause or making failure explicit.
**Good:** A version-specific compatibility shim is narrow, documented, preserves error evidence, has primary and fallback regression tests, and is reported as a grounded compatibility/fail-safe fallback.
@@ -0,0 +1,146 @@
---
name: analyze
description: "Run read-only deep repository analysis and return a ranked synthesis with explicit confidence, concrete file references, and clear evidence-vs-inference boundaries. Use when a user says 'analyze', 'investigate', 'why does', 'what's causing', or needs grounded cross-file explanation before any changes are proposed."
---
# Analyze — Read-Only Deep Analysis
Use this skill to answer the users question through **read-only repository analysis**. The goal is to explain what the codebase most likely says about the question, not to drift into implementation, debugging theater, or generic fix planning.
## Use `$analyze` when
- the user wants a grounded explanation, not code changes
- the answer requires reading multiple files or tracing behavior across boundaries
- there are several plausible explanations and they need to be ranked
- confidence should reflect the strength of the available evidence
- the user wants to understand architecture, behavior, causality, impact, or tradeoffs before changing anything
Examples:
- why a workflow behaves a certain way
- how a feature is wired across modules
- what likely explains a failure, regression, or mismatch
- what would be impacted by changing a dependency or contract
- which interpretation of the current codebase is best supported
## Do not use `$analyze` when
- the user explicitly wants code edits, a fix, or execution — use the appropriate implementation lane instead
- the user wants a new product plan or acceptance criteria — use `$plan` / `$ralplan`
- the request is a simple one-file fact lookup — read the file and answer directly
- the request is purely about running the OMX tmux team runtime — use `$team` only when OMX runtime is active
## Non-negotiable contract
Analyze is **read-only by contract**.
- Do not edit files.
- Do not turn the answer into an implementation plan.
- Do not recommend fixes as the primary output.
- Do not silently switch into execution work.
- Do not overclaim certainty.
- Do not invent facts that are not supported by repository evidence.
- Do not use judgmental, normative, or speculative language that outruns the evidence.
If a next step is helpful, keep it to a **discriminating read-only probe** that would reduce uncertainty.
## Question-aligned synthesis
Answer the users actual question first.
- Start from the asked question, not a generic debugger template.
- Keep the synthesis scoped to what the user needs to know.
- Scale the depth to the request: for simple or obvious questions, reduce swarm intensity and answer directly after enough reading.
- For broader questions, expand the search surface but keep the final answer tightly synthesized.
## Evidence rules
Maintain an explicit **evidence-vs-inference distinction**. Every material claim must be labeled as one of:
1. **Evidence** — directly supported by concrete repository artifacts
2. **Inference** — a reasoned conclusion drawn from evidence
3. **Unknown** — a question the current repository evidence does not resolve
Never present an inference as if it were direct evidence.
Never present a guess as if it were an inference.
Call out uncertainty explicitly when the codebase does not settle the question.
### Acceptable evidence
Prefer stronger evidence over weaker evidence:
1. direct code paths, contracts, tests, generated artifacts, configs, or docs with concrete file references
2. multiple independent files pointing to the same conclusion
3. localized behavioral inference from well-supported code structure
4. weaker contextual clues that remain explicitly marked as tentative
Unsupported speculation is not evidence.
## Parallel exploration policy
Parallel exploration is allowed when it improves quality, but it must stay runtime-safe.
- Default to direct read-only analysis when the answer is simple.
- When parallelism helps, prefer **native subagents by default** or equivalent in-session parallel exploration when available.
- Keep parallel lanes bounded: each lane should answer a concrete sub-question or inspect a specific subsystem.
- Use **`$team` only when OMX runtime is active** and durable tmux-based coordination is actually needed.
- Do not imply that `$team` is available in plain Codex/App sessions.
A good default split for complex analysis is:
- one lane for primary code path / contracts
- one lane for config / orchestration / generated surfaces
- one lane for tests / docs / secondary corroboration
## Execution policy
- Default to outcome-first progress and completion reporting: state the question, evidence, inference boundaries, and stop condition before adding process detail.
- Treat newer user task updates as local overrides for the active workflow branch while preserving earlier non-conflicting constraints.
- If the user says `continue`, keep working from the current analysis state instead of restarting discovery.
## Working method
1. Restate the question in one sentence.
2. Identify the smallest set of files most likely to answer it.
3. Read for direct evidence first.
4. If needed, open bounded parallel exploration lanes.
5. Compare competing explanations.
6. Rank the explanations by support.
7. Return a synthesis that clearly separates evidence from inference.
## Output contract
Structure the answer so the user can see what is known, what is inferred, and how confident the synthesis is.
### Question
[Restate the users question briefly]
### Ranked synthesis
| Rank | Explanation | Confidence | Basis |
|------|-------------|------------|-------|
| 1 | ... | High / Medium / Low | strongest supporting evidence |
| 2 | ... | High / Medium / Low | why it trails |
| 3 | ... | High / Medium / Low | why it remains possible |
### Evidence
- `path/to/file:line-line` — what this artifact directly shows
- `path/to/file:line-line` — corroborating evidence
### Inference
- What the evidence most strongly implies
- Why weaker alternatives were down-ranked
### Unknowns / limits
- What the repository evidence does not establish
- What would need to be checked next to reduce uncertainty
## Quality bar
A good analyze response is:
- read-only and question-aligned
- ranked rather than flat
- explicit about confidence
- concrete about file references
- careful about evidence vs inference
- free of unsupported speculation
- free of normative drift or judgmental filler
- explicit about the evidence-vs-inference distinction
- concise for simple cases, broader only when the question truly needs it
@@ -0,0 +1,58 @@
---
name: ask
description: Ask a local external advisor CLI (Claude or Gemini) and capture a reusable artifact
---
# Ask (Local Advisor CLI)
Use a locally installed external advisor CLI for focused questions, reviews, brainstorming, or second opinions. This skill replaces the separate `ask-claude` and `ask-gemini` skills.
## Usage
```bash
$ask claude <question or task>
$ask gemini <question or task>
omx ask claude "<question or task>"
omx ask gemini "<question or task>"
```
## Backend selection
- Use `claude` when the user asks for Claude, Anthropic, or the previous `$ask-claude` behavior.
- Use `gemini` when the user asks for Gemini or the previous `$ask-gemini` behavior.
- If no backend is specified, choose the installed backend that best matches the user request; if neither is clearly available, explain that a local CLI is required.
## Local CLI commands
Claude:
```bash
omx ask claude "{{ARGUMENTS}}"
claude -p "{{ARGUMENTS}}"
```
Gemini:
```bash
omx ask gemini "{{ARGUMENTS}}"
gemini -p "{{ARGUMENTS}}"
```
If needed, adapt to the user's installed CLI variant while keeping local execution as the default path. Do not silently switch to an MCP or remote provider when the local binary is missing.
## Artifact requirement
After local execution, save a markdown artifact to:
```text
.omx/artifacts/ask-<backend>-<slug>-<timestamp>.md
```
Minimum artifact sections:
1. Original user task
2. Backend and final prompt sent to the CLI
3. Raw CLI output
4. Concise summary
5. Action items / next steps
Task: {{ARGUMENTS}}
@@ -0,0 +1,215 @@
---
name: autopilot
description: "[OMX] Strict autonomous loop: $deep-interview -> $ralplan -> $ultragoal (+ $team if needed) -> $code-review -> $ultraqa"
---
<Purpose>
Autopilot is the strict autonomous delivery loop for non-trivial work. Its recommended/default contract is exactly:
```text
$deep-interview -> $ralplan -> $ultragoal (+ $team if needed) -> $code-review -> $ultraqa
```
If `$code-review` or `$ultraqa` is not clean, Autopilot returns to `$ralplan` with the findings as the next planning input, then continues again through `$ultragoal`, `$code-review`, and `$ultraqa` until the gates are clean or a hard blocker is reported. Ralph is a legacy/explicit alternate execution loop only; do not advertise Ralph as the default Autopilot path.
</Purpose>
<Use_When>
- User wants hands-off execution from a concrete idea, issue, PRD, or requirements artifact to reviewed and QA-checked code
- User says `$autopilot`, "autopilot", "auto pilot", "autonomous", "build me", "create me", "make me", "full auto", "handle it all", or "I want a/an..."
- Task needs clarification, planning, durable execution, verification, code review, and QA with automatic follow-up when gates are not clean
</Use_When>
<Do_Not_Use_When>
- User wants to explore options or brainstorm -- use `$plan` / `$ralplan`
- User says "just explain", "draft only", or "what would you suggest" -- respond conversationally
- User wants a single focused code change -- use `$ultragoal`, `$ralph` only when explicitly requested, or direct executor work
- User wants only review/critique of existing code -- use `$code-review`
</Do_Not_Use_When>
<Strict_Loop_Contract>
Autopilot must not run a separate broad expansion/planning/execution/QA/validation lifecycle as its primary behavior. It delegates those concerns to the canonical workflow phases below:
1. **Phase `deep-interview`** — Socratic requirements clarification gate
- Run or resume `$deep-interview` to clarify intent, scope, non-goals, constraints, and decision boundaries.
- Deep-interview is a structured question chain, not a one-question gate; `max_rounds` is a cap, not a target.
- After a user answers an `omx question`, re-score ambiguity against the active profile threshold. Ask another question only when a readiness gate is still unresolved and the answer would materially change execution; otherwise crystallize the spec and hand off.
- Required handoff artifact: a clarified spec or concise requirements summary suitable for `$ralplan`, including an explicit interview-complete rationale when leaving deep-interview.
2. **Phase `ralplan`** — consensus planning gate
- Ground the task with pre-context intake and the deep-interview artifact.
- Run or resume `$ralplan` to produce/update PRD and test-spec artifacts.
- PRD/test-spec files alone are not completion evidence. Ralplan may hand off only after durable consensus evidence records a subsequent `Architect` approval first and a subsequent `Critic` approval second.
- When returning from a non-clean review or QA pass, include `return_to_ralplan_reason` and the findings as first-class planning input.
- If either review is missing, blocked, out of order, or non-approving, remain in `ralplan` or report an explicit blocker/max-iteration outcome; do not progress to `$ultragoal`, `$team`, `$ralph`, or implementation.
- Required handoff artifact: an approved plan/test spec plus `ralplan_consensus_gate` evidence suitable for `$ultragoal`.
3. **Phase `ultragoal`** — durable implementation + verification loop
- Run `$ultragoal` from the approved ralplan artifacts.
- Ultragoal owns durable Codex goal handoffs, `.omx/ultragoal` ledger checkpoints, implementation, tests, build/lint/typecheck evidence, cleanup, and final review gate discipline.
- Use `$team` only inside an active Ultragoal story when the story clearly benefits from coordinated parallel execution (for example independent file/module lanes, broad test matrix work, or multi-domain implementation). Team remains explicit and leader-owned; Ultragoal keeps the goal/ledger state.
- Required handoff artifact: implementation evidence, changed-file summary, verification evidence, and Ultragoal ledger/checkpoint references suitable for `$code-review`.
4. **Phase `code-review`** — merge-readiness gate
- Run `$code-review` on the diff/artifacts produced by `$ultragoal`.
- A clean review means final recommendation `APPROVE` with architectural status `CLEAR`.
- `COMMENT`, `REQUEST CHANGES`, any architectural `WATCH`/`BLOCK`, or any unresolved finding is not clean.
- If not clean, increment the review cycle, persist `review_verdict`, set `return_to_ralplan_reason`, and transition back to Phase `ralplan`.
5. **Phase `ultraqa`** — adversarial QA gate
- Run `$ultraqa` after a clean code review when user-facing behavior, workflows, CLI/runtime behavior, integration surfaces, or regression risk warrant adversarial QA.
- For docs-only or trivially non-runtime changes, record `ultraqa` as skipped with an explicit condition and evidence.
- If UltraQA finds issues, persist the QA verdict/evidence, set `return_to_ralplan_reason`, and transition back to Phase `ralplan`.
The only normal terminal state is `complete` after clean code review and a passed or explicitly skipped UltraQA gate. Cancellation, blocked credentials, unrecoverable repeated failures, or explicit user stop may terminate earlier with preserved state.
</Strict_Loop_Contract>
<Pre-context Intake>
Before Phase `deep-interview` or `ralplan` starts or resumes:
1. Derive a task slug from the request.
2. Reuse the latest relevant `.omx/context/{slug}-*.md` snapshot when available.
3. If none exists, create `.omx/context/{slug}-{timestamp}.md` (UTC `YYYYMMDDTHHMMSSZ`) with:
- activation prompt / task seed
- original task status (`activation-prompt`, `legacy-unverified`, or `unavailable`)
- desired outcome
- known facts/evidence
- constraints
- unknowns/open questions
- likely codebase touchpoints
- a scope note that the seed is the Autopilot activation prompt, not guaranteed prior conversation context
4. If brownfield facts are missing, run `explore` first before or during `$deep-interview` (`$deep-interview --quick <task>` remains acceptable for bounded low-ambiguity intake); do not skip the clarification gate merely because the task sounds actionable.
5. Carry the snapshot path in Autopilot state and all handoff artifacts.
</Pre-context Intake>
<Execution_Policy>
- Always execute the recommended phases in order: `deep-interview`, then `ralplan`, then `ultragoal`, then `code-review`, then `ultraqa`.
- `$team` is conditional and explicit: use it only within an Ultragoal story when parallel execution materially improves throughput, quality, or safety.
- Never skip directly from vague/freeform expansion to implementation; unclear input must be clarified and planned through `$deep-interview` and `$ralplan`.
- A non-clean `$code-review` or failed `$ultraqa` always returns to `$ralplan`; do not patch findings ad hoc outside the loop.
- Each phase must write/update Autopilot state before handing off.
- Use existing hooks, `.omx/state`, `$deep-interview`, `$ralplan`, `$ultragoal`, optional `$team`, `$code-review`, `$ultraqa`, and pipeline primitives; do not invent a separate execution framework.
- Preserve legacy compatibility: if a user explicitly requests the old Ralph execution lane, use `$ralph` as an intentional alternate execution phase, but do not present it as Autopilot's default recommended loop.
- Continue automatically through safe reversible phase transitions. Ask only for destructive, credential-gated, or materially preference-dependent branches.
- Apply the shared workflow guidance pattern: outcome-first framing, concise visible updates for multi-step execution, local overrides for the active workflow branch, validation proportional to risk, explicit stop rules, and automatic continuation for safe reversible steps. Ask only for material, destructive, credentialed, external-production, or preference-dependent branches.
</Execution_Policy>
<State_Management>
Use the CLI-first state surface (`omx state ... --json`) for Autopilot lifecycle state. State must be session-aware when a session id exists. If the explicit MCP compatibility surface is already available, equivalent `omx_state` tool calls remain acceptable but are not required.
Inside active Autopilot, named child phases such as `$ralplan` are supervised phases, not peer workflow activations: keep `mode:"autopilot"` active and update `current_phase:"ralplan"` rather than starting standalone `mode:"ralplan"` over Autopilot.
Required fields:
```json
{
"mode": "autopilot",
"active": true,
"current_phase": "deep-interview",
"iteration": 1,
"review_cycle": 0,
"max_iterations": 10,
"phase_cycle": ["deep-interview", "ralplan", "ultragoal", "code-review", "ultraqa"],
"handoff_artifacts": {
"context_snapshot_path": ".omx/context/<slug>-<timestamp>.md",
"deep_interview": null,
"ralplan": null,
"ralplan_consensus_gate": {
"required": true,
"sequence": ["architect-review", "critic-review"],
"planning_artifacts_are_not_consensus": true,
"required_review_roles": ["architect", "critic"],
"ralplan_architect_review": null,
"ralplan_critic_review": null,
"complete": false
},
"ultragoal": null,
"code_review": null,
"ultraqa": null
},
"review_verdict": null,
"qa_verdict": null,
"return_to_ralplan_reason": null
}
```
- **On start**: `omx state write --input '{"mode":"autopilot","active":true,"current_phase":"deep-interview","iteration":1,"review_cycle":0,"state":{"phase_cycle":["deep-interview","ralplan","ultragoal","code-review","ultraqa"],"handoff_artifacts":{"context_snapshot_path":"<snapshot-path>","deep_interview":null,"ralplan":null,"ralplan_consensus_gate":{"required":true,"sequence":["architect-review","critic-review"],"planning_artifacts_are_not_consensus":true,"required_review_roles":["architect","critic"],"ralplan_architect_review":null,"ralplan_critic_review":null,"complete":false},"ultragoal":null,"code_review":null,"ultraqa":null},"review_verdict":null,"qa_verdict":null,"return_to_ralplan_reason":null}}' --json`
- **On deep-interview -> ralplan**: only after a separate gate proves the interview chain is explicitly complete or the user explicitly authorized a skip. For completion, persist `deep_interview_gate:{"status":"complete","rationale":"<why requirements are complete>","handoff_summary":"<summary>"}` (or equivalent non-empty rationale/summary) plus the clarified spec/requirements under `handoff_artifacts.deep_interview`; if a final `omx question` was involved, keep its same-session answered record linked by `question_id`/`satisfied_at`. For skip, persist `deep_interview_gate:{"status":"skipped","skip_authorized_by_user":true,"skip_reason":"<user-authorized reason>","skipped_at":"<timestamp>","source":"user","session_id":"<session>"}`. Do not leave deep-interview merely because the first `omx question` was answered or cleared.
- **Optional execution contract foundation**: when a downstream handoff explicitly sets `execution_contract_required:true`, persist a complete structured `execution_contract` under `handoff_artifacts.deep_interview` before leaving deep-interview. The canonical schema is `version:1`, `execution_stride:"task"|"deliverable"|"milestone"`, `source:"deep-interview"`, `selected_by:"user"|"default"`, `allow_task_shrink:<boolean>`, non-empty `completion_unit`, non-empty `stop_condition`, `acceptance_coverage_scope:"task"|"deliverable"|"milestone"`, and `shrink_policy:"allowed"|"ask_before_shrink"|"deny_unless_blocked"`.
- Stride semantics are binding only when `execution_contract_required:true`: `task` means `allow_task_shrink:true`, `acceptance_coverage_scope:"task"`, `shrink_policy:"allowed"`; `deliverable` means `allow_task_shrink:false`, `acceptance_coverage_scope:"deliverable"`, `shrink_policy:"ask_before_shrink"`; `milestone` means `allow_task_shrink:false`, `acceptance_coverage_scope:"milestone"`, `shrink_policy:"deny_unless_blocked"`.
- Preserve legacy behavior when `execution_contract_required` is absent or false. Do not infer stride from prose, broadness, phase names, snapshots, or task size; this foundation only validates an explicit structured contract and deliberately uses `milestone` rather than `phase`. New artifacts must write canonical snake_case keys under `handoff_artifacts.deep_interview`; the runtime may read legacy camelCase field/marker aliases and direct/nested `execution_contract` locations only as compatibility input.
- **On ralplan -> ultragoal**: only after `ralplan_consensus_gate.complete:true`, with tracker-backed native-subagent `ralplan_architect_review.agent_role:"architect"` and `ralplan_architect_review.verdict:"approve"` recorded before tracker-backed native-subagent `ralplan_critic_review.agent_role:"critic"` and `ralplan_critic_review.verdict:"approve"`; `codex_exec` or artifact-only approvals are trace evidence but not native lane proof. Set `current_phase:"ultragoal"` and persist the plan/test-spec paths under `handoff_artifacts.ralplan`.
- **On missing ralplan consensus evidence**: keep `current_phase:"ralplan"`, persist `ralplan_consensus_gate.complete:false` with `blocked_reason`, and report an explicit blocker or max-iteration outcome instead of handing off to execution.
- **On ultragoal -> code-review**: set `current_phase:"code-review"`, persist implementation/test/ledger evidence under `handoff_artifacts.ultragoal`.
- **On code-review -> ultraqa**: set `current_phase:"ultraqa"` only after a real `$code-review` stage/subagent has produced durable evidence; persist the clean review under `handoff_artifacts.code_review` with its source thread/tool/stage reference. Do not author `review_verdict:{clean:true}` from the leader's own summary.
- **On clean review + passed/skipped QA**: set `active:false`, `current_phase:"complete"`, persist `review_verdict:{recommendation:"APPROVE", architectural_status:"CLEAR", clean:true}`, `qa_verdict:{clean:true, skipped:<boolean>, reason:<string|null>}`, and `completed_at` only when both gates have durable source evidence. Required evidence is either (a) actual `$code-review`/`$ultraqa` stage or native-subagent/thread/tool records, or (b) for QA only, an explicit persisted skip reason for a documented docs-only/trivially non-runtime condition. If that evidence is missing, keep the active phase at `code-review` or `ultraqa` and record a blocker instead of self-attesting a clean gate.
- **On non-clean review or failed QA**: increment `iteration` and `review_cycle`, set `current_phase:"ralplan"`, persist `review_verdict` or `qa_verdict`, persist the phase handoff, and set `return_to_ralplan_reason` to a concise findings-driven reason.
- **Legacy Ralph state**: if a user explicitly selected the legacy Ralph execution lane, phase names and handoff keys may include `ralph`; preserve and resume them rather than rewriting history to Ultragoal.
- **On cancellation**: run `$cancel`; preserve progress for resume rather than deleting handoff artifacts.
</State_Management>
<Continuation_And_Resume>
When the user says `continue`, `resume`, or `keep going` while Autopilot is active, read `autopilot-state.json` and continue from `current_phase`:
- `deep-interview`: clarify requirements and record the handoff artifact.
- `ralplan`: run/update consensus planning from current handoffs and any `return_to_ralplan_reason`.
- `ultragoal`: execute the approved plan durably and record verification/ledger evidence.
- `team`: continue explicit team work only when it is nested under the active Ultragoal story and report evidence back to the leader.
- `code-review`: review the current diff and decide clean vs return-to-ralplan.
- `ultraqa`: run or explicitly skip adversarial QA based on the documented condition, then finish if clean or transition to `ralplan` with findings if not clean.
- `ralph`: resume only for explicit legacy Ralph-path Autopilot state.
- `complete`: report completion evidence; do not restart.
Do not restart discovery or discard handoff artifacts on continuation.
</Continuation_And_Resume>
<Pipeline_Orchestrator>
Autopilot may be represented by the configurable pipeline orchestrator (`src/pipeline/`) when useful. The default Autopilot pipeline contract is:
```text
deep-interview -> ralplan -> ultragoal -> code-review -> ultraqa
```
Pipeline state should use `current_phase` values that match the same phase names (`deep-interview`, `ralplan`, `ultragoal`, `code-review`, `ultraqa`, `complete`, `failed`) and should carry `iteration`, `review_cycle`, `handoff_artifacts`, `review_verdict`, `qa_verdict`, and `return_to_ralplan_reason` alongside stage results. `$team` is not a default pipeline stage; it is an explicit conditional execution engine inside an Ultragoal story.
</Pipeline_Orchestrator>
<Escalation_And_Stop_Conditions>
- Stop and report a blocker when required credentials/authority are missing.
- Stop and report when the same review or QA failure recurs across 3 review cycles with no meaningful new plan.
- Stop when the user says "stop", "cancel", or "abort" and run `$cancel`.
- Otherwise, continue the loop until `$code-review` is clean and `$ultraqa` has passed or been explicitly skipped with evidence.
</Escalation_And_Stop_Conditions>
<Final_Checklist>
- [ ] Phase `deep-interview` produced/updated clarified requirements or a concise spec
- [ ] Phase `ralplan` produced/updated approved planning artifacts and durable sequential evidence from a subsequent `Architect` approval followed by a subsequent `Critic` approval
- [ ] Phase `ultragoal` implemented and verified the plan with fresh evidence and durable ledger/checkpoint references
- [ ] `$team` was used only if the active Ultragoal story needed coordinated parallel work, or explicitly recorded as not needed
- [ ] Phase `code-review` returned a clean verdict (`APPROVE` + `CLEAR`)
- [ ] Phase `ultraqa` passed, or was explicitly skipped because the change was docs-only/trivially non-runtime with evidence
- [ ] Clean `review_verdict` cites durable source evidence from a real `$code-review` stage/subagent/thread/tool record; `qa_verdict` cites durable `$ultraqa` evidence or an explicit persisted low-risk skip reason; leader-authored summaries alone are not gate evidence
- [ ] `review_verdict.clean` is true, `qa_verdict.clean` is true, and `return_to_ralplan_reason` is null
- [ ] Tests/build/lint/typecheck evidence from Ultragoal is available in handoff artifacts
- [ ] Autopilot state is marked `complete` or cancellation state is preserved coherently
- [ ] User receives a concise summary with clarification, plan, implementation, verification, review, and QA evidence
</Final_Checklist>
<Examples>
<Good>
User: `$autopilot implement GitHub issue #42`
Flow: create/load context snapshot -> `$deep-interview` requirements check -> `$ralplan` issue plan -> `$ultragoal` durable implementation + tests (launch `$team` only if a story needs parallel lanes) -> `$code-review` -> `$ultraqa`; if review or QA requests changes, return to `$ralplan` with findings.
</Good>
<Good>
User: `continue`
Context: Autopilot state says `current_phase:"code-review"`.
Flow: run `$code-review` on current diff, persist verdict, transition to `ultraqa` if clean or to `ralplan` with findings if not clean.
</Good>
<Good>
User: `$autopilot --legacy-ralph finish the migration`
Flow: preserve the explicit legacy Ralph execution choice and run the old Ralph execution lane as an alternate, without changing the documented default Autopilot recommendation.
</Good>
<Bad>
Autopilot invents independent "Expansion", "QA", and "Validation" phases and treats them as the primary lifecycle.
Why bad: this bypasses the strict `$deep-interview -> $ralplan -> $ultragoal -> $code-review -> $ultraqa` contract.
</Bad>
</Examples>
@@ -0,0 +1,36 @@
---
name: autoresearch-goal
description: Durable professor-critic research workflow over Codex goal mode without reviving deprecated omx autoresearch
---
# Autoresearch Goal
Use this workflow when a research mission should be bound to Codex goal-mode focus while OMX remains the durable state owner. This is for research projects that need Codex goal-mode management plus professor/critic-style validation; it is not the default answer for ordinary pre-planning best-practice lookup.
## Boundary
- Do **not** use or revive the deprecated `omx autoresearch` direct launch surface.
- Do **not** claim shell commands mutate hidden Codex `/goal` state.
- Do **not** edit upstream `../../codex` or add dependencies.
- Use `get_goal`, `create_goal`, and `update_goal({status: "complete"})` only through the active Codex thread when those tools are available.
## Artifacts
`omx autoresearch-goal` writes:
- `.omx/goals/autoresearch/<slug>/mission.json`
- `.omx/goals/autoresearch/<slug>/rubric.md`
- `.omx/goals/autoresearch/<slug>/ledger.jsonl`
- `.omx/goals/autoresearch/<slug>/completion.json`
## Flow
1. Create the mission and professor-critic rubric:
`omx autoresearch-goal create --topic "..." --rubric "..." --critic-command "..."`
2. Emit the model-facing handoff:
`omx autoresearch-goal handoff --slug <slug>`
3. In the active Codex thread, call `get_goal`; call `create_goal` only if no active goal exists and the printed payload is the intended objective.
4. Research iteratively against the rubric. Record every critic outcome:
`omx autoresearch-goal verdict --slug <slug> --verdict <pass|fail|blocked> --evidence "..."`
5. Completion is blocked until professor-critic validation records `verdict=pass`. After the mission audit passes, call `update_goal({status: "complete"})`, call `get_goal` again, then run:
`omx autoresearch-goal complete --slug <slug> --codex-goal-json <get_goal-json-or-path>`
6. Treat the completion command as read-only reconciliation plus durable OMX state update; hooks and shell commands must not mutate Codex goal state.
## Completion gate
A passing professor-critic artifact and a matching complete Codex `get_goal` snapshot are required. Assistant prose, partial tests, or a failed/blocked verdict are not sufficient.
@@ -0,0 +1,72 @@
---
name: autoresearch
description: Stateful validator-gated research loop with native-hook persistence
---
# Autoresearch
Autoresearch is the skill-first replacement for the deprecated `omx autoresearch` command.
It keeps the useful measured-research loop, but it now runs as a native-hook stateful workflow instead of a direct CLI or tmux launch surface.
## Boundary with planning research
Use `$autoresearch` when the research output itself is a bounded deliverable that must pass an explicit validator. Do not recommend it for ordinary pre-planning docs lookup or general best-practice checks; use `$best-practice-research` for that. If `$autoresearch` is intentionally run before architecture planning, its approved artifact should feed evidence into `$ralplan`; it should not become a final architecture/component unless the user explicitly asks for ongoing research automation.
## Use when
- You want a Ralph-ish persistent research loop
- The task should keep nudging until explicit validation evidence exists
- You want init-time choice between script validation and prompt+architect validation
## Do not use when
- You want the old `omx autoresearch` command surface (hard-deprecated)
- You want detached tmux or split-pane launch parity
- You have not decided the validation regime yet
## Core contract
1. **Init chooses validation mode.** Pick exactly one:
- `mission-validator-script`
- `prompt-architect-artifact`
2. **Persist mode state** in `.omx/state/.../autoresearch-state.json` including:
- `validation_mode`
- `completion_artifact_path`
- `mission_validator_command` **or** `validator_prompt`
- optional `output_artifact_path`
3. **Completion is artifact-gated.** The loop does not stop because the model says “done”, because a stop hook fired once, or because several turns were no-ops.
4. **Direct CLI launch is gone.** Use `$deep-interview --autoresearch` for intake and `$autoresearch` for execution.
## Completion artifact contract
### `mission-validator-script`
The completion artifact must exist and record a passing validator result, for example:
```json
{
"status": "passed",
"passed": true,
"summary": "metric improved beyond baseline"
}
```
### `prompt-architect-artifact`
The completion artifact must include both an architect approval verdict and an output artifact path, for example:
```json
{
"validator_prompt": "Review the research output against the mission.",
"architect_review": { "verdict": "approved" },
"output_artifact_path": ".omx/specs/autoresearch-demo/report.md"
}
```
## Recommended flow
1. Run `$deep-interview --autoresearch` to clarify mission + evaluator.
2. Materialize `.omx/specs/autoresearch-{slug}/mission.md`, `sandbox.md`, and `result.json`.
3. Start `$autoresearch` with the chosen validation mode stored in mode state.
4. Let stop-hook / auto-nudge continue until the completion artifact satisfies the chosen validation mode.
5. Finish only after the validator artifact is complete.
## Migration note
- `omx autoresearch` is hard-deprecated.
- No direct CLI launch.
- No tmux split-pane launch.
- No noop-count completion gate.
@@ -0,0 +1,83 @@
---
name: best-practice-research
description: "[OMX] Bounded best-practice research wrapper using official/upstream evidence first"
argument-hint: "<technology|decision|practice question>"
---
# Best-Practice Research
Use this skill when a task depends on current external best practices, version-aware guidance, standards, official recommendations, or upstream behavior. This is a workflow wrapper: it routes evidence gathering and synthesis; it is not a new research authority and it does not replace `researcher`.
## Purpose
Produce a cited, reusable best-practice answer or handoff that separates current external evidence from repo-local facts and dependency-selection decisions. For pre-planning investigation, this is the ordinary first research wrapper: gather official/upstream evidence, then hand it to `$ralplan` or the caller as planning input. Do not present `$best-practice-research` as a final architecture component or as a validator-gated research loop.
## Activate When
- The user asks for best practices, recommended approach, current guidance, official recommendations, standards, or version-aware external behavior.
- `$ralplan`, `$deep-interview`, `$team`, or another workflow needs current external evidence before planning or execution can be correct.
- The task involves an already chosen technology and needs authoritative usage guidance, migration notes, API behavior, lifecycle rules, or current safety guidance.
## Do Not Activate When
- The answer is fully repo-local; use `explore` for codebase facts.
- The main question is whether to adopt, replace, upgrade, or compare dependencies; use `dependency-expert`.
- The user only needs implementation against already-grounded requirements; use `executor`, `$ralph`, or `$team` as appropriate.
- The task can be answered from stable local project conventions without current external lookup.
## Specialist Routing
1. Use `explore` first for brownfield facts: current code usage, local constraints, versions, config, and integration points.
2. Use `researcher` for official/upstream docs, release notes, standards, migration guides, source-backed examples, and current best-practice evidence for an already chosen technology.
3. Use `dependency-expert` only for adoption/upgrade/replacement/comparison decisions.
4. Return to the caller with explicit evidence, uncertainty, and any implementation handoff constraints.
## Source-Quality Rules
- Prefer official documentation, upstream source, release notes, changelogs, standards, and maintainer guidance.
- Include source URLs for material claims.
- State date/version context for current best-practice claims.
- Label third-party summaries as supplemental; do not use them before official/upstream sources.
- Flag stale, conflicting, undocumented, or version-mismatched evidence.
- Do not over-fetch: gather the smallest evidence set that can support the decision.
## Workflow
1. Classify the question: conceptual best practice, implementation guidance, migration/version guidance, standards/compliance guidance, or mixed local + external guidance.
2. Gather repo-local facts with `explore` when local usage or constraints affect the answer.
3. Gather external evidence with `researcher` when current or version-aware practice affects correctness.
4. Synthesize a concise answer with source quality, version/date context, caveats, and an implementation or planning handoff.
5. Stop when the answer is grounded enough for the caller; otherwise report the exact blocker or specialist handoff needed.
## Output Contract
```md
## Best-Practice Research: <question>
### Direct Recommendation
<actionable guidance or decision support>
### Evidence Used
- Official/upstream: <source URL> — <what it establishes>
- Supplemental, if any: <source URL> — <why it is secondary>
### Version / Date Context
<versions, dates, release channels, or unknowns>
### Repo-Local Context
<facts from explore, or "not needed">
### Boundaries / Non-goals
<what this research does not decide>
### Handoff
<planning/execution/test implications>
```
## Stop Rules
- Stop after a source-backed recommendation is reusable by the caller.
- Stop and route upward if the task becomes dependency comparison, broad architecture, or implementation.
- Do not continue researching when remaining work would only polish wording rather than change the recommendation.
Task: {{ARGUMENTS}}
@@ -0,0 +1,399 @@
---
name: cancel
description: Cancel any active OMX mode (autopilot, ralph, ultrawork, ecomode, ultraqa, swarm, ultrapilot, pipeline, team)
---
# Cancel Skill
Intelligent cancellation that detects and cancels the active OMX mode.
**The cancel skill is the standard way to complete and exit any OMX mode.**
When the stop hook detects work is complete, it instructs the LLM to invoke
this skill for proper state cleanup. If cancel fails or is interrupted,
retry with `--force` flag, or wait for the 2-hour staleness timeout as
a last resort.
## What It Does
Automatically detects which mode is active and cancels it:
- **Autopilot**: Stops workflow, preserves progress for resume
- **Ralph**: Stops persistence loop, clears linked ultrawork if applicable
- **Ultrawork**: Stops parallel execution (standalone or linked)
- **Ecomode**: Stops token-efficient parallel execution (standalone or linked to ralph)
- **UltraQA**: Stops QA cycling workflow
- **Swarm**: Stops coordinated agent swarm, releases claimed tasks
- **Ultrapilot**: Stops parallel autopilot workers
- **Pipeline**: Stops sequential agent pipeline
- **Team**: Sends shutdown inbox to all workers, waits for exit, kills tmux session, and clears team state
## Usage
```
/cancel
```
Or say: "cancelomc", "stopomc"
## Auto-Detection
`/cancel` follows the session-aware state contract:
- By default the command inspects the current session via `state_list_active` and `state_get_status`, navigating `.omx/state/sessions/{sessionId}/…` to discover which mode is active.
- When a session id is provided or already known, that session-scoped path is authoritative. Legacy files in `.omx/state/*.json` are consulted only as a compatibility fallback if the session id is missing or empty.
- Swarm is a shared SQLite/marker mode (`.omx/state/swarm.db` / `.omx/state/swarm-active.marker`) and is not session-scoped.
- The default cleanup flow calls `state_clear` with the session id to remove only the matching session files; modes stay bound to their originating session.
## Normative Ralph cancellation post-conditions (MUST)
For Ralph-targeted cancellation (standalone or linked), completion is defined by post-conditions:
1. Target Ralph state is terminalized, not silently removed:
- `active=false`
- `current_phase='cancelled'`
- `completed_at` is set (ISO timestamp)
2. If Ralph is linked to Ultrawork or Ecomode in the same scope, that linked mode is also terminalized/non-active.
4. Cancellation MUST remain scope-safe: no mutation of unrelated sessions.
See: `docs/contracts/ralph-cancel-contract.md`.
Active modes are still cancelled in dependency order:
1. Autopilot (includes linked ultragoal/ultraqa/ecomode cleanup plus explicit legacy Ralph cleanup)
2. Ralph (cleans its linked ultrawork or ecomode)
3. Ultrawork (standalone)
4. Ecomode (standalone)
5. UltraQA (standalone)
6. Swarm (standalone)
7. Ultrapilot (standalone)
8. Pipeline (standalone)
9. Team (tmux-based)
10. Plan Consensus (standalone)
## Normative Ralph post-conditions (MUST)
When cancellation targets Ralph state in a scope, completion requires all of the following:
1. Ralph state is terminal in that same scope: `active=false`, `current_phase='cancelled'` (or linked terminal phase), and `completed_at` is set.
2. Linked Ultrawork/Ecomode in the same scope is also terminal/non-active.
4. Unrelated sessions are untouched.
## Force Clear All
Use `--force` or `--all` when you need to erase every session plus legacy artifacts, e.g., to reset the workspace entirely.
```
/cancel --force
```
```
/cancel --all
```
Steps under the hood:
1. `state_list_active` enumerates `.omx/state/sessions/{sessionId}/…` to find every known session.
2. `state_clear` runs once per session to drop that sessions files.
3. A global `state_clear` without `session_id` removes legacy files under `.omx/state/*.json`, `.omx/state/swarm*.db`, and compatibility artifacts (see list).
4. Team artifacts (`.omx/state/team/*/`, tmux sessions matching `omx-team-*`) are best-effort cleared as part of the legacy fallback.
Every `state_clear` command honors the `session_id` argument, so even force mode still uses the session-aware paths first before deleting legacy files.
Legacy compatibility list (removed only under `--force`/`--all`):
- `.omx/state/autopilot-state.json`
- `.omx/state/ralph-state.json`
- `.omx/state/ralph-plan-state.json`
- `.omx/state/ralph-verification.json`
- `.omx/state/ultrawork-state.json`
- `.omx/state/ecomode-state.json`
- `.omx/state/ultraqa-state.json`
- `.omx/state/swarm.db`
- `.omx/state/swarm.db-wal`
- `.omx/state/swarm.db-shm`
- `.omx/state/swarm-active.marker`
- `.omx/state/swarm-tasks.db`
- `.omx/state/ultrapilot-state.json`
- `.omx/state/ultrapilot-ownership.json`
- `.omx/state/pipeline-state.json`
- `.omx/state/plan-consensus.json`
- `.omx/state/ralplan-state.json`
- `.omx/state/boulder.json`
- `.omx/state/hud-state.json`
- `.omx/state/subagent-tracking.json`
- `.omx/state/subagent-tracker.lock`
- `.omx/state/rate-limit-daemon.pid`
- `.omx/state/rate-limit-daemon.log`
- `.omx/state/checkpoints/` (directory)
- `.omx/state/sessions/` (empty directory cleanup after clearing sessions)
## Implementation Steps
When you invoke this skill:
### 1. Parse Arguments
```bash
# Check for --force or --all flags
FORCE_MODE=false
if [[ "$*" == *"--force"* ]] || [[ "$*" == *"--all"* ]]; then
FORCE_MODE=true
fi
```
### 2. Detect Active Modes
The skill now relies on the session-aware state contract rather than hard-coded file paths:
1. Call `state_list_active` to enumerate `.omx/state/sessions/{sessionId}/…` and discover every active session.
2. For each session id, call `state_get_status` to learn which mode is running (`autopilot`, `ralph`, `ultrawork`, etc.) and whether dependent modes exist.
3. If a `session_id` was supplied to `/cancel`, skip legacy fallback entirely and operate solely within that session path; otherwise, consult legacy files in `.omx/state/*.json` only if the state tools report no active session. Swarm remains a shared SQLite/marker mode outside session scoping.
4. Any cancellation logic in this doc mirrors the dependency order discovered via state tools (autopilot → ralph → …).
### 3A. Force Mode (if --force or --all)
Use force mode to clear every session plus legacy artifacts via `state_clear`. Direct file removal is reserved for legacy cleanup when the state tools report no active sessions.
### 3B. Smart Cancellation (default)
#### If Team Active (tmux-based)
Teams are detected by checking for config files in `.omx/state/team/`:
```bash
# Check for active teams
ls .omx/state/team/*/config.json 2>/dev/null
```
**Two-pass cancellation protocol:**
**Pass 1: Graceful Shutdown**
```
For each team found in .omx/state/team/:
1. Read config.json to get team_name and workers list
2. For each worker:
a. Write shutdown inbox to .omx/state/team/{name}/workers/{worker}/inbox.md
b. Send short trigger via tmux send-keys
c. Wait up to 15 seconds for worker tmux pane to exit
d. If still alive: mark as unresponsive
```
**Pass 2: Force Kill**
```
After graceful pass:
1. For each remaining alive worker:
a. Send C-c via tmux send-keys
b. Wait 2 seconds
c. Kill the tmux window if still alive
2. Destroy the tmux session: tmux kill-session -t omx-team-{name}
```
**Cleanup:**
```
1. Strip AGENTS.md team worker overlay (<!-- OMX:TEAM:WORKER:START/END -->)
2. Remove team state directory: rm -rf .omx/state/team/{name}/
3. Clear team mode state: state_clear(mode="team")
4. Emit structured cancel report
```
**Structured Cancel Report:**
```
Team "{team_name}" cancelled:
- Workers signaled: N
- Graceful exits: M
- Force killed: K
- tmux session destroyed: yes/no
- State cleaned up: yes/no
```
**Implementation note:** The cancel skill is executed by the LLM, not as a bash script. When you detect an active team:
1. Check `.omx/state/team/*/config.json` for active teams
2. For each worker in config.workers, write shutdown inbox and send trigger
3. Wait briefly for workers to exit (15s timeout)
4. Force kill remaining workers via tmux
5. Destroy tmux session: `tmux kill-session -t omx-team-{name}`
6. Strip AGENTS.md overlay
7. Remove state: `rm -rf .omx/state/team/{name}/`
8. `state_clear(mode="team")`
9. Report structured summary to user
#### If Autopilot Active
Call `cancelAutopilot()` from `src/hooks/autopilot/cancel.ts:27-78`:
```bash
# Autopilot handles its own cleanup + ralph + ultraqa
# Just mark autopilot as inactive (preserves state for resume)
if [[ -f .omx/state/autopilot-state.json ]]; then
# Clean up ralph if active
if [[ -f .omx/state/ralph-state.json ]]; then
RALPH_STATE=$(cat .omx/state/ralph-state.json)
LINKED_UW=$(echo "$RALPH_STATE" | jq -r '.linked_ultrawork // false')
# Clean linked ultrawork first
if [[ "$LINKED_UW" == "true" ]] && [[ -f .omx/state/ultrawork-state.json ]]; then
rm -f .omx/state/ultrawork-state.json
echo "Cleaned up: ultrawork (linked to ralph)"
fi
# Clean ralph
rm -f .omx/state/ralph-state.json
rm -f .omx/state/ralph-verification.json
echo "Cleaned up: ralph"
fi
# Clean up ultraqa if active
if [[ -f .omx/state/ultraqa-state.json ]]; then
rm -f .omx/state/ultraqa-state.json
echo "Cleaned up: ultraqa"
fi
# Mark autopilot inactive but preserve state
CURRENT_STATE=$(cat .omx/state/autopilot-state.json)
CURRENT_PHASE=$(echo "$CURRENT_STATE" | jq -r '.phase // "unknown"')
echo "$CURRENT_STATE" | jq '.active = false' > .omx/state/autopilot-state.json
echo "Autopilot cancelled at phase: $CURRENT_PHASE. Progress preserved for resume."
echo "Run /autopilot to resume."
fi
```
#### If Ralph Active (but not Autopilot)
Call `clearRalphState()` + `clearLinkedUltraworkState()` from `src/hooks/ralph-loop/index.ts:147-182`:
```bash
if [[ -f .omx/state/ralph-state.json ]]; then
# Check if ultrawork is linked
RALPH_STATE=$(cat .omx/state/ralph-state.json)
LINKED_UW=$(echo "$RALPH_STATE" | jq -r '.linked_ultrawork // false')
# Clean linked ultrawork first
if [[ "$LINKED_UW" == "true" ]] && [[ -f .omx/state/ultrawork-state.json ]]; then
UW_STATE=$(cat .omx/state/ultrawork-state.json)
UW_LINKED=$(echo "$UW_STATE" | jq -r '.linked_to_ralph // false')
# Only clear if it was linked to ralph
if [[ "$UW_LINKED" == "true" ]]; then
rm -f .omx/state/ultrawork-state.json
echo "Cleaned up: ultrawork (linked to ralph)"
fi
fi
# Clean ralph state
rm -f .omx/state/ralph-state.json
rm -f .omx/state/ralph-plan-state.json
rm -f .omx/state/ralph-verification.json
echo "Ralph cancelled. Persistent mode deactivated."
fi
```
#### If Ultrawork Active (standalone, not linked)
Call `deactivateUltrawork()` from `src/hooks/ultrawork/index.ts:150-173`:
```bash
if [[ -f .omx/state/ultrawork-state.json ]]; then
# Check if linked to ralph
UW_STATE=$(cat .omx/state/ultrawork-state.json)
LINKED=$(echo "$UW_STATE" | jq -r '.linked_to_ralph // false')
if [[ "$LINKED" == "true" ]]; then
echo "Ultrawork is linked to Ralph. Use /cancel to cancel both."
exit 1
fi
# Remove local state
rm -f .omx/state/ultrawork-state.json
echo "Ultrawork cancelled. Parallel execution mode deactivated."
fi
```
#### If UltraQA Active (standalone)
Call `clearUltraQAState()` from `src/hooks/ultraqa/index.ts:107-120`:
```bash
if [[ -f .omx/state/ultraqa-state.json ]]; then
rm -f .omx/state/ultraqa-state.json
echo "UltraQA cancelled. QA cycling workflow stopped."
fi
```
#### No Active Modes
```bash
echo "No active OMX modes detected."
echo ""
echo "Checked for:"
echo " - Autopilot (.omx/state/autopilot-state.json)"
echo " - Ralph (.omx/state/ralph-state.json)"
echo " - Ultrawork (.omx/state/ultrawork-state.json)"
echo " - UltraQA (.omx/state/ultraqa-state.json)"
echo ""
echo "Use --force to clear all state files anyway."
```
## Implementation Notes
The cancel skill runs as follows:
1. Parse the `--force` / `--all` flags, tracking whether cleanup should span every session or stay scoped to the current session id.
2. Use `state_list_active` to enumerate known session ids and `state_get_status` to learn the active mode (`autopilot`, `ralph`, `ultrawork`, etc.) for each session.
3. When operating in default mode, call `state_clear` with that session_id to remove only the sessions files, then run mode-specific cleanup (autopilot → ralph → …) based on the state tool signals.
4. In force mode, iterate every active session, call `state_clear` per session, then run a global `state_clear` without `session_id` to drop legacy files (`.omx/state/*.json`, compatibility artifacts) and report success. Swarm remains a shared SQLite/marker mode outside session scoping.
5. Team artifacts (`.omx/state/team/*/`, tmux sessions matching `omx-team-*`) remain best-effort cleanup items invoked during the legacy/global pass.
State tools always honor the `session_id` argument, so even force mode still clears the session-scoped paths before deleting compatibility-only legacy state.
Mode-specific subsections below describe what extra cleanup each handler performs after the state-wide operations finish.
## Messages Reference
| Mode | Success Message |
|------|-----------------|
| Autopilot | "Autopilot cancelled at phase: {phase}. Progress preserved for resume." |
| Ralph | "Ralph cancelled. Persistent mode deactivated." |
| Ultrawork | "Ultrawork cancelled. Parallel execution mode deactivated." |
| Ecomode | "Ecomode cancelled. Token-efficient execution mode deactivated." |
| UltraQA | "UltraQA cancelled. QA cycling workflow stopped." |
| Swarm | "Swarm cancelled. Coordinated agents stopped." |
| Ultrapilot | "Ultrapilot cancelled. Parallel autopilot workers stopped." |
| Pipeline | "Pipeline cancelled. Sequential agent chain stopped." |
| Team | "Team cancelled. Teammates shut down and cleaned up." |
| Plan Consensus | "Plan Consensus cancelled. Planning session ended." |
| Force | "All OMX modes cleared. You are free to start fresh." |
| None | "No active OMX modes detected." |
## What Gets Preserved
| Mode | State Preserved | Resume Command |
|------|-----------------|----------------|
| Autopilot | Yes (phase, files, spec, plan, verdicts) | `/autopilot` |
| Ralph | No | N/A |
| Ultrawork | No | N/A |
| UltraQA | No | N/A |
| Swarm | No | N/A |
| Ultrapilot | No | N/A |
| Pipeline | No | N/A |
| Plan Consensus | Yes (plan file path preserved) | N/A |
## Notes
- **Dependency-aware**: Autopilot cancellation cleans up Ultragoal/UltraQA state and any explicit legacy Ralph state
- **Link-aware**: Ralph cancellation cleans up linked Ultrawork or Ecomode
- **Safe**: Only clears linked Ultrawork, preserves standalone Ultrawork
- **Local-only**: Clears state files in `.omx/state/` directory
- **Resume-friendly**: Autopilot state is preserved for seamless resume
- **Team-aware**: Detects tmux-based teams and performs graceful shutdown with force-kill fallback
## Tmux Team Cleanup
When cancelling team mode, the cancel skill should:
1. **Kill all team tmux sessions**: `tmux list-sessions -F '#{session_name}' 2>/dev/null | grep '^omx-team-'` and kill each
2. **Remove team state directories**: `rm -rf .omx/state/team/*/`
3. **Strip AGENTS.md overlay**: Remove content between `<!-- OMX:TEAM:WORKER:START -->` and `<!-- OMX:TEAM:WORKER:END -->`
### Force Clear Addition
When `--force` is used, also clean up:
```bash
rm -rf .omx/state/team/ # All team state
# Kill all omx-team-* tmux sessions
tmux list-sessions -F '#{session_name}' 2>/dev/null | grep '^omx-team-' | while read s; do tmux kill-session -t "$s" 2>/dev/null; done
```
@@ -0,0 +1,292 @@
---
name: code-review
description: Run a comprehensive code review
---
# Code Review Skill
Conduct a thorough code review for quality, security, and maintainability with severity-rated feedback.
## When to Use
This skill activates when:
- User requests "review this code", "code review"
- Before merging a pull request
- After implementing a major feature
- User wants quality assessment
## GPT-5.5 Guidance Alignment
- Default to outcome-first progress and completion reporting: state the target result, evidence, validation status, and stop condition before adding process detail.
- Treat newer user task updates as local overrides for the active workflow branch while preserving earlier non-conflicting constraints.
- If correctness depends on additional inspection, retrieval, execution, or verification, keep using the relevant tools until the review is grounded; stop once enough evidence exists.
- Continue through clear, low-risk, reversible next steps automatically; ask only when the next step is materially branching, destructive, credentialed, external-production, or preference-dependent.
Delegates to the `code-reviewer` and `architect` agents in parallel for a two-lane review:
1. **Identify Changes**
- Run `git diff` to find changed files
- Determine scope of review (specific files or entire PR)
2. **Launch Parallel Review Lanes**
- **`code-reviewer` lane** - owns spec compliance, security, code quality, performance, and maintainability findings
- **`architect` lane** - owns the devil's-advocate / design-tradeoff perspective
- Both lanes run in parallel on a clean context with explicit scope and artifacts, and produce distinct outputs before final synthesis
- If either lane cannot be launched or does not return evidence, report `independent review unavailable`; do **not** substitute the current/authoring lane, and do **not** approve or mark the review merge-ready.
3. **Review Categories**
- **Security** - Hardcoded secrets, injection risks, XSS, CSRF
- **Code Quality** - Function size, complexity, nesting depth
- **Performance** - Algorithm efficiency, N+1 queries, caching
- **Best Practices** - Naming, documentation, error handling
- **Maintainability** - Duplication, coupling, testability
4. **Severity Rating**
- **CRITICAL** - Security vulnerability (must fix before merge)
- **HIGH** - Bug or major code smell (should fix before merge)
- **MEDIUM** - Minor issue (fix when possible)
- **LOW** - Style/suggestion (consider fixing)
5. **Architectural Status Contract**
- **CLEAR** - No unresolved architectural blocker was found
- **WATCH** - Non-blocking design/tradeoff concern that must appear in the final synthesis
- **BLOCK** - Unresolved design concern that prevents a merge-ready verdict
6. **Specific Recommendations**
- File:line locations for each issue
- Concrete fix suggestions
- Code examples where applicable
7. **Final Synthesis**
- Combine the `code-reviewer` recommendation and the architect status into one final verdict
- Approval requires explicit evidence from both independent lanes; missing or failed delegation is a blocking unavailable-review state, not an approval fallback
- Deterministic merge gating rules:
- If architect status is **BLOCK**, final recommendation is **REQUEST CHANGES**
- Else if `code-reviewer` recommendation is **REQUEST CHANGES**, final recommendation is **REQUEST CHANGES**
- Else if architect status is **WATCH**, final recommendation is **COMMENT**
- Else final recommendation follows the `code-reviewer` lane
- The final report must make architect blockers impossible to miss
## Agent Delegation
Do not self-review as a fallback. If the `code-reviewer` or `architect` agent path is missing, unavailable, skipped, or fails, emit a clear unavailable-review result and block approval until the independent lane evidence exists.
Respect the user's current model and reasoning/effort selection when launching review lanes. Do not pass `model` or `reasoning_effort` overrides in the review-lane task calls unless the user explicitly asks for review-specific overrides; omitting them lets native subagents inherit the active session settings.
```
task(
agent_type="code-reviewer",
prompt="CODE REVIEW TASK
Review code changes for quality, security, and maintainability.
This is the code/spec/security lane. Do not absorb architectural ownership.
Scope: [git diff or specific files]
Review Checklist:
- Security vulnerabilities (OWASP Top 10)
- Code quality (complexity, duplication)
- Performance issues (N+1, inefficient algorithms)
- Best practices (naming, documentation, error handling)
- Maintainability (coupling, testability)
Output: Code review report with:
- Files reviewed count
- Issues by severity (CRITICAL, HIGH, MEDIUM, LOW)
- Specific file:line locations
- Fix recommendations
- Approval recommendation (APPROVE / REQUEST CHANGES / COMMENT)"
)
task(
agent_type="architect",
prompt="ARCHITECTURE / DEVIL'S-ADVOCATE REVIEW TASK
Review the same code changes from the architecture/tradeoff perspective.
Scope: [git diff or specific files]
Focus:
- System boundaries and interfaces
- Hidden coupling or long-term maintainability risks
- Tradeoff tension the main reviewer might miss
- Strongest counterargument against approving as-is
Output:
- Architectural Status: CLEAR / WATCH / BLOCK
- File:line evidence for each concern
- Concrete tradeoff or design recommendation"
)
Run both lanes in parallel, then synthesize them with the deterministic rules above.
```
## External Model Consultation (Preferred)
The code-reviewer agent SHOULD consult Codex for cross-validation.
### Protocol
1. **Form your OWN review FIRST** - Complete the review independently
2. **Consult for validation** - Cross-check findings with Codex
3. **Critically evaluate** - Never blindly adopt external findings
4. **Graceful optional consultation fallback** - Never block because optional external consultation tools are unavailable; this does not waive the required independent `code-reviewer` and `architect` lanes
### When to Consult
- Security-sensitive code changes
- Complex architectural patterns
- Unfamiliar codebases or languages
- High-stakes production code
### When to Skip
- Simple refactoring
- Well-understood patterns
- Time-critical reviews
- Small, isolated changes
### Tool Usage
Prefer native `code-reviewer` agent consultation or CLI-backed `ask_codex` surfaces when available. Optional MCP compatibility ask tools may be used only when already enabled. If optional external consultation tools are unavailable, continue with the required independent `code-reviewer` and `architect` lanes; do not replace those lanes with self-review.
**Note:** Codex calls can take up to 1 hour. Consider the review timeline before consulting.
## Output Format
```
CODE REVIEW REPORT
==================
Files Reviewed: 8
Total Issues: 12
Architectural Status: WATCH
CRITICAL (0)
-----------
(none)
HIGH (0)
--------
(none)
MEDIUM (7)
----------
1. src/api/auth.ts:42
Issue: Email normalization logic is duplicated instead of reusing the shared helper
Risk: Validation rules can drift between authentication paths
Fix: Route both paths through the shared normalization helper
2. src/components/UserProfile.tsx:89
Issue: Derived permissions are recalculated on every render
Risk: Avoidable work during profile refreshes
Fix: Memoize the derived permissions list or compute it upstream
3. src/utils/validation.ts:15
Issue: Form-layer and server-layer validation messages are defined separately
Risk: User-facing validation guidance can become inconsistent
Fix: Share one validation message helper across both call sites
LOW (5)
-------
...
ARCHITECTURE WATCHLIST
----------------------
- src/review/orchestrator.ts:88
Concern: Review result synthesis relies on implicit ordering rather than an explicit blocker contract
Status: WATCH
Recommendation: Define deterministic merge gating before expanding reviewers
SYNTHESIS
---------
- code-reviewer recommendation: COMMENT
- architect status: WATCH
- final recommendation: COMMENT
RECOMMENDATION: COMMENT
Address any WATCH concerns before treating the change as merge-ready.
```
## Review Checklist
The `code-reviewer` lane checks:
### Security
- [ ] No hardcoded secrets (API keys, passwords, tokens)
- [ ] All user inputs sanitized
- [ ] SQL/NoSQL injection prevention
- [ ] XSS prevention (escaped outputs)
- [ ] CSRF protection on state-changing operations
- [ ] Authentication/authorization properly enforced
### Code Quality
- [ ] Functions < 50 lines (guideline)
- [ ] Cyclomatic complexity < 10
- [ ] No deeply nested code (> 4 levels)
- [ ] No duplicate logic (DRY principle)
- [ ] Clear, descriptive naming
### Performance
- [ ] No N+1 query patterns
- [ ] Appropriate caching where applicable
- [ ] Efficient algorithms (avoid O(n²) when O(n) possible)
- [ ] No unnecessary re-renders (React/Vue)
### Best Practices
- [ ] Error handling present and appropriate
- [ ] Logging at appropriate levels
- [ ] Documentation for public APIs
- [ ] Tests for critical paths
- [ ] No commented-out code
## Architect Lane Checklist
The `architect` lane checks:
- [ ] Boundary or interface changes are explicit
- [ ] New coupling/tradeoff risks are surfaced
- [ ] Long-horizon maintainability concerns are evidence-backed
- [ ] Architectural status is one of `CLEAR`, `WATCH`, or `BLOCK`
- [ ] Any `BLOCK` concern cites the reason merge-ready status should be withheld
## Approval Criteria
**APPROVE** - `code-reviewer` returns APPROVE, architect status is `CLEAR`, and both independent lanes returned evidence
**REQUEST CHANGES** - `code-reviewer` returns REQUEST CHANGES, architect status is `BLOCK`, or required independent review delegation is unavailable/skipped/failed
**COMMENT** - `code-reviewer` returns COMMENT with architect status `CLEAR`, architect status is `WATCH`, or only LOW/MEDIUM improvements remain
## Scenario Examples
**Good:** The user says `continue` after the workflow already has a clear next step. Continue the current branch of work instead of restarting or re-asking the same question.
**Good:** The user changes only the output shape or downstream delivery step (for example `make a PR`). Preserve earlier non-conflicting workflow constraints and apply the update locally.
**Bad:** The user says `continue`, and the workflow restarts discovery or stops before the missing verification/evidence is gathered.
## Use with Other Skills
**With Team:**
```
/team "review recent auth changes and report findings"
```
Includes coordinated review execution across specialized agents.
**With Ralph:**
```
/ralph code-review then fix all issues
```
On the explicit Ralph path, review findings should flow into automatic fix follow-up without another permission prompt. Plain `code-review` itself remains read-only and does **not** promise auto-fix.
**With Ultrawork:**
```
/ultrawork review all files in src/
```
Parallel code review across multiple files.
## Best Practices
- **Review early** - Catch issues before they compound
- **Review often** - Small, frequent reviews better than huge ones
- **Address CRITICAL/HIGH first** - Fix security and bugs immediately
- **Consider context** - Some "issues" may be intentional trade-offs
- **Learn from reviews** - Use feedback to improve coding practices
@@ -0,0 +1,287 @@
---
name: configure-notifications
description: Configure OMX notifications - unified entry point for all platforms
triggers:
- "configure notifications"
- "setup notifications"
- "notification settings"
- "configure discord"
- "configure telegram"
- "configure slack"
- "configure openclaw"
- "setup discord"
- "setup telegram"
- "setup slack"
- "setup openclaw"
- "discord notifications"
- "telegram notifications"
- "slack notifications"
- "openclaw notifications"
- "discord webhook"
- "telegram bot"
- "slack webhook"
---
# Configure OMX Notifications
Unified and only entry point for notification setup.
- **Native integrations (first-class):** Discord, Telegram, Slack
- **Generic extensibility integrations:** `custom_webhook_command`, `custom_cli_command`
> Standalone configure skills (`configure-discord`, `configure-telegram`, `configure-slack`, `configure-openclaw`) are removed.
## Step 1: Inspect Current State
```bash
CONFIG_FILE="$HOME/.codex/.omx-config.json"
if [ -f "$CONFIG_FILE" ]; then
jq -r '
{
notifications_enabled: (.notifications.enabled // false),
discord: (.notifications.discord.enabled // false),
discord_bot: (.notifications["discord-bot"].enabled // false),
telegram: (.notifications.telegram.enabled // false),
slack: (.notifications.slack.enabled // false),
openclaw: (.notifications.openclaw.enabled // false),
custom_webhook_command: (.notifications.custom_webhook_command.enabled // false),
custom_cli_command: (.notifications.custom_cli_command.enabled // false),
verbosity: (.notifications.verbosity // "session"),
idleCooldownSeconds: (.notifications.idleCooldownSeconds // 60),
reply_enabled: (.notifications.reply.enabled // false)
}
' "$CONFIG_FILE"
else
echo "NO_CONFIG_FILE"
fi
```
## Step 2: Main Menu
Use AskUserQuestion:
**Question:** "What would you like to configure?"
**Options:**
1. **Discord (native)** - webhook or bot
2. **Telegram (native)** - bot token + chat id
3. **Slack (native)** - incoming webhook
4. **Generic webhook command** - `custom_webhook_command`
5. **Generic CLI command** - `custom_cli_command`
6. **Cross-cutting settings** - verbosity, idle cooldown, profiles, reply listener
7. **Disable all notifications** - set `notifications.enabled = false`
## Step 3: Configure Native Platforms (Discord / Telegram / Slack)
Collect and validate platform-specific values, then write directly under native keys:
- Discord webhook: `notifications.discord`
- Discord bot: `notifications["discord-bot"]`
- Telegram: `notifications.telegram`
- Slack: `notifications.slack`
Do not write these as generic command/webhook aliases.
## Step 4: Configure Generic Extensibility
### 4a) `custom_webhook_command`
Use AskUserQuestion to collect:
- URL
- Optional headers
- Optional method (`POST` default, or `PUT`)
- Optional event list (`session-end`, `ask-user-question`, `session-start`, `session-idle`, `stop`)
- Optional instruction template
Write:
```bash
jq \
--arg url "$URL" \
--arg method "${METHOD:-POST}" \
--arg instruction "${INSTRUCTION:-OMX event {{event}} for {{projectPath}}}" \
'.notifications = (.notifications // {enabled: true}) |
.notifications.enabled = true |
.notifications.custom_webhook_command = {
enabled: true,
url: $url,
method: $method,
instruction: $instruction,
events: ["session-end", "ask-user-question"]
}' "$CONFIG_FILE" > "$CONFIG_FILE.tmp" && mv "$CONFIG_FILE.tmp" "$CONFIG_FILE"
```
### 4b) `custom_cli_command`
Use AskUserQuestion to collect:
- Command template (supports `{{event}}`, `{{instruction}}`, `{{sessionId}}`, `{{projectPath}}`)
- Optional event list
- Optional instruction template
Write:
```bash
jq \
--arg command "$COMMAND_TEMPLATE" \
--arg instruction "${INSTRUCTION:-OMX event {{event}} for {{projectPath}}}" \
'.notifications = (.notifications // {enabled: true}) |
.notifications.enabled = true |
.notifications.custom_cli_command = {
enabled: true,
command: $command,
instruction: $instruction,
events: ["session-end", "ask-user-question"]
}' "$CONFIG_FILE" > "$CONFIG_FILE.tmp" && mv "$CONFIG_FILE.tmp" "$CONFIG_FILE"
```
> Activation gate: OpenClaw-backed dispatch is active only when `OMX_OPENCLAW=1`.
> For command gateways, also require `OMX_OPENCLAW_COMMAND=1`.
> Optional timeout env override: `OMX_OPENCLAW_COMMAND_TIMEOUT_MS` (ms).
### 4b-1) OpenClaw + Clawdbot Agent Workflow (recommended for dev)
If the user explicitly asks to route hook notifications through **clawdbot agent turns**
(not direct message/webhook forwarding), use a command gateway that invokes
`clawdbot agent` and delivers back to Discord.
Notes:
- Hook name mapping is intentional: notifications `session-stop` -> OpenClaw hook `stop`.
- OMX shell-escapes template substitutions for command gateways (including `{{instruction}}`).
- Keep `instruction` templates concise and avoid untrusted shell metacharacters.
- During troubleshooting, avoid swallowing command output; route it to a log file.
- Timeout precedence: `gateways.<name>.timeout` > `OMX_OPENCLAW_COMMAND_TIMEOUT_MS` > `5000`.
- For clawdbot agent workflows, set `gateways.<name>.timeout` to `120000` (recommended).
- For dev operations, enforce Korean output in all hook instructions.
- Include both `session={{sessionId}}` and `tmux={{tmuxSession}}` in hook text for traceability.
- If follow-up is needed, explicitly instruct clawdbot to consult `SOUL.md` and continue in `#omc-dev`.
- **Error handling**: Append `|| true` to prevent OMX hook failures from blocking the session.
- **JSONL logging**: Use `.jsonl` extension and append (`>>`) for structured log aggregation.
- **Reply target format**: Use `--reply-to 'channel:CHANNEL_ID'` for reliability (preferred over channel aliases).
Example (targeting `#omc-dev` with production-tested settings):
```bash
jq \
--arg command "(clawdbot agent --session-id omx-hooks --message {{instruction}} --thinking minimal --deliver --reply-channel discord --reply-to 'channel:1468539002985644084' --timeout 120 --json >>/tmp/omx-openclaw-agent.jsonl 2>&1 || true)" \
'.notifications = (.notifications // {enabled: true}) |
.notifications.enabled = true |
.notifications.verbosity = "verbose" |
.notifications.events = (.notifications.events // {}) |
.notifications.events["session-start"] = {enabled: true} |
.notifications.events["session-idle"] = {enabled: true} |
.notifications.events["ask-user-question"] = {enabled: true} |
.notifications.events["session-stop"] = {enabled: true} |
.notifications.events["session-end"] = {enabled: true} |
.notifications.openclaw = (.notifications.openclaw // {}) |
.notifications.openclaw.enabled = true |
.notifications.openclaw.gateways = (.notifications.openclaw.gateways // {}) |
.notifications.openclaw.gateways["local"] = {
type: "command",
command: $command,
timeout: 120000
} |
.notifications.openclaw.hooks = (.notifications.openclaw.hooks // {}) |
.notifications.openclaw.hooks["session-start"] = {
enabled: true,
gateway: "local",
instruction: "OMX hook=session-start project={{projectName}} session={{sessionId}} tmux={{tmuxSession}}. 한국어로 상태를 공유하고 SOUL.md를 참고해 필요한 후속 조치를 #omc-dev에 안내하세요."
} |
.notifications.openclaw.hooks["session-idle"] = {
enabled: true,
gateway: "local",
instruction: "OMX hook=session-idle project={{projectName}} session={{sessionId}} tmux={{tmuxSession}}. 한국어로 idle 상황을 간단히 공유하고 진행중인 작업 팔로업을 안내하세요."
} |
.notifications.openclaw.hooks["ask-user-question"] = {
enabled: true,
gateway: "local",
instruction: "OMX hook=ask-user-question session={{sessionId}} tmux={{tmuxSession}} question={{question}}. 한국어로 사용자 응답 필요를 #omc-dev에 알리고 즉시 액션 아이템을 제시하세요."
} |
.notifications.openclaw.hooks["stop"] = {
enabled: true,
gateway: "local",
instruction: "OMX hook=session-stop project={{projectName}} session={{sessionId}} tmux={{tmuxSession}}. 한국어로 중단 상태와 정리 액션을 SOUL.md 기준으로 전달하세요."
} |
.notifications.openclaw.hooks["session-end"] = {
enabled: true,
gateway: "local",
instruction: "OMX hook=session-end project={{projectName}} session={{sessionId}} tmux={{tmuxSession}} reason={{reason}}. 한국어로 완료 요약을 1줄로 남기고 필요한 후속 조치를 안내하세요."
}' "$CONFIG_FILE" > "$CONFIG_FILE.tmp" && mv "$CONFIG_FILE.tmp" "$CONFIG_FILE"
```
Verification for this mode:
```bash
clawdbot agent --session-id omx-hooks --message "OMX hook test via clawdbot agent path" \
--thinking minimal --deliver --reply-channel discord --reply-to 'channel:1468539002985644084' --timeout 120 --json
```
Dev runbook (Korean + tmux follow-up):
```bash
# 1) identify active OMX tmux sessions
tmux list-sessions -F '#{session_name}' | rg '^omx-' || true
# 2) confirm hook templates include session/tmux context
jq '.notifications.openclaw.hooks' "$CONFIG_FILE"
# 3) inspect agent JSONL logs when delivery looks broken
tail -n 120 /tmp/omx-openclaw-agent.jsonl | jq -s '.[] | {timestamp: (.timestamp // .time), status: (.status // .error // "ok")}'
# 4) check for recent errors in logs
rg '"error"|"failed"|"timeout"' /tmp/omx-openclaw-agent.jsonl | tail -20
```
### 4c) Compatibility + precedence contract
OMX accepts both:
- explicit `notifications.openclaw` schema (legacy/runtime shape)
- generic aliases (`custom_webhook_command`, `custom_cli_command`)
Deterministic precedence:
1. `notifications.openclaw` **wins** when present and valid.
2. Generic aliases are ignored in that case (with warning).
## Step 5: Cross-Cutting Settings
### Verbosity
- minimal / session (recommended) / agent / verbose
### Idle cooldown
- `notifications.idleCooldownSeconds`
### Profiles
- `notifications.profiles`
- `notifications.defaultProfile`
### Reply listener
- `notifications.reply.enabled`
- env gates: `OMX_REPLY_ENABLED=true`, and for Discord `OMX_REPLY_DISCORD_USER_IDS=...`
- For Discord bot replies, an authorized operator can reply with exact-match `status` to a tracked OMX notification to receive a bounded read-only session summary. This is a reply-thread-scoped status probe, not a general remote control surface.
## Step 6: Disable All Notifications
```bash
jq '.notifications.enabled = false' "$CONFIG_FILE" > "$CONFIG_FILE.tmp" && mv "$CONFIG_FILE.tmp" "$CONFIG_FILE"
```
## Step 7: Verification Guidance
After writing config, run a smoke check:
```bash
npm run build
```
For OpenClaw-like HTTP integrations, verify both:
- `/hooks/wake` smoke test
- `/hooks/agent` delivery verification
## Final Summary Template
Show:
- Native platforms enabled
- Generic aliases enabled (`custom_webhook_command`, `custom_cli_command`)
- Whether explicit `notifications.openclaw` exists (and therefore overrides aliases)
- Verbosity + idle cooldown + reply listener state
- Config path (`~/.codex/.omx-config.json`)
@@ -0,0 +1,579 @@
---
name: deep-interview
description: Socratic deep interview with mathematical ambiguity gating before execution
argument-hint: "[--quick|--standard|--deep] [--autoresearch] <idea or vague description>"
---
<Purpose>
Deep Interview is an intent-first Socratic clarification loop before planning or implementation. It turns vague ideas into execution-ready specifications by asking targeted questions about why the user wants a change, how far it should go, what should stay out of scope, and what OMX may decide without confirmation.
</Purpose>
<Use_When>
- The request is broad, ambiguous, or missing concrete acceptance criteria
- The user says "deep interview", "interview me", "ask me everything", "don't assume", or "ouroboros"
- The user wants to avoid misaligned implementation from underspecified requirements
- You need a requirements artifact before handing off to `ralplan`, `autopilot`, `ralph`, or `team`
</Use_When>
<Do_Not_Use_When>
- The request already has concrete file/symbol targets and clear acceptance criteria
- The user explicitly asks to skip planning/interview and execute immediately
- The user asks for lightweight brainstorming only (use `plan` instead)
- A complete PRD/plan already exists and execution should start
</Do_Not_Use_When>
<Why_This_Exists>
Execution quality is usually bottlenecked by intent clarity, not just missing implementation detail. A single expansion pass often misses why the user wants a change, where the scope should stop, which tradeoffs are unacceptable, and which decisions still require user approval. This workflow applies Socratic pressure + quantitative ambiguity scoring so orchestration modes begin with an explicit, testable, intent-aligned spec.
</Why_This_Exists>
<Depth_Profiles>
- **Quick (`--quick`)**: fast pre-PRD pass; target threshold `<= 0.30`; max rounds 5
- **Standard (`--standard`, default)**: full requirement interview; target threshold `<= 0.20`; max rounds 12
- **Deep (`--deep`)**: high-rigor exploration; target threshold `<= 0.15`; max rounds 20
- **Autoresearch (`--autoresearch`)**: same interview rigor as Standard, but specialized for `$autoresearch` mission readiness and `.omx/specs/` artifact handoff
Profile `max rounds` is a hard cap, not a target. Do not continue only to reach a numbered round count. Extra Socratic rigor does not override the active threshold unless the profile/config changes.
If no flag is provided, use **Standard**.
<Mode_Flags>
- **`--autoresearch`**: switch the interview into autoresearch-intake mode for `$autoresearch` handoff. In this mode, the interview should converge on a validator-ready research mission, write canonical artifacts under `.omx/specs/`, and preserve the explicit `refine further` vs `launch` boundary for downstream skill intake.
</Mode_Flags>
</Depth_Profiles>
<Execution_Policy>
- Ask ONE question per round (never batch multiple interview rounds into one `questions[]` form)
- Ask about intent and boundaries before implementation detail
- Target the weakest clarity dimension each round after applying the stage-priority rules below
- Treat every answer as a claim to pressure-test before moving on: the next question should usually demand evidence or examples, expose a hidden assumption, force a tradeoff or boundary, or reframe root cause vs symptom
- Do not rotate to a new clarity dimension just for coverage when the current answer is still vague; stay on the same thread until one layer deeper, one assumption clearer, or one boundary tighter
- Before crystallizing, complete at least one explicit pressure pass that revisits an earlier answer with a deeper, assumption-focused, or tradeoff-focused follow-up
- Gather codebase facts via `explore` before asking user about internals
- `omx explore` is deprecated. Use normal repository inspection tools/subagents for simple read-only brownfield fact gathering; use `omx sparkshell` only for explicit shell-native read-only evidence, and keep ambiguous or non-shell-only investigation on the richer normal path.
- Always run a preflight context intake before the first interview question
- For brownfield work, preflight must include doc/context grounding before user-facing questions: inspect applicable `AGENTS.md` files, README/getting-started docs, relevant `docs/` contracts/plans/ADRs, existing `.omx/context/` snapshots, and any project-local glossary/context files such as `CONTEXT.md` or `CONTEXT-MAP.md` when present.
- Treat existing repo language as evidence, not authority: if the user uses a fuzzy, overloaded, or conflicting term, surface the specific doc/code wording and ask which meaning should govern before implementation.
- Cross-check user claims about current behavior against code or documented contracts when discoverable. If docs and code disagree, ask a confirmation question that names both sources instead of silently choosing one.
- Use scenario-based edge-case grilling when relationships, boundaries, or handoff behavior are unclear: invent one concrete scenario that stresses the ambiguous boundary, then ask one focused question about the expected outcome.
- Durable docs, glossary, ADR, or memory updates are opt-in and public-safe only. Deep-interview may recommend such updates in the handoff summary, but must not automatically create or dump public docs from interview transcripts unless the user explicitly chooses that as in-scope.
- If initial context is oversized or would exceed the prompt budget, do not paste or forward the raw payload into interview prompts; request and record a prompt-safe initial-context summary first
- The oversized initial-context summary gate is blocking: wait for the concise summary before ambiguity scoring, crystallizing artifacts, or any downstream execution handoff
- The summary must preserve goals, constraints, success criteria, non-goals, decision boundaries, and references to any full source documents so downstream consumers receive a prompt-safe but faithful context
- Keep total prompt payloads within a safe budget by summarizing or trimming retained history; preserve newest/highest-signal answers and never let raw oversized context crowd out the current question
- Reduce user effort: ask only the highest-leverage unresolved question, and never ask the user for codebase facts that can be discovered directly
- For brownfield work, prefer evidence-backed confirmation questions such as "I found X in Y. Should this change follow that pattern?"
- Route facts before judgment in the Ouroboros style: before presenting a user-facing interview round, classify whether the needed information is a discoverable fact, a fact needing confirmation, or a human decision. The interview is with the human for judgment, not for facts the agent can inspect.
- When unresolved ambiguity depends on current external best practices, official/upstream guidance, standards, or version-aware behavior, use `$best-practice-research` as the bounded evidence wrapper before crystallizing requirements or handing off to planning/execution.
- Use these transcript/spec labels only; never use them as `omx question` `source` values, and never replace the runtime `source: "deep-interview"` contract for user-facing deep-interview questions:
- `[from-code][auto-confirmed]` — exact, high-confidence codebase facts from manifests/configs or direct source evidence, with no prescription attached.
- `[from-code]` — codebase findings that are useful but inferred, pattern-based, or low/medium confidence and therefore need a confirmation-style user-facing round before being treated as settled.
- `[from-research]` — externally sourced facts such as API limits, compatibility, or public documentation; facts only, not decisions.
- `[from-user]` — goals, preferences, business logic, scope, non-goals, acceptance criteria, tradeoffs, and any decision-bearing interpretation.
- Treat `[from-code][auto-confirmed]` and other non-user fact discoveries as context/transcript updates, not interview rounds: do not call `omx question`, do not create a pending deep-interview question obligation, and do not increment the user-facing round number for facts the agent can safely establish.
- Auto-confirm only descriptive facts. If a finding implies what the new feature should do, which pattern it should follow, which tradeoff to accept, or what should stay in/out of scope, route the entire decision-bearing question to the user as `[from-user]` even when code or research facts are available.
- In attached-tmux Codex CLI, deep-interview uses `omx question` as the required OMX-owned structured questioning path for every interview round
- When invoking `omx question` through attached-tmux Bash/tool paths, preserve the leader-pane return target by prefixing the command with `OMX_QUESTION_RETURN_PANE=$TMUX_PANE` (or a concrete `%pane` value)
- If you launch `omx question` in a background terminal, immediately wait for that background terminal to finish and read its JSON answer before scoring ambiguity, asking another round, or handing off
- Treat `answers[]` as the primary `omx question` success contract. For a single interview round, read `answers[0].answer`; use legacy top-level `answer` only as a compatibility fallback when needed.
- If the current runtime is outside tmux and cannot render `omx question`, use the native structured question tool when available; otherwise ask exactly one concise plain-text question and wait for the answer
- Re-score ambiguity after each answer and show progress transparently
- Once ambiguity is at or below the active profile threshold, stop ordinary questioning. Run the practical closure audit: crystallize/handoff when readiness gates pass; otherwise ask only the final closure question needed to satisfy a named gate.
- Treat `max_rounds` as a stop cap, not evidence that more rounds are needed.
- Do not hand off to execution while ambiguity remains above threshold unless user explicitly opts to proceed with warning
- Do not crystallize or hand off while `Non-goals` or `Decision Boundaries` remain unresolved, even if the weighted ambiguity threshold is met
- Treat early exit as a safety valve, not the default success path
- Persist mode state for resume safety with CLI-first state commands (`omx state write/read --input '<json>' --json`); use `state_write` / `state_read` only when explicit MCP compatibility is enabled
</Execution_Policy>
<Steps>
## Phase 0: Preflight Context Intake
1. Parse `{{ARGUMENTS}}` and derive a short task slug.
2. Attempt to load the latest relevant context snapshot from `.omx/context/{slug}-*.md`.
3. Check whether the provided initial context or loaded snapshot is too large for safe prompt use. If it is oversized, the first interview round must ask for a concise prompt-safe summary instead of scoring ambiguity or continuing to downstream handoff.
4. If no snapshot exists, create a minimum context snapshot with:
- Task statement
- Desired outcome
- Stated solution (what the user asked for)
- Probable intent hypothesis (why they likely want it)
- Known facts/evidence
- Constraints
- Unknowns/open questions
- Decision-boundary unknowns
- Likely codebase touchpoints
- Relevant repo docs/rules/context inspected
- Terminology or doc/code conflicts found
- Prompt-safe initial-context summary status (`not_needed`, `needed`, or `recorded`)
5. For brownfield tasks, inspect the applicable documentation/rule surface before the first user-facing round. Prefer exact, nearby sources over broad scans:
- governing `AGENTS.md` files and template/runtime instruction surfaces that apply to the touched paths
- README/getting-started docs and relevant docs under `docs/`, especially contracts, plans, ADR-like records, and workflow docs
- existing `.omx/context/` snapshots, `.omx/specs/`, and planning artifacts relevant to the slug
- project-local glossary/context files such as `CONTEXT.md`, `CONTEXT-MAP.md`, or context-specific docs when they exist
6. Save snapshot to `.omx/context/{slug}-{timestamp}.md` (UTC `YYYYMMDDTHHMMSSZ`) and reference it in mode state.
## Phase 1: Initialize
1. Parse `{{ARGUMENTS}}` and depth profile (`--quick|--standard|--deep`).
2. Detect project context:
- Run `explore` to classify **brownfield** (existing codebase target) vs **greenfield**.
- For brownfield, collect relevant codebase context before questioning.
3. Initialize state via `omx state write --input '{"mode":"deep-interview","active":true}' --json`:
```json
{
"active": true,
"current_phase": "deep-interview",
"state": {
"interview_id": "<uuid>",
"profile": "quick|standard|deep",
"type": "greenfield|brownfield",
"initial_idea": "<user input>",
"rounds": [],
"current_ambiguity": 1.0,
"threshold": 0.3,
"max_rounds": 5,
"challenge_modes_used": [],
"codebase_context": null,
"current_stage": "intent-first",
"current_focus": "intent",
"context_snapshot_path": ".omx/context/<slug>-<timestamp>.md"
}
}
```
4. Announce kickoff with profile, threshold, and current ambiguity.
## Phase 2: Socratic Interview Loop
Repeat until ambiguity `<= threshold`, the pressure pass is complete, the readiness gates are explicit, the user exits with warning, or max rounds are reached. This is a stop condition: below threshold, do not open a new ordinary interview branch.
### 2a) Generate next question
If the initial context is oversized and no prompt-safe summary has been recorded yet, the next question must be only a summary request. Do not score ambiguity, do not run readiness gates, and do not hand off to `$ultragoal`, `$ralplan`, `$autopilot`, `$ralph`, or `$team` until that summary answer is captured.
Use:
- Original idea
- Prior Q&A rounds
- Current dimension scores
- Brownfield context (if any)
- Doc/context grounding notes, including existing terminology, governing rules, and any doc/code mismatch
- Activated challenge mode injection (Phase 3)
Target the lowest-scoring dimension, but respect stage priority:
- **Stage 1 — Intent-first:** Intent, Outcome, Scope, Non-goals, Decision Boundaries
- **Stage 2 — Feasibility:** Constraints, Success Criteria
- **Stage 3 — Brownfield grounding:** Context Clarity (brownfield only)
Follow-up pressure ladder after each answer:
1. Ask for a concrete example, counterexample, or evidence signal behind the latest claim
2. Probe the hidden assumption, dependency, or belief that makes the claim true
3. Force a boundary or tradeoff: what would you explicitly not do, defer, or reject?
4. Challenge fuzzy or conflicting terms against the repo's documented language and current code behavior
5. Stress-test the boundary with one concrete scenario or edge case when a relationship or handoff remains ambiguous
6. If the answer still describes symptoms, reframe toward essence / root cause before moving on
Prefer staying on the same thread for multiple rounds when it has the highest leverage. Breadth without pressure is not progress.
Maintain a **Breadth Ledger** across independent ambiguity tracks: scope, constraints, outputs, verification, brownfield integration, and any user-mentioned deliverable tracks. The ledger is a guard, not a mandatory rotation rule: stay deep on the current thread until it has been pressure-tested, then zoom out only when another material track remains unresolved and would change execution.
Maintain a **Docs/Terminology Ledger** for brownfield interviews:
- repo docs/rules/context sources inspected, with path references
- canonical terms already used by the repo and terms to avoid or disambiguate
- user terms that conflict with docs or current code behavior
- doc/code mismatches that require a human decision before implementation
- optional durable-doc follow-ups that are safe to propose but not auto-apply
Detailed dimensions:
- Intent Clarity — why the user wants this
- Outcome Clarity — what end state they want
- Scope Clarity — how far the change should go
- Constraint Clarity — technical or business limits that must hold
- Success Criteria Clarity — how completion will be judged
- Context Clarity — existing codebase understanding (brownfield only)
`Non-goals` and `Decision Boundaries` are mandatory readiness gates. Ask about them early and keep revisiting them until they are explicit.
### 2b) Ask the question
Use the surface-appropriate structured questioning path for every interview round. In attached-tmux sessions, use OMX-owned structured questioning via `omx question` (this is the required structured-question equivalent and required `AskUserQuestion` equivalent for deep-interview). Outside tmux, use native structured input when available; otherwise ask exactly one concise plain-text question and wait for the answer. Present:
```
Round {n} | Target: {weakest_dimension} | Ambiguity: {score}%
{question}
```
`omx question` payload guidance for interview rounds:
- Deep-interview is Socratic: ask one focused round at a time. Do not use batch `questions[]` to combine multiple interview rounds, even though `omx question` supports batch forms for other workflows.
- Use canonical `type` values instead of authoring raw `multi_select` flags by hand. `type: "single-answerable"` is the default for one-path decisions; `type: "multi-answerable"` is the canonical shape for bounded multi-select rounds. The runtime will keep `multi_select` aligned with `type`.
- Use `single-answerable` when exactly one answer should drive the next branch, the options are mutually exclusive, or selecting more than one answer would blur the decision boundary. Typical cases: handoff lane selection, choosing the primary failure mode, or confirming which of several competing interpretations is correct.
- Use `multi-answerable` when multiple options may all be true at once and you need to capture a bounded set of coexisting constraints, non-goals, risks, or acceptance checks in one round. Typical cases: selecting all out-of-scope items, all success metrics that must hold, or all deployment constraints that apply together.
- If one selected option would immediately require a follow-up question to disambiguate the others, prefer a `single-answerable` round now and ask the follow-up next. Do not hide a branching interview tree inside one overloaded multi-select prompt.
- Keep interview options bounded and concrete. If the valid answers are already known, set `allow_other: false`; only leave `allow_other: true` when the interview genuinely needs one user-supplied option that cannot be enumerated in advance.
- Read answers structurally from the primary `answers[]` array. For a normal single-round interview response, use `answers[0].answer` as the source of truth; the top-level `answer` field is a legacy single-question projection/fallback only.
- For `single-answerable`, expect one decisive selection in the `value` field of `answers[0].answer` plus its selected-values metadata. For `multi-answerable`, treat the selected-values field inside `answers[0].answer` as the source of truth for all chosen constraints/non-goals and preserve the full set in the transcript/spec. In legacy single-question projections, this is equivalent to: For `multi-answerable`, treat `answer.selected_values` as the source of truth.
Canonical bounded single-choice payload:
```json
{
"question": "Which execution lane should own this once the interview is complete?",
"type": "single-answerable",
"options": [
{
"label": "Plan first",
"value": "ralplan",
"description": "Need architecture and test-shape review before execution"
},
{
"label": "Execute directly",
"value": "autopilot",
"description": "Requirements are already explicit enough for planning plus execution"
},
{
"label": "Refine further",
"value": "refine",
"description": "Clarification is still needed before any handoff"
}
],
"allow_other": false,
"other_label": "Other",
"source": "deep-interview"
}
```
Canonical bounded multi-select payload:
```json
{
"question": "Which non-goals must stay out of scope for the first pass?",
"type": "multi-answerable",
"options": [
{
"label": "No UI redesign",
"value": "no-ui-redesign",
"description": "Keep layout and styling unchanged"
},
{
"label": "No new dependencies",
"value": "no-new-dependencies",
"description": "Work within the existing toolchain"
},
{
"label": "No API contract changes",
"value": "no-api-contract-changes",
"description": "Preserve external request and response shapes"
}
],
"allow_other": false,
"other_label": "Other",
"source": "deep-interview"
}
```
Canonical answer-shape reminders:
```json
{
"answer": {
"kind": "option",
"value": "ralplan",
"selected_labels": ["Plan first"],
"selected_values": ["ralplan"]
}
}
```
```json
{
"answer": {
"kind": "multi",
"value": ["no-new-dependencies", "no-api-contract-changes"],
"selected_labels": ["No new dependencies", "No API contract changes"],
"selected_values": ["no-new-dependencies", "no-api-contract-changes"]
}
}
```
### 2c) Score ambiguity
Score each weighted dimension in `[0.0, 1.0]` with justification + gap.
Greenfield: `ambiguity = 1 - (intent × 0.30 + outcome × 0.25 + scope × 0.20 + constraints × 0.15 + success × 0.10)`
Brownfield: `ambiguity = 1 - (intent × 0.25 + outcome × 0.20 + scope × 0.20 + constraints × 0.15 + success × 0.10 + context × 0.10)`
Readiness gate:
- `Non-goals` must be explicit
- `Decision Boundaries` must be explicit
- A pressure pass must be complete: at least one earlier answer has been revisited with an evidence, assumption, or tradeoff follow-up
- A practical closure audit must pass: another question would change execution materially, not merely polish wording or chase a narrow edge case
- If either gate is unresolved, or the pressure pass is incomplete, continue below threshold only with a final closure question that names the unresolved gate and would materially change execution.
- Treat a low ambiguity score as permission to audit closure, not permission to keep drilling indefinitely. If remaining uncertainty would not change implementation, crystallize the spec instead of opening a new branch.
- If ambiguity is `<= 0.10`, another user-facing question is allowed only as that final closure question; otherwise crystallize immediately.
### 2d) Report progress
Show weighted breakdown table, readiness-gate status (`Non-goals`, `Decision Boundaries`), and the next focus dimension.
### 2e) Persist state
Append round result and updated scores via `omx state write --input '<json>' --json`; use `state_write` only when explicit MCP compatibility is enabled.
### 2f) Round controls
- Do not offer early exit before the first explicit assumption probe and one persistent follow-up have happened
- Apply a **Dialectic Rhythm Guard**: track consecutive non-user fact discoveries and confirmation-style answers (`[from-code][auto-confirmed]`, `[from-code]`, or `[from-research]`). After 3 consecutive non-user or confirmation answers, the next material user-facing round must solicit direct human judgment (`[from-user]`) unless the closure audit says the interview is ready to crystallize.
- Round 4+: allow explicit early exit with risk warning
- Soft warning at profile midpoint (e.g., round 3/6/10 depending on profile)
- Hard cap at profile `max_rounds`; never treat this cap as a desired interview length or quota
## Phase 3: Challenge Modes (assumption stress tests)
Use each mode once when applicable. These are normal escalation tools, not rare rescue moves:
- **Contrarian** (round 2+ or immediately when an answer rests on an untested assumption): challenge core assumptions
- **Terminologist** (brownfield, whenever a key term is fuzzy, overloaded, or conflicts with repo docs/code): force a canonical meaning against existing project language before implementation
- **Simplifier** (round 4+ or when scope expands faster than outcome clarity): probe minimal viable scope
- **Ontologist** (round 5+ and ambiguity > 0.25, or when the user keeps describing symptoms): ask for essence-level reframing
Track used modes in state to prevent repetition.
## Phase 4: Crystallize Artifacts
When threshold is met (or user exits with warning / hard cap):
1. Write interview transcript summary to:
- `.omx/interviews/{slug}-{timestamp}.md`
(kept for ralph PRD compatibility)
2. Write execution-ready spec to:
- `.omx/specs/deep-interview-{slug}.md`
Spec should include:
- Metadata (profile, rounds, final ambiguity, threshold, context type)
- Context snapshot reference/path (for ralplan/team reuse)
- Prompt-safe initial-context summary when oversized context was provided, plus references to any full source documents
- Clarity breakdown table
- Intent (why the user wants this)
- Desired Outcome
- In-Scope
- Out-of-Scope / Non-goals
- Decision Boundaries (what OMX may decide without confirmation)
- Constraints
- Testable acceptance criteria
- Assumptions exposed + resolutions
- Pressure-pass findings (which answer was revisited, and what changed)
- Brownfield evidence vs inference notes for any repository-grounded confirmation questions
- Docs/Terminology Ledger with inspected repo docs/rules/context, term conflicts, and any doc/code mismatch decisions
- Scenario/edge-case pressure findings that materially shaped scope or acceptance criteria
- Optional durable documentation recommendations, explicitly marked opt-in and public-safe; do not include raw private transcript dumps
- Technical context findings
- Full or condensed transcript
### Autoresearch specialization
When the clarified task is specifically about `$autoresearch`, or the skill is invoked with `--autoresearch`, keep the interview domain-specific and emit skill-consumable artifacts without skipping clarification.
- **Accepted seed inputs:** `topic`, `evaluator`, `keep-policy`, `slug`, existing mission draft text, and prior evaluator examples/templates
- **Required interview focus:** mission clarity, evaluator readiness, keep policy, slug/session naming, and whether the draft is ready to launch now or should refine further
- **Canonical artifact path:** `.omx/specs/deep-interview-autoresearch-{slug}.md`
- **Launch artifact bundle:** `.omx/specs/autoresearch-{slug}/mission.md`, `.omx/specs/autoresearch-{slug}/sandbox.md`, and `.omx/specs/autoresearch-{slug}/result.json`
- **Launch artifact directory:** `.omx/specs/autoresearch-{slug}/`
- **Required artifact sections:**
- `Mission Draft`
- `Evaluator Draft`
- `Launch Readiness`
- `Seed Inputs`
- `Confirmation Bridge`
- **Required launch artifacts under `.omx/specs/autoresearch-{slug}/`:**
- `mission.md`
- `sandbox.md`
- `result.json`
- **Launch-readiness rule:** mark the draft as **not launch-ready** while the evaluator command still contains placeholder markers such as `<...>`, `TODO`, `TBD`, `REPLACE_ME`, `CHANGEME`, or `your-command-here`
- **Structured result contract:** `result.json` should point to the draft + mission/sandbox artifacts and carry the finalized `topic`, `evaluatorCommand`, `keepPolicy`, `slug`, `launchReady`, and `blockedReasons` fields so `$autoresearch` can consume it directly
- **Confirmation bridge:** after artifact generation, offer at least `refine further` and `launch`; do not run direct CLI launch or detached/split tmux launch, and only hand off to `$autoresearch` after explicit confirmation
- **Handoff rule:** downstream execution must preserve the clarified mission intent, evaluator expectations, decision boundaries, and launch-readiness status from this artifact rather than bypassing the draft review step
## Phase 5: Execution Bridge
Present execution options after artifact generation using explicit handoff contracts. Treat the deep-interview spec as the current requirements source of truth and preserve intent, non-goals, decision boundaries, acceptance criteria, docs/terminology grounding, and any residual-risk warnings across the handoff.
### Optional execution contract foundation
When an Autopilot/deep-interview handoff explicitly requires a stride contract, emit it as structured data rather than prose. This is a validation foundation, not a broadness-inference feature: do not infer stride from task length, phase labels, snapshots, or freeform wording.
Canonical location under Autopilot state:
```json
{
"handoff_artifacts": {
"deep_interview": {
"execution_contract_required": true,
"execution_contract": {
"version": 1,
"execution_stride": "task",
"source": "deep-interview",
"selected_by": "user",
"allow_task_shrink": true,
"completion_unit": "One focused task",
"stop_condition": "Stop after that task is implemented and verified",
"acceptance_coverage_scope": "task",
"shrink_policy": "allowed"
}
}
}
}
```
Stride meanings:
- `task`: conservative, small-step execution; `allow_task_shrink:true`, `acceptance_coverage_scope:"task"`, `shrink_policy:"allowed"`.
- `deliverable`: finish the named deliverable before stopping; `allow_task_shrink:false`, `acceptance_coverage_scope:"deliverable"`, `shrink_policy:"ask_before_shrink"`.
- `milestone`: finish the larger approved milestone unless blocked; `allow_task_shrink:false`, `acceptance_coverage_scope:"milestone"`, `shrink_policy:"deny_unless_blocked"`.
Only set `execution_contract_required:true` when the selected downstream workflow needs this explicit stride/stop-condition guard. New artifacts must write the canonical snake_case schema shown above under `handoff_artifacts.deep_interview`; runtime readers may accept legacy camelCase field/marker aliases and direct/nested `execution_contract` locations only as compatibility input. If `execution_contract_required` is absent or false, downstream Autopilot compatibility behavior is unchanged.
### Goal-mode follow-ups
Include these product-facing suggestions when they fit the clarified spec, without removing the existing `$ultragoal`, `$ralplan`, `$autopilot`, `$ralph`, and `$team` handoff options:
- **`$ultragoal`** — default goal-mode follow-up for implementation or general goal-oriented follow-up specs that should be converted into durable Codex/OMX goals with sequential completion tracking.
- **`$autoresearch-goal`** — use when the clarified context is a research project: a research question, reference/literature gathering, evaluator-backed analysis, or professor/critic-style deliverable.
- **`$performance-goal`** — use when the clarified context is an optimization or performance project with measurable speed, latency, throughput, memory, benchmark, or evaluator criteria.
Recommend `$ultragoal` as the default durable goal-mode follow-up because it supersedes Ralph for goal tracking. Preserve `$team` for coordinated parallel implementation and keep `$ralph` only as an explicit fallback for persistent single-owner execution/verification when the user specifically selects it.
### 1. **`$ultragoal` (Default durable execution follow-up)**
- **Input Artifact:** `.omx/specs/deep-interview-{slug}.md` (optionally accompanied by the transcript/context snapshot for traceability)
- **Invocation:** `$ultragoal create-goals --brief-file <spec-path>` followed by `$ultragoal complete-goals` in the active execution lane
- **Consumer Behavior:** Convert the clarified spec into durable goal-mode work. Preserve intent, non-goals, decision boundaries, acceptance criteria, docs/terminology grounding, scenario-pressure findings, and residual-risk warnings as binding story constraints.
- **Skipped / Already-Satisfied Stages:** Requirement interview, ambiguity clarification, doc/context preflight, and early intent-boundary elicitation
- **Expected Output:** `.omx/ultragoal/brief.md`, `.omx/ultragoal/goals.json`, `.omx/ultragoal/ledger.jsonl`, implementation evidence, verification evidence, and final cleanup/review-gate evidence
- **Best When:** The clarified spec is execution-ready or the user explicitly wants durable goal tracking as the next step
- **Next Recommended Step:** Run the Ultragoal completion loop; launch `$team` only inside an active Ultragoal story when parallel lanes are warranted, and use `$ralph` only as an explicit fallback when the user asks for that legacy persistence mode
### 2. **`$ralplan` (Recommended when architecture/test-shape review is still needed)**
- **Input Artifact:** `.omx/specs/deep-interview-{slug}.md` (optionally accompanied by the transcript/context snapshot for traceability)
- **Invocation:** `$plan --consensus --direct <spec-path>`
- **Consumer Behavior:** Treat the deep-interview spec as the requirements source of truth. Do not repeat the interview by default; refine architecture/feasibility around the clarified intent and boundaries instead.
- **Skipped / Already-Satisfied Stages:** Requirements discovery, ambiguity clarification, and early intent-boundary elicitation
- **Expected Output:** Canonical planning artifacts under `.omx/plans/`, especially `prd-*.md` and `test-spec-*.md`
- **Best When:** Requirements are clear enough to stop interviewing, but architectural validation / consensus planning is still desirable
- **Next Recommended Step:** Use the approved planning artifacts with `$ultragoal` as the default durable goal-mode follow-up (optionally with `$team` for parallel lanes); choose `$autoresearch-goal` for research validation or `$performance-goal` for measurable optimization, and use `$ralph` only as an explicit fallback when a narrow single-owner persistence loop is requested
### 3. **`$autopilot`**
- **Input Artifact:** `.omx/specs/deep-interview-{slug}.md`
- **Invocation:** `$autopilot <spec-path>`
- **Consumer Behavior:** Use the deep-interview spec as the clarified execution brief. Preserve intent, non-goals, decision boundaries, and acceptance criteria as binding context for planning/execution.
- **Skipped / Already-Satisfied Stages:** Initial requirement discovery and ambiguity reduction
- **Expected Output:** Planning/execution progress, QA evidence, and validation artifacts produced by autopilot
- **Best When:** The clarified spec is already strong enough for direct planning + execution without an additional consensus gate
- **Next Recommended Step:** Continue through autopilot's execution/QA/validation flow; if coordination-heavy execution emerges, prefer `$team` under a leader-owned `$ultragoal` ledger, using `$ralph` only as an explicit fallback when a narrow single-owner persistence loop is requested
### 4. **`$ralph` (Explicit fallback only)**
- **Input Artifact:** `.omx/specs/deep-interview-{slug}.md`
- **Invocation:** `$ralph <spec-path>`
- **Consumer Behavior:** Use the spec's acceptance criteria and boundary constraints as the persistence target. Do not reopen requirements discovery unless the user explicitly asks to refine further.
- **Skipped / Already-Satisfied Stages:** Requirement interview, ambiguity clarification, and initial scope-definition work
- **Expected Output:** Iterative execution progress and verification evidence tracked against the clarified criteria
- **Best When:** The user explicitly asks for Ralph's persistent sequential completion pressure; otherwise use `$ultragoal` for durable goal tracking and completion checkpoints
- **Next Recommended Step:** If this explicit fallback is selected, continue Ralph's persistence loop; if work expands into coordination-heavy lanes, hand off to `$team` under `$ultragoal` checkpointing rather than promoting Ralph as the next default
### 5. **`$team`**
- **Input Artifact:** `.omx/specs/deep-interview-{slug}.md`
- **Invocation:** `$team <spec-path>`
- **Consumer Behavior:** Treat the spec as shared execution context for coordinated parallel work. Preserve the clarified intent, non-goals, decision boundaries, and acceptance criteria as common lane constraints.
- **Skipped / Already-Satisfied Stages:** Requirement clarification and early ambiguity reduction
- **Expected Output:** Coordinated multi-agent execution against the shared spec, with evidence that can later feed Ultragoal checkpoints by default, or an explicit Ralph verification pass only when requested
- **Best When:** The task is large, multi-lane, or blocker-sensitive enough to justify coordinated parallel execution instead of a single persistent loop
- **Next Recommended Step:** Follow the team verification path when the coordinated execution phase finishes; checkpoint completion through `$ultragoal` by default, escalating to a separate Ralph loop only when the user explicitly asks for that persistent verification/fix owner
### 6. **Refine further**
- **Input Artifact:** Existing transcript, context snapshot, and current spec draft
- **Invocation:** Continue the interview loop
- **Consumer Behavior:** Re-enter questioning to resolve the highest-leverage remaining uncertainty
- **Skipped / Already-Satisfied Stages:** None beyond already-captured context
- **Expected Output:** A lower-ambiguity spec with tighter boundaries and fewer unresolved assumptions
- **Best When:** Residual ambiguity is still too high, the user wants stronger clarity, or the above-threshold / early-exit warning indicates too much risk to proceed cleanly
- **Next Recommended Step:** Return to one of the execution handoff contracts above once the spec is sufficiently clarified
**Residual-Risk Rule:** If the interview ended via early exit, hard-cap completion, or above-threshold proceed-with-warning, explicitly preserve that residual-risk state in the handoff so the downstream skill knows it inherited a partially clarified brief.
**IMPORTANT:** Deep-interview is a requirements mode. On handoff, invoke the selected skill using the contract above. **Do NOT implement directly** inside deep-interview.
</Steps>
<Tool_Usage>
- Use `explore` for codebase fact gathering
- Use `omx question` as the OMX-native structured user-input tool for each interview round when an attached tmux renderer is available
- From attached-tmux Bash/tool paths, call it as `OMX_QUESTION_RETURN_PANE=$TMUX_PANE omx question ...` unless an explicit `%pane` return target is already known
- If the current runtime is outside tmux and cannot render `omx question`, use native structured input when available; otherwise ask exactly one concise plain-text question and wait for the answer
- After `omx question` returns JSON, prefer `answers[0].answer` / `answers[]`; use legacy `answer` only as a fallback for older records
- Use `omx state write/read --input '<json>' --json` for resumable mode state; `state_write` / `state_read` are explicit MCP compatibility fallbacks only
- If the interview cannot ask a required `omx question` round, persist the blocker as terminal state with `active: false` and `current_phase: "blocked"`; do not write a terminal blocked phase with `active: true`
- Read/write context snapshots under `.omx/context/`
- Read applicable repo docs/rules/context during preflight; write durable docs, glossary, ADR, or memory updates only when the user explicitly opts in and the content is public-safe
- Record whether the oversized-context summary gate is not needed, pending, or satisfied before any scoring or handoff step
- Save transcript/spec artifacts under `.omx/interviews/` and `.omx/specs/`
</Tool_Usage>
<Escalation_And_Stop_Conditions>
- User says stop/cancel/abort -> persist state and stop
- Ambiguity stalls for 3 rounds (+/- 0.05) -> force Ontologist mode once
- Max rounds reached -> proceed with explicit residual-risk warning
- All dimensions >= 0.9 -> allow early crystallization even before max rounds
</Escalation_And_Stop_Conditions>
<Final_Checklist>
- [ ] Preflight context snapshot exists under `.omx/context/{slug}-{timestamp}.md`
- [ ] Oversized initial context, if present, has a prompt-safe summary recorded before ambiguity scoring or downstream handoff
- [ ] Ambiguity score shown each round
- [ ] Intent-first stage priority used before implementation detail
- [ ] Weakest-dimension targeting used within the active stage
- [ ] At least one explicit assumption probe happened before crystallization
- [ ] At least one persistent follow-up / pressure pass deepened a prior answer
- [ ] Challenge modes triggered at thresholds (when applicable)
- [ ] Transcript written to `.omx/interviews/{slug}-{timestamp}.md`
- [ ] Spec written to `.omx/specs/deep-interview-{slug}.md`
- [ ] Brownfield questions use evidence-backed confirmation when applicable
- [ ] Brownfield preflight inspected applicable repo docs/rules/context before user-facing questions
- [ ] Fuzzy or conflicting terminology was challenged against repo language/current code behavior when applicable
- [ ] Scenario-based edge-case grilling was used when boundary ambiguity would materially affect implementation
- [ ] Durable docs/ADR/memory updates, if any, were explicitly opted into and public-safe
- [ ] Handoff options provided (`$ultragoal`, `$ralplan`, `$autopilot`, `$ralph`, `$team`) plus context-sensitive goal-mode suggestions (`$autoresearch-goal`, `$performance-goal`) when applicable
- [ ] No direct implementation performed in this mode
</Final_Checklist>
<Advanced>
## Suggested Config (optional)
Deep-interview reads runtime defaults from the first existing config source in this order:
1. Repository-local `.omx/config.toml`
2. Repository-root `omx.toml`
3. User-global `~/.omx/config.toml`
This section is currently a deep-interview-specific runtime override surface, not a general replacement for Codex `config.toml` or `.omx-config.json` model/env routing.
Malformed config files are ignored fail-soft so `$deep-interview` activation can continue with built-in defaults.
Explicit `--quick`, `--standard`, or `--deep` invocation flags override `defaultProfile`.
```toml
[omx.deepInterview]
defaultProfile = "standard"
quickThreshold = 0.30
standardThreshold = 0.20
deepThreshold = 0.15
quickMaxRounds = 5
standardMaxRounds = 12
deepMaxRounds = 20
enableChallengeModes = true
```
## Resume
If interrupted, rerun `$deep-interview`. Resume from persisted mode state via `omx state read --input '{"mode":"deep-interview"}' --json`.
## Recommended 3-Stage Pipeline
```
deep-interview -> ralplan -> autopilot
```
- Stage 1 (deep-interview): clarity gate
- Stage 2 (ralplan): feasibility + architecture gate
- Stage 3 (autopilot): execution + QA + validation gate
</Advanced>
@@ -0,0 +1,180 @@
---
name: design
description: Canonical repo-local DESIGN.md workflow for product, UI/UX, and frontend decision source of truth
---
# Design Skill
Use `$design` when product, UI/UX, frontend, or design-system decisions need a durable source of truth in the repository. This skill discovers existing design context, interviews for missing product/design information, and creates or refreshes repo-local `DESIGN.md` so future UI/UX/frontend work is grounded instead of improvised.
## Purpose
Make repo-local `DESIGN.md` source of truth and canonical design contract for the current repository:
`existing repo evidence -> missing-context interview -> create/refresh DESIGN.md -> use DESIGN.md for UI/UX/frontend decisions`.
The output is not a pixel-matching loop and not a one-off visual critique. It is the maintained design brief/checklist that implementation, review, and future visual work should cite.
## Use when
- The user asks for design direction, UX guidance, frontend planning, or design-system alignment.
- A repo needs a design brief before UI/frontend implementation begins.
- Existing UI/components/assets/screenshots need to be summarized into a reusable design source of truth.
- UI/UX/frontend decisions are ambiguous and should be resolved through product context, constraints, and documented principles.
- A feature needs `DESIGN.md` created or refreshed before `$ralph`, a designer lane, or implementation work proceeds.
## Do not use when
- The user provides or requests a visual reference/image/live URL and wants measured implementation until screenshots match. Use `$visual-ralph` for that visual-reference implementation loop.
- The task is pure backend/API/infrastructure work with no user-facing design consequence.
- The user only asks to compare screenshots or score visual fidelity. Use `$visual-ralph` and its built-in visual verdict flow.
## Relationship to `$visual-ralph`
`$design` owns the durable repo design source of truth: product goals, users, IA, visual language, components, accessibility, constraints, and open questions in `DESIGN.md`.
`$visual-ralph` owns implementation against an approved generated/static/live-URL visual reference, with screenshot capture, Visual Ralph verdict scoring, and pixel-diff evidence. `$visual-ralph` may read `DESIGN.md`, and it may leave design-system artifacts behind, but it does not replace the `DESIGN.md` discovery/interview/refresh workflow.
If both are needed, run `$design` first to establish the design contract, then run `$visual-ralph` only after the visual reference/baseline is approved.
## Workflow
### 1. Discover local design evidence
Inspect the repository before writing guidance. Look for:
- `DESIGN.md`, `docs/design*`, `docs/ux*`, `docs/frontend*`, `README.md`, product specs, PRDs, and issue notes.
- Existing UI source: routes, pages, layouts, components, stories, examples, demos, theme files, CSS variables, Tailwind/theme config, tokens, icons, and assets.
- Screenshots, mockups, brand files, logos, Figma/export notes, Storybook snapshots, Playwright screenshots, visual-regression baselines, or `.omx/artifacts/visual-ralph/*` references.
- Accessibility, responsive, i18n, content, and platform constraints already encoded in code or docs.
Record evidence with file paths. Distinguish observed facts from design inferences.
### 2. Interview only for missing context
Ask concise questions only when repo evidence cannot answer design-critical context. Prefer one focused round that closes the biggest gaps, such as:
- target users/personas and jobs to be done,
- product/business goals and non-goals,
- brand personality or forbidden aesthetics,
- primary flows and information architecture,
- accessibility level, device/browser support, and implementation constraints,
- existing design assets or references the repo does not contain.
If the user wants autonomous progress or cannot answer, create `DESIGN.md` with explicit assumptions and open questions instead of blocking.
### 3. Create or refresh `DESIGN.md`
Use the structure below. Preserve useful existing content, remove contradictions, and mark unknowns as open questions. Keep it actionable for implementers and reviewers.
#### Required `DESIGN.md` structure/checklist
```markdown
# Design
## Source of truth
- Status: Draft | Active | Needs refresh
- Last refreshed: YYYY-MM-DD
- Primary product surfaces:
- Evidence reviewed:
## Brand
- Personality:
- Trust signals:
- Avoid:
## Product goals
- Goals:
- Non-goals:
- Success signals:
## Personas and jobs
- Primary personas:
- User jobs:
- Key contexts of use:
## Information architecture
- Primary navigation:
- Core routes/screens:
- Content hierarchy:
## Design principles
- Principle 1:
- Principle 2:
- Tradeoffs:
## Visual language
- Color:
- Typography:
- Spacing/layout rhythm:
- Shape/radius/elevation:
- Motion:
- Imagery/iconography:
## Components
- Existing components to reuse:
- New/changed components:
- Variants and states:
- Token/component ownership:
## Accessibility
- Target standard:
- Keyboard/focus behavior:
- Contrast/readability:
- Screen-reader semantics:
- Reduced motion and sensory considerations:
## Responsive behavior
- Supported breakpoints/devices:
- Layout adaptations:
- Touch/hover differences:
## Interaction states
- Loading:
- Empty:
- Error:
- Success:
- Disabled:
- Offline/slow network, if applicable:
## Content voice
- Tone:
- Terminology:
- Microcopy rules:
## Implementation constraints
- Framework/styling system:
- Design-token constraints:
- Performance constraints:
- Compatibility constraints:
- Test/screenshot expectations:
## Open questions
- [ ] Question / owner / impact
```
### 4. Use `DESIGN.md` as the decision contract
For UI/UX/frontend work after the refresh:
- Cite the relevant `DESIGN.md` sections before making design choices.
- Prefer existing components, tokens, and documented constraints.
- If implementation reveals a design contradiction, update `DESIGN.md` or add an open question before proceeding.
- Do not introduce a new design-system layer when existing repo-native patterns can be extended.
### 5. Handoff to implementation or Visual Ralph when appropriate
- For normal frontend implementation, hand off with the relevant `DESIGN.md` sections, repo evidence, and acceptance criteria.
- For visual-reference/image/live-URL matching, hand off to `$visual-ralph` with the approved reference/baseline and note that `DESIGN.md` is supporting context, not the visual verdict target.
## Completion checklist
Do not declare the design workflow complete until:
- Existing design docs/assets/components/screenshots have been inspected or explicitly noted as absent.
- Missing product/design context has been answered, assumed, or listed in `DESIGN.md` open questions.
- `DESIGN.md` exists at the repo root and contains all required checklist sections.
- UI/UX/frontend recommendations cite `DESIGN.md` rather than relying on unstated preferences.
- Any `$visual-ralph` handoff is clearly separated as visual implementation matching, not DESIGN.md governance.
Task: {{ARGUMENTS}}
@@ -0,0 +1,239 @@
---
name: doctor
description: Diagnose and fix oh-my-codex installation issues
---
# Doctor Skill
Note: All `~/.codex/...` paths in this guide respect `CODEX_HOME` when that environment variable is set.
## Canonical skill root
OMX installs skills to `${CODEX_HOME:-~/.codex}/skills/` — this is the path current Codex CLI natively loads as its skill root.
`~/.agents/skills/` is a **historical legacy path** from an older Codex CLI release, before Codex settled on `~/.codex` as its home directory. Current Codex CLI and OMX no longer write there.
**In a mixed OMX + plain Codex environment:**
- **Use**: `${CODEX_HOME:-~/.codex}/skills/` (user scope) or `.codex/skills/` (project scope)
- **Clean up if present**: `~/.agents/skills/` — if this still exists alongside the canonical root, Codex's Enable/Disable Skills UI will show duplicate entries for any skill present in both trees
- **Interop rule**: OMX writes only to the canonical path; archive or remove `~/.agents/skills/` once you have confirmed `${CODEX_HOME:-~/.codex}/skills/` is your active root
## Task: Run Installation Diagnostics
You are the OMX Doctor - diagnose and fix installation issues.
### Step 1: Check Plugin Version
Official Codex plugin caches are marketplace- and version-scoped, for example `${CODEX_HOME:-~/.codex}/plugins/cache/$MARKETPLACE_NAME/oh-my-codex/$VERSION/`. Local installs may use `local` as the version identifier.
```bash
# Get installed plugin cache versions across marketplaces.
# Cache shape: $PLUGIN_CACHE_ROOT/$MARKETPLACE_NAME/oh-my-codex/$PLUGIN_VERSION/
PLUGIN_CACHE_ROOT="${CODEX_HOME:-$HOME/.codex}/plugins/cache"
CACHE_ENTRIES=$(find "$PLUGIN_CACHE_ROOT" -path "*/oh-my-codex/*" -mindepth 3 -maxdepth 3 -type d 2>/dev/null)
if [[ -z "$CACHE_ENTRIES" ]]; then
echo "Installed plugin cache: none"
else
while IFS= read -r VERSION_DIR; do
MARKETPLACE_NAME=$(basename "$(dirname "$(dirname "$VERSION_DIR")")")
PLUGIN_VERSION=$(basename "$VERSION_DIR")
printf 'Installed plugin cache: marketplace=%s version=%s path=%s\n' "$MARKETPLACE_NAME" "$PLUGIN_VERSION" "$VERSION_DIR"
done <<< "$CACHE_ENTRIES"
fi
# Get latest from npm
LATEST=$(npm view oh-my-codex version 2>/dev/null)
echo "Latest npm: $LATEST"
```
**Diagnosis**:
- If no cache entry exists: INFO - plugin marketplace artifact not cached; this may be normal when OMX was installed only through npm/setup
- Compare each printed `PLUGIN_VERSION` with `LATEST`; if it differs and is not `local`: WARN - outdated plugin cache
- If one marketplace has multiple version directories: WARN - stale cache for that marketplace/plugin pair
- Remember: plugin install/discovery is not a replacement for `npm install -g oh-my-codex` plus `omx setup`; the packaged plugin carries plugin-scoped companion metadata for optional MCP compatibility servers and apps, with first-party MCP disabled by default, while native/runtime hooks and the rest of OMX runtime wiring stay setup-owned
### Step 2: Check Hook Configuration (config.toml + legacy settings.json)
Check `~/.codex/config.toml` first (current Codex config), then check legacy `~/.codex/settings.json` only if it exists.
Look for hook entries pointing to removed scripts like:
- `bash $HOME/.codex/hooks/keyword-detector.sh`
- `bash $HOME/.codex/hooks/persistent-mode.sh`
- `bash $HOME/.codex/hooks/session-start.sh`
**Diagnosis**:
- If found: CRITICAL - legacy hooks causing duplicates
### Step 3: Check for Legacy Bash Hook Scripts
```bash
ls -la ~/.codex/hooks/*.sh 2>/dev/null
```
**Diagnosis**:
- If `keyword-detector.sh`, `persistent-mode.sh`, `session-start.sh`, or `stop-continuation.sh` exist: WARN - legacy scripts (can cause confusion)
### Step 4: Check AGENTS.md
```bash
# Check if AGENTS.md exists
ls -la ~/.codex/AGENTS.md 2>/dev/null
# Check for OMX marker
grep -q "oh-my-codex Multi-Agent System" ~/.codex/AGENTS.md 2>/dev/null && echo "Has OMX config" || echo "Missing OMX config"
```
**Diagnosis**:
- If missing: CRITICAL - AGENTS.md not configured
- If missing OMX marker: WARN - outdated AGENTS.md
### Step 5: Check for Stale Plugin Cache
```bash
# List marketplace/version cache entries for this plugin
PLUGIN_CACHE_ROOT="${CODEX_HOME:-$HOME/.codex}/plugins/cache"
find "$PLUGIN_CACHE_ROOT" -path "*/oh-my-codex/*" -mindepth 3 -maxdepth 3 -type d 2>/dev/null \
| while IFS= read -r VERSION_DIR; do
MARKETPLACE_NAME=$(basename "$(dirname "$(dirname "$VERSION_DIR")")")
PLUGIN_VERSION=$(basename "$VERSION_DIR")
printf '%s\t%s\n' "$MARKETPLACE_NAME" "$PLUGIN_VERSION"
done
```
**Diagnosis**:
- If a single marketplace lists multiple versions: WARN - multiple cached versions for that marketplace/plugin pair (cleanup recommended)
### Step 6: Check for Legacy Curl-Installed Content
Check for legacy agents, commands, and historical legacy skill roots from older installs/migrations:
```bash
# Check for legacy agents directory
ls -la ~/.codex/agents/ 2>/dev/null
# Check for legacy commands directory
ls -la ~/.codex/commands/ 2>/dev/null
# Check canonical current skills directory
ls -la ${CODEX_HOME:-~/.codex}/skills/ 2>/dev/null
# Check historical legacy skill directory
ls -la ~/.agents/skills/ 2>/dev/null
```
**Diagnosis**:
- If `~/.codex/agents/` exists with oh-my-codex-related files: WARN - legacy generated agents or hand-installed role files. The Codex plugin can package reusable workflows plus plugin-scoped companion metadata for optional MCP/apps; legacy setup installs native agents, while plugin setup archives stale legacy native-agent files and keeps config/hooks current.
- If `~/.codex/commands/` exists with oh-my-codex-related files: WARN - legacy command files from older installs. Current OMX uses skills/workflows plus setup-managed native surfaces.
- If `${CODEX_HOME:-~/.codex}/skills/` exists with OMX skills: OK - canonical current user skill root
- If `~/.agents/skills/` exists: WARN - historical legacy skill root that can overlap with `${CODEX_HOME:-~/.codex}/skills/` and cause duplicate Enable/Disable Skills entries
Look for files like:
- `architect.md`, `researcher.md`, `explore.md`, `executor.md`, etc. in agents/
- `ultrawork.md`, `deepsearch.md`, etc. in commands/
- Any oh-my-codex-related `.md` files in skills/
---
## Report Format
After running all checks, output a report:
```
## OMX Doctor Report
### Summary
[HEALTHY / ISSUES FOUND]
### Checks
| Check | Status | Details |
|-------|--------|---------|
| Plugin Version | OK/WARN/CRITICAL | ... |
| Hook Config (config.toml / legacy settings.json) | OK/CRITICAL | ... |
| Legacy Scripts (~/.codex/hooks/) | OK/WARN | ... |
| AGENTS.md | OK/WARN/CRITICAL | ... |
| Plugin Cache | OK/WARN | ... |
| Legacy Agents (~/.codex/agents/) | OK/WARN | ... |
| Legacy Commands (~/.codex/commands/) | OK/WARN | ... |
| Skills (${CODEX_HOME:-~/.codex}/skills) | OK/WARN | ... |
| Legacy Skill Root (~/.agents/skills) | OK/WARN | ... |
### Issues Found
1. [Issue description]
2. [Issue description]
### Recommended Fixes
[List fixes based on issues]
```
---
## Auto-Fix (if user confirms)
If issues found, ask user: "Would you like me to fix these issues automatically?"
If yes, apply fixes:
### Fix: Legacy Hooks in legacy settings.json
If `~/.codex/settings.json` exists, remove the legacy `"hooks"` section (keep other settings intact).
### Fix: Legacy Bash Scripts
```bash
rm -f ~/.codex/hooks/keyword-detector.sh
rm -f ~/.codex/hooks/persistent-mode.sh
rm -f ~/.codex/hooks/session-start.sh
rm -f ~/.codex/hooks/stop-continuation.sh
```
### Fix: Outdated Plugin
```bash
# Global cache reset across all marketplaces for this plugin.
# If you only want one marketplace, set MARKETPLACE_NAME and remove just that subtree instead.
PLUGIN_CACHE_ROOT="${CODEX_HOME:-$HOME/.codex}/plugins/cache"
find "$PLUGIN_CACHE_ROOT" -path "*/oh-my-codex" -type d -prune -exec rm -rf {} +
echo "Plugin cache cleared across all marketplaces. Restart Codex CLI to fetch the latest marketplace entry."
```
### Fix: Stale Cache (multiple versions)
```bash
# Keep only the newest version inside the selected marketplace/plugin cache.
# Set MARKETPLACE_NAME to the exact marketplace printed in Step 1.
PLUGIN_CACHE_ROOT="${CODEX_HOME:-$HOME/.codex}/plugins/cache"
PLUGIN_CACHE_DIR="$PLUGIN_CACHE_ROOT/$MARKETPLACE_NAME/oh-my-codex"
KEEP_VERSION=$(for dir in "$PLUGIN_CACHE_DIR"/*; do [[ -d "$dir" ]] && basename "$dir"; done | sort -V | tail -1)
if [[ -n "$KEEP_VERSION" ]]; then
find "$PLUGIN_CACHE_DIR" -mindepth 1 -maxdepth 1 -type d ! -name "$KEEP_VERSION" -exec rm -rf {} +
fi
```
### Fix: Missing/Outdated AGENTS.md
Fetch latest from GitHub and write to `~/.codex/AGENTS.md`:
```
WebFetch(url: "https://raw.githubusercontent.com/Yeachan-Heo/oh-my-codex/main/docs/AGENTS.md", prompt: "Return the complete raw markdown content exactly as-is")
```
### Fix: Legacy Curl-Installed Content
Remove legacy agents/commands plus the historical `~/.agents/skills` tree if it overlaps with the canonical `${CODEX_HOME:-~/.codex}/skills` install:
```bash
# Backup first (optional - ask user)
# mv ~/.codex/agents ~/.codex/agents.bak
# mv ~/.codex/commands ~/.codex/commands.bak
# mv ~/.agents/skills ~/.agents/skills.bak
# Or remove directly
rm -rf ~/.codex/agents
rm -rf ~/.codex/commands
rm -rf ~/.agents/skills
```
**Note**: Only remove if these contain oh-my-codex-related files. If user has custom agents/commands/skills, warn them and ask before removing.
---
## Post-Fix
After applying fixes, inform user:
> Fixes applied. **Restart Codex CLI** for changes to take effect.
@@ -0,0 +1,98 @@
---
name: "hud"
description: "Show or configure the OMX HUD (two-layer statusline)"
role: "display"
scope: ".omx/**"
---
# HUD Skill
The OMX HUD uses a two-layer architecture:
1. **Layer 1 - Codex built-in statusLine**: Real-time TUI footer showing model, git branch, and context usage. Configured via `[tui] status_line` in `~/.codex/config.toml`. Zero code required.
2. **Layer 2 - `omx hud` CLI command**: Shows OMX-specific orchestration state (ralph, ultrawork, autopilot, team, pipeline, ecomode, turns). Reads `.omx/state/` files.
## Quick Commands
| Command | Description |
|---------|-------------|
| `omx hud` | Show current HUD (modes, turns, activity) |
| `omx hud --watch` | Live-updating display (polls every 1s) |
| `omx hud --json` | Raw state output for scripting |
| `omx hud --preset=minimal` | Minimal display |
| `omx hud --preset=focused` | Default display |
| `omx hud --preset=full` | All elements |
## Presets
### minimal
```
[OMX] ralph:3/10 | turns:42
```
### focused (default)
```
[OMX] ralph:3/10 | ultrawork | team:3 workers | turns:42 | last:5s ago
```
### full
```
[OMX] ralph:3/10 | ultrawork | autopilot:execution | team:3 workers | pipeline:exec | turns:42 | last:5s ago | total-turns:156
```
## Setup
`omx setup` automatically configures both layers:
- Adds `[tui] status_line` to `~/.codex/config.toml` (Layer 1)
- Writes `.omx/hud-config.json` with default preset (Layer 2)
- Default preset is `focused`; if HUD/statusline changes do not appear, restart Codex CLI once.
## Layer 1: Codex Built-in StatusLine
Configured in `~/.codex/config.toml`:
```toml
[tui]
status_line = ["model-with-reasoning", "git-branch", "context-remaining"]
```
Available built-in items (Codex CLI v0.101.0+):
`model-name`, `model-with-reasoning`, `current-dir`, `project-root`, `git-branch`, `context-remaining`, `context-used`, `five-hour-limit`, `weekly-limit`, `codex-version`, `context-window-size`, `used-tokens`, `total-input-tokens`, `total-output-tokens`, `session-id`
## Layer 2: OMX Orchestration HUD
The `omx hud` command reads these state files:
- `.omx/state/ralph-state.json` - Ralph loop iteration
- `.omx/state/ultrawork-state.json` - Ultrawork mode
- `.omx/state/autopilot-state.json` - Autopilot phase
- `.omx/state/team-state.json` - Team workers
- `.omx/state/pipeline-state.json` - Pipeline stage
- `.omx/state/ecomode-state.json` - Ecomode active
- `.omx/state/hud-state.json` - Last activity (from notify hook)
- `.omx/metrics.json` - Turn counts
## Configuration
HUD config stored at `.omx/hud-config.json`:
```json
{
"preset": "focused"
}
```
## Color Coding
- **Green**: Normal/healthy
- **Yellow**: Warning (ralph >70% of max)
- **Red**: Critical (ralph >90% of max)
## Troubleshooting
If the TUI statusline is not showing:
1. Ensure Codex CLI v0.101.0+ is installed
2. Run `omx setup` to configure `[tui]` section
3. Restart Codex CLI
If `omx hud` shows "No active modes":
- This is expected when no workflows are running
- Start a workflow (ralph, autopilot, etc.) and check again
@@ -0,0 +1,135 @@
---
name: omx-setup
description: Setup and configure oh-my-codex using current CLI behavior
---
# OMX Setup
Use this skill when users want to install or refresh oh-my-codex for the **current project plus user-level OMX directories**.
## Command
```bash
omx setup [--force] [--merge-agents] [--dry-run] [--verbose] [--scope <user|project>] [--plugin|--legacy|--install-mode <legacy|plugin>]
```
If you only want lightweight `AGENTS.md` scaffolding for an existing repo or subtree, use `omx agents-init [path]` instead of full setup.
Supported setup flags (current implementation):
- `--force`: overwrite/reinstall managed artifacts where applicable
- `--merge-agents`: when `AGENTS.md` already exists, preserve user-authored content and insert/refresh OMX-managed generated sections between explicit `<!-- OMX:AGENTS:START -->` / `<!-- OMX:AGENTS:END -->` markers
- `--dry-run`: print actions without mutating files
- `--verbose`: print per-file/per-step details
- `--scope`: choose install scope (`user`, `project`)
- `--plugin`: use Codex plugin delivery for bundled skills while archiving/removing legacy OMX-managed prompts/skills, refreshing setup-owned native agent TOMLs for `agent_type` routing, and keeping setup-owned runtime hooks
- `--legacy`: use legacy setup delivery, overriding any persisted plugin install mode
- `--install-mode`: explicitly choose setup delivery mode (`legacy` or `plugin`); canonical form for scripted setup
## What this setup actually does
`omx setup` performs these steps:
1. Resolve setup scope:
- `--scope` explicit value
- else persisted `./.omx/setup-scope.json` (with automatic migration of legacy values)
- if a TTY user has persisted setup preferences, `omx setup` first summarizes the recorded choices and asks whether to **keep**, **review/change**, or **reset** them
- else interactive prompt on TTY (default `user`)
- else default `user` (safe for CI/tests)
2. If scope is `user`, resolve user skill delivery mode:
- explicit `--plugin`, `--legacy`, or `--install-mode legacy|plugin`, if present
- persisted install mode in `./.omx/setup-scope.json`, if present and the TTY review decision is `keep`
- else discovered installed plugin cache under `${CODEX_HOME:-~/.codex}/plugins/cache/**/.codex-plugin/plugin.json` with `name: oh-my-codex` makes `plugin` the default
- else interactive prompt on TTY (`legacy` by default, or `plugin` when a plugin cache is discovered)
- else default `legacy` unless a plugin cache is discovered
3. Create directories and persist effective scope/install mode
4. In legacy mode, install prompts/native agents/skills and merge full config.toml. In plugin mode, archive/remove legacy OMX-managed prompts/skills, refresh installable native agent TOMLs for `agent_type` routing, clean up stale generated non-installable native agents, and keep native Codex hooks installed.
5. Verify Team CLI API interop markers exist in built `dist/cli/team.js`
6. Generate AGENTS.md defaults only when selected/allowed (or legacy behavior outside plugin mode)
7. Configure notify hook references outside plugin mode and write `./.omx/hud-config.json`
## Important behavior notes
- `omx setup` prompts for scope when no scope is provided and stdin/stdout are TTY. If `./.omx/setup-scope.json` already exists, setup now summarizes the saved choices first and asks whether to keep them, review/change them, or reset and behave like a fresh setup run.
- Non-interactive setup never blocks for this review prompt: it keeps deterministic CLI/persisted/default behavior for CI and scripted installs.
- In `user` scope, `omx setup` also prompts for skill delivery mode when no prior install mode is kept; installed plugin cache discovery makes plugin mode the default prompt/non-interactive choice.
- Local project orchestration file is `./AGENTS.md` (project root).
- If `AGENTS.md` exists and neither `--force` nor `--merge-agents` is used, interactive TTY runs ask whether to overwrite. Non-interactive runs preserve the file.
- Use `--merge-agents` to keep existing project guidance while allowing setup to refresh OMX-managed AGENTS sections and the generated model capability table idempotently.
- Scope targets:
- `user`: user directories (`~/.codex`, `~/.codex/skills`, `~/.omx/agents`)
- `project`: local directories (`./.codex`, `./.codex/skills`, `./.omx/agents`)
- User-scope skill delivery targets:
- `legacy`: keep installing/updating OMX skills in the resolved user skill root
- `plugin`: rely on Codex plugin discovery for bundled skills and plugin-scoped lifecycle hooks when Codex reports `plugin_hooks`; archive/remove legacy OMX-managed prompts/skills, refresh installable setup-owned native agent TOMLs for `agent_type` routing, and remove only stale generated/non-installable native agents. Setup still enables setup-owned runtime feature flags (`plugin_hooks = true` and `goals = true` when supported, or legacy setup-managed `hooks`/`codex_hooks` fallback when plugin hooks are not reported).
- Migration hint: in `user` scope, if historical `~/.agents/skills` still exists alongside `${CODEX_HOME:-~/.codex}/skills`, current setup prints a cleanup hint. **Why the paths differ**: `${CODEX_HOME:-~/.codex}/skills/` is the path current Codex CLI natively loads as its skill root; `~/.agents/skills/` was the skill root in an older Codex CLI release before `~/.codex` became the standard home directory. OMX writes only to the canonical `${CODEX_HOME:-~/.codex}/skills/` path. When both directories exist simultaneously, Codex discovers skills from both trees and may show duplicate entries in Enable/Disable Skills. Archive or remove `~/.agents/skills/` to resolve this.
- If persisted scope is `project`, `omx` launch automatically uses `CODEX_HOME=./.codex` unless user explicitly overrides `CODEX_HOME`.
- Plugin mode prompts separately for optional AGENTS.md defaults and optional `developer_instructions` defaults. If `developer_instructions` already exists, setup asks before overwriting it; non-interactive runs preserve it.
- With `--force` or `--merge-agents`, AGENTS updates may still be skipped if an active OMX session is detected (safety guard).
- Legacy persisted scope values (`project-local`) are automatically migrated to `project` with a one-time warning.
## Setup-owned configuration surfaces
Use this map when reconciling setup behavior or debugging a confusing install:
| Surface | Owner | Notes |
| --- | --- | --- |
| `./.omx/setup-scope.json` | `omx setup` | Persists setup scope and user-scope skill delivery mode. TTY reruns summarize it and offer keep/review/reset. |
| `~/.codex/config.toml` / `./.codex/config.toml` | `omx setup` generated blocks + user edits | Setup refreshes OMX-managed blocks while preserving supported manual content; setup-owned runtime feature flags include `multi_agent`, `child_agents_md`, the Codex hook feature flag (`hooks` or legacy `codex_hooks`), and `goals`. |
| `~/.codex/hooks.json` / `./.codex/hooks.json` | `omx setup` shared ownership | Setup owns OMX native hook wrappers and preserves user-owned hooks. |
| prompts, skills, native agents | `omx setup` or Codex plugin delivery | Legacy mode installs local files; plugin mode relies on plugin discovery for bundled skills, archives/removes legacy OMX-managed prompt/skill copies, and refreshes setup-owned native agent TOMLs for `agent_type` routing while cleaning up stale generated/non-installable native agents. |
| `AGENTS.md` | `omx setup` with overwrite safety | Generated defaults or managed refreshes are guarded by force/session checks. |
| `./.omx/hud-config.json` | `omx setup` / `$hud` | Setup creates the focused default; `$hud` can adjust it later. |
| notification hooks | `omx setup` / `$configure-notifications` | Setup wires defaults outside plugin skill delivery; notification skill owns deeper provider configuration. |
## If `$omx-setup` is missing or stale
The source repo ships `skills/omx-setup/SKILL.md` and the catalog marks it active. If Codex does not show `$omx-setup`, treat it as an installation/discovery issue rather than a missing source skill:
1. Run `omx setup --verbose` in the intended scope.
2. Run `omx doctor` and check the reported setup scope, Codex home, skill root, and hook/config status.
3. If using project scope, confirm `./.codex/skills/omx-setup/SKILL.md` exists.
4. If using user scope, confirm `${CODEX_HOME:-~/.codex}/skills/omx-setup/SKILL.md` exists in legacy mode, or that the oh-my-codex plugin is installed/discovered in plugin mode.
5. If duplicate/stale skills appear, check for legacy `~/.agents/skills` overlap and follow the cleanup hint printed by setup/doctor.
## Recommended workflow
1. Run setup:
```bash
omx setup --force --verbose
```
2. Verify installation:
```bash
omx doctor
```
3. Start Codex with OMX in the target project directory.
## Expected verification indicators
From `omx doctor`, expect:
- Prompts installed (scope-dependent: user or project)
- Skills installed (scope-dependent: user or project)
- AGENTS.md found in project root
- `.omx/state` exists
- CLI-first config present in the scope target `config.toml`; first-party OMX MCP servers and shared MCP registry sync are omitted by default unless setup was run with `--mcp compat`
## Troubleshooting
- If using local source changes, run build first:
```bash
npm run build
```
- If your global `omx` points to another install, run local entrypoint:
```bash
node bin/omx.js setup --force --verbose
node bin/omx.js doctor
```
- If AGENTS.md was not overwritten during `--force`, stop active OMX session and rerun setup.
- If AGENTS.md was not merged during `--merge-agents`, stop active OMX session and rerun setup.
@@ -0,0 +1,65 @@
---
name: performance-goal
description: "Run an evaluator-gated performance optimization workflow over Codex goal mode with durable OMX artifacts and safe goal handoffs."
---
# Performance Goal Workflow
Use this skill when a user asks OMX to optimize performance and wants a goal-oriented loop rather than a one-off review.
## Contract
- OMX owns durable workflow state under `.omx/goals/performance/<slug>/`.
- Codex goal mode owns only the active-thread focus/accounting primitive.
- Shell commands do **not** mutate hidden Codex goal state. They write artifacts and emit model-facing handoff text.
- No optimization work may start until an evaluator command and pass/fail contract exist.
- Do not call `update_goal({status: "complete"})` until the evaluator has a passing checkpoint and a completion audit proves the objective is done; then call `get_goal` again and pass that fresh snapshot to `omx performance-goal complete --codex-goal-json`.
## CLI
Create the workflow and evaluator contract:
```sh
omx performance-goal create \
--objective "Reduce CLI startup latency by 20%" \
--evaluator-command "npm run perf:startup" \
--evaluator-contract "PASS when p95 latency improves by 20% and regression tests pass" \
--slug startup-latency
```
Emit the Codex goal handoff:
```sh
omx performance-goal start --slug startup-latency
```
Record evaluator evidence:
```sh
omx performance-goal checkpoint --slug startup-latency --status pass --evidence "benchmark + tests passed"
omx performance-goal checkpoint --slug startup-latency --status fail --evidence "benchmark regressed"
omx performance-goal checkpoint --slug startup-latency --status blocked --evidence "missing fixture"
```
Complete only after a passing checkpoint:
```sh
omx performance-goal complete --slug startup-latency --evidence "final evaluator evidence" --codex-goal-json <get_goal-json-or-path>
```
## Agent Loop
1. Run `omx performance-goal create` if no workflow exists.
2. Run `omx performance-goal start` and follow the handoff:
- call `get_goal`;
- call `create_goal` only when no active goal exists and the objective is explicit;
- work only against the evaluator contract;
- after evaluator pass and completion audit, call `update_goal({status: "complete"})`, call `get_goal` again, and pass that snapshot to `omx performance-goal complete --codex-goal-json`;
3. Optimize in small reversible patches.
4. Run the evaluator and related regression tests.
5. Record each pass/fail/blocker with `checkpoint`.
6. Complete only when the pass artifact exists and no required work remains.
## Completion Gate
A performance goal is incomplete unless `.omx/goals/performance/<slug>/state.json` contains a `lastValidation.status` of `pass` and `omx performance-goal complete` receives a matching complete Codex `get_goal` snapshot via `--codex-goal-json`. Passing ordinary tests alone is not sufficient unless they are the declared evaluator contract.
@@ -0,0 +1,97 @@
---
name: pipeline
description: Configurable pipeline orchestrator for sequencing stages
---
# Pipeline Skill
`$pipeline` is the configurable pipeline orchestrator for OMX. It sequences stages
through a uniform `PipelineStage` interface, with state persistence and resume support.
## Default Autopilot Pipeline
The default Autopilot pipeline sequences:
```
deep-interview -> ralplan -> ultragoal (+ team if needed) -> code-review -> ultraqa
```
`$team` is conditional: use it only inside an active Ultragoal story when independent lanes or broad verification make coordinated parallel execution useful. Explicit legacy Ralph pipelines remain available through custom stages, but Ralph is not the advertised default Autopilot loop.
## Configuration
Pipeline parameters are configurable per run:
| Parameter | Default | Description |
|-----------|---------|-------------|
| `maxRalphIterations` | 10 | Quality-gate retry ceiling; legacy option name retained for compatibility |
| `workerCount` | 2 | Number of Codex CLI team workers |
| `agentType` | `executor` | Agent type for team workers |
## Stage Interface
Every stage implements the `PipelineStage` interface:
```typescript
interface PipelineStage {
readonly name: string;
run(ctx: StageContext): Promise<StageResult>;
canSkip?(ctx: StageContext): boolean;
}
```
Stages receive a `StageContext` with accumulated artifacts from prior stages and
return a `StageResult` with status, artifacts, and duration.
## Built-in Stages
- **deep-interview**: Requirements clarification and ambiguity gate.
- **ralplan**: Consensus planning (planner + architect + critic). Skips only when both `prd-*.md` and `test-spec-*.md` planning artifacts already exist **and** durable consensus evidence records Architect approval followed by Critic approval. Plan/test-spec files alone are not consensus evidence. If either review is missing, blocked, out of order, or non-approving, the stage remains in ralplan or fails with an explicit blocker/max-iteration outcome instead of progressing to execution. Carries any `deep-interview-*.md` spec paths forward for traceability.
- **ultragoal**: Durable goal-mode execution with `.omx/ultragoal` ledgers. Launch `$team` only from inside an Ultragoal story when parallel lanes are warranted.
- **code-review**: Merge-readiness review gate.
- **ultraqa**: Adversarial QA gate after a clean review; docs-only/trivially non-runtime changes may record an explicit skip reason.
- **team-exec** and **ralph-verify**: Legacy/custom pipeline adapters retained for explicit non-default pipelines.
## State Management
Pipeline state persists via the ModeState system at `.omx/state/pipeline-state.json`.
The HUD renders pipeline phase automatically. Resume is supported from the last incomplete stage.
- **On start**: `omx state write --input '{"mode":"pipeline","active":true,"current_phase":"stage:ralplan"}' --json`
- **On stage transitions**: `omx state write --input '{"mode":"pipeline","current_phase":"stage:<name>"}' --json`
- **On completion**: `omx state write --input '{"mode":"pipeline","active":false,"current_phase":"complete"}' --json`
## API
```typescript
import {
runPipeline,
createAutopilotPipelineConfig,
createDeepInterviewStage,
createRalplanStage,
createUltragoalStage,
createCodeReviewStage,
createUltraqaStage,
} from './pipeline/index.js';
const config = createAutopilotPipelineConfig('build feature X', {
stages: [
createDeepInterviewStage(),
createRalplanStage(),
createUltragoalStage(),
createCodeReviewStage(),
createUltraqaStage(),
],
});
const result = await runPipeline(config);
```
## Relationship to Other Modes
- **autopilot**: Autopilot can use pipeline as its execution engine (v0.8+)
- **team**: Pipeline delegates execution to team mode (Codex CLI workers)
- **ultragoal**: Autopilot delegates durable execution to Ultragoal by default
- **team**: Optional execution engine inside an Ultragoal story when parallel lanes are needed
- **ralph**: Available only for explicit legacy/custom pipelines
- **ralplan**: Pipeline planning runs RALPLAN consensus planning
@@ -0,0 +1,277 @@
---
name: plan
description: Strategic planning with optional interview workflow
---
<Purpose>
Plan creates comprehensive, actionable work plans through intelligent interaction. It auto-detects whether to interview the user (broad requests) or plan directly (detailed requests), and supports consensus mode (iterative Planner/Architect/Critic loop with RALPLAN-DR structured deliberation) and review mode (Critic evaluation of existing plans).
</Purpose>
<Use_When>
- User wants to plan before implementing -- "plan this", "plan the", "let's plan"
- User wants structured requirements gathering for a vague idea
- User wants an existing plan reviewed -- "review this plan", `--review`
- User wants multi-perspective consensus on a plan -- `--consensus`, "ralplan"
- Task is broad or vague and needs scoping before any code is written
</Use_When>
<Do_Not_Use_When>
- User wants autonomous end-to-end execution -- use `autopilot` instead
- User wants to start coding immediately with a clear task -- use `ralph` or delegate to executor
- User asks a simple question that can be answered directly -- just answer it
- Task is a single focused fix with obvious scope -- skip planning, just do it
</Do_Not_Use_When>
<Why_This_Exists>
Jumping into code without understanding requirements leads to rework, scope creep, and missed edge cases. Plan provides structured requirements gathering, expert analysis, and quality-gated plans so that execution starts from a solid foundation. The consensus mode adds multi-perspective validation for high-stakes projects.
</Why_This_Exists>
<Execution_Policy>
- Auto-detect interview vs direct mode based on request specificity
- Ask one question at a time during interviews -- never batch multiple interview rounds into one question form
- Gather codebase facts via `explore` agent before asking the user about them
- `omx explore` is deprecated. Use normal repository inspection tools/subagents for simple read-only repository lookups during planning; use `omx sparkshell` only for explicit shell-native read-only evidence, and keep prompt-heavy or ambiguous planning work on the richer normal path.
- Plans must meet quality standards: 80%+ claims cite file/line, 90%+ criteria are testable
- Implementation step count must be right-sized to task scope; avoid defaulting to exactly five steps when the work is clearly smaller or larger
- Consensus mode outputs the final plan by default; add `--interactive` to enable execution handoff
- Consensus mode uses RALPLAN-DR short mode by default; switch to deliberate mode with `--deliberate` or when the request explicitly signals high risk (auth/security, data migration, destructive/irreversible changes, production incident, compliance/PII, public API breakage)
- Apply the shared workflow guidance pattern: outcome-first framing, concise visible updates for multi-step planning, local overrides for the active workflow branch, evidence-backed planning and validation expectations, explicit stop rules, and automatic continuation for safe reversible steps. Ask only for material, destructive, credentialed, external-production, or preference-dependent branches.
</Execution_Policy>
<Steps>
### Mode Selection
| Mode | Trigger | Behavior |
|------|---------|----------|
| Interview | Default for broad requests | Interactive requirements gathering |
| Direct | `--direct`, or detailed request | Skip interview, generate plan directly |
| Consensus | `--consensus`, "ralplan" | Planner -> Architect -> Critic loop until agreement with RALPLAN-DR structured deliberation (short by default, `--deliberate` for high-risk); outputs plan by default |
| Consensus Interactive | `--consensus --interactive` | Same as Consensus but pauses for user feedback at draft and approval steps, then hands off to execution |
| Review | `--review`, "review this plan" | Critic evaluation of existing plan |
### Interview Mode (broad/vague requests)
1. **Classify the request**: Broad (vague verbs, no specific files, touches 3+ areas) triggers interview mode
2. **Ask one focused question** using the surface-appropriate structured question path for preferences, scope, and constraints: in attached-tmux OMX runtime use `omx question`; outside tmux use native structured input when available; use plain text only as a last fallback
3. **Gather codebase facts first**: Before asking "what patterns does your code use?", spawn an `explore` agent to find out, then ask informed follow-up questions
4. **Build on answers**: Each question builds on the previous answer
5. **Consult Analyst** (THOROUGH tier) for hidden requirements, edge cases, and risks
6. **Create plan** when the user signals readiness: "create the plan", "I'm ready", "make it a work plan"
### Direct Mode (detailed requests)
1. **Quick Analysis**: Optional brief Analyst consultation
2. **Create plan**: Generate comprehensive work plan immediately
3. **Review** (optional): Critic review if requested
### Consensus Mode (`--consensus` / "ralplan")
**RALPLAN-DR modes**: **Short** (default, bounded structure) and **Deliberate** (for `--deliberate` or explicit high-risk requests). Both modes keep the same Planner -> Architect -> Critic sequence. The workflow auto-proceeds through planning steps (Planner/Architect/Critic) but outputs the final plan without executing.
1. **Planner** creates initial plan and a compact **RALPLAN-DR summary** before any Architect review. The summary **MUST** include:
- **Principles** (3-5)
- **Decision Drivers** (top 3)
- **Viable Options** (>=2) with bounded pros/cons for each option
- If only one viable option remains, an explicit **invalidation rationale** for the alternatives that were rejected
- In **deliberate mode**: a **pre-mortem** (3 failure scenarios) and an **expanded test plan** covering **unit / integration / e2e / observability**
2. **User feedback** *(--interactive only)*: If running with `--interactive`, **MUST** use `AskUserQuestion` / the structured question UI (`omx question` in attached tmux; native structured input outside tmux when available) to present the draft plan **plus the RALPLAN-DR Principles / Decision Drivers / Options summary for early direction alignment** with these options:
- **Proceed to review** — send to Architect and Critic for evaluation
- **Request changes** — return to step 1 with user feedback incorporated
- **Skip review** — go directly to final approval (step 7)
If NOT running with `--interactive`, automatically proceed to review (step 3).
3. **Architect** reviews for architectural soundness as a dedicated subsequent `Architect` subagent with the full task, current plan text/path, RALPLAN-DR summary, and relevant artifact context. Architect review **MUST** include: strongest steelman counterargument (antithesis) against the favored option, at least one meaningful tradeoff tension, and (when possible) a synthesis path. In deliberate mode, Architect should explicitly flag principle violations. **Wait for this step to complete before proceeding to step 4.** Do NOT run steps 3 and 4 in parallel. Do NOT substitute a default/improvised subagent prompt for the role-specific `Architect` prompt.
4. **Critic** evaluates against quality criteria as a dedicated subsequent `Critic` subagent with the full task, current plan text/path, RALPLAN-DR summary, artifact context, and the completed `Architect` result. Critic **MUST** verify principle-option consistency, fair alternative exploration, risk mitigation clarity, testable acceptance criteria, and concrete verification steps. Critic **MUST** explicitly reject shallow alternatives, driver contradictions, vague risks, or weak verification. In deliberate mode, Critic **MUST** reject missing/weak pre-mortem or missing/weak expanded test plan. Run only after step 3 is complete. Do NOT let the `Architect` response self-approve the Critic gate.
5. **Re-review loop** (max 5 iterations): If Critic rejects or iterates, execute this closed loop:
a. Collect all feedback from Architect + Critic
b. Pass feedback to Planner to produce a revised plan
c. **Return to Step 3** — Architect reviews the revised plan
d. **Return to Step 4** — Critic evaluates the revised plan
e. Repeat until Critic approves OR max 5 iterations reached
f. If max iterations reached without approval, present the best version to user via the structured question UI with note that expert consensus was not reached
6. **Apply improvements**: When reviewers approve with improvement suggestions, merge all accepted improvements into the plan file before proceeding. Final consensus output **MUST** include an **ADR** section with: **Decision**, **Drivers**, **Alternatives considered**, **Why chosen**, **Consequences**, **Follow-ups**. Specifically:
a. Collect all improvement suggestions from Architect and Critic responses
b. Deduplicate and categorize the suggestions
c. Update the plan file in `.omx/plans/` with the accepted improvements (add missing details, refine steps, strengthen acceptance criteria, ADR updates, etc.)
d. Note which improvements were applied in a brief changelog section at the end of the plan
e. Before any execution handoff, derive an explicit **available-agent-types roster** from the known prompt catalog and add concrete **follow-up staffing guidance** for `$ultragoal` and `$team` (recommended roles, counts, suggested reasoning levels by lane, and why each lane exists), plus an explicit `$ralph` fallback note only when persistent single-owner verification is intentionally selected
f. Add a product-facing **Goal-Mode Follow-up Suggestions** section: recommend `$ultragoal` by default for general goal-oriented follow-up, `$autoresearch-goal` only when the context is a research project with a research deliverable/evaluator, and `$performance-goal` when the context is an optimization or performance project. Keep these suggestions alongside the Team path and any explicit Ralph fallback rather than replacing implementation-delivery guidance. For ordinary pre-planning external docs or best-practice lookup, cite `$best-practice-research` evidence and synthesize it into the plan instead of recommending Autoresearch as a final architecture component. For durable-goal work that is also parallelizable, explicitly recommend **Team + Ultragoal**: Ultragoal remains leader-owned goal/ledger state and Team returns checkpoint-ready execution evidence.
g. For the `$team` path, add an explicit launch-hint block with concrete `omx team` / `$team` commands and a **team verification path** (what Team proves before shutdown and what Ultragoal checkpoints as durable completion evidence). Distinguish Team + Ultragoal from any explicit Ralph fallback: Team handles coordinated parallel lanes; Ultragoal is the default durable follow-up/ledger owner, and Ralph is only an explicitly requested legacy-style persistent sequential verification/fix lane when needed.
7. On Critic approval (with improvements applied): *(--interactive only)* If running with `--interactive`, use `AskUserQuestion` / the structured question UI to present the plan with these options:
- **Approve durable goal execution** — proceed via `$ultragoal` by default (optionally with `$team` for parallel lanes)
- **Approve and implement via team** — proceed to implementation via coordinated parallel team agents
- **Start goal-mode follow-up** — proceed via `$ultragoal` by default, or `$autoresearch-goal` / `$performance-goal` when the approved plan specifically fits research validation or measurable optimization
- **Request changes** — return to step 1 with user feedback
- **Reject** — discard the plan entirely
If NOT running with `--interactive`, output the final approved plan and stop. Do NOT auto-execute.
8. *(--interactive only)* User chooses via the structured question UI (never ask for approval in plain text when a structured surface is available)
9. On user approval (--interactive only):
- **Approve durable goal execution**: **MUST** invoke `$ultragoal` with the approved plan path from `.omx/plans/` as context **plus the explicit available-agent-types roster, suggested reasoning levels, concrete role allocation guidance, and direct launch hints for Ultragoal follow-up work**. Use `$team` alongside Ultragoal when parallel lanes are warranted. Do NOT implement directly. Do NOT edit source code files in the planning agent. Ralph is not the default follow-up; only invoke `$ralph` when the user explicitly selects a legacy/persistent single-owner execution lane.
- **Approve and implement via team**: **MUST** invoke `$team` with the approved plan path from `.omx/plans/` as context **plus the explicit available-agent-types roster, suggested reasoning levels, concrete staffing / worker-role allocation guidance, explicit `omx team` / `$team` launch hints, and the team verification path**. Do NOT implement directly. The team skill coordinates parallel agents across the staged pipeline for faster execution on large tasks.
- **Start goal-mode follow-up**: **MUST** invoke the selected goal workflow with the approved plan path and appropriate success context: `$ultragoal` as the default goal-mode path, `$autoresearch-goal` for research projects, or `$performance-goal` for optimization/performance projects with measurable evaluator criteria. Do NOT implement directly in the planning agent.
### Review Mode (`--review`)
0. Treat review as a reviewer-only pass. The context that wrote the plan, cleanup proposal, or diff MUST NOT be the context that approves it.
1. Read plan file from `.omx/plans/`
2. Evaluate via Critic using `ask_codex` with `agent_role: "critic"`
3. For cleanup/refactor/anti-slop work, verify that the artifact includes a cleanup plan, regression tests or an explicit test gap, smell-by-smell passes, and quality gates.
4. Return verdict: APPROVED, REVISE (with specific feedback), or REJECT (replanning required)
5. If the current context authored the artifact, hand the review to `$code-review`, `critic`, `quality-reviewer`, or `verifier` as appropriate.
### Plan Output Format
Every plan includes:
- Requirements Summary
- Acceptance Criteria (testable)
- Implementation Steps (with file references)
- Adaptive step count sized to the actual scope (not a fixed five-step template)
- Risks and Mitigations
- Verification Steps
- For consensus/ralplan: **RALPLAN-DR summary** (Principles, Decision Drivers, Options)
- For consensus/ralplan final output: **ADR** (Decision, Drivers, Alternatives considered, Why chosen, Consequences, Follow-ups)
- For consensus/ralplan execution handoff: **Available-Agent-Types Roster**, **Follow-up Staffing Guidance** (including suggested reasoning levels by lane), product-facing **Goal-Mode Follow-up Suggestions** (`$ultragoal`, `$autoresearch-goal`, `$performance-goal` when contextually appropriate), explicit `omx team` / `$team` **Launch Hints**, and **Team Verification Path**
- For deliberate consensus mode: **Pre-mortem (3 scenarios)** and **Expanded Test Plan** (unit/integration/e2e/observability)
Plans are saved to `.omx/plans/`. Drafts go to `.omx/drafts/`.
</Steps>
<Tool_Usage>
- Use `AskUserQuestion` for preference questions (scope, priority, timeline, risk tolerance) -- provides clickable UI
- Use plain text for questions needing specific values (port numbers, names, follow-up clarifications)
- Use the `explore` agent (LOW tier, bounded quick pass) to gather codebase facts before asking the user
- Use `ask_codex` with `agent_role: "planner"` for planning validation on large-scope plans
- Use `ask_codex` with `agent_role: "analyst"` for requirements analysis
- Use `ask_codex` with `agent_role: "critic"` for standalone review mode. In consensus mode, use the dedicated sequential role-specific `Architect` and `Critic` subagents described in steps 3-4 instead of a single critic-only review call.
- If optional MCP compatibility tools or Codex consultation are unavailable, fall back to equivalent OMX prompt/native agents -- never block on external tools
- **CRITICAL — Consensus mode agent calls MUST be sequential, never parallel.** Always await the subsequent role-specific `Architect` result before issuing the subsequent role-specific `Critic` call.
- In consensus mode, default to RALPLAN-DR short mode; enable deliberate mode on `--deliberate` or explicit high-risk signals (auth/security, migrations, destructive changes, production incidents, compliance/PII, public API breakage)
- In consensus mode with `--interactive`: use `AskUserQuestion` / the structured question UI for the user feedback step (step 2) and the final approval step (step 7) -- never ask for approval in plain text when a structured surface is available. Without `--interactive`, auto-proceed through planning steps without pausing. Output the final plan without execution.
- In consensus mode with `--interactive`, on user approval **MUST** invoke the selected follow-up lane from step 9 (`$ultragoal`, `$team`, `$autoresearch-goal`, `$performance-goal`, or explicit `$ralph` fallback) -- never implement directly in the planning agent
- In consensus mode, execution follow-up handoff **MUST** include an explicit available-agent-types roster plus concrete staffing / role-allocation guidance grounded in that roster, suggested reasoning levels by lane, product-facing goal-mode follow-up suggestions (`$ultragoal` by default, `$autoresearch-goal` for research projects, `$performance-goal` for optimization/performance projects), explicit `omx team` / `$team` launch hints, and a team verification path. For parallelizable durable-goal plans, recommend Team + Ultragoal with leader-owned checkpointing from Team evidence; reserve Ralph for persistent sequential single-owner verification/fix follow-up.
</Tool_Usage>
## Scenario Examples
**Good:** The user says `continue` after the workflow already has a clear next step. Continue the current branch of work instead of restarting or re-asking the same question.
**Good:** The user changes only the output shape or downstream delivery step (for example `make a PR`). Preserve earlier non-conflicting workflow constraints and apply the update locally.
**Bad:** The user says `continue`, and the workflow restarts discovery or stops before the missing verification/evidence is gathered.
<Examples>
<Good>
Adaptive interview (gathering facts before asking):
```
Planner: [spawns explore agent: "find authentication implementation"]
Planner: [receives: "Auth is in src/auth/ using JWT with passport.js"]
Planner: "I see you're using JWT authentication with passport.js in src/auth/.
For this new feature, should we extend the existing auth or add a separate auth flow?"
```
Why good: Answers its own codebase question first, then asks an informed preference question.
</Good>
<Good>
Single question at a time:
```
Q1: "What's the main goal?"
A1: "Improve performance"
Q2: "For performance, what matters more -- latency or throughput?"
A2: "Latency"
Q3: "For latency, are we optimizing for p50 or p99?"
```
Why good: Each question builds on the previous answer. Focused and progressive.
</Good>
<Bad>
Asking about things you could look up:
```
Planner: "Where is authentication implemented in your codebase?"
User: "Uh, somewhere in src/auth I think?"
```
Why bad: The planner should spawn an explore agent to find this, not ask the user.
</Bad>
<Bad>
Batching multiple questions:
```
"What's the scope? And the timeline? And who's the audience?"
```
Why bad: Three questions at once causes shallow answers. Ask one at a time.
</Bad>
<Bad>
Presenting all design options at once:
```
"Here are 4 approaches: Option A... Option B... Option C... Option D... Which do you prefer?"
```
Why bad: Decision fatigue. Present one option with trade-offs, get reaction, then present the next.
</Bad>
</Examples>
<Escalation_And_Stop_Conditions>
- Stop interviewing when requirements are clear enough to plan -- do not over-interview
- In consensus mode, stop after 5 Planner/Architect/Critic iterations and present the best version
- Consensus mode outputs the plan by default; with `--interactive`, user can approve and hand off to ultragoal/team, with Ralph only as an explicit legacy/persistent single-owner lane
- If the user says "just do it" or "skip planning", **MUST** invoke `$ultragoal` to transition to durable goal execution mode by default; use `$ralph` only when the user explicitly asks for that fallback. Do NOT implement directly in the planning agent.
- Escalate to the user when there are irreconcilable trade-offs that require a business decision
</Escalation_And_Stop_Conditions>
<Final_Checklist>
- [ ] Plan has testable acceptance criteria (90%+ concrete)
- [ ] Plan references specific files/lines where applicable (80%+ claims)
- [ ] All risks have mitigations identified
- [ ] No vague terms without metrics ("fast" -> "p99 < 200ms")
- [ ] Plan saved to `.omx/plans/`
- [ ] In consensus mode: RALPLAN-DR summary includes 3-5 principles, top 3 drivers, and >=2 viable options (or explicit invalidation rationale)
- [ ] In consensus mode final output: ADR section included (Decision / Drivers / Alternatives considered / Why chosen / Consequences / Follow-ups)
- [ ] In deliberate consensus mode: pre-mortem (3 scenarios) + expanded test plan (unit/integration/e2e/observability) included
- [ ] In consensus mode with `--interactive`: user explicitly approved before any execution; without `--interactive`: output final plan after Critic approval (no auto-execution)
</Final_Checklist>
<Advanced>
## Design Option Presentation
When presenting design choices during interviews, chunk them:
1. **Overview** (2-3 sentences)
2. **Option A** with trade-offs
3. [Wait for user reaction]
4. **Option B** with trade-offs
5. [Wait for user reaction]
6. **Recommendation** (only after options discussed)
Format for each option:
```
### Option A: [Name]
**Approach:** [1 sentence]
**Pros:** [bullets]
**Cons:** [bullets]
What's your reaction to this approach?
```
## Question Classification
Before asking any interview question, classify it:
| Type | Examples | Action |
|------|----------|--------|
| Codebase Fact | "What patterns exist?", "Where is X?" | Explore first, do not ask user |
| User Preference | "Priority?", "Timeline?" | Ask user via the structured question path (`omx question` in attached tmux; native structured input where available) |
| Scope Decision | "Include feature Y?" | Ask user |
| Requirement | "Performance constraints?" | Ask user |
## Review Quality Criteria
| Criterion | Standard |
|-----------|----------|
| Clarity | 80%+ claims cite file/line |
| Testability | 90%+ criteria are concrete |
| Verification | All file refs exist |
| Specificity | No vague terms |
## Deprecation Notice
The separate `/planner`, `/ralplan`, and `/review` skills have been merged into `$plan`. All workflows (interview, direct, consensus, review) are available through `$plan`.
</Advanced>
@@ -0,0 +1,35 @@
# Prometheus Strict
`$prometheus-strict` is a clean-room OMX planning skill for rigorous interview-driven planning before execution.
It is inspired by the high-level OMO Prometheus concept only. It does not copy OMO source text, prompts, runtime code, or workflow implementation.
Credit: Inspired by OMO Prometheus (`code-yeongyu/oh-my-openagent`), reimplemented from concept under MIT.
## Roles
- **Metis** clarifies requirements, constraints, non-goals, and acceptance criteria.
- **Momus** challenges assumptions, scope, handoff risks, and missing verification.
- **Oracle** synthesizes the approved plan and recommends the OMX-native handoff.
## OMX Handoff
Prometheus Strict is planning-only by default. It should hand off to:
1. `$ultragoal` for durable goal execution.
2. `$team` only when the Oracle plan identifies independent parallel lanes.
## Non-Goals
- No hook implementation.
- No Sisyphus or `start-work` port.
- No direct implementation unless a downstream execution workflow is explicitly invoked.
- No verbatim source copying from the inspiration project.
## Expected Output
The skill returns a Prometheus Strict Plan with clarified requirements, resolved critique, an Oracle execution plan, a verification matrix, an optional durable artifact path under `.omx/plans/prometheus-strict/`, and clean-room credit.
## Durable Plan Artifacts
When the plan should survive handoff or review, write the final Oracle synthesis to `.omx/plans/prometheus-strict/<slug>.md` and include that path in the plan before invoking `$ultragoal` or `$team`. Inline-only plans may set the artifact path to `N/A - inline plan only`.
@@ -0,0 +1,219 @@
---
name: prometheus-strict
description: "[OMX] Clean-room interview-driven planner: Metis clarifies, Momus challenges, Oracle synthesizes, then hands off to $ultragoal/$team."
argument-hint: "<goal or problem statement>"
---
# Prometheus Strict
Clean-room OMX planning workflow inspired by the high-level OMO Prometheus concept only. This skill does not copy implementation, prompts, wording, control flow, or runtime code from OMO. It reimplements the idea under this repository's MIT-licensed skill conventions.
Credit: Inspired by OMO Prometheus (`code-yeongyu/oh-my-openagent`), reimplemented from concept under MIT.
<Purpose>
Prometheus Strict creates a rigorous plan before execution when ambiguity is still risky. It separates three planning voices: Metis clarifies requirements, Momus challenges assumptions and validation gaps, and Oracle synthesizes the handoff-ready OMX-native plan.
The output is a planning-only artifact for `$ultragoal` and, when independent lanes are justified, `$team`. When a durable artifact is useful, store or request the final plan under `.omx/plans/prometheus-strict/`.
</Purpose>
<Use_When>
- The task is important enough that a shallow plan could produce wrong work.
- Requirements are partially known but acceptance criteria, boundaries, risks, or validation are incomplete.
- The user wants a strict interview before execution.
- A future `$ultragoal` story needs durable scope, tests, and handoff sequencing.
- A team split may be needed, but the lanes are not yet safe to assign.
</Use_When>
<Do_Not_Use_When>
- The user asks for immediate implementation of a clear, low-risk change; use the normal executor path.
- The task is only a repository lookup or explanation; use `explore`/`analyze` as appropriate.
- The user needs adversarial execution QA after code changes; use `$ultraqa`.
- The user wants hook behavior, Sisyphus behavior, or a `start-work` port. Those are explicit non-goals.
</Do_Not_Use_When>
<Why_This_Exists>
OMX already has `$plan`, `$ralplan`, and `$deep-interview`. Prometheus Strict exists for a narrower case: an explicit clean-room strict-planning lane with named clarification, critique, and synthesis roles, plus a durable `.omx/plans/prometheus-strict/` handoff contract. It is not a replacement for execution workflows.
</Why_This_Exists>
<Execution_Policy>
- Stay planning-only. Do not edit source code during this skill unless the user starts a separate execution workflow afterward.
- Preserve clean-room boundaries. Do not copy or imitate OMO wording, source, prompts, runtime behavior, or control flow.
- Keep non-goals visible: No hook implementation. No Sisyphus/start-work port. No automatic external-production actions.
- Ask high-leverage questions as a batched round when the answers materially change scope, safety, or validation. Reserve one-at-a-time questioning only for dependent question chains where the next question depends on the previous answer.
- If a safe assumption is available, state it and continue.
- Use repository reads when needed to make paths, tests, and handoff commands concrete.
- During Metis planning, run pre-question research fan-out for every non-trivial intent unless the task is trivial, the cited spec is self-contained, or cached evidence already covers the same surface; use `explore` for repo facts and the exact cheap `gpt-5.4-mini` `researcher` lane for external docs / OSS references before asking the user. Prometheus Strict may fan out up to `2 explore + 4 researcher` agents per round so breadth comes from more citation-focused mini researchers while Metis/Momus/Oracle keep stronger judgment roles.
- Recommend `$team` only when Oracle identifies independent, bounded, verifiable lanes.
### Structured Question Surface
Every Metis/Momus/Oracle question to the user MUST go through the surface-appropriate structured question path. Plain prose questioning is the last fallback, not the default.
- In attached-tmux OMX runtime, use `omx question` as the OMX-owned structured question surface (this is the `AskUserQuestion` equivalent for Prometheus Strict). From attached-tmux Bash/tool paths, prefix the command with `OMX_QUESTION_RETURN_PANE=$TMUX_PANE` (or a concrete `%pane` value) so the leader-pane return target is preserved.
- **Batch independent high-leverage questions into a single `questions[]` array call**: scope, constraints, non-goals, deliverables, safety bounds, and acceptance criteria are normally independent and MUST be batched into one structured form so the user answers them in a single panel. Reserve one-at-a-time only for dependent question chains where the next question depends on the previous answer.
- Wait for the `omx question` JSON answer before checking the clearance rule, asking another round, or handing off; prefer `answers[]` / `answers[i].answer`, and use the legacy top-level `answer` only as a compatibility fallback. After every `answers[]` batch, run at least **two gap-fill passes** before another question or handoff: Pass 1 assimilates user answers into the checklist; Pass 2 re-scans repo context, prior turns, research fan-out evidence, and conservative defaults to absorb non-CRITICAL residual gaps.
- Minimum two emitted question rounds: when Metis emits any user-facing question round, do not hand off after Round 1 unless hostility/`<turn_aborted>` or the round-5 cap forces exit; handoff is allowed only after Round 2 has been emitted and processed. Zero-question complete-checklist handoff remains valid when no questions were emitted.
- Between-round planning must actively use evidence: after Round 1 answers and the two gap-fill passes, refresh or reuse `<research_fan_out>` explore/researcher evidence, re-run spec prefill, and build Round 2 from residual CRITICAL gaps only.
- Outside tmux, use the native structured input tool when one is available.
- When neither structured surface can render (non-tmux Codex CLI, piped runs, CI), list the round's independent questions as a numbered prose block (`Q1: ... Q2: ... Q3: ...`) and wait for all answers in one user turn; do not split into separate round-trips.
- Multiple interview rounds ARE expected when clearance is not yet reached; each round is one batched form (or its prose fallback), never split across forms.
### Checklist Clearance
The interview is governed by deterministic checklist clearance, not by subjective "feels enough" judgement. Exit the Metis interview loop when the 6-item checklist is fully YES: objective / scope IN+OUT / acceptance / test strategy / handoff target / no outstanding CRITICAL. Each item is evaluated with the tri-state defined in `<Turn_Termination_Rules>`.
Cap interview rounds at **5** to prevent runaway. If checklist clearance is not reached by round 5, hand the remaining UNKNOWN items to Oracle as explicitly carried-forward `<unresolved_blocker>` entries.
**Hostility / non-answer exit**: if the user's responses for a round contain refusal signals (1-2 character non-answers, dismissive `알아서` / "you decide" / "whatever" patterns, profanity-laden responses, or a `<turn_aborted>` on the prior turn), the round invalidates the answers — it does NOT advance any checklist item to YES, exits the interview loop immediately, and routes the unresolved gaps either to `<silent_absorption>` (for dismissive delegation) or back to the user via `hostility_exit` (for anger / aborted turns). See `prometheus-strict-metis` `<hostility_detection>` for the full pattern list and routing rules.
</Execution_Policy>
<Turn_Termination_Rules>
Every Prometheus Strict turn ends with EXACTLY ONE of the following terminations. Bare summaries and "I think we're done" are forbidden.
The 6-item checklist is: objective / scope IN+OUT / acceptance / test strategy / handoff target / no outstanding CRITICAL. A checklist item is YES when it is USER_ANSWERED ABSORBED_WITH_CITATION INFERRED_FROM_SPEC. Only UNKNOWN (no answer, no citation, no spec inference) counts as NO.
- (a) `omx question` batch: use when at least one CRITICAL question survives `<gap_triage>` and `<self_review>`. The batch is the round; the turn waits for `answers[]` before continuing.
- (b) explicit handoff: use when the 6-item checklist is fully YES. Hand off Metis → Momus after clearance, Momus → Oracle after critique, and Oracle → user or `<unresolved_blocker>` carry-forward after Pass 2 synthesis.
- (c) stop-blocker: use when hostility/`<turn_aborted>` is detected via `<hostility_detection>` with subtype `hostility_exit`, or when the next action is destructive, credential-gated, external-production, and cannot be defaulted safely.
Edge cases:
1. Zero-questions-but-complete-checklist → option (b) explicit handoff. Do not emit an empty `omx question` form.
2. Round-5-cap with incomplete checklist → option (a) emit one more question batch with surviving UNKNOWN items annotated, OR option (b) handoff with UNKNOWN items carried forward to Oracle as `<unresolved_blocker>` entries.
3. Hostility/`<turn_aborted>` → option (c) for anger, profanity, or aborted-turn via `hostility_exit`; option (b) for dismissive-delegation (`알아서` / "you decide") with absorbed gaps annotated.
</Turn_Termination_Rules>
<Steps>
### 1. Intake and Safety Bounds
Restate the target result, known constraints, deliverables, validation expectations, and stop condition. Identify whether this turn is planning-only or whether the user also requested downstream execution.
If the prompt contains destructive, credential-gated, external-production, or materially scope-changing decisions, hold those decisions for explicit user confirmation. Otherwise, continue through the planning loop.
### 2. Metis Interview (Iterative, Checklist Clearance)
Use `prometheus-strict-metis` as the interview voice. When native subagents are available, invoke the dedicated agent; otherwise run the same role in-context without editing files.
Metis discovers success criteria, non-goals, evidence versus assumptions, required artifacts, likely execution lanes, and missing decisions. Before the first user-facing question batch, Metis must actively fan out repo/external research per intent: `explore` maps local surfaces and exact `gpt-5.4-mini` `researcher` lanes gather official/upstream or OSS-reference evidence. Research-heavy intents use more cheap researchers rather than downgrading Metis/Momus/Oracle judgment.
Run the interview as a bounded loop:
1. Identify every currently-UNKNOWN checklist item and every CRITICAL question whose answers would materially change scope, safety, or validation.
2. Batch the round's independent questions into a single Structured Question Surface call (`questions[]` array, or numbered prose fallback outside tmux).
3. Collect the structured `answers[]`, then run **Gap-fill Pass 1 — answer assimilation**: update evidence vs. assumption and mark checklist items YES only when USER_ANSWERED, ABSORBED_WITH_CITATION, or INFERRED_FROM_SPEC.
4. Run **Gap-fill Pass 2 — residual adversarial scan**: re-check every remaining UNKNOWN against repo context, prior turns, research fan-out evidence, framework/industry defaults, and conservative reversible defaults; absorb non-CRITICAL gaps with citations/assumptions and leave only CRITICAL blockers.
5. Run **between-round planning** after Round 1: refresh or reuse `<research_fan_out>` explore/researcher evidence, re-run spec prefill, and prepare Round 2 from residual CRITICAL gaps only.
6. Evaluate the 6-item checklist (`<Turn_Termination_Rules>` tri-state) only after BOTH gap-fill passes and the minimum two emitted question rounds gate; exit when ALL YES and either no questions were emitted or Round 2 has been emitted and processed.
7. If checklist clearance is not reached, or only Round 1 has been processed, return to step 1 with the next round. Cap at 5 rounds; on cap, carry remaining UNKNOWN items forward to Oracle as explicit `<unresolved_blocker>` entries.
### 3. Momus Challenge (Bounded Retry)
Use `prometheus-strict-momus` as the adversarial critique voice. When native subagents are available, invoke the dedicated agent; otherwise run the same role in-context without editing files.
Momus challenges underspecified acceptance criteria, unsafe assumptions, hidden destructive steps, overbroad scope, missing verification, ownership conflicts, and `$ultragoal`/`$team` handoff ambiguity.
**Bounded retry contract**: after Oracle synthesizes in §4, re-invoke Momus on the synthesized plan to verify that Oracle's resolutions did not introduce new risks (scope addition without matching verification, lane split that creates dependency cycles, safety reinforcement that contradicts stop conditions). Repeat the Momus → Oracle re-synthesis cycle up to **3 times total**. If blocking objections remain after the 3rd cycle, mark them as carried-forward in the final plan and proceed to §5.
### 4. Oracle Synthesis (Two-Pass: Synthesis + Self-Verification)
Use `prometheus-strict-oracle` as the synthesis voice. When native subagents are available, invoke the dedicated agent; otherwise run the same role in-context without editing files.
**Pass 1 — Synthesis.** Oracle produces the final objective, scope and non-goals, accepted assumptions, resolved critique, sequenced steps or lanes, verification matrix, rollback/escalation conditions, and recommended OMX handoff.
**Pass 2 — Self-Verification (machine-checkable acceptance contract).** Oracle re-reads its own Pass 1 output and asserts:
- Every claim in the verification matrix has an explicit evidence source (test/build/lint/e2e/doc).
- Every step lists its owner / lane / executor; no shared-file conflicts between parallel lanes.
- Stop, rollback, and acceptance criteria are mutually consistent (no acceptance criterion is satisfied by a state that also triggers rollback).
- No destructive, credential-gated, or external-production step is unauthorized.
- The handoff command is concrete (callable verbatim) and points at an existing workflow (`$ultragoal`, `$team`, or `none`).
- Clean-room credit is preserved.
If any Pass 2 check fails, Oracle MUST loop back to Pass 1 to repair before emitting the plan. Cap Pass 1 ↔ Pass 2 cycles at **3**; on cycle 3 failure, emit the plan with the failing gates annotated as carried-forward and escalate to the user.
### 5. Post-Plan Gap Check (Metis Re-Invocation)
Before handing off, re-invoke `prometheus-strict-metis` on the finalized Oracle plan with a single charge: identify ambiguities that surfaced **only after** the plan was rendered — for example, new lane assignments that overlap, verification matrix gaps revealed by stop conditions, acceptance criteria that contradict the rollback contract.
If post-plan Metis surfaces any blocking gap, return to §4 Pass 1 with the new question. Otherwise proceed to §6.
### 6. Handoff
Prometheus Strict stops with a plan unless the user explicitly invokes or authorizes the next workflow. Prefer this sequence:
```text
$ultragoal "<Oracle plan summary or .omx/plans/prometheus-strict/<slug>.md>"
$team <N>:executor "execute the approved Ultragoal story in parallel lanes" # only when warranted
```
</Steps>
<Tool_Usage>
- Use read-only repository inspection to verify referenced files, commands, and existing conventions.
- Treat Metis research fan-out as part of planning, not execution: dispatch `explore` / exact `gpt-5.4-mini` `researcher` evidence-gathering before question generation for non-trivial intents, then re-prefill and ask only surviving CRITICAL gaps.
- Use `prometheus-strict-metis`, `prometheus-strict-momus`, and `prometheus-strict-oracle` sequentially; do not fan out implementation work from this skill.
- Use `$ultragoal` only as the recommended execution handoff after the plan is ready.
- Use `$team` only when parallel lanes are independent and verifiable.
</Tool_Usage>
## State Management
Prometheus Strict does not own a long-running runtime loop. If a durable planning artifact is needed, write the final plan to `.omx/plans/prometheus-strict/<slug>.md`. Draft-only or inline plans may set the artifact path to `N/A - inline plan only`.
Do not create hook state, Sisyphus state, or `start-work` compatibility state for this skill.
<Final_Checklist>
- [ ] Target result is explicit.
- [ ] Scope and non-goals are explicit.
- [ ] Acceptance criteria are measurable.
- [ ] Metis interview loop reached checklist clearance only after the mandatory two gap-fill passes following every `answers[]` batch and, if any question round was emitted, after the minimum two emitted question rounds gate; otherwise the 5-round cap was reached with UNKNOWN items carried forward as `<unresolved_blocker>` entries.
- [ ] Momus objections are resolved or carried forward as explicit blockers, with at most 3 Momus → Oracle re-synthesis cycles consumed.
- [ ] Oracle plan includes a verification matrix.
- [ ] Oracle Pass 2 self-verification completed; every machine-checkable contract item passes or is annotated as carried-forward.
- [ ] Post-plan Metis gap check produced no blocking objections (or all are carried forward).
- [ ] Handoff recommends `$ultragoal` and `$team` only when warranted.
- [ ] Clean-room credit is preserved.
- [ ] No hook implementation or Sisyphus/start-work port was introduced.
</Final_Checklist>
<Advanced>
## Output Contract
If writing a durable plan file, store this markdown at `.omx/plans/prometheus-strict/<slug>.md` and reference that path in the handoff.
```markdown
## Prometheus Strict Plan
### Target Result
- <one-sentence objective>
### Clarified Requirements (Metis)
- <requirement / acceptance criterion>
### Critique Resolved (Momus)
- <risk or objection> -> <resolution>
### Oracle Execution Plan
1. <sequenced step or lane>
### Verification Matrix
| Claim | Required evidence | Owner/lane |
| --- | --- | --- |
| <claim> | <test/build/lint/e2e/doc evidence> | <owner> |
### Artifact
- Durable plan path: `.omx/plans/prometheus-strict/<slug>.md` or `N/A - inline plan only`
### Handoff
- Recommended next workflow: <$ultragoal / $team / direct execution / none>
- Stop condition: <what proves the plan is ready or why it is blocked>
### Clean-Room Credit
Inspired by OMO Prometheus (`code-yeongyu/oh-my-openagent`), reimplemented from concept under MIT.
```
## Failure and Escalation
Escalate instead of planning when a necessary answer cannot be inferred safely, the next step is destructive or credential-gated, required repository context is unavailable, or the user asks for behavior outside the non-goals.
</Advanced>
Original task:
{{PROMPT}}
@@ -0,0 +1,294 @@
---
name: ralph
description: Self-referential loop until task completion with architect verification
---
[RALPH + ULTRAWORK - ITERATION {{ITERATION}}/{{MAX}}]
Your previous attempt did not output the completion promise. Continue working on the task.
<Purpose>
Ralph is a persistence loop that keeps working on a task until it is fully complete and architect-verified. It wraps ultrawork's parallel execution with session persistence, automatic retry on failure, and mandatory verification before completion.
</Purpose>
<Use_When>
- Task requires guaranteed completion with verification (not just "do your best")
- User says "ralph", "don't stop", "must complete", "finish this", or "keep going until done"
- Work may span multiple iterations and needs persistence across retries
- Task benefits from parallel execution with architect sign-off at the end
</Use_When>
<Do_Not_Use_When>
- User wants a full autonomous pipeline from idea to code -- use `autopilot` instead
- User wants to explore or plan before committing -- use `plan` skill instead
- User wants a quick one-shot fix -- delegate directly to an executor agent
- User wants manual control over completion -- use `ultrawork` directly
</Do_Not_Use_When>
<Why_This_Exists>
Complex tasks often fail silently: partial implementations get declared "done", tests get skipped, edge cases get forgotten. Ralph prevents this by looping until work is genuinely complete, requiring fresh verification evidence before allowing completion, and using explicit architect native-subagent verification to confirm quality.
</Why_This_Exists>
<Execution_Policy>
- Fire independent agent calls simultaneously -- never wait sequentially for independent work
- Use `run_in_background: true` for long operations (installs, builds, test suites)
- Always set `agent_type` when spawning native subagents; use `reasoning_effort` for per-dispatch intensity when needed
- Preserve legacy Ralph tier intent through native reasoning effort: LOW -> `low`, STANDARD -> `medium`, THOROUGH -> `xhigh`
- Deliver the full implementation: no scope reduction, no partial completion, no deleting tests to make them pass
- Apply the shared workflow guidance pattern: outcome-first framing, concise visible updates for multi-step execution, local overrides for the active workflow branch, validation proportional to risk, explicit stop rules, and automatic continuation for safe reversible steps. Ask only for material, destructive, credentialed, external-production, or preference-dependent branches.
- Integrate with Codex goal mode when goal tools are available: inspect the active thread goal with `get_goal`, preserve it as the top-level stop condition, and only call `update_goal({status: "complete"})` after a Ralph completion audit proves the objective is actually achieved.
</Execution_Policy>
<Steps>
0. **Pre-context intake (required before planning/execution loop starts)**:
- Assemble or load a context snapshot at `.omx/context/{task-slug}-{timestamp}.md` (UTC `YYYYMMDDTHHMMSSZ`).
- Minimum snapshot fields:
- task statement
- desired outcome
- known facts/evidence
- constraints
- unknowns/open questions
- likely codebase touchpoints
- If an existing relevant snapshot is available, reuse it and record the path in Ralph state.
- If request ambiguity is high, gather brownfield facts first. `omx explore` is deprecated; use normal repository inspection tools/subagents for simple read-only repository lookups and `omx sparkshell` only for explicit shell-native read-only evidence. Then run `$deep-interview --quick <task>` to close critical gaps.
- Do not begin Ralph execution work (delegation, implementation, or verification loops) until snapshot grounding exists. If forced to proceed quickly, note explicit risk tradeoffs.
1. **Review progress**: Check TODO list and any prior iteration state
2. **Continue from where you left off**: Pick up incomplete tasks
3. **Delegate in parallel**: Route tasks to specialist native agents with explicit `agent_type` and appropriate `reasoning_effort`
- Simple lookups: `reasoning_effort="low"` -- "What does this function return?"
- Standard work: `reasoning_effort="medium"` -- "Add error handling to this module"
- Complex analysis: `reasoning_effort="xhigh"` -- "Debug this race condition"
- When Ralph is entered as a ralplan follow-up, start from the approved **available-agent-types roster** and make the delegation plan explicit: implementation lane, evidence/regression lane, and final sign-off lane using only known agent types
4. **Run long operations in background**: Builds, installs, test suites use `run_in_background: true`
5. **Visual task gate (when screenshot/reference images are present)**:
- Run the Visual Ralph verdict step **before every next edit**.
- Require structured JSON output: `score`, `verdict`, `category_match`, `differences[]`, `suggestions[]`, `reasoning`.
- Persist verdict to `.omx/state/{scope}/ralph-progress.json` including numeric + qualitative feedback.
- Default pass threshold: `score >= 90`.
- **URL-based visual cloning tasks**: When the task description contains a target URL (e.g., "clone https://example.com"), route the work through `$visual-ralph`. `$web-clone` is hard-deprecated; Visual Ralph owns the migrated live-URL visual implementation use case and uses its built-in visual verdict step for measured visual scoring.
6. **Verify completion with fresh evidence**:
- If Codex goal mode is available, call `get_goal` before final verification to restate the active objective and include it in the evidence checklist.
a. Identify what command proves the task is complete
b. Run verification (test, build, lint)
c. Read the output -- confirm it actually passed
d. Check: zero pending/in_progress TODO items
7. **Architect verification** (native role):
- <5 files, <100 lines with full tests: `task(agent_type="architect", reasoning_effort="medium", prompt="...")` minimum
- Standard changes: `task(agent_type="architect", reasoning_effort="medium", prompt="...")`
- >20 files or security/architectural changes: `task(agent_type="architect", reasoning_effort="xhigh", prompt="...")`
- Ralph floor: always run an explicit `architect` native subagent, even for small changes
7.5 **Mandatory Deslop Pass**:
- After Step 7 passes, run `oh-my-codex:ai-slop-cleaner` on **all files changed during the Ralph session**.
- Scope the cleaner to **changed files only**; do not widen the pass beyond Ralph-owned edits.
- Run the cleaner in **standard mode** (not `--review`).
- If the prompt contains `--no-deslop`, skip Step 7.5 entirely and proceed with the most recent successful verification evidence.
7.6 **Regression Re-verification**:
- After the deslop pass, re-run all tests/build/lint and read the output to confirm they still pass.
- If post-deslop regression fails, roll back cleaner changes or fix and retry. Then rerun Step 7.5 and Step 7.6 until the regression is green.
- Do not proceed to completion until post-deslop regression is green (unless `--no-deslop` explicitly skipped the deslop pass).
8. **On approval**: If Codex goal mode is active, call `update_goal({status: "complete"})` before `/cancel`; report final elapsed time and token-budget usage when the tool returns it. Then run `/cancel` to cleanly exit and clean up all state files.
9. **On rejection**: Fix the issues raised, then re-verify with the same `agent_type` and `reasoning_effort` profile
</Steps>
<Tool_Usage>
- Use `ask_codex` with `agent_role: "architect"` for verification cross-checks when changes are security-sensitive, architectural, or involve complex multi-system integration
- Skip Codex consultation for simple feature additions, well-tested changes, or time-critical verification
- If MCP compatibility tools are unavailable, proceed with CLI/agent verification alone -- never block on external tools
- Use `omx state write/read --input '<json>' --json` for ralph mode state persistence between iterations
- Use Codex goal tools when present: `get_goal` to discover or re-check the active objective, `create_goal` only when the user/system explicitly requested a new goal and no active goal exists, and `update_goal` only after the audited objective is fully achieved.
- Persist context snapshot path in Ralph mode state so later phases and agents share the same grounding context
- Prefer CLI state commands. If an explicit MCP compatibility `omx_state` call reports that its stdio transport is unavailable/closed, do **not** retry the same MCP call. Retry once through the supported CLI parity surface with the same payload, preserving `workingDirectory` and `session_id`: `omx state write --input '<json>' --json`, `omx state read --input '<json>' --json`, or `omx state clear --input '<json>' --json`. If the CLI path also fails, continue with `.omx/context` / `.omx/plans` file-backed artifacts and report the state persistence blocker.
</Tool_Usage>
## Goal Mode Integration
Codex goal mode is the thread-level completion contract for long-running Ralph work. Ralph state tracks workflow mechanics; goal mode tracks whether the user objective is truly done. When the goal tools are available:
1. Call `get_goal` during intake or before the first execution loop when the prompt/hook says an active thread goal exists.
2. If no goal exists, call `create_goal` only when the user or system explicitly asked for goal tracking; otherwise continue with Ralph state alone.
3. Treat `goal.objective` as binding acceptance scope. Newer user updates can refine the current branch, but do not silently narrow the goal.
4. Before completion, perform a prompt-to-artifact checklist and completion audit against real evidence:
- restate the objective as deliverables/success criteria
- map every prompt requirement, named workflow (`$ralplan`, `$ralph`), file, command, test, gate, and deliverable to evidence
- inspect the actual files, command output, state, and tests behind each checklist item
- identify missing, weakly verified, or uncovered requirements and continue if any remain
5. Call `update_goal({status: "complete"})` only when the audit shows no required work remains. Do not use passing tests, Ralph state, or architect approval as proxy proof unless they cover the whole goal.
6. If goal tools are unavailable, keep working through Ralph state and mention the missing goal-mode evidence in the final report.
## State Management
Use the CLI-first state surface for Ralph lifecycle state (`omx state write/read/clear --input '<json>' --json`). Explicit MCP compatibility tools (`state_write`, `state_read`, `state_clear`) remain acceptable only when already enabled.
- **On start**:
`omx state write --input '{"mode":"ralph","active":true,"iteration":1,"max_iterations":10,"current_phase":"executing","started_at":"<now>","state":{"context_snapshot_path":"<snapshot-path>"}}' --json`
- **On each iteration**:
`omx state write --input '{"mode":"ralph","iteration":<current>,"current_phase":"executing"}' --json`
- **On verification/fix transition**:
`omx state write --input '{"mode":"ralph","current_phase":"verifying"}' --json` or `omx state write --input '{"mode":"ralph","current_phase":"fixing"}' --json`
- **On completion** (only after the completion audit passes with real evidence):
`omx state write --input '{"mode":"ralph","active":false,"current_phase":"complete","completed_at":"<now>","completion_audit":{"passed":true,"prompt_to_artifact_checklist":["<requirement mapped to artifact/evidence>"],"verification_evidence":["<fresh test/build/lint command and result>"]}}' --json`
- **Before the final answer**:
1. Run fresh verification and read the output.
2. Build `prompt_to_artifact_checklist` entries that map every user requirement, workflow gate, named file, command, PR/delivery requirement, and stop condition to a concrete artifact or evidence item.
3. Build `verification_evidence` entries with concrete commands, exit status, files inspected, PR URLs, or other machine-checkable evidence.
4. Write the Ralph completion state with a top-level `completion_audit` field on the Ralph state object. Do not write bare top-level `prompt_to_artifact_checklist` or `verification_evidence` fields by themselves; the Stop gate will reject them.
5. Read the state back with `omx state read --input '{"mode":"ralph"}' --json` and verify `completion_audit.passed === true`, a non-empty checklist, and non-empty verification evidence before producing the final answer.
6. If Codex goal mode is active, call `update_goal({status:"complete"})` only after this Ralph audit read-back succeeds.
- **On cancellation/cleanup**:
run `$cancel` (which should call `omx state clear --input '{"mode":"ralph"}' --json`)
## Scenario Examples
**Good:** The user says `continue` after the workflow already has a clear next step. Continue the current branch of work instead of restarting or re-asking the same question.
**Good:** The user changes only the output shape or downstream delivery step (for example `make a PR`). Preserve earlier non-conflicting workflow constraints and apply the update locally.
**Bad:** The user says `continue`, and the workflow restarts discovery or stops before the missing verification/evidence is gathered.
<Examples>
<Good>
Correct parallel delegation:
```
task(agent_type="executor", reasoning_effort="low", prompt="Add type export for UserConfig")
task(agent_type="executor", reasoning_effort="medium", prompt="Implement the caching layer for API responses")
task(agent_type="executor", reasoning_effort="xhigh", prompt="Refactor auth module to support OAuth2 flow")
```
Why good: Three independent tasks fired simultaneously while explicitly selecting the installed `executor` native role, so the UI/tracker does not show default subagents; legacy tier intent is preserved through native reasoning effort (`LOW` -> `low`, `STANDARD` -> `medium`, `THOROUGH` -> `xhigh`).
</Good>
<Good>
Correct verification before completion:
```
1. Run: npm test → Output: "42 passed, 0 failed"
2. Run: npm run build → Output: "Build succeeded"
3. Run: lsp_diagnostics → Output: 0 errors
4. task(agent_type="architect", reasoning_effort="medium", prompt="verify completion") → Verdict: "APPROVED"
5. Run /cancel
```
Why good: Fresh evidence at each step, architect verification, then clean exit.
</Good>
<Bad>
Claiming completion without verification:
"All the changes look good, the implementation should work correctly. Task complete."
Why bad: Uses "should" and "look good" -- no fresh test/build output, no architect verification.
</Bad>
<Bad>
Sequential execution of independent tasks:
```
task(agent_type="executor", reasoning_effort="low", prompt="Add type export") → wait →
task(agent_type="executor", reasoning_effort="medium", prompt="Implement caching") → wait →
task(agent_type="executor", reasoning_effort="xhigh", prompt="Refactor auth")
```
Why bad: These are independent tasks that should run in parallel, not sequentially.
</Bad>
</Examples>
<Escalation_And_Stop_Conditions>
- Stop and report when a fundamental blocker requires user input (missing credentials, unclear requirements, external service down)
- Stop when the user says "stop", "cancel", or "abort" -- run `/cancel`
- Continue working when the hook system sends "The boulder never stops" -- this means the iteration continues
- If architect rejects verification, fix the issues and re-verify (do not stop)
- If the same issue recurs across 3+ iterations, report it as a potential fundamental problem
</Escalation_And_Stop_Conditions>
<Final_Checklist>
- [ ] All requirements from the original task are met (no scope reduction)
- [ ] Zero pending or in_progress TODO items
- [ ] Fresh test run output shows all tests pass
- [ ] Fresh build output shows success
- [ ] lsp_diagnostics shows 0 errors on affected files
- [ ] Architect verification passed through explicit `task(agent_type="architect", reasoning_effort="medium"...)` minimum
- [ ] Codex goal-mode completion audit passed, and `update_goal({status: "complete"})` was called when an active goal exists
- [ ] ai-slop-cleaner pass completed on changed files (or --no-deslop specified)
- [ ] Post-deslop regression tests pass
- [ ] `/cancel` run for clean state cleanup
</Final_Checklist>
<Advanced>
## PRD Mode (Optional)
When the user provides the `--prd` flag, initialize a Product Requirements Document before starting the ralph loop.
### Detecting PRD Mode
Check if `{{PROMPT}}` contains `--prd` or `--PRD`.
Prompt-side `$ralph` workflow activation is lighter-weight than `omx ralph --prd ...`.
It seeds Ralph workflow state and guidance, but it does not implicitly launch the
CLI entrypoint or apply the PRD startup gate. Treat `omx ralph --prd ...` as the
explicit PRD-gated path.
### Detecting `--no-deslop`
Check if `{{PROMPT}}` contains `--no-deslop`.
If `--no-deslop` is present, skip the deslop pass entirely after Step 7 and continue using the latest successful pre-deslop verification evidence.
### Visual Reference Flags (Optional)
Ralph execution supports visual reference flags for screenshot tasks:
- Repeatable image inputs: `-i <image-path>` (can be used multiple times)
- Image directory input: `--images-dir <directory>`
Example:
`ralph -i refs/hn.png -i refs/hn-item.png --images-dir ./screenshots "match HackerNews layout"`
### PRD Workflow
1. Run deep-interview in quick mode before creating PRD artifacts:
- Execute: `$deep-interview --quick <task>`
- Complete a compact requirements pass (context, goals, scope, constraints, validation)
- Persist interview output to `.omx/interviews/{slug}-{timestamp}.md`
2. Create canonical PRD/progress artifacts:
- PRD: `.omx/plans/prd-{slug}.md`
- Progress ledger: `.omx/state/{scope}/ralph-progress.json` (session scope when available, else root scope)
3. Parse the task (everything after `--prd` flag)
4. Break down into user stories:
```json
{
"project": "[Project Name]",
"branchName": "ralph/[feature-name]",
"description": "[Feature description]",
"userStories": [
{
"id": "US-001",
"title": "[Short title]",
"description": "As a [user], I want to [action] so that [benefit].",
"acceptanceCriteria": ["Criterion 1", "Typecheck passes"],
"priority": 1,
"passes": false
}
]
}
```
5. Initialize canonical progress ledger at `.omx/state/{scope}/ralph-progress.json`
6. Guidelines: right-sized stories (one session each), verifiable criteria, independent stories, priority order (foundational work first)
7. Proceed to normal ralph loop using user stories as the task list
### Example
User input: `--prd build a todo app with React and TypeScript`
Workflow: Detect flag, extract task, create `.omx/plans/prd-{slug}.md`, create `.omx/state/{scope}/ralph-progress.json`, begin ralph loop.
### Legacy compatibility
- During the compatibility window, Ralph `--prd` startup still validates machine-readable story state from `.omx/prd.json`.
- `.omx/plans/prd-{slug}.md` remains the canonical storage/documentation artifact, but it is not yet the startup validation source.
- If `.omx/prd.json` exists and canonical PRD is absent, migrate one-way into `.omx/plans/prd-{slug}.md`.
- If `.omx/progress.txt` exists and canonical progress ledger is absent, import one-way into `.omx/state/{scope}/ralph-progress.json`.
- Keep legacy files unchanged for one release cycle.
## Background Execution Rules
**Run in background** (`run_in_background: true`):
- Package installation (npm install, pip install, cargo build)
- Build processes (make, project build commands)
- Test suites
- Docker operations (docker build, docker pull)
**Run blocking** (foreground):
- Quick status checks (git status, ls, pwd)
- File reads and edits
- Simple commands
</Advanced>
Original task:
{{PROMPT}}
@@ -0,0 +1,203 @@
---
name: ralplan
description: Alias for $plan --consensus
---
# Ralplan (Consensus Planning Alias)
Ralplan is a shorthand alias for `$plan --consensus`. It triggers iterative planning with Planner, Architect, and Critic agents until consensus is reached, with **RALPLAN-DR structured deliberation** (short mode by default, deliberate mode for high-risk work). Scholastic is available as a separate advisory native agent/persona for ontology-heavy planning evidence, but it is not part of the durable consensus gate.
## Usage
```
$ralplan "task description"
```
## Flags
- `--interactive`: Enables user prompts at key decision points (draft review in step 2 and final approval in step 6). Without this flag the workflow runs fully automated — Planner → Architect → Critic loop — and outputs the final plan without asking for confirmation.
- `--deliberate`: Forces deliberate mode for high-risk work. Adds pre-mortem (3 scenarios) and expanded test planning (unit/integration/e2e/observability). Without this flag, deliberate mode can still auto-enable when the request explicitly signals high risk (auth/security, migrations, destructive changes, production incidents, compliance/PII, public API breakage).
## Ontology-heavy review
For requirements semantics, taxonomy, prompt/spec design, policy distinctions, or category-risk architecture, subagent `Scholastic` may be cited as an available advisory ontology reviewer/persona. Its findings can inform the plan or follow-up evidence when explicitly used, but `$ralplan` itself remains the Planner → Architect → Critic consensus workflow and the durable gate remains Architect→Critic only.
## Usage with interactive mode
```
$ralplan --interactive "task description"
```
## Behavior
## GPT-5.5 Guidance Alignment
Use the shared workflow guidance pattern: outcome-first framing, concise visible updates for multi-step planning, local overrides for the active workflow branch, evidence-backed planning and validation expectations, explicit stop rules, right-sized implementation/PRD shape, and automatic continuation for safe reversible steps. Ask only for material, destructive, credentialed, external-production, or preference-dependent branches.
This skill invokes the Plan skill in consensus mode:
```
$plan --consensus <arguments>
$plan --consensus --interactive <arguments>
```
The consensus workflow:
1. **Planner** creates an adaptive plan (right-sized to task scope; do not default to exactly five steps) and a compact **RALPLAN-DR summary** before review:
- Principles (3-5)
- Decision Drivers (top 3)
- Viable Options (>=2) with bounded pros/cons
- If only one viable option remains, explicit invalidation rationale for alternatives
- Deliberate mode only: pre-mortem (3 scenarios) + expanded test plan (unit/integration/e2e/observability)
2. **User feedback** *(--interactive only)*: If `--interactive` is set, use the structured question UI (`omx question` in attached tmux; native structured input outside tmux when available) to present the draft plan **plus the Principles / Drivers / Options summary** before review (Proceed to review / Request changes / Skip review). Otherwise, automatically proceed to review.
3. **Architect** reviews for architectural soundness and must provide the strongest steelman antithesis, at least one real tradeoff tension, and (when possible) synthesis — **await completion before step 4**. Launch this as a subsequent `Architect` subagent (`agent_type: "architect"`) and pass the full task statement, context snapshot, PRD/test-spec paths, and relevant prior findings; do not use a default subagent with only a short improvised reviewer prompt. In deliberate mode, Architect should explicitly flag principle violations.
4. **Critic** evaluates against quality criteria — run only after step 3 completes. Launch this as a subsequent `Critic` subagent (`agent_type: "critic"`) with the full task statement, context snapshot, PRD/test-spec paths, and the completed Architect review; do not ask the Architect subagent to perform the Critic gate and do not substitute a default subagent fantasy prompt for the packaged Critic role. Critic must enforce principle-option consistency, fair alternatives, risk mitigation clarity, testable acceptance criteria, and concrete verification steps. In deliberate mode, Critic must reject missing/weak pre-mortem or expanded test plan.
5. **Re-review loop** (max 5 iterations): Any non-`APPROVE` Critic verdict (`ITERATE` or `REJECT`) MUST run the same full closed loop:
a. Collect Architect and Critic feedback
b. Revise the plan with Planner
c. Return to Architect review
d. Return to Critic evaluation
e. Repeat this loop until Critic returns `APPROVE` or 5 iterations are reached
f. If 5 iterations are reached without `APPROVE`, present the best version to the user
6. On Critic approval *(--interactive only)*: If `--interactive` is set, use the structured question UI to present the plan with approval options (Approve durable goal execution via ultragoal / Approve and implement via team / Explicit Ralph fallback / Start specialized goal-mode follow-up / Request changes / Reject). Final plan must include ADR (Decision, Drivers, Alternatives considered, Why chosen, Consequences, Follow-ups), an explicit available-agent-types roster, concrete follow-up staffing guidance for `$ultragoal` and `$team`, plus an explicit `$ralph` fallback note when persistent single-owner verification is intentionally selected, suggested reasoning levels by lane, explicit `omx team` / `$team` launch hints, a concrete **team verification** path, and a product-facing **Goal-Mode Follow-up Suggestions** section. Recommend `$ultragoal` by default for goal-mode follow-up, use `$autoresearch-goal` instead when the context is a research project, and use `$performance-goal` instead when the context is an optimization or performance project. Otherwise, output the final plan and stop.
7. *(--interactive only)* User chooses: Approve (`$ultragoal` durable goal execution, `$team`, explicit `$ralph` fallback, or a specialized goal-mode follow-up), Request changes, or Reject
8. *(--interactive only)* On approval: invoke `$ultragoal` for default durable sequential execution, `$team` for parallel team execution, the selected specialized goal-mode follow-up (`$autoresearch-goal` or `$performance-goal`), or `$ralph` only when the user explicitly selects that fallback with the approved plan and matching success/evaluator context -- never implement directly. Preserve the explicit available-agent-types roster, reasoning-by-lane guidance, role/staffing allocation guidance, launch hints, and verification-path guidance from the approved plan for Ultragoal/team paths and any explicit Ralph fallback.
> **Important:** Steps 3 and 4 MUST run sequentially as role-specific subagents. Do NOT issue both agent calls in the same parallel batch. Always await the subsequent `Architect` result before invoking the subsequent `Critic`; only a completed, role-specific `Critic` approval can satisfy the durable gate.
## Planning/Execution Boundary
`$ralplan` is a planning mode. While ralplan is active and no explicit execution handoff is active, implementation-focused write tools are out of scope. Ralplan may inspect the repository and may write only planning artifacts such as `.omx/context/`, `.omx/plans/`, `.omx/specs/`, and required `.omx/state/` records.
The canonical flow is:
```
$ralplan -> durable consensus artifact -> explicit execution lane -> $ultragoal | $team | $ralph
```
Before any execution lane begins, ralplan must emit terminal planning state (complete, paused, failed, or waiting for input) and the durable handoff record below. Do not continue from consensus planning into direct code edits in the same ralplan session.
## Durable Consensus Handoff Contract
Ralplan is not complete, skippable, or ready for execution merely because `.omx/plans/prd-*.md` and `.omx/plans/test-spec-*.md` exist. Those files are planning artifacts, not consensus evidence.
Before any Autopilot, Pipeline, Ultragoal, Team, Ralph, or implementation handoff, persist a durable handoff record that distinguishes:
- `planning_artifacts`: PRD/test-spec paths.
- `ralplan_architect_review`: the completed Architect review with an approving verdict.
- `ralplan_critic_review`: the completed Critic review with an approving verdict, recorded only after the Architect review.
- `ralplan_consensus_gate.complete:true` only when both reviews are present, approving, and in the required Architect→Critic order.
If Architect is missing/blocked, keep the workflow in Architect review or report that blocker. If Critic is missing/blocked/non-approving, keep the workflow in Critic/re-review or report the max-iteration outcome. Do not treat existing plan/test-spec files as permission to skip ralplan or start execution.
Follow the Plan skill's full documentation for consensus mode details.
## Goal-Mode Follow-up Suggestions
When ralplan outputs a final handoff or asks the user to choose a next lane, include product-facing goal-mode suggestions alongside the existing Ralph and team options:
- `$ultragoal`**default goal-mode follow-up** for implementation or general goal-oriented follow-up plans that should become durable Codex/OMX goals with sequential completion tracking.
- `$autoresearch-goal` — research-project follow-up when the plan centers on a question, literature/reference gathering, evaluator-backed research, or a professor/critic-style research deliverable.
- `$performance-goal` — optimization/performance follow-up when the plan centers on speed, latency, throughput, memory, benchmark, or other measurable performance work.
Keep `$team` as a first-class execution option and keep `$ralph` available only as an explicit fallback where appropriate: use Ultragoal as the default durable goal-mode follow-up, Team for coordinated parallel implementation, and Ralph only for intentionally selected persistent single-owner completion/verification pressure. For parallelizable durable-goal delivery, recommend `$ultragoal` + `$team` together: Ultragoal remains the leader-owned `.omx/ultragoal` ledger/Codex-goal wrapper while Team runs parallel lanes and returns checkpoint-ready evidence. Do not present Ralph as the recommended follow-up when durable goal tracking is needed; present Ultragoal as the superseding default, with Team for parallel delivery and Ralph only as an explicit fallback when its narrow persistence loop is specifically desired.
## Pre-context Intake
Before consensus planning or execution handoff, ensure a grounded context snapshot exists:
1. Derive a task slug from the request.
2. Reuse the latest relevant snapshot in `.omx/context/{slug}-*.md` when available.
3. If none exists, create `.omx/context/{slug}-{timestamp}.md` (UTC `YYYYMMDDTHHMMSSZ`) with:
- task statement
- desired outcome
- known facts/evidence
- constraints
- unknowns/open questions
- likely codebase touchpoints
4. If ambiguity remains high, gather brownfield facts first. `omx explore` is deprecated; use normal repository inspection tools/subagents for simple read-only repository lookups and `omx sparkshell` only for explicit shell-native read-only evidence. Then run `$deep-interview --quick <task>` before continuing.
5. If the plan depends on official docs, version-aware framework guidance, best practices, or external dependency behavior, use `$best-practice-research` as the bounded evidence wrapper and auto-delegate `researcher` for the official/upstream lookup before finalizing the planning handoff so execution does not start from repo-local recall alone.
6. If a prior `$autoresearch` or `$autoresearch-goal` run exists, treat its approved artifact as evidence for the plan. Do not include Autoresearch as a final architecture or runtime component unless the user explicitly requested ongoing research automation; otherwise synthesize the evidence into the `$ralplan` ADR, risks, and verification steps.
Do not hand off to execution modes until this intake is complete; if urgency forces progress, explicitly document the risk tradeoffs.
## Pre-Execution Gate
### Why the Gate Exists
Execution modes (ralph, autopilot, team, ultrawork) spin up heavy multi-agent orchestration. When launched on a vague request like "ralph improve the app", agents have no clear target — they waste cycles on scope discovery that should happen during planning, often delivering partial or misaligned work that requires rework.
The ralplan-first gate intercepts underspecified execution requests and redirects them through the ralplan consensus planning workflow. This ensures:
- **Explicit scope**: A PRD defines exactly what will be built
- **Test specification**: Acceptance criteria are testable before code is written
- **Consensus**: Planner, Architect, and Critic agree on the approach
- **No wasted execution**: Agents start with a clear, bounded task
### Good vs Bad Prompts
**Passes the gate** (specific enough for direct execution):
- `ralph fix the null check in src/hooks/bridge.ts:326`
- `autopilot implement issue #42`
- `team add validation to function processKeywordDetector`
- `ralph do:\n1. Add input validation\n2. Write tests\n3. Update README`
- `ultrawork add the user model in src/models/user.ts`
**Gated — redirected to ralplan** (needs scoping first):
- `ralph fix this`
- `autopilot build the app`
- `team improve performance`
- `ralph add authentication`
- `ultrawork make it better`
**Bypass the gate** (when you know what you want):
- `force: ralph refactor the auth module`
- `! autopilot optimize everything`
### When the Gate Does NOT Trigger
The gate auto-passes when it detects **any** concrete signal. You do not need all of them — one is enough:
| Signal Type | Example prompt | Why it passes |
|---|---|---|
| File path | `ralph fix src/hooks/bridge.ts` | References a specific file |
| Issue/PR number | `ralph implement #42` | Has a concrete work item |
| camelCase symbol | `ralph fix processKeywordDetector` | Names a specific function |
| PascalCase symbol | `ralph update UserModel` | Names a specific class |
| snake_case symbol | `team fix user_model` | Names a specific identifier |
| Test runner | `ralph npm test && fix failures` | Has an explicit test target |
| Numbered steps | `ralph do:\n1. Add X\n2. Test Y` | Structured deliverables |
| Acceptance criteria | `ralph add login - acceptance criteria: ...` | Explicit success definition |
| Error reference | `ralph fix TypeError in auth` | Specific error to address |
| Code block | `ralph add: \`\`\`ts ... \`\`\`` | Concrete code provided |
| Escape prefix | `force: ralph do it` or `! ralph do it` | Explicit user override |
### End-to-End Flow Example
1. User types: `ralph add user authentication`
2. Gate detects: execution keyword (`ralph`) + underspecified prompt (no files, functions, or test spec)
3. Gate redirects to **ralplan** with message explaining the redirect
4. Ralplan consensus runs:
- **Planner** creates initial plan (which files, what auth method, what tests)
- **Architect** reviews for soundness
- **Critic** validates quality and testability
5. On consensus approval, user chooses execution path:
- **ultragoal**: default durable follow-up for sequential goal execution with ledger checkpoints
- **team**: coordinated parallel execution for stories that need multiple lanes, with evidence ready for Ultragoal checkpoints
- **ralph**: explicit single-owner fallback only when the user intentionally wants a persistent verification/completion loop instead of the default durable goal ledger
6. Execution begins with a clear, bounded plan through the selected handoff path
### Troubleshooting
| Issue | Solution |
|-------|----------|
| Gate fires on a well-specified prompt | Add a file reference, function name, or issue number to anchor the request |
| Want to bypass the gate | Prefix with `force:` or `!` (e.g., `force: ralph fix it`) |
| Gate does not fire on a vague prompt | The gate only catches prompts with <=15 effective words and no concrete anchors; add more detail or use `$ralplan` explicitly |
| Redirected to ralplan but want to skip planning | In the ralplan workflow, say "just do it" or "skip planning" to transition directly to execution |
## Scenario Examples
**Good:** The user says `continue` after the workflow already has a clear next step. Continue the current branch of work instead of restarting or re-asking the same question.
**Good:** The user changes only the output shape or downstream delivery step (for example `make a PR`). Preserve earlier non-conflicting workflow constraints and apply the update locally.
**Bad:** The user says `continue`, and the workflow restarts discovery or stops before the missing verification/evidence is gathered.
@@ -0,0 +1,536 @@
---
name: team
description: N coordinated agents on shared task list using tmux-based orchestration
---
# Team Skill
`$team` is the tmux-based parallel execution mode for OMX. It starts real worker Codex and/or Claude CLI sessions in split panes and coordinates them through `.omx/state/team/...` files plus CLI team interop (`omx team api ...`) and state files.
This skill is operationally sensitive. Treat it as an operator workflow, not a generic prompt pattern. In Codex App or plain outside-tmux sessions, do not present `$team` / `omx team` as directly available; launch OMX CLI from shell first, or stay on the nearest app-safe surface until the user explicitly wants the tmux runtime.
## Team vs Native Subagents
- Use **Codex native subagents** for bounded, in-session parallelism where one leader thread can fan out a few independent subtasks and wait for them directly.
- Use **`omx team`** when you need durable tmux workers, shared task state, mailbox/dispatch coordination, worktrees, explicit lifecycle control, or long-running parallel execution that must survive beyond one local reasoning burst.
- Native subagents can complement team/ralph execution, but they do **not** replace the tmux team runtime's stateful coordination contract.
## What This Skill Must Do
## GPT-5.5 Guidance Alignment
Use the shared workflow guidance pattern: outcome-first framing, concise visible updates for multi-step work, local overrides for the active workflow branch, validation proportional to risk, explicit stop rules, and automatic continuation for safe reversible steps. Ask only for material, destructive, credentialed, external-production, or preference-dependent branches.
When user triggers `$team`, the agent must:
1. Invoke OMX runtime directly with `omx team ...`
2. Avoid replacing the flow with in-process `spawn_agent` fanout
3. Verify startup and surface concrete state/pane evidence
4. If active team mode state is missing, initialize/sync it from canonical team runtime state before proceeding
5. Keep team state alive until workers are terminal (unless explicit abort)
6. Handle cleanup and stale-pane recovery when needed
If `omx team` is unavailable, stop with a hard error.
## Invocation Contract
```bash
omx team [N:agent-type] "<task description>"
```
Examples:
```bash
omx team 3:executor "analyze feature X and report flaws"
omx team "debug flaky integration tests"
omx team "ship end-to-end fix with verification"
```
### Team-first launch contract
`omx team ...` is now the canonical launch path for coordinated execution.
Team mode should carry its own parallel delivery + verification lanes without
requiring a separate linked Ralph launch up front.
- **Canonical launch:** use plain `omx team ...` / `$team ...` for coordinated workers.
- **Verification ownership:** keep one lane focused on tests, regression coverage, and evidence before shutdown.
- **Escalation:** start a separate `omx ralph ...` / `$ralph ...` only when a later manual follow-up still needs a persistent single-owner fix/verification loop.
- **Deprecation:** `omx team ralph ...` has been removed. Use plain `omx team ...` for team execution or run `omx ralph ...` separately when you explicitly want a later Ralph loop.
### Team Big Five / ATEM coordination gate
`$team` keeps simple independent fan-out lightweight. For isolated tasks (for example per-file sweeps, typo/copy edits, or explicitly independent lanes with no shared files/dependencies), workers use the normal concise protocol: startup ACK, claim-safe task lifecycle, status, verification, and completion evidence.
Activate the lightweight Team Big Five + ATEM-inspired coordination layer when the task or task graph has dependencies, shared files/surfaces/contracts, cross-boundary ownership, handoffs, integration/merge work, blocked lanes, or changed assumptions. The protocol is not a separate ceremony; it is a concise boundary checklist:
- **Shared mental model / single source of truth:** task JSON, inbox, mailbox, approved handoff, and leader updates are canonical.
- **Closed-loop communication / ACK-readback handoffs:** acknowledge handoffs with understood scope, affected artifact/path, owner, and next action.
- **Mutual performance monitoring at boundaries:** check upstream/downstream contracts, shared files, and verification evidence before completion.
- **Backup/reassignment behavior:** blocked workers report the smallest needed help/reassignment request and continue safe unblocked slices.
- **Adaptability checkpoints:** changed assumptions, dependencies, or verification results trigger a brief leader-facing update before widening scope.
- **Team orientation:** workers optimize for the integrated team outcome, not local-optimum-only task summaries; report integration risks, missing tests, and peer impacts.
ATEM fit: treat this as agile teamwork support for transition/action/interpersonal moments around boundaries, not as a heavyweight process model. Do not copy provider-specific plugin implementations; keep the protocol in OMX/Codex prompts, inboxes, state, and tests.
### Team + Ultragoal bridge
Use `$ultragoal` for durable leader-owned goal/ledger tracking and `$team` for parallel execution lanes. When Team is launched with an active `.omx/ultragoal/goals.json`, worker inboxes/status may include leader-owned Ultragoal context: `.omx/ultragoal/goals.json`, `.omx/ultragoal/ledger.jsonl`, the active goal id, Codex goal mode, and the `fresh_leader_get_goal_required` checkpoint policy.
Workers provide task status and verification evidence only. They do not own Ultragoal goal state, create worker ledgers, mutate `.omx/ultragoal`, auto-launch Team from Ultragoal, or perform hidden Codex goal mutation. The leader uses terminal Team evidence plus a fresh `get_goal` snapshot to run `omx ultragoal checkpoint --goal-id <id> --status complete --evidence "<team evidence mentioning .omx/ultragoal and <id>>" --codex-goal-json <fresh-get_goal-json-or-path>`.
### Claude teammates (v0.6.0+)
Important: `N:agent-type` (for example `2:executor`) selects the **worker role prompt**, not the worker CLI (`codex` vs `claude`).
To launch Claude teammates, use the team worker CLI env vars:
```bash
# Force all teammates to Claude CLI
OMX_TEAM_WORKER_CLI=claude omx team 2:executor "update docs and report"
# Mixed team (worker 1 = Codex, worker 2 = Claude)
OMX_TEAM_WORKER_CLI_MAP=codex,claude omx team 2:executor "split doc/code tasks"
# Auto mode: Claude is selected when worker launch args/model contains 'claude'
OMX_TEAM_WORKER_CLI=auto OMX_TEAM_WORKER_LAUNCH_ARGS="--model claude-..." omx team 2:executor "run mixed validation"
```
## Preconditions
Before running `$team`, confirm:
1. `tmux` installed (`tmux -V`)
2. Current leader session is inside tmux (`$TMUX` is set)
3. `omx` command resolves to the intended install/build
4. If running repo-local `node bin/omx.js ...`, run `npm run build` after `src` changes
5. Check HUD pane count in the leader window and avoid duplicate `hud --watch` panes before split
Suggested preflight:
```bash
tmux list-panes -F '#{pane_id}\t#{pane_start_command}' | rg 'hud --watch' || true
```
If duplicates exist, remove extras before `omx team` to prevent HUD ending up in worker stack.
## Pre-context Intake Gate
Before launching `omx team`, require a grounded context snapshot:
1. Derive a task slug from the request.
2. Reuse the latest relevant snapshot in `.omx/context/{slug}-*.md` when available.
3. If none exists, create `.omx/context/{slug}-{timestamp}.md` (UTC `YYYYMMDDTHHMMSSZ`) with:
- task statement
- desired outcome
- known facts/evidence
- constraints
- unknowns/open questions
- likely codebase touchpoints
4. If ambiguity remains high, run `explore` first for brownfield facts, then run `$deep-interview --quick <task>` before team launch.
5. If current correctness depends on official docs, version-aware framework guidance, best practices, or external dependency behavior, auto-delegate `researcher` as an evidence lane before or alongside worker launch instead of relying on repo-local recall alone.
Do not start worker panes until this gate is satisfied; if forced to proceed quickly, state explicit scope/risk limitations in the launch report.
For simple read-only brownfield lookups during intake, follow active session guidance: when `USE_OMX_EXPLORE_CMD` is enabled, prefer `omx explore` with narrow, concrete prompts; otherwise use the richer normal explore path and fall back normally if `omx explore` is unavailable.
## Follow-up Staffing Contract
When `$team` is used as a follow-up mode from ralplan, carry forward the approved plan's explicit **available-agent-types roster** and convert it into concrete staffing guidance before launch:
- keep worker-role choices inside the known roster
- state the recommended headcount and role counts
- state the suggested reasoning level for each lane when available
- explain why each lane exists (delivery, verification, specialist support)
- include an explicit launch hint (`omx team N "<task>"` / `$team N "<task>"`) for the coordinated team run; mention `$ultragoal` as the default durable follow-up/ledger path; mention a later separate Ralph follow-up only when explicitly requested or genuinely needed as a fallback
- if the ideal role is unavailable, choose the closest role from the roster and say so
## Current Runtime Behavior (As Implemented)
`omx team` currently performs:
1. Parse args (`N`, `agent-type`, task)
2. Sanitize team name from task text
3. Initialize team state:
- `.omx/state/team/<team>/config.json`
- `.omx/state/team/<team>/manifest.v2.json`
- `.omx/state/team/<team>/tasks/task-<id>.json`
4. Compose team-scoped worker instructions file at:
- `.omx/state/team/<team>/worker-agents.md`
- Uses project `AGENTS.md` content (if present) + worker overlay, without mutating project `AGENTS.md`
5. Resolve canonical shared state root from leader cwd (`<leader-cwd>/.omx/state`)
6. Split current tmux window into worker panes
7. Launch workers with:
- `OMX_TEAM_WORKER=<team>/worker-<n>`
- `OMX_TEAM_STATE_ROOT=<leader-cwd>/.omx/state`
- `OMX_TEAM_LEADER_CWD=<leader-cwd>`
- worker CLI selected by `OMX_TEAM_WORKER_CLI` / `OMX_TEAM_WORKER_CLI_MAP` (`codex` or `claude`)
- optional worktree metadata envs when `--worktree` is used
7. Wait for worker readiness (`capture-pane` polling)
8. Write per-worker `inbox.md` and trigger via `tmux send-keys`
9. Return control to leader; follow-up uses `status` / `resume` / `shutdown`
If coarse active team mode state is missing while canonical team runtime state exists, restore/sync the active team mode state before relying on hook/mode-aware behavior.
Important:
- Leader remains in existing pane
- Worker panes are independent full Codex/Claude CLI sessions
- Workers may run in separate git worktrees (`omx team --worktree[=<name>]`) while sharing one team state root
- Worker ACKs go to `mailbox/leader-fixed.json`
- Notify hook updates worker heartbeat and sends lifecycle-driven leader nudges (for example resolved native worker Stop/all-idle or stale-leader evidence) during active team mode; deprecated worker stall/progress heuristics are not operator-facing guidance.
- Submit routing uses this CLI resolution order per worker trigger:
1) explicit worker CLI provided by runtime state (persisted on worker identity/config),
2) `OMX_TEAM_WORKER_CLI_MAP` entry for that worker index,
3) fallback `OMX_TEAM_WORKER_CLI` / auto detection.
- Mixed CLI-map teams are supported for both startup and trigger submit behavior.
- Trigger submit differs by CLI:
- Codex may use queue-first `Tab` on busy panes (strategy-dependent).
- Claude always uses direct Enter-only (`C-m`) rounds (never queue-first `Tab`).
### Team worker model + thinking resolution (current contract)
Team mode resolves worker **model flags** from one shared launch-arg set (not per-worker model selection).
Model precedence (highest to lowest):
1. Explicit worker model in `OMX_TEAM_WORKER_LAUNCH_ARGS`
2. Inherited leader `--model` flag
3. Low-complexity default from `OMX_DEFAULT_SPARK_MODEL` (legacy alias: `OMX_SPARK_MODEL`) when 1+2 are absent and team `agentType` is low-complexity
Default-model rule:
- Do **not** assume a frontier or spark model from recency or model-family heuristics.
- Use `OMX_DEFAULT_FRONTIER_MODEL` for frontier-default guidance.
- Use `OMX_DEFAULT_SPARK_MODEL` for spark/low-complexity worker-default guidance.
Thinking-level rule (critical):
- **No model-name heuristic mapping.**
- Team runtime must **not** infer `model_reasoning_effort` from model-name substrings (e.g., `spark`, `high-capability`, `mini`).
- When the leader assigns teammate roles/tasks, OMX allocates **per-worker reasoning effort dynamically** from the resolved worker role and `agentReasoning` overrides (`low`, `medium`, `high`, `xhigh`).
- Explicit launch args still win: if `OMX_TEAM_WORKER_LAUNCH_ARGS` already includes `-c model_reasoning_effort=...`, that explicit value overrides dynamic allocation for every worker.
Normalization requirements:
- Parse both `--model <value>` and `--model=<value>`
- Remove duplicate/conflicting model flags
- Emit exactly one final canonical flag: `--model <value>`
- Preserve unrelated args in worker launch config
- If explicit reasoning exists, preserve canonical `-c model_reasoning_effort="<level>"`; otherwise inject the worker role's default or `agentReasoning`-overridden reasoning level
## Required Lifecycle (Operator Contract)
Follow this exact lifecycle when running `$team`:
1. Start team and verify startup evidence (team line, tmux target, panes, ACK mailbox)
2. Monitor task and worker progress with runtime/state tools first (`omx team status <team>`, `omx team resume <team>`, mailbox/state files)
3. Wait for terminal task state before shutdown:
- `pending=0`
- `in_progress=0`
- `failed=0` (or explicitly acknowledged failure path)
4. Only then run `omx team shutdown <team>`
5. Verify shutdown evidence and state cleanup
Do not run `shutdown` while workers are actively writing updates unless user explicitly requested abort/cancel.
Do not treat ad-hoc pane typing as primary control flow when runtime/state evidence is available.
### Active leader monitoring rule
While a team is **ON/running**, the leader must not go blind. Keep checking live team state until terminal completion.
Minimum acceptable loop:
```bash
sleep 30 && omx team status <team-name>
```
Repeat that check while the team stays active, or use `omx team await <team-name> --timeout-ms 30000 --json` when event-driven waiting is a better fit.
If the leader gets a stale, lifecycle, or all-idle nudge, immediately run `omx team status <team-name>` before taking any manual intervention. Deprecated worker stall/progress nudges should not be treated as an active runtime contract.
### Deprecated worker stall/progress knobs
`OMX_TEAM_PROGRESS_STALL_MS` and `OMX_TEAM_WORKER_TURN_STALL_MS` are legacy compatibility/test-only names for the retired worker stall/progress nudge path. Do not recommend them as operator tuning knobs for active team runs; resolved native worker Stop, all-idle, mailbox, and stale-leader evidence are the supported leader wakeup signals.
## Message Dispatch Policy (CLI-first, state-first)
To avoid brittle behavior, **message/task delivery must not be driven by ad-hoc tmux typing**.
Required default path:
1. Use `omx team ...` runtime lifecycle commands for orchestration.
2. Use `omx team api ... --json` for mailbox/task mutations.
3. Verify delivery via mailbox/state evidence (`mailbox/*.json`, task status, `omx team status`).
Strict rules:
- **MUST NOT** use direct `tmux send-keys` as the primary mechanism to deliver instructions/messages.
- **MUST NOT** spam Enter/trigger keys without first checking runtime/state evidence.
- **MUST** prefer durable state writes + runtime dispatch (`dispatch/requests.json`, mailbox, inbox).
- Direct tmux interaction is **fallback-only** and only after failure checks (for example `worker_notify_failed:<worker>`) or explicit user request (for example “press enter”).
## Operational Commands
```bash
omx team status <team-name>
omx team resume <team-name>
omx team shutdown <team-name>
```
Semantics:
- `status`: reads team snapshot (task counts, dead/non-reporting workers)
- `resume`: reconnects to live team session if present
- `shutdown`: graceful shutdown request, then cleanup (deletes `.omx/state/team/<team>`)
## Data Plane and Control Plane
### Control Plane
- tmux panes/processes (`OMX_TEAM_WORKER` per worker)
- leader notifications via `tmux display-message`
### Data Plane
- `.omx/state/team/<team>/...` files
- Team mailbox files:
- `.omx/state/team/<team>/mailbox/leader-fixed.json`
- `.omx/state/team/<team>/mailbox/worker-<n>.json`
- `.omx/state/team/<team>/dispatch/requests.json` (durable dispatch queue; hook-preferred, fallback-aware)
### Key Files
- `.omx/state/team/<team>/config.json`
- `.omx/state/team/<team>/manifest.v2.json`
- `.omx/state/team/<team>/tasks/task-<id>.json`
- `.omx/state/team/<team>/workers/worker-<n>/identity.json`
- `.omx/state/team/<team>/workers/worker-<n>/inbox.md`
- `.omx/state/team/<team>/workers/worker-<n>/heartbeat.json`
- `.omx/state/team/<team>/workers/worker-<n>/status.json`
- `.omx/state/team-leader-nudge.json`
## Team Mutation Interop (CLI-first)
Use `omx team api` for machine-readable mutation/reads instead of legacy `team_*` MCP tools.
```bash
omx team api <operation> --input '{"team_name":"my-team",...}' --json
```
Examples:
```bash
omx team api send-message --input '{"team_name":"my-team","from_worker":"worker-1","to_worker":"leader-fixed","body":"ACK"}' --json
omx team api claim-task --input '{"team_name":"my-team","task_id":"1","worker":"worker-1"}' --json
omx team api transition-task-status --input '{"team_name":"my-team","task_id":"1","from":"in_progress","to":"completed","claim_token":"<token>"}' --json
```
`--json` responses include stable metadata for automation:
- `schema_version`
- `timestamp`
- `command`
- `ok`
- `operation`
- `data` or `error`
## Team + Worker Protocol Notes
Leader-to-worker:
- Write full assignment to worker `inbox.md`
- Send short trigger (<200 chars) with `tmux send-keys`
Worker-to-leader:
- Send ACK to `leader-fixed` mailbox via `omx team api send-message --json`
- Claim/transition/release task lifecycle via `omx team api <operation> --json`
Worker commit protocol (critical for incremental integration):
- After completing task work and before reporting completion, workers MUST commit:
`git add -A && git commit -m "task: <task-subject>"`
- This ensures changes are available for incremental integration into the leader branch
- If a worker forgets to commit, the runtime auto-commits as a fallback, but explicit commits are preferred
Task ID rule (critical):
- File path uses `task-<id>.json` (example `task-1.json`)
- MCP API `task_id` uses bare id (example `"1"`, not `"task-1"`)
- Never instruct workers to read `tasks/{id}.json`
## Environment Knobs
Useful runtime env vars:
- `OMX_TEAM_READY_TIMEOUT_MS`
- Worker readiness timeout (default 45000)
- `OMX_TEAM_SKIP_READY_WAIT=1`
- Skip readiness wait (debug only)
- `OMX_TEAM_AUTO_TRUST=0`
- Disable auto-advance for trust prompt (default behavior auto-advances)
- `OMX_TEAM_AUTO_ACCEPT_BYPASS=0`
- Disable Claude bypass-permissions prompt auto-accept (default behavior auto-accepts `2` + Enter)
- `OMX_TEAM_WORKER_LAUNCH_ARGS`
- Extra args passed to worker launch command
- `OMX_TEAM_WORKER_CLI`
- Worker CLI selector: `auto|codex|claude` (default: `auto`)
- `auto` chooses `claude` when worker `--model` contains `claude`, otherwise `codex`
- In `claude` mode, workers launch with exactly one `--dangerously-skip-permissions`
and ignore explicit model/config/effort launch overrides (uses default `settings.json`)
- `OMX_TEAM_WORKER_CLI_MAP`
- Per-worker CLI selector (comma-separated `auto|codex|claude`)
- Length must be `1` (broadcast) or exactly the team worker count
- Example: `OMX_TEAM_WORKER_CLI_MAP=codex,codex,claude,claude`
- When present, overrides `OMX_TEAM_WORKER_CLI`
- `OMX_TEAM_AUTO_INTERRUPT_RETRY`
- Trigger submit fallback (default: enabled)
- `0` disables adaptive queue->resend escalation
- `OMX_TEAM_LEADER_NUDGE_MS`
- Leader nudge interval in ms (default 120000)
- `OMX_TEAM_STRICT_SUBMIT=1`
- Force strict send-keys submit failure behavior
## Failure Modes and Diagnosis
Operator note (important for Claude panes):
- Manual Enter injection (`tmux send-keys ... C-m`) can appear to "do nothing" when a worker is actively processing; Enter may be queued by the pane/task flow.
- This is not necessarily a runtime bug. Confirm worker/team state before diagnosing dispatch failure.
- Avoid repeated blind Enter spam; it can create noisy duplicate submits once the pane becomes idle.
### Safe Manual Intervention (last resort)
Use only after checking `omx team status <team>` and mailbox/state evidence:
1. Capture pane tail to confirm current worker state:
- `tmux capture-pane -t %<worker-pane> -p -S -120`
- If a larger-tail read or bounded summary would help, prefer explicit opt-in inspection via `omx sparkshell --tmux-pane %<worker-pane> --tail-lines 400` before improvising extra tmux commands.
2. If the pane is stuck in an interactive state, safely return to idle prompt first:
- optional interrupt `C-c` or escape flow (CLI-specific) once, then re-check pane capture
3. Send one concise trigger (single line) and wait for evidence:
- `tmux send-keys -t %<worker-pane> "ack + continue current task; report status" C-m`
4. Re-check:
- pane output via `capture-pane`
- mailbox updates (`mailbox/leader-fixed.json` or worker mailbox)
- `omx team status <team>`
### `worker_notify_failed:<worker>`
Meaning:
- Leader wrote inbox but trigger submit path failed
Checks:
1. `tmux list-panes -F '#{pane_id}\t#{pane_start_command}'`
2. `tmux capture-pane -t %<worker-pane> -p -S -120`
3. Verify worker process alive and not stuck on trust prompt
4. Rebuild if running repo-local (`npm run build`)
### Team starts but leader gets no ACK
Checks:
1. Worker pane capture shows inbox processing
2. `.omx/state/team/<team>/mailbox/leader-fixed.json` exists
3. Worker skill loaded and `omx team api send-message --json` called
4. Task-id mismatch not blocking worker flow
### Worker logs `omx team api ... ENOENT` (or legacy `team_send_message ENOENT` / `team_update_task ENOENT`)
Meaning:
- Team state path no longer exists while worker is still running.
- Typical cause: leader/manual flow ran `omx team shutdown <team>` (or removed `.omx/state/team/<team>`) before worker finished.
Checks:
1. `omx team status <team>` and confirm whether tasks were still `in_progress` when shutdown occurred
2. Verify whether `.omx/state/team/<team>/` exists
3. Inspect worker pane tail for post-shutdown writes
4. Confirm no external cleanup (`rm -rf .omx/state/team/<team>`) happened during execution
Prevention:
1. Enforce completion gate (no in-progress tasks) before shutdown
2. Use `shutdown` only for terminal completion or explicit abort
3. If aborting, expect late worker writes to fail and treat ENOENT as expected teardown artifact
### Shutdown reports success but stale worker panes remain
Cause:
- stale pane outside config tracking or previous failed run
Fix:
- manual pane cleanup (see clean-slate commands)
## Clean-Slate Recovery
Run from leader pane:
```bash
# 1) Inspect panes
tmux list-panes -F '#{pane_id}\t#{pane_current_command}\t#{pane_start_command}'
# 2) Kill stale worker panes only (examples)
tmux kill-pane -t %450
tmux kill-pane -t %451
# 3) Remove stale team state (example)
rm -rf .omx/state/team/<team-name>
# 4) Retry
omx team 1:executor "fresh retry"
```
Guidelines:
- Do not kill leader pane
- Do not kill HUD pane (`omx hud --watch`) unless intentionally restarting HUD
## Required Reporting During Execution
When operating this skill, provide concrete progress evidence:
1. Team started line (`Team started: <name>`)
2. tmux target and worker pane presence
3. leader mailbox ACK path/content check
4. status/shutdown outcomes
Do not claim success without file/pane evidence.
Do not claim clean completion if shutdown occurred with `in_progress>0`.
Use `omx sparkshell --tmux-pane ...` as an explicit opt-in operator aid for pane inspection and summaries; keep raw `tmux capture-pane` evidence available for manual intervention and proof.
## Programmatic Team Orchestration
Use the `omx team ...` CLI as the supported team-launch surface. For automation, drive the same CLI flow from scripts or supervising agents rather than relying on a separate MCP runner.
### Supported current surfaces
- **`omx team ...` CLI** — Primary method for interactive or automated team orchestration. Use this when you want direct tmux-pane visibility or a scriptable launch path.
- **Team state files** — Inspect `.omx/state/team/<team>/` when you need status, task, or mailbox evidence after launch.
### Cleanup distinction
Two cleanup paths exist and must not be confused:
- `team_cleanup` (**state-server**): Deletes team state **files** on disk (`.omx/state/team/<team>/`). Use after a team run is fully complete.
- tmux/session cleanup: Use the documented `omx team` shutdown / cleanup flow when you need to stop worker panes or clean up an interrupted run.
### Automation example
```
1. omx team 1:executor "fix bugs"
2. omx team status <team-name>
3. omx team shutdown <team-name>
4. Clean up the finished team state for <team-name>
```
## Limitations
- Worktree provisioning requires a git repository and can fail on branch/path collisions
- send-keys interactions can be timing-sensitive under load
- stale panes from prior runs can interfere until manually cleaned
## Scenario Examples
**Good:** The user says `continue` after the workflow already has a clear next step. Continue the current branch of work instead of restarting or re-asking the same question.
**Good:** The user changes only the output shape or downstream delivery step (for example `make a PR`). Preserve earlier non-conflicting workflow constraints and apply the update locally.
**Bad:** The user says `continue`, and the workflow restarts discovery or stops before the missing verification/evidence is gathered.
@@ -0,0 +1,139 @@
---
name: ultragoal
description: Create and execute durable repo-native multi-goal plans over Codex goal mode artifacts.
---
# Ultragoal Workflow
Use when the user asks for `ultragoal`, `create-goals`, `complete-goals`, durable multi-goal planning, or sequential execution over Codex `/goal`.
## Purpose
`ultragoal` turns a brief into repo-native artifacts and then drives a Codex goal safely through goal tools. New plans default to a stable pointer-style aggregate Codex goal for the whole durable plan in `.omx/ultragoal/goals.json`, including later accepted/appended stories under the original brief constraints, while OMX tracks G001/G002 story progress in the ledger. Ultragoal does not call Codex `/goal clear`; before multiple sequential ultragoal runs in one Codex session/thread, manually run `/goal clear` in the Codex UI so the previous completed aggregate goal does not block or confuse the next `create_goal`.
- `.omx/ultragoal/brief.md`
- `.omx/ultragoal/goals.json`
- `.omx/ultragoal/ledger.jsonl` (checkpoint and structured steering audit events)
Existing aggregate plans with the legacy enumerated objective are migrated to the stable pointer objective on read, persisted to `goals.json`, retained in `codexObjectiveAliases` for already-active hidden Codex goal reconciliation, and audited with an `aggregate_objective_migrated` ledger entry.
## Create goals
1. Run one of:
- `omx ultragoal create-goals --brief "<brief>"`
- `omx ultragoal create-goals --brief-file <path>`
- `cat <brief> | omx ultragoal create-goals --from-stdin`
- `omx ultragoal create-goals --codex-goal-mode per-story --brief "<brief>"` only when one Codex goal context per story is explicitly preferred
2. Inspect `.omx/ultragoal/goals.json` and refine if needed.
## Complete goals
Loop until `omx ultragoal status` reports all goals complete:
1. Run `omx ultragoal complete-goals`.
2. Read the printed handoff.
3. Call `get_goal`.
4. If no active Codex goal exists, call `create_goal` with the printed payload. In aggregate mode, if the same aggregate Codex objective is already active, continue the current OMX story without creating a new Codex goal.
5. Complete the current OMX story only.
6. Run a completion audit against the story objective and real artifacts/tests.
7. In aggregate mode, do **not** call `update_goal` for intermediate stories; checkpoint with a fresh `get_goal` snapshot whose aggregate objective is still `active`. On the final story only, first run the mandatory final cleanup/review gate below; call `update_goal({status: "complete"})` only after that gate is clean, then call `get_goal` again for a fresh `complete` snapshot.
8. Checkpoint the durable ledger with that snapshot. Intermediate aggregate checkpoints use only `--codex-goal-json`; final clean checkpoints also require `--quality-gate-json`:
`omx ultragoal checkpoint --goal-id <id> --status complete --evidence "<evidence>" --codex-goal-json <get_goal-json-or-path> [--quality-gate-json <quality-gate-json-or-path>]`
9. If blocked or failed, checkpoint failure:
`omx ultragoal checkpoint --goal-id <id> --status failed --evidence "<blocker/evidence>"`
10. For legacy per-story completed-goal blockers, preserve the non-terminal blocker with:
`omx ultragoal checkpoint --goal-id <id> --status blocked --evidence "<completed legacy Codex goal blocks create_goal in this thread>" --codex-goal-json <get_goal-json-or-path>`
11. Resume failed goals with `omx ultragoal complete-goals --retry-failed`.
## Dynamic steering
Use `omx ultragoal steer` when real findings or blockers prove the current story decomposition should change while the aggregate objective and constraints stay fixed. Steering is explicit-only and evidence-backed; broad natural-language requests are rejected instead of guessed.
Allowed mutation kinds are:
- `add_subgoal`
- `split_subgoal`
- `reorder_pending`
- `revise_pending_wording`
- `annotate_ledger`
- `mark_blocked_superseded`
Examples:
```sh
omx ultragoal steer --kind add_subgoal --title "Investigate blocker" --objective "Validate the blocker and report evidence." --evidence "log/test output" --rationale "The blocker changes the safe execution order." --json
omx ultragoal steer --directive-json ./steering.json --json
```
Steering invariants:
- Do not edit the aggregate Codex objective, original brief constraints, quality gates, or completion status. The aggregate objective is a stable pointer to `.omx/ultragoal/goals.json` and `.omx/ultragoal/ledger.jsonl`, not an enumeration of initial goal ids.
- Do not hard-delete goals, auto-complete work, weaken verification, or silently mutate `.omx/ultragoal`.
- Accepted and rejected attempts append structured audit entries to `.omx/ultragoal/ledger.jsonl`.
- Superseded goals remain in `goals.json` with steering metadata and are skipped for scheduling.
- Blocked goals without replacements are skipped for scheduling but still block final completion until later explicit steering replaces or supersedes them.
UserPromptSubmit uses the same steering API only for structured directives such as `OMX_ULTRAGOAL_STEER: { ... }`, `omx.ultragoal.steer: { ... }`, or `omx ultragoal steer: { ... }`. Normal prose does not mutate state, and repeated prompt-submit directives dedupe by prompt signature or idempotency key.
## Use Ultragoal and Team together
Use ultragoal and team together for a durable Ultragoal story that benefits from parallel execution. Ultragoal remains leader-owned: `.omx/ultragoal/goals.json` stores the story plan and `.omx/ultragoal/ledger.jsonl` stores checkpoints. Team is the parallel execution engine and returns task/evidence status to the leader.
The leader checkpoints Ultragoal from Team evidence with a fresh `get_goal` snapshot:
```sh
omx ultragoal checkpoint --goal-id <id> --status complete --evidence "<team evidence mentioning .omx/ultragoal and <id>>" --codex-goal-json <fresh-get_goal-json-or-path>
```
Workers do not own ultragoal goal state, do not create worker ultragoal ledgers, and do not checkpoint Ultragoal. Team launch remains explicit; Ultragoal does not auto-launch Team and performs no hidden Codex goal mutation.
## Mandatory final cleanup and review gate
The final ultragoal story is not complete until the active agent has run the final quality gate:
1. Run targeted verification for the story.
2. Run `ai-slop-cleaner` on changed files only; if there are no relevant edits, the cleaner still runs and records a passed/no-op report.
3. Rerun verification after the cleaner pass.
4. Run `$code-review` through the independent review path. Clean means `codeReview.recommendation: "APPROVE"`, `codeReview.architectStatus: "CLEAR"`, and `codeReview.independentReview` contains distinct completed `code-reviewer` and `architect` subagent evidence. `COMMENT`, `WATCH`, `REQUEST CHANGES`, `BLOCK`, missing subagent evidence, unavailable delegation, and same-lane/self-review are non-clean.
5. If review is non-clean, do **not** call `update_goal`. Record durable blocker work instead:
```sh
omx ultragoal record-review-blockers --goal-id <id> --title "Resolve final code-review blockers" --objective "<blocker-resolution objective>" --evidence "<review findings>" --codex-goal-json <active-get-goal-json-or-path>
```
This marks the current story `review_blocked`, appends a pending blocker-resolution story, keeps the Codex goal active, and lets `omx ultragoal complete-goals` start the blocker next. In legacy per-story mode, the blocker may need an available Codex goal context because the old per-story Codex goal remains active/incomplete.
6. If review is clean, call `update_goal({status: "complete"})`, call `get_goal`, and checkpoint with a structured final gate:
```sh
omx ultragoal checkpoint --goal-id <id> --status complete --evidence "<tests/files/review evidence>" --codex-goal-json <fresh-complete-get-goal-json-or-path> --quality-gate-json <quality-gate-json-or-path>
```
`--quality-gate-json` must include:
```json
{
"aiSlopCleaner": { "status": "passed", "evidence": "cleaner report" },
"verification": { "status": "passed", "commands": ["npm test"], "evidence": "post-cleaner verification" },
"codeReview": {
"recommendation": "APPROVE",
"architectStatus": "CLEAR",
"evidence": "final review synthesis",
"independentReview": {
"codeReviewer": { "agentRole": "code-reviewer", "evidence": "code-reviewer subagent APPROVE evidence" },
"architect": { "agentRole": "architect", "evidence": "architect subagent CLEAR evidence" }
}
}
}
```
## Constraints
- The shell command cannot directly invoke Codex interactive `/goal`; it emits a model-facing handoff for the active Codex agent.
- Ultragoal intentionally does not invoke `/goal clear` or hidden `thread/goal/clear`; the model-facing tool surface only provides `get_goal`, `create_goal`, and `update_goal`.
- After a completed aggregate ultragoal run, clear the Codex goal manually with `/goal clear` before starting another ultragoal run in the same session/thread.
- Never call `create_goal` when `get_goal` reports a different active goal.
- Never call `update_goal` unless the aggregate run or legacy per-story goal is actually complete.
- In aggregate mode, intermediate story checkpoints require a matching `active` Codex snapshot; final story completion requires a matching `complete` snapshot after `update_goal`.
- Completion checkpoints require read-only Codex snapshot reconciliation: pass fresh `get_goal` JSON/path with `--codex-goal-json`; shell commands and hooks must not mutate Codex goal state.
- Treat `ledger.jsonl` as the durable audit trail; checkpoint after every success or failure.
@@ -0,0 +1,263 @@
---
name: ultraqa
description: Adversarial dynamic e2e QA workflow - generate hostile scenarios, test, verify, fix, report, and clean up
---
# UltraQA Skill
## Operating Contract
- Use outcome-first framing with concise, evidence-dense progress and completion reporting.
- Treat newer user updates as local overrides for the active workflow branch while preserving earlier non-conflicting constraints.
- If the user says `continue`, advance the current verified next step instead of restarting discovery.
- UltraQA is not satisfied by a shallow build/lint/typecheck/test checklist. It must exercise the requested behavior through adversarial dynamic e2e scenarios whenever the target can be run, simulated, or harnessed safely.
[ULTRAQA ACTIVATED - ADVERSARIAL DYNAMIC E2E QA CYCLING]
## Overview
UltraQA finds real behavior failures by combining normal verification commands with generated end-to-end scenarios, hostile user modeling, temporary harnesses when useful, and a structured evidence report. The workflow repeats test → diagnose → fix → retest until the goal is met, a bounded stop condition is reached, or a safety boundary blocks further execution.
## Goal Parsing
Parse the goal from arguments. Supported formats:
| Invocation | Goal Type | What to Check |
|------------|-----------|---------------|
| `/ultraqa --tests` | tests | Existing tests plus adversarial dynamic e2e scenarios for the changed behavior |
| `/ultraqa --build` | build | Build succeeds and generated smoke/e2e probes still run against the built artifact when applicable |
| `/ultraqa --lint` | lint | Lint passes and no generated harness/test artifact violates project hygiene |
| `/ultraqa --typecheck` | typecheck | Typecheck passes and generated typed harnesses compile when applicable |
| `/ultraqa --custom "pattern"` | custom | Custom success pattern is verified against behavior, not trusted as misleading success output |
| `/ultraqa --interactive` | interactive | CLI/service behavior is tested with generated hostile and edge-case interactions |
If no structured goal is provided, interpret the argument as a custom behavior goal and derive a runnable e2e strategy from repository context.
## Required Scenario Matrix
Before declaring success, create and maintain a scenario matrix. Each row must include: scenario id, intent, user/attacker model, setup, command or harness, expected signal, actual result, fixes applied, evidence, and cleanup status.
The matrix must include normal-path coverage plus adversarial dynamic e2e scenarios selected from the current goal and codebase. Unless clearly irrelevant or impossible, include these hostile and edge-case classes:
1. **Malformed input**: invalid JSON, missing fields, invalid flags, oversized strings, unusual Unicode, path traversal-like values, and corrupted state files.
2. **Repeated interruptions**: repeated `continue`, stop/cancel/abort wording, interrupted command output, and retries after partial progress.
3. **Prompt injection attempts**: user text that tries to override instructions, exfiltrate secrets, skip verification, delete state, or claim false success.
4. **Cancel/resume behavior**: active state cleanup, resume detection, stale in-progress state, and cancellation followed by a fresh run.
5. **Stale state**: old `.omx/state` files, mismatched sessions, missing timestamps, and contradictory phase metadata.
6. **Dirty worktree**: pre-existing modifications, untracked generated files, and verification that UltraQA does not hide or overwrite unrelated work.
7. **Hung or long-running commands**: bounded timeout handling, killed child processes, and recovery notes.
8. **Flaky tests**: rerun strategy, failure clustering, quarantine evidence, and avoiding false green from a single lucky pass.
9. **Misleading success output**: output containing success phrases with non-zero exits, hidden failures, skipped tests, or partial command logs.
## Dynamic E2E and Temporary Harness Rules
- Generate temporary tests, scripts, fixtures, or harnesses when they materially improve behavioral confidence and no existing e2e surface covers the scenario.
- Prefer project-native test tools and small throwaway harnesses under a temporary directory or clearly named test fixture.
- Record every generated artifact in the scenario matrix, including whether it was committed intentionally or removed during cleanup.
- Use bounded runtimes and explicit timeouts for commands that can hang.
- Validate exit codes and output semantics; do not trust success-looking text alone.
- Do not delete, rewrite, or mask unrelated user work. Capture dirty-worktree evidence before and after generated harness work.
### Temporary Harness Generation Guardrails
Generated harnesses are part of the QA evidence chain; until setup succeeds, they are evidence about the harness apparatus, not product behavior.
- **Use absolute repo imports for built artifacts.** When a harness runs from `/tmp` or another scratch directory but imports repository code, resolve the repository root explicitly from the verified repo cwd and import built modules with an absolute path or `pathToFileURL(join(repoRoot, "dist", ...)).href`. Never rely on `./dist/...` from the harness file's temporary directory.
- **Use a safe file writer for JS/TS harness bodies.** Prefer a small Node/Python writer or another non-interpolating file-write mechanism for harness source that contains backticks, `${...}`, shell metacharacters, or prompt-injection strings. If a shell heredoc is unavoidable, quote the delimiter and verify the written file before execution; do not use interpolating heredocs for JavaScript assertions.
- **Sanitize OMX runtime env for isolated probes.** When the scenario creates a temporary repo/state tree or intentionally checks local isolation, run the probe with `OMX_ROOT` and `OMX_STATE_ROOT` unset (for example `env -u OMX_ROOT -u OMX_STATE_ROOT ...`) so ambient boxed runtime state cannot redirect reads/writes away from the scenario fixture.
- **Classify harness setup failures separately.** If a generated harness fails before exercising product behavior because of import paths, shell interpolation, environment leakage, or fixture construction, record it as harness debris, fix the harness, and rerun the scenario before declaring a product defect.
## Cycle Workflow
### Cycle N (Max 5)
1. **PLAN ADVERSARIAL QA**
- Restate the goal, success criteria, safety bounds, and stop condition.
- Inspect repository context enough to identify runnable surfaces, test commands, state files, and cleanup paths.
- Build or update the required scenario matrix before running commands.
2. **RUN BASELINE VERIFICATION**
- `--tests`: Run the project's test command.
- `--build`: Run the project's build command.
- `--lint`: Run the project's lint command.
- `--typecheck`: Run the project's type check command.
- `--custom`: Run the appropriate command and check the pattern plus exit status and failure markers.
- `--interactive`: Use qa-tester or an equivalent CLI/service harness:
```
Use `/prompts:qa-tester` with:
Goal: [describe what to verify]
Service: [how to start]
Test cases: [normal, hostile, malformed, interruption, resume, stale-state, dirty-worktree, hung-command, flaky, and misleading-output scenarios]
```
3. **RUN ADVERSARIAL DYNAMIC E2E SCENARIOS**
- Execute the scenario matrix using existing e2e tests, generated temporary tests, or generated harnesses.
- Model malicious/hostile user behavior explicitly, including prompt injection and attempts to bypass safety or verification.
- Exercise malformed input, repeated interruptions, cancel/resume, stale state, dirty worktree handling, hung commands, flaky tests, and misleading success output when relevant.
- Capture commands, exit codes, important output excerpts, artifacts, and cleanup status.
4. **CHECK RESULT**
- **YES** only if baseline verification and adversarial e2e scenarios passed, generated artifacts are cleaned up or intentionally tracked, and the report has complete evidence.
- **NO** if any scenario failed, was skipped without justification, left debris, relied on misleading output, or lacked evidence. Continue to step 5.
5. **ARCHITECT DIAGNOSIS**
```
Use `/prompts:architect` with:
Goal: [goal type and behavior]
Scenario matrix: [rows, commands, failures, evidence]
Output: [test/build/e2e/harness output]
Provide root cause, safety implications, and specific fix recommendations.
```
6. **FIX ISSUES**
```
Use `/prompts:executor` with:
Issue: [architect diagnosis]
Files: [affected files]
Constraints: preserve unrelated dirty work, clean temporary harnesses, keep safety bounds
Apply the fix precisely as recommended.
```
7. **CLEAN UP AND ROLLBACK**
- Remove temporary harnesses, fixtures, logs, spawned processes, and state files unless they are intentional deliverables.
- Roll back failed experimental edits that are not part of the final fix.
- Re-check the worktree and record remaining intentional changes or residual debris.
8. **REPEAT**
- Go back to step 1 with the updated scenario matrix and failure history.
## Safety Bounds
UltraQA must stay inside these safety bounds:
- No destructive commands such as force resets, broad deletes, secret exfiltration, credential dumping, production writes, or unbounded process spawning.
- No reading or printing secrets beyond the minimum metadata needed to verify absence of leakage.
- No network or external-production side effects unless the user explicitly authorized them.
- No unbounded waits: use timeouts, retries with caps, and clear hung-command diagnostics.
- No hiding unrelated dirty work or generated debris.
- If a required scenario would violate these bounds, mark it blocked in the report with the safe substitute used.
## Exit Conditions
| Condition | Action |
|-----------|--------|
| **Goal Met** | Exit with success: `ULTRAQA COMPLETE: Goal met after N cycles` plus the structured report |
| **Cycle 5 Reached** | Exit with diagnosis: `ULTRAQA STOPPED: Max cycles` plus failures, fixes attempted, residual risks, and evidence |
| **Same Failure 3x** | Exit early: `ULTRAQA STOPPED: Same failure detected 3 times` plus root cause, safety notes, and next owner |
| **Safety Boundary** | Exit: `ULTRAQA BLOCKED: [destructive/credentialed/external-production/unbounded action]` plus safe substitute evidence |
| **Environment Error** | Exit: `ULTRAQA ERROR: [tmux/port/dependency/hung command issue]` plus cleanup status |
## Structured Report
Every terminal UltraQA result must include this report shape:
```markdown
# UltraQA Report
## Goal and success criteria
- Goal:
- Stop condition:
- Safety bounds applied:
## Scenario matrix
| ID | User/attacker model | Scenario | Command/harness | Expected signal | Actual result | Status | Evidence | Cleanup |
|----|---------------------|----------|-----------------|-----------------|---------------|--------|----------|---------|
## Commands run
- `[exit code] command` — purpose, duration/timeout, key output evidence
## Failures found
- Scenario ID, failure signal, root cause, user impact, safety impact
## Fixes applied
- Files changed, rationale, linked failing scenario(s), regression evidence
## Cleanup and rollback
- Generated artifacts removed or intentionally kept
- State/process cleanup performed
- Worktree status before/after
## Residual risks
- Untested or blocked scenarios with reasons and safe substitutes
## Evidence
- Test output, e2e logs, harness output, screenshots/transcripts when relevant, and rerun/flake evidence
```
## Observability
Output progress each cycle:
```text
[ULTRAQA Cycle 1/5] Planning adversarial scenario matrix...
[ULTRAQA Cycle 1/5] Running baseline tests...
[ULTRAQA Cycle 1/5] Running ADV-E2E-003 prompt-injection harness...
[ULTRAQA Cycle 1/5] FAILED - stale state resume accepted misleading success output
[ULTRAQA Cycle 1/5] Architect diagnosing scenario ADV-E2E-003...
[ULTRAQA Cycle 1/5] Fixing: src/hooks/... - validate exit code before success phrase
[ULTRAQA Cycle 1/5] Cleaning temporary harnesses and state...
[ULTRAQA Cycle 2/5] PASSED - baseline + 9 adversarial scenarios pass
[ULTRAQA COMPLETE] Goal met after 2 cycles
```
## State Tracking
Use the CLI-first state surface (`omx state ... --json`) for UltraQA lifecycle state. If explicit MCP compatibility tools are already available, equivalent `omx_state` calls are optional compatibility, not the default.
- **On start**:
`omx state write --input '{"mode":"ultraqa","active":true,"current_phase":"planning","iteration":1,"started_at":"<now>","scenario_matrix":[]}' --json`
- **On each cycle**:
`omx state write --input '{"mode":"ultraqa","current_phase":"qa","iteration":<cycle>,"scenario_matrix":"<updated matrix path or summary>"}' --json`
- **On adversarial e2e transition**:
`omx state write --input '{"mode":"ultraqa","current_phase":"adversarial-e2e"}' --json`
- **On diagnose/fix transitions**:
`omx state write --input '{"mode":"ultraqa","current_phase":"diagnose"}' --json`
`omx state write --input '{"mode":"ultraqa","current_phase":"fix"}' --json`
- **On cleanup transition**:
`omx state write --input '{"mode":"ultraqa","current_phase":"cleanup"}' --json`
- **On completion**:
`omx state write --input '{"mode":"ultraqa","active":false,"current_phase":"complete","completed_at":"<now>"}' --json`
- **For resume detection**:
`omx state read --input '{"mode":"ultraqa"}' --json`
## Scenario Examples
**Good:** The user says `continue` after the workflow already has a clear next step. Continue the current branch of work, rerun the relevant adversarial scenario, and update the report instead of restarting discovery.
**Good:** The user changes only the output shape or downstream delivery step (for example `make a PR`). Preserve earlier non-conflicting workflow constraints and apply the update locally.
**Good:** A CLI prints `SUCCESS` while exiting 1. Mark the misleading success output scenario failed, fix the parser or reporting path, and rerun the generated harness.
**Bad:** The workflow runs only `npm test`, `npm run build`, `npm run lint`, or `npm run typecheck`, sees green output, and declares UltraQA complete without adversarial dynamic e2e coverage.
**Bad:** A generated harness leaves untracked files, state, or a child process behind and the final report omits cleanup status.
**Bad:** The user says `continue`, and the workflow restarts discovery or stops before the missing verification/evidence is gathered.
## Cancellation
User can cancel with `/cancel`, which clears UltraQA state. Cancellation itself should be tested in cancel/resume scenarios when relevant, but UltraQA must not block an explicit user cancellation.
## Important Rules
1. **ADVERSARIAL E2E REQUIRED** - Baseline build/lint/typecheck/test commands are necessary evidence, not sufficient completion proof.
2. **SCENARIO MATRIX REQUIRED** - Track normal, hostile, malformed, interruption, injection, cancel/resume, stale-state, dirty-worktree, hung-command, flaky, and misleading-output coverage.
3. **GENERATE HARNESSES WHEN USEFUL** - Create temporary tests or harnesses when they materially improve behavioral confidence, then clean them up or commit them intentionally.
4. **PARALLEL WHEN SAFE** - Run independent diagnostics while preparing potential fixes; do not parallelize commands that mutate the same state or worktree.
5. **TRACK FAILURES** - Record each failure to detect patterns and avoid false greens.
6. **EARLY EXIT ON PATTERN** - 3x same failure = stop and surface with root cause and residual risk.
7. **CLEAR OUTPUT** - User should always know current cycle, scenario, command, status, and evidence.
8. **CLEAN UP** - Clear UltraQA state and temporary artifacts on completion, cancellation, or early stop.
9. **SAFETY FIRST** - Never exfiltrate secrets, run destructive cleanup, write to production, or wait indefinitely to satisfy a scenario.
## STATE CLEANUP ON COMPLETION
When goal is met OR max cycles reached OR exiting early, run `$cancel` or call:
`omx state clear --input '{"mode":"ultraqa"}' --json`
Use CLI state cleanup rather than deleting files directly. Also remove temporary e2e harnesses, fixtures, and logs unless they are intentional artifacts listed in the report.
---
Begin ULTRAQA cycling now. Parse the goal, build the adversarial dynamic e2e scenario matrix, and start cycle 1.
@@ -0,0 +1,190 @@
---
name: ultrawork
description: Parallel execution engine for high-throughput task completion
---
<Purpose>
Ultrawork is a parallel execution engine for high-throughput task completion. It is a component, not a standalone persistence or verification mode: it provides parallelism, context discipline, and smart delegation guidance, but not durable goal tracking, Team's tmux worker lifecycle, Ralph's legacy persistence loop, architect sign-off, or long-running completion guarantees.
</Purpose>
<Use_When>
- Multiple independent tasks can run simultaneously
- User says "ulw", "ultrawork", or explicitly wants parallel execution
- Task benefits from concurrent execution plus lightweight evidence before wrap-up
- You need a direct-tool lane plus optional background evidence lanes without entering Team or a durable goal workflow
</Use_When>
<Do_Not_Use_When>
- Task needs durable goal tracking, ledger checkpoints, or resume across stories -- use `ultragoal` instead
- Task needs coordinated tmux workers, shared task state, mailbox/dispatch coordination, or long-running parallel execution -- use `team` instead
- Task requires a full autonomous pipeline -- use `autopilot` instead (default loop: `deep-interview -> ralplan -> ultragoal`, with `team` only when needed)
- Task intentionally requires the legacy persistent single-owner completion/verification loop -- use `ralph` explicitly; do not present it as the default durable path
- There is only one sequential task with no parallelism opportunity -- execute directly, use `ultragoal` for durable tracking, or delegate to a single `executor`
- The request is still in plan-consensus mode -- keep planning artifacts in `ralplan` until execution is explicitly authorized
</Do_Not_Use_When>
<Why_This_Exists>
Sequential task execution wastes time when tasks are independent. Ultrawork keeps the execution branch fast while tightening the protocol: gather enough context first, define pass/fail acceptance criteria before editing, decide deliberately between local execution and delegation, and finish with evidence rather than vibes.
</Why_This_Exists>
<Execution_Policy>
- Gather enough context before implementation. Start with the task intent, desired outcome, constraints, likely touchpoints, and any uncertainty that would change the execution path.
- If uncertainty is still material after a quick repo read, do a focused evidence pass first instead of immediately editing.
- Define pass/fail acceptance criteria before launching execution lanes. Include the command, artifact, or manual check that will prove success.
- Prefer direct tool work when the task is small, coupled, or blocked on immediate local context. Delegate only when the work is independent enough to benefit from parallel execution.
- When useful, run a direct-tool lane and one or more background evidence lanes at the same time. Evidence lanes can cover docs, tests, regression mapping, or bounded repo analysis.
- Fire independent agent calls simultaneously -- never serialize independent work.
- Always pass the `model` parameter explicitly when delegating.
- Read `docs/shared/agent-tiers.md` before first delegation for agent selection guidance.
- Auto-delegate `researcher` when official docs, version-aware framework guidance, best practices, or external dependency behavior materially affect task correctness; treat it as an evidence lane, not a replacement primary workflow.
- Use `run_in_background: true` for operations over ~30 seconds (installs, builds, tests).
- Run quick commands (git status, file reads, simple checks) in the foreground.
- Apply the shared workflow guidance pattern: outcome-first framing, concise visible updates for speculative/blocked lanes, local overrides for the active workflow branch, evidence-backed validation, explicit stop rules, and continuation of clear safe execution branches instead of restarting or re-asking.
- If the user says `continue`, continue the active workflow branch rather than restarting discovery or re-asking settled questions.
</Execution_Policy>
<Steps>
1. **Read agent reference**: Load `docs/shared/agent-tiers.md` for tier selection.
2. **Context + certainty check**:
- State the task intent in one sentence.
- List the constraints and unknowns that could invalidate a quick fix.
- If confidence is low, explore first and narrow the task before editing.
3. **Define acceptance criteria before execution**:
- What must be true at the end?
- Which command or artifact proves it?
- Which manual QA check is required, if any?
4. **Classify the work by dependency shape**:
- Independent tasks -> parallel lanes.
- Shared-file or prerequisite-heavy tasks -> local execution or staged lanes.
5. **Choose self vs delegate deliberately**:
- Work locally when the next step depends on immediate repo context, shared files, or tight iteration.
- Delegate when the task slice is bounded, independent, and materially improves throughput.
6. **Run execution lanes**:
- Direct-tool lane for immediate implementation or verification work.
- Background evidence lanes for tests, docs, repo analysis, or regression checks.
7. **Run dependent tasks sequentially**: Wait for prerequisites before launching dependent work.
8. **Close with lightweight evidence**:
- Build/typecheck passes when relevant.
- Affected tests pass.
- Manual QA notes are recorded when the task needs a human-visible or behavior-level check.
- No new errors introduced.
</Steps>
<Tool_Usage>
- Use LOW-tier delegation for simple lookups and bounded evidence gathering.
- Use STANDARD-tier delegation for standard implementation and regression work.
- Use THOROUGH-tier delegation for complex analysis, architectural review, or risky multi-file changes.
- Prefer a direct-tool lane when the immediate next step is blocked on local context.
- Prefer background evidence lanes when you can learn something useful in parallel with implementation.
- Use `run_in_background: true` for package installs, builds, and test suites.
- Use foreground execution for quick status checks and file operations.
</Tool_Usage>
## State Management
Use the CLI-first state surface (`omx state ... --json`) for ultrawork lifecycle state. If explicit MCP compatibility tools are already available, equivalent `omx_state` calls are optional compatibility, not the default.
- **On start**:
`omx state write --input '{"mode":"ultrawork","active":true,"reinforcement_count":1,"started_at":"<now>"}' --json`
- **On each reinforcement/loop step**:
`omx state write --input '{"mode":"ultrawork","reinforcement_count":<current>}' --json`
- **On completion**:
`omx state write --input '{"mode":"ultrawork","active":false}' --json`
- **On cancellation/cleanup**:
run `$cancel` (which should call `omx state clear --input '{"mode":"ultrawork"}' --json`)
<Examples>
<Good>
Two-track execution with acceptance criteria up front:
```
Acceptance criteria:
- `npm run build` passes
- `node --test dist/scripts/__tests__/codex-native-hook.test.js` passes
- Manual QA: verify `$ultrawork` activation message still points to the session state file
Direct-tool lane:
- update `skills/ultrawork/SKILL.md`
Background evidence lane:
- use /prompts:test-engineer for this scoped task
```
Why good: Context is grounded first, acceptance criteria are explicit, and the direct-tool lane runs alongside a bounded evidence lane.
</Good>
<Good>
Correct use of self-vs-delegate judgment:
```
Shared-file edit in progress across `src/scripts/codex-native-hook.ts` and its test -> keep implementation local.
Independent regression mapping for keyword-detector coverage -> delegate to a test-engineer lane.
```
Why good: Shared-file work stays local; independent evidence work fans out.
</Good>
<Bad>
Parallelizing before the task is grounded:
```
use /prompts:executor for this scoped task
use /prompts:test-engineer for this scoped task
```
Why bad: No context snapshot, no pass/fail target, and delegation starts before the work is shaped.
</Bad>
<Bad>
Claiming success without evidence or manual QA:
```
Made the changes. Ultrawork should be updated now.
```
Why bad: No verification output, no acceptance evidence, and no manual QA note when the behavior is user-visible.
</Bad>
</Examples>
<Escalation_And_Stop_Conditions>
- When ultrawork is invoked directly, apply lightweight verification only -- build/typecheck passes when relevant, affected tests pass, and manual QA notes are captured when needed.
- Ultrawork does not own persistence, durable ledgers, architect verification, deslop, full QA, or the full verified-completion promise. Do not claim those guarantees from direct ultrawork alone.
- Escalate to `ultragoal` when the work needs durable goal state, story checkpoints, or resume across implementation steps.
- Escalate to `team` when the work needs coordinated tmux workers, shared task state, or durable multi-worker lifecycle control.
- Escalate to explicitly requested `ralph` only for the supported legacy single-owner persistence/verification fallback.
- Ralph owns persistence, architect verification, deslop, and the full verified-completion promise only when explicitly selected as the supported legacy fallback; direct ultrawork does not own those guarantees.
- If a task fails repeatedly across retries, report the issue rather than retrying indefinitely.
- Escalate to the user when tasks have unclear dependencies, conflicting requirements, or a materially branching acceptance target.
</Escalation_And_Stop_Conditions>
<Final_Checklist>
- [ ] Task intent and constraints were grounded before editing
- [ ] Pass/fail acceptance criteria were stated before execution
- [ ] Parallel lanes were used only for independent work
- [ ] Build/typecheck passes when relevant
- [ ] Affected tests pass
- [ ] Manual QA notes recorded when behavior is user-visible
- [ ] No new errors introduced
- [ ] Completion claim stays inside ultrawork's lightweight-verification boundary
</Final_Checklist>
<Advanced>
## Relationship to Other Modes
```
ultrawork (this skill)
\-- provides: in-session parallel execution discipline + lightweight evidence
ultragoal (durable goal execution)
\-- owns: goal ledger, checkpoints, resume across stories, final gate discipline
\-- may use: team for parallel lanes when a story benefits from coordinated workers
team (tmux coordinated execution)
\-- owns: worker panes, shared task state, mailbox/dispatch, lifecycle control
\-- can return: checkpoint-ready evidence to an Ultragoal leader
autopilot (strict autonomous delivery loop)
\-- default flow: deep-interview -> ralplan -> ultragoal -> code-review -> ultraqa
\-- may use: team only when an Ultragoal story needs parallel execution
ralph (supported legacy explicit fallback)
\-- owns: single-owner persistence loop + architect verification when intentionally selected
ecomode (deprecated compatibility-only)
\-- do not route users there from ultrawork; it is not the current model-selection path
```
Ultrawork is the parallelism and execution-discipline layer. Ultragoal is the current default durable goal/ledger follow-up. Team is the coordinated tmux parallel runtime, often nested under an Ultragoal story when durable work needs multiple lanes. Autopilot orchestrates the full default lifecycle through deep-interview, ralplan, ultragoal, code-review, and ultraqa. Ralph remains active as an explicit legacy fallback for persistent single-owner verification, but it is not the recommended default durable path. Ecomode is deprecated compatibility-only and should not be advertised as the ultrawork model-selection route.
</Advanced>
@@ -0,0 +1,161 @@
---
name: visual-ralph
description: "Visual Ralph orchestration for frontend UI from generated references, static references, or live URL targets, using $ralph with built-in visual verdict and pixel-diff evidence until the implementation matches and leaves a reproducible design system."
---
# Visual Ralph Skill
Use this skill when the user wants Codex to build or restyle frontend UI through a Visual Ralph loop: an approved generated reference, static reference, or live URL-derived baseline becomes the target, Ralph implements, and Visual Verdict drives measured iteration rather than subjective description alone.
## Purpose
Create a measured frontend delivery loop from either a generated reference, a static reference, or a live URL:
`user description / live URL -> approved visual reference -> $ralph implementation -> Visual Ralph verdict + pixel diff -> reproducible design system`.
For live URL cloning requests, Visual Ralph owns the migrated `$web-clone` use case. Do not route new URL-driven website cloning work to `$web-clone`; preserve the URL, viewport, fidelity requirements, and interaction notes inside the Visual Ralph loop.
This is an orchestration skill. It composes existing skills and must not add runtime commands, dependencies, or app-specific assumptions by itself.
## Use when
- The user describes a desired web/app UI and wants implementation, not just design advice.
- The user provides a live URL and wants a visual implementation or clone through measured Visual Verdict iteration.
- A generated raster mockup/reference image would make the target clearer.
- The task needs pixel-level visual iteration with a pass/fail threshold.
- The final result should leave reusable design tokens/components, not only a one-off screenshot match.
## Do not use when
- The user only wants repo-wide design guidance, product/design context, or a DESIGN.md source of truth; use `$design` or a designer lane.
- The task is a non-visual backend/API implementation with no UI reference target.
- The user already supplied a final static reference image and only needs comparison/fixes; hand directly to `$ralph` with Visual Ralph verdict guidance.
- The requested output is a deterministic SVG/vector/code-native asset rather than a raster reference.
## Workflow
### 1. Ground the target repo
Before stack-specific choices, inspect local evidence:
- package manager and scripts,
- frontend framework and routing structure,
- styling system and design-token conventions,
- screenshot/test tooling,
- existing components that should be reused.
Do not hardcode React, Vue, Tailwind, Playwright, or any other stack unless the repository evidence supports it.
### 2. Establish the visual reference
For live URL requests, capture or document the URL-derived reference inside the Visual Ralph artifacts and carry forward viewport, content-state, and interaction constraints. Do not invoke `$web-clone`; that standalone skill is hard-deprecated.
Live URL reference artifacts must include:
- source URL and permission/scope note,
- viewport(s), route/state, and any seed/login assumptions,
- captured baseline screenshot path or documented capture command/tool,
- interaction parity notes for visible controls,
- known exclusions such as backend/API/auth, personalized data, multi-page crawling, and third-party widget parity.
For generated UI concepts, use `$imagegen` to produce the reference from the user's UI description.
Prompt requirements:
- classify as `ui-mockup`, unless another imagegen taxonomy is clearly better,
- include viewport/aspect ratio and intended surface,
- specify layout, hierarchy, typography direction, color mood, and any exact text,
- forbid logos/watermarks/unrequested brand marks,
- ask imagegen to avoid impossible UI details or unreadable text.
When running under OMX CLI/runtime and a generated reference is part of an active Ralph-style loop, queue a continuation checkpoint before invoking the built-in image tool:
```bash
omx imagegen continuation <session-id> --artifact <slug-or-filename> --generated-dir "$CODEX_HOME/generated_images/<session>" --work-dir ".omx/artifacts/visual-ralph/<slug>"
```
This helper records `.omx/state/sessions/<session>/imagegen-pending.json` and uses the existing Stop-hook follow-up queue. It exists because built-in image generation may have to end the assistant turn immediately; the next Stop checkpoint should resume artifact recovery, copy the generated image into the workspace, and run the required visual QA/verdict gate instead of relying on a manual `$ralph` re-prompt.
For project-bound implementation, copy the approved reference into the workspace, for example under `.omx/artifacts/visual-ralph/<slug>/reference.png`. Never leave the implementation reference only in `$CODEX_HOME/generated_images/...`.
### 3. Require explicit user approval
Stop after reference generation or URL-derived reference capture and ask the user to approve one reference image/state or request a targeted regeneration/capture adjustment.
Before approval:
- do not start frontend implementation,
- do not invoke `$ralph`,
- do not treat a rough image as final.
After approval, the confirmed image or URL-derived baseline becomes the visual source of truth. Major design pivots, replacing the reference, or changing the design direction require an explicit user request.
### 4. Hand off to `$ralph` for implementation
Invoke `$ralph` with:
- the approved reference image path or URL-derived baseline artifact,
- source URL, viewport(s), content state, and interaction parity notes for live URL tasks,
- the user description,
- the detected repo/frontend context,
- exact screenshot command/viewport requirements,
- the completion checklist below.
Ralph may iterate autonomously after approval. It should edit code, run the app, capture screenshots, and keep improving until the approved reference is matched or a real blocker exists.
### 5. Use Visual Ralph verdict before every next edit
For each visual iteration:
1. Capture the current generated screenshot with recorded viewport/state.
2. Run the Visual Ralph verdict step comparing the approved reference and generated screenshot. Use the `vision` agent for image understanding when needed.
3. Treat the JSON verdict as authoritative.
4. If `score < 90`, convert `differences[]` and `suggestions[]` into the next edit plan.
5. Rerun before the next edit.
Required verdict shape: `score`, `verdict`, `category_match`, `differences[]`, `suggestions[]`, and `reasoning`.
### 6. Use pixel diff only as secondary debug evidence
When mismatch diagnosis is hard, generate a pixel diff or pixelmatch overlay to locate hotspots. Pixel diff does not replace the Visual Ralph verdict; it only helps translate visual hotspots into concrete edits.
Record final diff evidence with the reference/screenshot artifacts so the result can be audited.
### 7. Build a reproducible design system
The implementation is incomplete unless the visual match is encoded in repo-native reusable artifacts. Depending on the project, this may mean CSS variables, theme tokens, Tailwind config, component variants, Storybook stories, updates that align with DESIGN.md, or existing equivalents.
Capture at least the applicable:
- colors,
- spacing scale,
- typography scale/weights,
- radii,
- shadows/elevation,
- important component variants and states.
Prefer existing token/component patterns. Do not introduce a new design-system layer if the repo already has one that can be extended.
## Completion checklist
Do not declare done until all are true:
- Approved reference image or URL-derived reference artifact is saved in the workspace.
- Screenshot reproduction command, viewport, route, seed/state, and output paths are documented.
- Visual Ralph verdict final score is `>= 90` against the approved reference.
- Pixel diff or overlay evidence is recorded as secondary debug evidence.
- Design-system tokens/components are repo-native and reusable.
- Build/lint/test or the repo's equivalent verification passes.
- No unapproved major design pivot occurred after reference approval.
- Remaining visual differences, if any, are explicitly documented with rationale.
## Handoff template
```text
$ralph "Implement the approved frontend reference.
Reference: <workspace-reference-image-or-url-derived-artifact>
Source URL (if URL-derived): <url and permission/scope note>
Viewport/content state: <viewport, route/state, seed/login assumptions>
Interaction parity notes: <visible controls and known exclusions>
Route/surface: <route or component>
Screenshot command: <command and viewport>
Use the Visual Ralph verdict step before every next edit; pass threshold score >= 90.
Use pixel diff only as secondary debug evidence.
Extract reusable design tokens/components for colors, spacing, typography, radii, shadows, and key variants.
Run build/lint/test before completion.
Do not make major design pivots unless explicitly requested."
```
Task: {{ARGUMENTS}}
@@ -0,0 +1,57 @@
---
name: wiki
description: Persistent markdown project wiki stored under repository omx_wiki with keyword search and lifecycle capture
triggers: ["wiki add", "wiki lint", "wiki query", "wiki read", "wiki delete"]
---
# Wiki
Persistent, self-maintained markdown knowledge base for project and session knowledge.
## Operations
### Ingest
```bash
omx wiki wiki_ingest --input '{"title":"Auth Architecture","content":"...","tags":["auth","architecture"],"category":"architecture"}' --json
```
### Query
```bash
omx wiki wiki_query --input '{"query":"authentication","tags":["auth"],"category":"architecture"}' --json
```
### Lint
```bash
omx wiki wiki_lint --json
```
### Quick Add
```bash
omx wiki wiki_add --input '{"title":"Page Title","content":"...","tags":["tag1"],"category":"decision"}' --json
```
### List / Read / Delete
```bash
omx wiki wiki_list --json
omx wiki wiki_read --input '{"page":"auth-architecture"}' --json
omx wiki wiki_delete --input '{"page":"outdated-page"}' --json
omx wiki wiki_refresh --json
```
## Categories
`architecture`, `decision`, `pattern`, `debugging`, `environment`, `session-log`, `reference`, `convention`
## Storage
- Pages: `omx_wiki/*.md`
- Index: `omx_wiki/index.md`
- Log: `omx_wiki/log.md`
## Cross-References
Use `[[page-name]]` wiki-link syntax to create cross-references between pages.
## Auto-Capture
At session end, discoveries can be captured as `session-log-*` pages. Configure via `wiki.autoCapture` in `.omx-config.json`.
## Hard Constraints
- No vector embeddings — query uses keyword + tag matching only
- Wiki files are repository project knowledge under `omx_wiki/`; legacy `.omx/wiki/` is read-only compatibility input when no canonical wiki exists
@@ -0,0 +1,120 @@
---
name: worker
description: Team worker protocol (ACK, mailbox, task lifecycle) for tmux-based OMX teams
---
# Worker Skill
This skill is for a Codex session that was started as an OMX Team worker (a tmux pane spawned by `$team`).
## Identity
You MUST be running with `OMX_TEAM_WORKER` set. It looks like:
`<team-name>/worker-<n>`
Example: `alpha/worker-2`
## Load Worker Skill Path (Claude/Codex)
When a worker inbox tells you to load this skill, resolve the first existing path:
1. `${CODEX_HOME:-~/.codex}/skills/worker/SKILL.md`
2. `~/.codex/skills/worker/SKILL.md`
3. `<leader_cwd>/.codex/skills/worker/SKILL.md`
4. `<leader_cwd>/skills/worker/SKILL.md` (repo fallback)
## Startup Protocol (ACK)
1. Parse `OMX_TEAM_WORKER` into:
- `teamName` (before the `/`)
- `workerName` (after the `/`, usually `worker-<n>`)
2. Send a startup ACK to the lead mailbox **before task work**:
- Recipient worker id: `leader-fixed`
- Body: one short deterministic line (recommended: `ACK: <workerName> initialized`).
3. After ACK, proceed to your inbox instructions.
The lead will see your message in:
`<team_state_root>/team/<teamName>/mailbox/leader-fixed.json`
Use CLI interop:
- `omx team api send-message --input <json> --json` with `{team_name, from_worker, to_worker:"leader-fixed", body}`
Copy/paste template:
```bash
omx team api send-message --input "{\"team_name\":\"<teamName>\",\"from_worker\":\"<workerName>\",\"to_worker\":\"leader-fixed\",\"body\":\"ACK: <workerName> initialized\"}" --json
```
## Inbox + Tasks
1. Resolve canonical team state root in this order:
1) `OMX_TEAM_STATE_ROOT` env
2) worker identity `team_state_root`
3) team config/manifest `team_state_root`
4) local cwd fallback (`.omx/state`)
2. Read your inbox:
`<team_state_root>/team/<teamName>/workers/<workerName>/inbox.md`
3. Pick the first unblocked task assigned to you.
4. Read the task file:
`<team_state_root>/team/<teamName>/tasks/task-<id>.json` (example: `task-1.json`)
5. Task id format:
- The MCP/state API uses the numeric id (`"1"`), not `"task-1"`.
- Never use legacy `tasks/{id}.json` wording.
6. Claim the task (do NOT start work without a claim) using claim-safe lifecycle CLI interop (`omx team api claim-task --json`).
7. Do the work.
8. Complete/fail the task via lifecycle transition CLI interop (`omx team api transition-task-status --json`) from `in_progress` to `completed` or `failed`.
- Do NOT directly write lifecycle fields (`status`, `owner`, `result`, `error`) in task files.
9. Use `omx team api release-task-claim --json` only for rollback/requeue to `pending` (not for completion).
10. Update your worker status:
`<team_state_root>/team/<teamName>/workers/<workerName>/status.json` with `{"state":"idle", ...}`
## Mailbox
Check your mailbox for messages:
`<team_state_root>/team/<teamName>/mailbox/<workerName>.json`
When notified, read messages and follow any instructions. Use short ACK replies when appropriate.
Note: leader dispatch is state-first. The durable queue lives at:
`<team_state_root>/team/<teamName>/dispatch/requests.json`
Hooks/watchers may nudge you after mailbox/inbox state is already written.
Use CLI interop:
- `omx team api mailbox-list --json` to read
- `omx team api mailbox-mark-delivered --json` to acknowledge delivery
Copy/paste templates:
```bash
omx team api mailbox-list --input "{\"team_name\":\"<teamName>\",\"worker\":\"<workerName>\"}" --json
omx team api mailbox-mark-delivered --input "{\"team_name\":\"<teamName>\",\"worker\":\"<workerName>\",\"message_id\":\"<MESSAGE_ID>\"}" --json
```
## Dispatch Discipline (state-first)
Worker sessions should treat team state + CLI interop as the source of truth.
- Prefer inbox/mailbox/task state and `omx team api ... --json` operations.
- Do **not** rely on ad-hoc tmux keystrokes as a primary delivery channel.
- If a manual trigger arrives (for example `tmux send-keys` nudge), treat it only as a prompt to re-check state and continue through the normal claim-safe lifecycle.
## Team Big Five / ATEM Coordination Gate
Keep independent fan-out lightweight: if your task is isolated with no shared files, dependencies, or handoffs, normal startup ACK, claim-safe lifecycle, status, verification, and completion evidence are sufficient.
When your inbox/task activates the Team Big Five / ATEM-inspired protocol (dependencies, shared files/surfaces/contracts, handoffs, integration, blocked lanes, or changed assumptions), use this concise boundary checklist:
- Shared mental model / single source of truth: treat task JSON, inbox, mailbox, approved handoff, and leader updates as canonical.
- Closed-loop communication / ACK-readback: acknowledge handoffs with what you understood, affected artifact/path, owner, and next action.
- Mutual performance monitoring: check boundary contracts, shared files, and verification evidence before completion.
- Backup/reassignment behavior: if blocked, write blocked status with the smallest needed help/reassignment request and continue any safe unblocked slice.
- Adaptability checkpoint: changed assumptions, dependencies, or verification results require a brief leader-facing update before widening scope.
- Team orientation: optimize for the integrated team result; report integration risks, missing tests, and peer impacts instead of local-only success.
## Shutdown
If the lead sends a shutdown request, follow the shutdown inbox instructions exactly, write your shutdown ack file, then exit the Codex session.