The one and only agent harness for complex codebases. Project memory, planning, execution, and verified completion inside Codex.
JavaScript aiai-agentsclaudeclaude-codeclicodexdeveloper-toolslazylazycodexoh-my-openagentomoopenaiorchestrationtypescript
chore: sync Codex marketplace v4.7.3
YeonGyu-Kim10cecd175dc0
diff --git a/plugins/omo/components/rules/README.md b/plugins/omo/components/rules/README.mdindex 1cab797a..e732e064 100644--- a/plugins/omo/components/rules/README.md+++ b/plugins/omo/components/rules/README.md@@ -17,8 +17,6 @@ The runtime has no npm production dependencies, so a clean Codex marketplace copProject-level sources:-- `AGENTS.md`-- `CLAUDE.md`- `CONTEXT.md`- `.omo/rules/**/*.md`- `.claude/rules/**/*.md`@@ -26,7 +24,7 @@ Project-level sources:- `.github/instructions/**/*.md`- `.github/copilot-instructions.md`-User-home sources are also supported by the ported engine when available.+User-home sources are also supported by the ported engine when available. `AGENTS.md` is not part of `auto` source selection because Codex already loads it as native project instructions, so re-injecting it through hooks duplicates context; opt into it explicitly with `CODEX_RULES_ENABLED_SOURCES` if you need hook-level migration behavior. Claude user-home sources (`~/.claude/rules`, `~/.claude/CLAUDE.md`) are also excluded from `auto` because they usually contain Claude Code runtime instructions rather than Codex rules; opt into them explicitly when you want that migration behavior.Markdown rule files may use frontmatter such as:@@ -58,6 +56,8 @@ It also enables:[features]plugins = trueplugin_hooks = true+multi_agent = true+child_agents_md = true[plugins."omo@sisyphuslabs"]enabled = true@@ -73,7 +73,7 @@ Use `CODEX_RULES_*` environment variables:| `CODEX_RULES_MODE` | `both`, `static`, `dynamic`, `off` | `both` || `CODEX_RULES_MAX_RULE_CHARS` | positive integer | `12000` || `CODEX_RULES_MAX_RESULT_CHARS` | positive integer | `40000` |-| `CODEX_RULES_ENABLED_SOURCES` | comma-separated source names | `auto` |+| `CODEX_RULES_ENABLED_SOURCES` | comma-separated source names or `auto` | `auto` (excludes `AGENTS.md`, `~/.claude/rules`, `~/.claude/CLAUDE.md`) |For migration from `pi-rules`, equivalent `PI_RULES_*` variables are accepted as fallbacks.diff --git a/plugins/omo/components/rules/skills/rules/SKILL.md b/plugins/omo/components/rules/skills/rules/SKILL.mdindex 3ac40130..b1c27c4c 100644--- a/plugins/omo/components/rules/skills/rules/SKILL.md+++ b/plugins/omo/components/rules/skills/rules/SKILL.md@@ -14,10 +14,8 @@ Dynamic `PostToolUse` output is injected as additional context and is deduplicatSupported project sources:-- `AGENTS.md`-- `CLAUDE.md`- `CONTEXT.md`-- `.sisyphus/rules/**/*.md`+- `.omo/rules/**/*.md`- `.claude/rules/**/*.md`- `.cursor/rules/**/*.md`- `.github/instructions/**/*.md`@@ -29,6 +27,6 @@ Supported environment knobs:- `CODEX_RULES_MODE=both|static|dynamic|off`- `CODEX_RULES_MAX_RULE_CHARS=<number>`- `CODEX_RULES_MAX_RESULT_CHARS=<number>`-- `CODEX_RULES_ENABLED_SOURCES=AGENTS.md,.sisyphus/rules`+- `CODEX_RULES_ENABLED_SOURCES=CONTEXT.md,.omo/rules`The legacy `PI_RULES_*` variables are accepted as fallbacks for users migrating from `pi-rules`.diff --git a/plugins/omo/components/rules/src/config.ts b/plugins/omo/components/rules/src/config.tsindex 8db63e7b..7882508d 100644--- a/plugins/omo/components/rules/src/config.ts+++ b/plugins/omo/components/rules/src/config.ts@@ -77,7 +77,7 @@ function parseEnabledSources(value: string | undefined, disableBundledRules: boosources.push(source);}const enabledSources = disableBundledRules ? sources.filter((source) => source !== "plugin-bundled") : sources;- return enabledSources.length > 0 || sources.length > 0 ? enabledSources : "auto";+ return enabledSources;}function sourcesWithoutBundledRules(): RuleSource[] {@@ -91,15 +91,11 @@ function toRuleSource(value: string): RuleSource | null {case ".cursor/rules":case ".github/instructions":case ".github/copilot-instructions.md":- case "AGENTS.md":- case "CLAUDE.md":case "CONTEXT.md":case "plugin-bundled":case "~/.omo/rules":case "~/.opencode/rules":case "~/.claude/rules":- case "~/.config/opencode/AGENTS.md":- case "~/.claude/CLAUDE.md":return value;default:return null;diff --git a/plugins/omo/components/rules/src/dynamic-target-fingerprints.ts b/plugins/omo/components/rules/src/dynamic-target-fingerprints.tsindex 32a8cb6c..1c07e69c 100644--- a/plugins/omo/components/rules/src/dynamic-target-fingerprints.ts+++ b/plugins/omo/components/rules/src/dynamic-target-fingerprints.ts@@ -1,11 +1,11 @@import { statSync } from "node:fs";import { resolve } from "node:path";import { isSameOrChildPath, toPosixPath, uniqueStrings } from "./path-utils.js";-import { SOURCE_PRIORITY } from "./rules/constants.js";import { createRuleDiscoveryCache, findRuleCandidates } from "./rules/finder.js";import { hashContent } from "./rules/matcher.js";import { sortCandidates } from "./rules/ordering.js";import { findProjectRoot } from "./rules/project-root.js";+import { disabledSourcesFromConfig } from "./rules/sources.js";import type { PiRulesConfig, RuleCandidate } from "./rules/types.js";export interface DynamicTargetFingerprint {@@ -19,7 +19,7 @@ export function fingerprintDynamicTargets(targetPaths: ReadonlyArray<string>,config: PiRulesConfig,): DynamicTargetFingerprint[] {- const disabledSources = disabledSourcesFor(config);+ const disabledSources = disabledSourcesFromConfig(config);const discoveryCache = createRuleDiscoveryCache();const cwdProjectRoot = findProjectRoot(cwd);const fingerprints: DynamicTargetFingerprint[] = [];@@ -84,15 +84,6 @@ function fileFingerprint(filePath: string): string {}}-function disabledSourcesFor(config: PiRulesConfig): ReadonlySet<string> | undefined {- if (config.enabledSources === "auto") {- return undefined;- }-- const enabledSources = new Set(config.enabledSources);- return new Set([...SOURCE_PRIORITY.keys()].filter((source) => !enabledSources.has(source)));-}-function dynamicTargetCacheKey(targetPath: string): string {return toPosixPath(resolve(targetPath));}diff --git a/plugins/omo/components/rules/src/rules/constants.ts b/plugins/omo/components/rules/src/rules/constants.tsindex 97459275..12ad9f2c 100644--- a/plugins/omo/components/rules/src/rules/constants.ts+++ b/plugins/omo/components/rules/src/rules/constants.ts@@ -30,8 +30,6 @@ export const PROJECT_RULE_SUBDIRS: ReadonlyArray<readonly [string, string]> = [*/export const PROJECT_SINGLE_FILES: readonly string[] = [".github/copilot-instructions.md",- "AGENTS.md",- "CLAUDE.md","CONTEXT.md",];@@ -43,7 +41,7 @@ export const USER_HOME_RULE_SUBDIRS: readonly string[] = [".omo/rules", ".openco/*** User-home single-file rules. The first one to exist wins per "first-match" semantics.*/-export const USER_HOME_SINGLE_FILES: readonly string[] = [".config/opencode/AGENTS.md", ".claude/CLAUDE.md"];+export const USER_HOME_SINGLE_FILES: readonly string[] = [];/*** Bundled plugin rule directory relative to the rules component root.@@ -64,14 +62,10 @@ export const SOURCE_PRIORITY: ReadonlyMap<RuleSource, number> = new Map([[".cursor/rules", 2],[".github/instructions", 3],[".github/copilot-instructions.md", 4],- ["AGENTS.md", 5],- ["CLAUDE.md", 6],["CONTEXT.md", 7],["~/.omo/rules", 100],["~/.opencode/rules", 101],["~/.claude/rules", 102],- ["~/.config/opencode/AGENTS.md", 103],- ["~/.claude/CLAUDE.md", 104],["plugin-bundled", 200],]);diff --git a/plugins/omo/components/rules/src/rules/engine.ts b/plugins/omo/components/rules/src/rules/engine.tsindex 8634e729..6d9d94d5 100644--- a/plugins/omo/components/rules/src/rules/engine.ts+++ b/plugins/omo/components/rules/src/rules/engine.ts@@ -15,13 +15,13 @@ import {DEFAULT_POST_COMPACT_MAX_RESULT_CHARS,DEFAULT_POST_COMPACT_MAX_RULE_CHARS,PROJECT_SINGLE_FILES,- SOURCE_PRIORITY,} from "./constants.js";import { createRuleDiscoveryCache, type RuleDiscoveryCache } from "./finder.js";import { formatDynamicBlock, formatStaticBlock } from "./formatter.js";import { hashContent, matchRule } from "./matcher.js";import { sortCandidates } from "./ordering.js";import { parseRule } from "./parser.js";+import { disabledSourcesFromConfig } from "./sources.js";import type { LoadedRule, MatchReason, PiRulesConfig, RuleCandidate, RuleDiagnostic, SessionState } from "./types.js";interface LoadedRuleContent {@@ -97,7 +97,7 @@ export function createEngine(config: PiRulesConfig, deps: EngineDeps): Engine {projectRoot,targetFile: null,};- const disabledSources = disabledSourcesFor(config);+ const disabledSources = disabledSourcesFromConfig(config);if (disabledSources !== undefined) {findOptions.disabledSources = disabledSources;}@@ -121,7 +121,7 @@ export function createEngine(config: PiRulesConfig, deps: EngineDeps): Engine {const seenRules = new Set<string>();const loadedRuleContent = new Map<string, LoadedRuleContent | null>();const projectMembership = new Map<string, boolean>();- const disabledSources = disabledSourcesFor(config);+ const disabledSources = disabledSourcesFromConfig(config);const discoveryCache = createRuleDiscoveryCache();const candidateDiscoveryCache: CandidateDiscoveryCache = new Map();const cwdProjectRoot = deps.findProjectRoot(cwd);@@ -442,15 +442,6 @@ function staticMatchReason(rule: LoadedRule): MatchReason | null {return null;}-function disabledSourcesFor(config: PiRulesConfig): ReadonlySet<string> | undefined {- if (config.enabledSources === "auto") {- return undefined;- }-- const enabledSources = new Set(config.enabledSources);- return new Set([...SOURCE_PRIORITY.keys()].filter((source) => !enabledSources.has(source)));-}-function isDedupedRootSingleFile(candidate: RuleCandidate, rootSingleFileSelected: boolean): boolean {return rootSingleFileSelected && isRootSingleFile(candidate);}diff --git a/plugins/omo/components/rules/src/rules/finder-sources.ts b/plugins/omo/components/rules/src/rules/finder-sources.tsindex 5277323b..910652b3 100644--- a/plugins/omo/components/rules/src/rules/finder-sources.ts+++ b/plugins/omo/components/rules/src/rules/finder-sources.ts@@ -17,8 +17,6 @@ export function toProjectRuleSource(parentDirectory: string, subDirectory: strinexport function toProjectSingleFileSource(ruleFile: string): RuleSource {switch (ruleFile) {case ".github/copilot-instructions.md":- case "AGENTS.md":- case "CLAUDE.md":case "CONTEXT.md":return ruleFile;default:@@ -41,9 +39,6 @@ export function toUserHomeRuleSource(ruleSubdir: string): RuleSource {export function toUserHomeSingleFileSource(ruleFile: string): RuleSource {const source = `~/${ruleFile}`;switch (source) {- case "~/.config/opencode/AGENTS.md":- case "~/.claude/CLAUDE.md":- return source;default:throw new UnsupportedRuleSourceError(`Unsupported user-home single-file source: ${source}`);}diff --git a/plugins/omo/components/rules/src/rules/sources.ts b/plugins/omo/components/rules/src/rules/sources.tsnew file mode 100644index 00000000..1f3230b6--- /dev/null+++ b/plugins/omo/components/rules/src/rules/sources.ts@@ -0,0 +1,13 @@+import { SOURCE_PRIORITY } from "./constants.js";+import type { PiRulesConfig } from "./types.js";++export const DEFAULT_AUTO_DISABLED_SOURCES: readonly string[] = ["AGENTS.md", "~/.claude/rules", "~/.claude/CLAUDE.md"];++export function disabledSourcesFromConfig(config: PiRulesConfig): ReadonlySet<string> | undefined {+ if (config.enabledSources === "auto") {+ return new Set(DEFAULT_AUTO_DISABLED_SOURCES);+ }++ const enabledSources = new Set(config.enabledSources);+ return new Set([...SOURCE_PRIORITY.keys()].filter((source) => !enabledSources.has(source)));+}diff --git a/plugins/omo/components/rules/src/rules/types.ts b/plugins/omo/components/rules/src/rules/types.tsindex bb914bb1..862ac3c4 100644--- a/plugins/omo/components/rules/src/rules/types.ts+++ b/plugins/omo/components/rules/src/rules/types.ts@@ -51,7 +51,7 @@ export interface RuleCandidate {distance: number;isGlobal: boolean;/**- * True when this candidate is a SINGLE-FILE rule like AGENTS.md or+ * True when this candidate is a SINGLE-FILE rule like* `.github/copilot-instructions.md` (frontmatter optional, applies always).*/isSingleFile: boolean;@@ -81,15 +81,11 @@ export type RuleSource =| ".cursor/rules"| ".github/instructions"| ".github/copilot-instructions.md"- | "AGENTS.md"- | "CLAUDE.md"| "CONTEXT.md"| "plugin-bundled"| "~/.omo/rules"| "~/.opencode/rules"- | "~/.claude/rules"- | "~/.config/opencode/AGENTS.md"- | "~/.claude/CLAUDE.md";+ | "~/.claude/rules";/*** Why a candidate matched the target file. Surfaced in the injection block sodiff --git a/plugins/omo/components/rules/test/agent-doc-sources.test.ts b/plugins/omo/components/rules/test/agent-doc-sources.test.tsnew file mode 100644index 00000000..2634edd1--- /dev/null+++ b/plugins/omo/components/rules/test/agent-doc-sources.test.ts@@ -0,0 +1,119 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import {+ type CodexPostToolUseInput,+ type CodexSessionStartInput,+ runPostToolUseHook,+ runSessionStartHook,+} from "../src/codex-hook.js";++const REMOVED_AGENT_DOC_SOURCE_LISTS = ["AGENTS.md", "CLAUDE.md", "AGENTS.md,CLAUDE.md"] as const;++const tempDirectories: string[] = [];++type AgentDocProject = {+ readonly pluginData: string;+ readonly root: string;+ readonly nestedSourceFile: string;+};++afterEach(() => {+ for (const directory of tempDirectories.splice(0)) {+ rmSync(directory, { recursive: true, force: true });+ }+});++function makeAgentDocProject(): AgentDocProject {+ const root = mkdtempSync(path.join(tmpdir(), "codex-rules-agent-docs-"));+ const pluginData = mkdtempSync(path.join(tmpdir(), "codex-rules-agent-docs-data-"));+ tempDirectories.push(root, pluginData);++ writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "fixture" }));+ writeFileSync(path.join(root, "AGENTS.md"), "Root AGENTS.md must remain Codex-native.");+ writeFileSync(path.join(root, "CLAUDE.md"), "Root CLAUDE.md must stay outside rules hook context.");+ writeFileSync(path.join(root, "CONTEXT.md"), "Context source must not leak through removed-only allowlists.");++ mkdirSync(path.join(root, ".omo", "rules"), { recursive: true });+ writeFileSync(+ path.join(root, ".omo", "rules", "typescript.md"),+ [+ "---",+ "description: TypeScript",+ 'globs: ["**/*.ts"]',+ "---",+ "",+ "Dynamic .omo/rules context must not leak through removed-only allowlists.",+ ].join("\n"),+ );++ const nestedDirectory = path.join(root, "child", "src");+ mkdirSync(nestedDirectory, { recursive: true });+ writeFileSync(path.join(root, "child", "AGENTS.md"), "Child AGENTS.md must remain Codex-native.");+ const nestedSourceFile = path.join(nestedDirectory, "app.ts");+ writeFileSync(nestedSourceFile, "export const app = true;\n");++ return { root, pluginData, nestedSourceFile };+}++function sessionStartInput(root: string): CodexSessionStartInput {+ return {+ session_id: "session-1",+ transcript_path: null,+ cwd: root,+ hook_event_name: "SessionStart",+ model: "gpt-5.5",+ permission_mode: "default",+ source: "startup",+ };+}++function postToolUseInput(root: string, filePath: string): CodexPostToolUseInput {+ return {+ session_id: "session-1",+ turn_id: "turn-1",+ transcript_path: null,+ cwd: root,+ hook_event_name: "PostToolUse",+ model: "gpt-5.5",+ permission_mode: "default",+ tool_name: "mcp__filesystem__read_file",+ tool_input: { path: filePath },+ tool_response: { text: "file contents" },+ tool_use_id: "call-1",+ };+}++describe("agent doc sources", () => {+ for (const sourceList of REMOVED_AGENT_DOC_SOURCE_LISTS) {+ it(`#given ${sourceList} removed-only source allowlist #when SessionStart runs #then it emits no OMO rules context`, async () => {+ // given+ const { root, pluginData } = makeAgentDocProject();++ // when+ const output = await runSessionStartHook(sessionStartInput(root), {+ pluginDataRoot: pluginData,+ env: { CODEX_RULES_ENABLED_SOURCES: sourceList },+ });++ // then+ expect(output).toBe("");+ });+ }++ it("#given nested AGENTS.md and removed-only source allowlist #when PostToolUse targets a child file #then it emits no dynamic OMO rules context", async () => {+ // given+ const { root, pluginData, nestedSourceFile } = makeAgentDocProject();++ // when+ const output = await runPostToolUseHook(postToolUseInput(root, nestedSourceFile), {+ pluginDataRoot: pluginData,+ env: { CODEX_RULES_ENABLED_SOURCES: "AGENTS.md,CLAUDE.md" },+ });++ // then+ expect(output).toBe("");+ });+});diff --git a/plugins/omo/components/rules/test/codex-hook-post-compact-budget.test.ts b/plugins/omo/components/rules/test/codex-hook-post-compact-budget.test.tsindex a674fc33..ed3b2063 100644--- a/plugins/omo/components/rules/test/codex-hook-post-compact-budget.test.ts+++ b/plugins/omo/components/rules/test/codex-hook-post-compact-budget.test.ts@@ -13,7 +13,7 @@ import {const tempDirectories: string[] = [];const PROJECT_RULES_ENV = {- CODEX_RULES_ENABLED_SOURCES: "AGENTS.md,.omo/rules",+ CODEX_RULES_ENABLED_SOURCES: "CONTEXT.md,.omo/rules",CODEX_RULES_MAX_RESULT_CHARS: "50000",CODEX_RULES_MAX_RULE_CHARS: "30000",};@@ -56,7 +56,9 @@ function makeOversizedProject(): { root: string; pluginData: string } {const pluginData = mkdtempSync(path.join(tmpdir(), "codex-rules-post-compact-budget-data-"));tempDirectories.push(root, pluginData);writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "fixture" }));- writeFileSync(path.join(root, "AGENTS.md"), `Project rule\n${"A".repeat(30_000)}`);+ writeFileSync(path.join(root, "AGENTS.md"), "Project AGENTS.md should stay Codex-native.");+ writeFileSync(path.join(root, "CLAUDE.md"), "Project CLAUDE.md should stay outside rules hook context.");+ writeFileSync(path.join(root, "CONTEXT.md"), `Project rule\n${"A".repeat(30_000)}`);mkdirSync(path.join(root, ".omo", "rules"), { recursive: true });writeFileSync(path.join(root, ".omo", "rules", "typescript.md"),diff --git a/plugins/omo/components/rules/test/codex-hook-post-compact-dedup.test.ts b/plugins/omo/components/rules/test/codex-hook-post-compact-dedup.test.tsindex 87d76327..30ff2f91 100644--- a/plugins/omo/components/rules/test/codex-hook-post-compact-dedup.test.ts+++ b/plugins/omo/components/rules/test/codex-hook-post-compact-dedup.test.ts@@ -15,7 +15,7 @@ import {const tempDirectories: string[] = [];const PROJECT_ONLY_ENV = {- CODEX_RULES_ENABLED_SOURCES: "AGENTS.md,.omo/rules",+ CODEX_RULES_ENABLED_SOURCES: "CONTEXT.md,.omo/rules",};afterEach(() => {@@ -145,7 +145,9 @@ function makeTempProject(): { root: string; pluginData: string } {const pluginData = mkdtempSync(path.join(tmpdir(), "codex-rules-compact-dedup-data-"));tempDirectories.push(root, pluginData);writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "fixture" }));- writeFileSync(path.join(root, "AGENTS.md"), "Always wear safety goggles when refactoring.");+ writeFileSync(path.join(root, "AGENTS.md"), "Project AGENTS.md should stay Codex-native.");+ writeFileSync(path.join(root, "CLAUDE.md"), "Project CLAUDE.md should stay outside rules hook context.");+ writeFileSync(path.join(root, "CONTEXT.md"), "Always wear safety goggles when refactoring.");mkdirSync(path.join(root, ".omo", "rules"), { recursive: true });writeFileSync(path.join(root, ".omo", "rules", "typescript.md"),diff --git a/plugins/omo/components/rules/test/codex-hook.test.ts b/plugins/omo/components/rules/test/codex-hook.test.tsindex 5659e1f5..0e13e969 100644--- a/plugins/omo/components/rules/test/codex-hook.test.ts+++ b/plugins/omo/components/rules/test/codex-hook.test.ts@@ -55,9 +55,17 @@ function runHookCli(input: string, subcommand = "post-tool-use", env: NodeJS.Proconst tempDirectories: string[] = [];const PROJECT_ONLY_ENV = {+ CODEX_RULES_ENABLED_SOURCES: "CONTEXT.md,.omo/rules",+};++const AGENTS_AND_RULES_ENV = {CODEX_RULES_ENABLED_SOURCES: "AGENTS.md,.omo/rules",};+const CLAUDE_AND_RULES_ENV = {+ CODEX_RULES_ENABLED_SOURCES: "CLAUDE.md,.omo/rules",+};+const RULES_ONLY_ENV = {CODEX_RULES_ENABLED_SOURCES: ".omo/rules",};@@ -73,7 +81,9 @@ function makeTempProject(): { root: string; pluginData: string } {const pluginData = mkdtempSync(path.join(tmpdir(), "codex-rules-data-"));tempDirectories.push(root, pluginData);writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "fixture" }));- writeFileSync(path.join(root, "AGENTS.md"), "Always wear safety goggles when refactoring.");+ writeFileSync(path.join(root, "AGENTS.md"), "Project AGENTS.md should stay Codex-native.");+ writeFileSync(path.join(root, "CLAUDE.md"), "Project CLAUDE.md should stay outside rules hook context.");+ writeFileSync(path.join(root, "CONTEXT.md"), "Always wear safety goggles when refactoring.");mkdirSync(path.join(root, ".omo", "rules"), { recursive: true });writeFileSync(path.join(root, ".omo", "rules", "typescript.md"),@@ -211,6 +221,50 @@ describe("codex rules hooks", () => {expect(parsed.hookSpecificOutput?.additionalContext).toContain("Always wear safety goggles");});+ it("#given default auto sources #when SessionStart runs #then native Codex AGENTS.md is not duplicated", async () => {+ // given+ const { root, pluginData } = makeTempProject();++ // when+ const output = await runSessionStartHook(sessionStartInput(root), {+ pluginDataRoot: pluginData,+ });++ // then+ const parsed = parseHookOutput(output);+ expect(parsed.hookSpecificOutput?.additionalContext).toContain("## Project Instructions");+ expect(parsed.hookSpecificOutput?.additionalContext).not.toContain("Project AGENTS.md should stay Codex-native.");+ expect(parsed.hookSpecificOutput?.additionalContext).not.toContain("Project CLAUDE.md should stay outside rules hook context.");+ });++ it("#given project AGENTS.md #when SessionStart runs #then rules hook leaves AGENTS.md to Codex native handling", async () => {+ // given+ const { root, pluginData } = makeTempProject();++ // when+ const output = await runSessionStartHook(sessionStartInput(root), {+ pluginDataRoot: pluginData,+ env: AGENTS_AND_RULES_ENV,+ });++ // then+ expect(output).toBe("");+ });++ it("#given project CLAUDE.md #when SessionStart runs #then rules hook leaves CLAUDE.md out of context", async () => {+ // given+ const { root, pluginData } = makeTempProject();++ // when+ const output = await runSessionStartHook(sessionStartInput(root), {+ pluginDataRoot: pluginData,+ env: CLAUDE_AND_RULES_ENV,+ });++ // then+ expect(output).toBe("");+ });+it("#given static context already injected #when UserPromptSubmit runs #then it emits no duplicate context", async () => {// givenconst { root, pluginData } = makeTempProject();@@ -351,6 +405,23 @@ describe("codex rules hooks", () => {expect(readSessionCache(pluginData).dynamicTargetFingerprints).toEqual(cachedState.dynamicTargetFingerprints);});+ it("#given default auto sources #when excluded AGENTS.md changes #then PostToolUse fingerprint stays stable", async () => {+ // given+ const { root, pluginData } = makeTempProject();+ const filePath = path.join(root, "src", "app.ts");+ const input = postToolUseInput(root, filePath);+ await runPostToolUseHook(input, { pluginDataRoot: pluginData });+ const cachedState = readSessionCache(pluginData);+ writeFileSync(path.join(root, "AGENTS.md"), "Native Codex instructions changed outside codex-rules auto.");++ // when+ const output = await runPostToolUseHook(input, { pluginDataRoot: pluginData });++ // then+ expect(output).toBe("");+ expect(readSessionCache(pluginData).dynamicTargetFingerprints).toEqual(cachedState.dynamicTargetFingerprints);+ });+it("#given dynamic context remains in transcript but cache is missing #when PostToolUse repeats #then it emits no duplicate context", async () => {// givenconst { root, pluginData } = makeTempProject();diff --git a/plugins/omo/components/rules/test/config.test.ts b/plugins/omo/components/rules/test/config.test.tsnew file mode 100644index 00000000..855971ee--- /dev/null+++ b/plugins/omo/components/rules/test/config.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from "vitest";++import { configFromEnvironment } from "../src/config.js";++const REMOVED_AGENT_DOC_SOURCE_LISTS = ["AGENTS.md", "CLAUDE.md", "AGENTS.md,CLAUDE.md"] as const;++describe("rules config", () => {+ for (const sourceList of REMOVED_AGENT_DOC_SOURCE_LISTS) {+ it(`#given removed agent-doc source ${sourceList} #when parsing enabled sources #then preserves the explicit empty allowlist`, () => {+ // given+ const env = {+ CODEX_RULES_ENABLED_SOURCES: sourceList,+ } satisfies NodeJS.ProcessEnv;++ // when+ const config = configFromEnvironment(env);++ // then+ expect(config.enabledSources).toEqual([]);+ });+ }+});diff --git a/plugins/omo/components/rules/test/dynamic-target-fingerprints.test.ts b/plugins/omo/components/rules/test/dynamic-target-fingerprints.test.tsnew file mode 100644index 00000000..b43d4d47--- /dev/null+++ b/plugins/omo/components/rules/test/dynamic-target-fingerprints.test.ts@@ -0,0 +1,71 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { fingerprintDynamicTargets } from "../src/dynamic-target-fingerprints.js";+import { defaultConfig } from "../src/rules/engine.js";++const tempDirectories: string[] = [];++afterEach(() => {+ for (const directory of tempDirectories.splice(0)) {+ rmSync(directory, { recursive: true, force: true });+ }+});++describe("codex rules dynamic target fingerprints", () => {+ it("#given auto source mode #when an excluded source file changes #then cache key stays stable", () => {+ // given+ const { cwd, targetPath } = makeProjectWithDefaultSources();+ const config = defaultConfig();++ // when+ const initial = fingerprintDynamicTargets(cwd, [targetPath], config);+ writeFileSync(+ path.join(cwd, "AGENTS.md"),+ [+ "Always use the exact code style.",+ "Updated guidance.",+ "",+ "This file should be excluded from auto mode.",+ ].join("\n"),+ );+ const afterChange = fingerprintDynamicTargets(cwd, [targetPath], config);+ writeFileSync(+ path.join(cwd, ".github", "instructions", "workflow.md"),+ ["---", "description: Workflow rules", 'globs: ["**/*.ts"]', "---", "Prefer explicit return types."].join(+ "\n",+ ),+ );+ const afterEnabledChange = fingerprintDynamicTargets(cwd, [targetPath], config);+ const initialFingerprint = initial[0]?.fingerprint;++ // then+ expect(afterChange).toHaveLength(1);+ expect(afterEnabledChange).toHaveLength(1);+ expect(initialFingerprint).toBeDefined();+ expect(afterChange[0]?.fingerprint).toBe(initialFingerprint);+ expect(afterEnabledChange[0]?.fingerprint).not.toBe(initialFingerprint);+ });+});++function makeProjectWithDefaultSources(): { cwd: string; targetPath: string } {+ const root = mkdtempSync(path.join(tmpdir(), "codex-rules-fingerprint-"));+ const projectRoot = path.join(root, "repo");+ const instructionPath = path.join(projectRoot, ".github", "instructions");+ const targetPath = path.join(projectRoot, "src", "app.ts");+ tempDirectories.push(root);++ mkdirSync(instructionPath, { recursive: true });+ mkdirSync(path.dirname(targetPath), { recursive: true });+ writeFileSync(path.join(projectRoot, "package.json"), "{}");+ writeFileSync(path.join(projectRoot, "AGENTS.md"), "Default project AGENTS file.");+ writeFileSync(path.join(projectRoot, ".github", "copilot-instructions.md"), "Legacy copilot instruction");+ writeFileSync(+ path.join(instructionPath, "workflow.md"),+ ["---", "description: Workflow rules", 'globs: ["**/*.ts"]', "---", "Keep async/await explicit."].join("\n"),+ );+ writeFileSync(targetPath, "export const answer = 42;\n");+ return { cwd: projectRoot, targetPath };+}diff --git a/plugins/omo/components/rules/test/engine.test.ts b/plugins/omo/components/rules/test/engine.test.tsindex 4b936353..436d2438 100644--- a/plugins/omo/components/rules/test/engine.test.ts+++ b/plugins/omo/components/rules/test/engine.test.ts@@ -1,6 +1,7 @@import { join } from "node:path";import { describe, expect, it } from "vitest";+import { configFromEnvironment } from "../src/config.js";import { createEngine, defaultConfig, type EngineDeps } from "../src/rules/engine.js";import { matchRule as defaultMatchRule } from "../src/rules/matcher.js";import type { RuleCandidate } from "../src/rules/types.js";@@ -190,3 +191,54 @@ describe("rule engine dynamic matching", () => {expect(matchCalls).toBe(2);});});++describe("rule engine default source selection", () => {+ it("#given auto source selection #when loading static rules #then Codex-native and Claude-home sources are disabled by default", () => {+ // given+ let capturedDisabledSources: ReadonlySet<string> | undefined;+ const deps = {+ findProjectRoot: () => projectRoot,+ findCandidates: (options) => {+ capturedDisabledSources = options.disabledSources;+ return [];+ },+ readFile: () => null,+ } satisfies EngineDeps;+ const engine = createEngine(defaultConfig(), deps);++ // when+ engine.loadStaticRules(projectRoot);++ // then+ expect(capturedDisabledSources?.has("AGENTS.md")).toBe(true);+ expect(capturedDisabledSources?.has("~/.claude/rules")).toBe(true);+ expect(capturedDisabledSources?.has("~/.claude/CLAUDE.md")).toBe(true);+ expect(capturedDisabledSources?.has("CLAUDE.md")).toBe(false);+ });++ it("#given removed agent-doc sources and a real source are requested #when loading static rules #then only real sources are enabled", () => {+ // given+ let capturedDisabledSources: ReadonlySet<string> | undefined;+ const deps = {+ findProjectRoot: () => projectRoot,+ findCandidates: (options) => {+ capturedDisabledSources = options.disabledSources;+ return [];+ },+ readFile: () => null,+ } satisfies EngineDeps;+ const engine = createEngine(+ configFromEnvironment({ CODEX_RULES_ENABLED_SOURCES: "AGENTS.md,~/.claude/CLAUDE.md,plugin-bundled" }),+ deps,+ );++ // when+ engine.loadStaticRules(projectRoot);++ // then+ expect(capturedDisabledSources?.has("AGENTS.md")).toBe(false);+ expect(capturedDisabledSources?.has("~/.claude/CLAUDE.md")).toBe(false);+ expect(capturedDisabledSources?.has("plugin-bundled")).toBe(false);+ expect(capturedDisabledSources?.has(".omo/rules")).toBe(true);+ });+});diff --git a/plugins/omo/components/rules/test/finder.test.ts b/plugins/omo/components/rules/test/finder.test.tsindex 3f10ca7f..bed315f1 100644--- a/plugins/omo/components/rules/test/finder.test.ts+++ b/plugins/omo/components/rules/test/finder.test.ts@@ -24,6 +24,7 @@ function makeProject(): { projectRoot: string; homeRoot: string; targetPath: strmkdirSync(join(homeRoot, ".config", "opencode"), { recursive: true });writeFileSync(join(projectRoot, "package.json"), JSON.stringify({ name: "fixture" }));writeFileSync(join(projectRoot, "AGENTS.md"), "Project rule\n");+ writeFileSync(join(projectRoot, "CLAUDE.md"), "Claude rule\n");writeFileSync(join(projectRoot, "src", ".omo", "rules", "local.md"), "Local rule\n");writeFileSync(join(projectRoot, ".omo", "rules", "root.md"), "Root rule\n");writeFileSync(join(homeRoot, ".opencode", "rules", "global.md"), "Global rule\n");@@ -54,9 +55,7 @@ describe("findRuleCandidates", () => {expect(candidates.map(candidateSummary)).toEqual([".omo/rules:0:src/.omo/rules/local.md",".omo/rules:1:.omo/rules/root.md",- "AGENTS.md:1:AGENTS.md","~/.opencode/rules:9999:.opencode/rules/global.md",- "~/.config/opencode/AGENTS.md:9999:.config/opencode/AGENTS.md",]);});@@ -73,10 +72,7 @@ describe("findRuleCandidates", () => {});// then- expect(candidates.map(candidateSummary)).toEqual([- "AGENTS.md:1:AGENTS.md",- "~/.config/opencode/AGENTS.md:9999:.config/opencode/AGENTS.md",- ]);+ expect(candidates.map(candidateSummary)).toEqual([]);});it("#given skip user home #when finding candidates #then only project rules are returned", () => {@@ -96,7 +92,6 @@ describe("findRuleCandidates", () => {expect(candidates.map(candidateSummary)).toEqual([".omo/rules:0:src/.omo/rules/local.md",".omo/rules:1:.omo/rules/root.md",- "AGENTS.md:1:AGENTS.md",]);});});diff --git a/plugins/omo/components/rules/test/formatter.test.ts b/plugins/omo/components/rules/test/formatter.test.tsindex 903974c0..2471de80 100644--- a/plugins/omo/components/rules/test/formatter.test.ts+++ b/plugins/omo/components/rules/test/formatter.test.ts@@ -12,8 +12,8 @@ describe("rules formatter hook context", () => {it("#given multiline dynamic rules #when formatting PostToolUse context #then labels and bodies render on separate lines", () => {// givenconst rule = loadedRule({- path: "/repo/packages/AGENTS.md",- relativePath: "packages/AGENTS.md",+ path: "/repo/packages/CONTEXT.md",+ relativePath: "packages/CONTEXT.md",body: ["# packages", "", "## OVERVIEW", "23 sibling packages.", "", "## CONVENTIONS", "Use npm."].join("\n"),});@@ -29,7 +29,7 @@ describe("rules formatter hook context", () => {["Additional project instructions matched for packages/omo-codex/plugin/components/ulw-loop/src/paths.ts:","",- "Instructions from: /repo/packages/AGENTS.md",+ "Instructions from: /repo/packages/CONTEXT.md","","# packages","",@@ -45,8 +45,8 @@ describe("rules formatter hook context", () => {it("#given static rules #when formatting SessionStart context #then it avoids leading blank lines", () => {// givenconst rule = loadedRule({- path: "/repo/AGENTS.md",- relativePath: "AGENTS.md",+ path: "/repo/CONTEXT.md",+ relativePath: "CONTEXT.md",body: "Keep generated hook context readable.",});@@ -58,7 +58,7 @@ describe("rules formatter hook context", () => {["## Project Instructions","",- "Instructions from: /repo/AGENTS.md",+ "Instructions from: /repo/CONTEXT.md","","Keep generated hook context readable.",].join("\n"),@@ -82,13 +82,13 @@ describe("rules formatter hook context", () => {it("#given duplicate static rules with different line endings #when formatting context #then it renders one copy", () => {// givenconst lfRule = loadedRule({- path: "/repo/AGENTS.md",- relativePath: "AGENTS.md",+ path: "/repo/CONTEXT.md",+ relativePath: "CONTEXT.md",body: "Shared rule\nKeep one copy.",});const crlfRule = loadedRule({- path: "/repo/packages/AGENTS.md",- relativePath: "packages/AGENTS.md",+ path: "/repo/packages/CONTEXT.md",+ relativePath: "packages/CONTEXT.md",body: "Shared rule\r\nKeep one copy.",});@@ -97,7 +97,7 @@ describe("rules formatter hook context", () => {// thenexpect(occurrenceCount(block, "Shared rule\nKeep one copy.")).toBe(1);- expect(block).not.toContain("/repo/packages/AGENTS.md");+ expect(block).not.toContain("/repo/packages/CONTEXT.md");});it("#given multiple oversized rules #when formatting under a tight result budget #then every rule receives a fair truncated share with a read-full guide", () => {@@ -145,9 +145,9 @@ function loadedRule(input: {readonly source?: RuleSource;readonly matchReason?: MatchReason;}): LoadedRule {- const path = input.path ?? "/repo/AGENTS.md";- const relativePath = input.relativePath ?? "AGENTS.md";- const source = input.source ?? "AGENTS.md";+ const path = input.path ?? "/repo/CONTEXT.md";+ const relativePath = input.relativePath ?? "CONTEXT.md";+ const source = input.source ?? "CONTEXT.md";return {path,realPath: path,diff --git a/plugins/omo/components/rules/test/post-compact-test-fixture.ts b/plugins/omo/components/rules/test/post-compact-test-fixture.tsindex c34d54b0..b285e8ba 100644--- a/plugins/omo/components/rules/test/post-compact-test-fixture.ts+++ b/plugins/omo/components/rules/test/post-compact-test-fixture.ts@@ -5,7 +5,7 @@ import path from "node:path";import type { CodexPostCompactInput, CodexSessionStartInput, CodexUserPromptSubmitInput } from "../src/codex-hook.js";export const PROJECT_RULES_ENV = {- CODEX_RULES_ENABLED_SOURCES: "AGENTS.md,.omo/rules",+ CODEX_RULES_ENABLED_SOURCES: "CONTEXT.md,.omo/rules",CODEX_RULES_MAX_RESULT_CHARS: "50000",CODEX_RULES_MAX_RULE_CHARS: "30000",};@@ -30,7 +30,9 @@ export function makeOversizedProject(prefix = "budget"): { root: string; pluginDconst pluginData = mkdtempSync(path.join(tmpdir(), `codex-rules-post-compact-${prefix}-data-`));tempDirectories.push(root, pluginData);writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "fixture" }));- writeFileSync(path.join(root, "AGENTS.md"), `Project rule\n${"A".repeat(30_000)}`);+ writeFileSync(path.join(root, "AGENTS.md"), "Project AGENTS.md should stay Codex-native.");+ writeFileSync(path.join(root, "CLAUDE.md"), "Project CLAUDE.md should stay outside rules hook context.");+ writeFileSync(path.join(root, "CONTEXT.md"), `Project rule\n${"A".repeat(30_000)}`);mkdirSync(path.join(root, ".omo", "rules"), { recursive: true });writeFileSync(path.join(root, ".omo", "rules", "typescript.md"),diff --git a/plugins/omo/components/rules/test/sources.test.ts b/plugins/omo/components/rules/test/sources.test.tsnew file mode 100644index 00000000..02d4fbc9--- /dev/null+++ b/plugins/omo/components/rules/test/sources.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest";++import { SOURCE_PRIORITY } from "../src/rules/constants.js";+import { defaultConfig } from "../src/rules/engine.js";+import { disabledSourcesFromConfig } from "../src/rules/sources.js";+import type { PiRulesConfig } from "../src/rules/types.js";++describe("rules source selection", () => {+ it("#given default config #when disabled sources are derived #then opt-out sources stay disabled", () => {+ // given+ const config = defaultConfig();+ const expected = new Set(["AGENTS.md", "~/.claude/rules", "~/.claude/CLAUDE.md"]);++ // when+ const disabledSources = disabledSourcesFromConfig(config);+ expect(disabledSources).toBeDefined();+ if (disabledSources === undefined) return;++ // then+ expect(disabledSources).toEqual(expected);+ });++ it("#given explicit enabled sources #when disabled source set is derived #then all other known sources are omitted", () => {+ // given+ const config: PiRulesConfig = {+ ...defaultConfig(),+ enabledSources: [".omo/rules", "plugin-bundled"],+ };++ // when+ const disabledSources = disabledSourcesFromConfig(config);+ expect(disabledSources).toBeDefined();+ if (disabledSources === undefined) return;++ // then+ for (const source of [".omo/rules", "plugin-bundled"]) {+ expect(disabledSources.has(source)).toBe(false);+ }+ expect(disabledSources.has("~/.claude/rules")).toBe(true);+ expect(disabledSources).toEqual(+ new Set(+ [...SOURCE_PRIORITY.keys()].filter((source) => source !== ".omo/rules" && source !== "plugin-bundled"),+ ),+ );+ });+});diff --git a/plugins/omo/components/ultrawork/README.md b/plugins/omo/components/ultrawork/README.mdindex 09b0ecde..5ed4fa16 100644--- a/plugins/omo/components/ultrawork/README.md+++ b/plugins/omo/components/ultrawork/README.md@@ -35,6 +35,8 @@ node ${PLUGIN_ROOT}/dist/cli.js hook user-prompt-submitCodex passes the prompt payload on stdin. When the pattern `\b(?:ultrawork|ulw)\b` (case-insensitive) matches, the hook writes the directive to stdout — Codex injects non-JSON stdout as `additional_context` for the next turn. Otherwise the hook writes nothing and exits 0. Malformed input also exits 0 to never block the turn.+If a prior `UserPromptSubmit` hook output in transcript JSONL already contains `<ultrawork-mode>`, the hook suppresses itself so the same directive is not injected repeatedly. Plain transcript text containing `<ultrawork-mode>` is ignored unless it comes from hook output.+Bundled agent role TOMLs in `agents/` ship to `CODEX_HOME/agents/` at install time, not via a runtime hook. The installer creates a symlink on Linux / macOS and a file copy on Windows (because symlinks require admin privileges or Developer Mode). For the public marketplace, the source is the stable installed-marketplace snapshot, not the versioned plugin cache, so agent role configs remain valid when Codex replaces `~/.codex/plugins/cache/sisyphuslabs/omo/<version>/` during auto-update. Both code paths overwrite stale files and write a `.installed-agents.json` manifest next to the source root for clean uninstall tracking.## Smoke testdiff --git a/plugins/omo/components/ultrawork/src/codex-hook.ts b/plugins/omo/components/ultrawork/src/codex-hook.tsindex 49317db9..72c5d1ee 100644--- a/plugins/omo/components/ultrawork/src/codex-hook.ts+++ b/plugins/omo/components/ultrawork/src/codex-hook.ts@@ -3,6 +3,8 @@ import { readFileSync } from "node:fs";import { ULTRAWORK_DIRECTIVE } from "./directive.js";const ULTRAWORK_PATTERN = /\b(?:ultrawork|ulw)\b/i;+const ULTRAWORK_DIRECTIVE_MARKER = "<ultrawork-mode>";+const TRANSCRIPT_SEARCH_BYTES = 512_000;const CONTEXT_PRESSURE_MARKERS = ["context compacted","context_length_exceeded",@@ -29,10 +31,54 @@ interface UserPromptSubmitHookOutput {export function runUserPromptSubmitHook(input: unknown): string {if (!isCodexUserPromptSubmitInput(input)) return "";if (isContextPressureRecoveryPrompt(input.prompt)) return "";+ if (hasUltraworkDirectiveAlreadyInTranscript(input.transcript_path)) return "";if (isContextPressureTranscript(input.transcript_path)) return "";return isUltraworkPrompt(input.prompt) ? formatAdditionalContextOutput(ULTRAWORK_DIRECTIVE) : "";}+function hasUltraworkDirectiveAlreadyInTranscript(transcriptPath: string | null | undefined): boolean {+ if (transcriptPath === undefined || transcriptPath === null) return false;+ try {+ const rawTranscript = readTranscriptTail(transcriptPath);+ for (const line of rawTranscript.split(/\r?\n/)) {+ const parsed = parseJsonLine(line);+ if (parsed === null) {+ continue;+ }++ if (!isRecord(parsed)) {+ continue;+ }++ const hookSpecificOutput = parsed["hookSpecificOutput"];+ if (!isRecord(hookSpecificOutput)) {+ continue;+ }++ if (hookSpecificOutput["hookEventName"] !== "UserPromptSubmit") {+ continue;+ }++ if (+ typeof hookSpecificOutput["additionalContext"] === "string" &&+ hookSpecificOutput["additionalContext"].includes(ULTRAWORK_DIRECTIVE_MARKER)+ ) {+ return true;+ }+ }+ } catch (error) {+ if (error instanceof Error) return false;+ throw error;+ }++ return false;+}++function readTranscriptTail(transcriptPath: string): string {+ const rawTranscript = readFileSync(transcriptPath);+ return rawTranscript.subarray(Math.max(0, rawTranscript.byteLength - TRANSCRIPT_SEARCH_BYTES)).toString("utf8");+}+export function isUltraworkPrompt(prompt: string): boolean {return ULTRAWORK_PATTERN.test(prompt);}@@ -68,6 +114,22 @@ function normalizeAdditionalContext(additionalContext: string): string {return additionalContext.replace(/\r\n/g, "\n").replace(/\r/g, "\n").trim();}+function parseJsonLine(line: string): unknown | null {+ if (line.trim().length === 0) {+ return null;+ }++ try {+ const parsed: unknown = JSON.parse(line);+ return parsed;+ } catch (error) {+ if (error instanceof Error) {+ return null;+ }+ throw error;+ }+}+function isCodexUserPromptSubmitInput(value: unknown): value is CodexUserPromptSubmitInput {return (isRecord(value) &&diff --git a/plugins/omo/components/ultrawork/test/codex-hook.test.ts b/plugins/omo/components/ultrawork/test/codex-hook.test.tsindex a59f8d8e..25f5fbd5 100644--- a/plugins/omo/components/ultrawork/test/codex-hook.test.ts+++ b/plugins/omo/components/ultrawork/test/codex-hook.test.ts@@ -31,6 +31,49 @@ describe("codex ultrawork hook", () => {expect(parsed.hookSpecificOutput.additionalContext).toMatch(/First user-visible line this turn MUST be exactly:/);});+ it("#given transcript already contains ultrawork directive #when hook sees ultrawork prompt #then it does not repeat directive", () => {+ // given+ const payload = {+ hook_event_name: "UserPromptSubmit",+ prompt: "please ulw this change",+ transcript_path: writeTranscript(+ JSON.stringify({+ hookSpecificOutput: {+ hookEventName: "UserPromptSubmit",+ additionalContext: "<ultrawork-mode>\nexisting directive",+ },+ }),+ ),+ };++ // when+ const output = runUserPromptSubmitHook(payload);++ // then+ expect(output).toBe("");+ });++ it("#given transcript only mentions ultrawork marker in user content #when hook sees first ultrawork prompt #then it emits directive", () => {+ // given+ const payload = {+ hook_event_name: "UserPromptSubmit",+ prompt: "please ulw this change",+ transcript_path: writeTranscript(+ JSON.stringify({+ role: "user",+ content: "Please inspect text containing <ultrawork-mode> but do not activate yet.",+ }),+ ),+ };++ // when+ const output = runUserPromptSubmitHook(payload);+ const parsed = parseHookOutput(output);++ // then+ expect(parsed.hookSpecificOutput.additionalContext).toMatch(/^<ultrawork-mode>/);+ });+it("#given identifier-like ulw #when hook runs #then does not emit directive", () => {// givenconst payload = {@@ -244,6 +287,14 @@ function writeContextPressureTranscript(): string {return transcriptPath;}+function writeTranscript(...lines: string[]): string {+ const root = mkdtempSync(path.join(tmpdir(), "codex-ultrawork-transcript-"));+ tempDirectories.push(root);+ const transcriptPath = path.join(root, "transcript.jsonl");+ writeFileSync(transcriptPath, `${lines.join("\n")}\n`);+ return transcriptPath;+}+function writeCodexContextWindowTranscript(): string {const root = mkdtempSync(path.join(tmpdir(), "codex-ultrawork-context-window-"));tempDirectories.push(root);diff --git a/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.md b/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.mdindex f68c1cc6..2847532f 100644--- a/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.md+++ b/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.md@@ -172,7 +172,7 @@ Trigger only when one goal remains and all its criteria are passing.1. Run targeted verification for changed behavior.2. Run `ai-slop-cleaner` on changed files. If no relevant edits exist, record a passed no-op cleaner report.3. Rerun verification after cleanup.-4. Run `$code-review`.+4. Judge the change size. Spawn the `codex-ultrawork-reviewer` agent (`spawn_agent(agent_type="codex-ultrawork-reviewer", fork_turns="none", ...)`; fall back to `agent_type="worker"` with a scoped reviewer assignment if unavailable) only when the work is large or risky (multi-file, cross-cutting, new architecture, security/data surfaces, or you are unsure it is sound); for a small, local, low-risk change, do the review yourself and record `codeReview` with `evidence` starting `UNCONDITIONAL APPROVAL` plus a one-line justification of why the change was small enough to self-review.5. Clean review means `codeReview.recommendation == "APPROVE"` and `codeReview.architectStatus == "CLEAR"`.6. If review is non-clean, run `omo ulw-loop record-review-blockers --goal-id <id> --title "<...>" --objective "<...>" --evidence "<review findings>" --codex-goal-json <snapshot> --json`.7. If clean, checkpoint final completion:diff --git a/plugins/omo/components/ulw-loop/src/codex-goal-instruction.ts b/plugins/omo/components/ulw-loop/src/codex-goal-instruction.tsindex 48224672..e55954f2 100644--- a/plugins/omo/components/ulw-loop/src/codex-goal-instruction.ts+++ b/plugins/omo/components/ulw-loop/src/codex-goal-instruction.ts@@ -100,18 +100,18 @@ function formatCriterionLine(criterion: UlwLoopSuccessCriterion): string {function finalSection(plan: UlwLoopPlan, goal: UlwLoopItem, isFinal: boolean, aggregate: boolean): string {if (!isFinal)- return "- This is not the final ulw-loop story; do not run the final ai-slop-cleaner/$code-review gate yet.";+ return "- This is not the final ulw-loop story; do not run the final ai-slop-cleaner/code-review gate yet.";const option = sessionOption(plan);const blockerCommand = `omo ulw-loop record-review-blockers${option} --goal-id ${goal.id} --title "Resolve final code-review blockers" --objective "<blocker-resolution objective>" --evidence "<review findings>" --codex-goal-json "<active get_goal JSON or path>"`;const checkpointCommand = `omo ulw-loop checkpoint${option} --goal-id ${goal.id} --status complete --evidence "<tests/files/PR evidence>" --codex-goal-json "<fresh complete get_goal JSON or path>" --quality-gate-json "<quality gate JSON or path>"`;return joinLines(["Final story — run mandatory quality gate before update_goal:",- "- Run ai-slop-cleaner on changed files even when it is a no-op, rerun verification, then run $code-review.",- "- If final $code-review is not APPROVE with architect status CLEAR, do not call update_goal. Record blocker work first:",+ "- Run ai-slop-cleaner on changed files even when it is a no-op, rerun verification, then run the code review (spawn_agent(agent_type=\"codex-ultrawork-reviewer\", fork_turns=\"none\", ...); fall back to agent_type=\"worker\" with a scoped reviewer assignment if unavailable).",+ "- If the final review is not APPROVE with architect status CLEAR, do not call update_goal. Record blocker work first:",` ${blockerCommand}`,aggregate- ? '- If final $code-review is clean, call update_goal({status: "complete"}), call get_goal again, then checkpoint the aggregate story:'- : '- If final $code-review is clean, call update_goal({status: "complete"}), call get_goal again, then checkpoint:',+ ? '- If the final review is clean, call update_goal({status: "complete"}), call get_goal again, then checkpoint the aggregate story:'+ : '- If the final review is clean, call update_goal({status: "complete"}), call get_goal again, then checkpoint:',` ${checkpointCommand}`,]);}diff --git a/plugins/omo/components/ulw-loop/src/quality-gate.ts b/plugins/omo/components/ulw-loop/src/quality-gate.tsindex 4303b99a..baa6924e 100644--- a/plugins/omo/components/ulw-loop/src/quality-gate.ts+++ b/plugins/omo/components/ulw-loop/src/quality-gate.ts@@ -12,6 +12,7 @@ const GHCR_PATTERN =/\b(ghcr|github container registry|read packages|imagepullsecret|package api|anonymous|container image)\b/;const GHCR_401_PATTERN = /\b(401|unauthorized|anonymous pull|authentication required)\b/;const GHCR_403_PATTERN = /\b(403|forbidden|read packages|package api)\b/;+const UNCONDITIONAL_APPROVAL_PATTERN = /\bUNCONDITIONAL\s+APPROVAL\b/i;function invalid(message: string, field: string): never {throw new UlwLoopError(message, "ULW_LOOP_QUALITY_GATE_INVALID", { details: { field } });@@ -42,6 +43,58 @@ function stringArray(value: unknown, field: string): string[] {return value.map((item) => nonEmptyString(item, field));}+function normalizeReviewerField({+ value,+ field,+ expectedValue,+ evidenceApproved,+}: {+ value: unknown;+ field: string;+ expectedValue: "APPROVE";+ evidenceApproved: boolean;+}): "APPROVE";+function normalizeReviewerField({+ value,+ field,+ expectedValue,+ evidenceApproved,+}: {+ value: unknown;+ field: string;+ expectedValue: "CLEAR";+ evidenceApproved: boolean;+}): "CLEAR";+function normalizeReviewerField({+ value,+ field,+ expectedValue,+ evidenceApproved,+}: {+ value: unknown;+ field: string;+ expectedValue: "APPROVE" | "CLEAR";+ evidenceApproved: boolean;+}): "APPROVE" | "CLEAR" {+ if (typeof value === "string") {+ const trimmed = value.trim();+ if (trimmed === "") {+ if (evidenceApproved) return expectedValue;+ invalid(+ `${field} must be ${expectedValue} or codeReview.evidence should include UNCONDITIONAL APPROVAL.`,+ field,+ );+ }+ if (trimmed === expectedValue) return expectedValue;+ invalid(`${field} must be ${expectedValue}.`, field);+ }+ if (value === undefined) {+ if (evidenceApproved) return expectedValue;+ invalid(`${field} must be ${expectedValue} or codeReview.evidence should include UNCONDITIONAL APPROVAL.`, field);+ }+ invalid(`${field} must be ${expectedValue}.`, field);+}+export function validateQualityGate(input: unknown): UlwLoopQualityGate {const gate = section(input, "qualityGate");const cleaner = section(gate["aiSlopCleaner"], "aiSlopCleaner");@@ -50,8 +103,6 @@ export function validateQualityGate(input: unknown): UlwLoopQualityGate {const coverage = section(gate["criteriaCoverage"], "criteriaCoverage");if (cleaner["status"] !== "passed") invalid("aiSlopCleaner.status must be passed.", "aiSlopCleaner.status");if (verification["status"] !== "passed") invalid("verification.status must be passed.", "verification.status");- if (review["recommendation"] !== "APPROVE") invalid("recommendation must be APPROVE.", "codeReview.recommendation");- if (review["architectStatus"] !== "CLEAR") invalid("architectStatus must be CLEAR.", "codeReview.architectStatus");const totalCriteria = numberField(coverage["totalCriteria"], "criteriaCoverage.totalCriteria");const passCount = numberField(coverage["passCount"], "criteriaCoverage.passCount");if (passCount < totalCriteria)@@ -61,10 +112,23 @@ export function validateQualityGate(input: unknown): UlwLoopQualityGate {const cleanerEvidence = nonEmptyString(cleaner["evidence"], "aiSlopCleaner.evidence");const verificationEvidence = nonEmptyString(verification["evidence"], "verification.evidence");const reviewEvidence = nonEmptyString(review["evidence"], "codeReview.evidence");+ const approvalEvidence = UNCONDITIONAL_APPROVAL_PATTERN.test(reviewEvidence);+ const recommendation = normalizeReviewerField({+ value: review["recommendation"],+ field: "codeReview.recommendation",+ expectedValue: "APPROVE",+ evidenceApproved: approvalEvidence,+ });+ const architectStatus = normalizeReviewerField({+ value: review["architectStatus"],+ field: "codeReview.architectStatus",+ expectedValue: "CLEAR",+ evidenceApproved: approvalEvidence,+ });const result: UlwLoopQualityGate = {aiSlopCleaner: { status: "passed", evidence: cleanerEvidence },verification: { status: "passed", commands, evidence: verificationEvidence },- codeReview: { recommendation: "APPROVE", architectStatus: "CLEAR", evidence: reviewEvidence },+ codeReview: { recommendation, architectStatus, evidence: reviewEvidence },};Object.assign(result, { criteriaCoverage: { totalCriteria, passCount, adversarialClassesCovered: covered } });return result;diff --git a/plugins/omo/components/ulw-loop/test/quality-gate.test.ts b/plugins/omo/components/ulw-loop/test/quality-gate.test.tsindex 9dd0aebc..6c276e97 100644--- a/plugins/omo/components/ulw-loop/test/quality-gate.test.ts+++ b/plugins/omo/components/ulw-loop/test/quality-gate.test.ts@@ -81,6 +81,57 @@ describe("validateQualityGate", () => {expect(gate).toMatchObject({ criteriaCoverage: { totalCriteria: 9, passCount: 9 } });});+ it("infers APPROVE/CLEAR when clean reviewer evidence omits structured fields", () => {+ // given+ const input = makeGate({+ codeReview: {+ evidence: "UNCONDITIONAL APPROVAL\nAll criteria and QA evidence are complete.",+ },+ });++ // when+ const gate = validateQualityGate(input);++ // then+ expect(gate.codeReview.recommendation).toBe("APPROVE");+ expect(gate.codeReview.architectStatus).toBe("CLEAR");+ expect(gate.codeReview.evidence).toBe("UNCONDITIONAL APPROVAL\nAll criteria and QA evidence are complete.");+ });++ it("infers APPROVE/CLEAR when clean reviewer evidence has blank structured fields", () => {+ // given+ const input = makeGate({+ codeReview: {+ recommendation: "",+ architectStatus: " ",+ evidence: "UNCONDITIONAL APPROVAL\nAll criteria and QA evidence are complete.",+ },+ });++ // when+ const gate = validateQualityGate(input);++ // then+ expect(gate.codeReview.recommendation).toBe("APPROVE");+ expect(gate.codeReview.architectStatus).toBe("CLEAR");+ });++ it("throws when reviewer fields are omitted and evidence has no approval verdict", () => {+ // given+ const input = makeGate({+ codeReview: {+ evidence: "review completed without an explicit verdict",+ },+ });++ // when+ const error = getQualityGateError(input);++ // then+ expect(error.code).toBe("ULW_LOOP_QUALITY_GATE_INVALID");+ expect(error.message).toContain("UNCONDITIONAL APPROVAL");+ });+it("throws UlwLoopError when aiSlopCleaner missing", () => {// whenconst error = getQualityGateError(makeGate({ aiSlopCleaner: undefined }));diff --git a/plugins/omo/scripts/migrate-codex-config.mjs b/plugins/omo/scripts/migrate-codex-config.mjsindex 3c481f72..fd8b5bad 100644--- a/plugins/omo/scripts/migrate-codex-config.mjs+++ b/plugins/omo/scripts/migrate-codex-config.mjs@@ -1,6 +1,6 @@#!/usr/bin/env node-import { mkdir, readFile, stat, writeFile } from "node:fs/promises";+import { lstat, mkdir, readFile, writeFile } from "node:fs/promises";import { homedir } from "node:os";import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";@@ -169,7 +169,9 @@ async function configPaths({ env, cwd }) {const codexHome = resolve(env.CODEX_HOME?.trim() || join(homedir(), ".codex"));const paths = new Set([join(codexHome, "config.toml")]);for (const projectConfig of projectConfigPaths({ cwd, stopAt: homedir() })) {- if (await pathExists(projectConfig)) paths.add(projectConfig);+ if (!(await isRegularFile(projectConfig))) continue;+ if (!(await isRegularDirectory(dirname(projectConfig)))) continue;+ paths.add(projectConfig);}return [...paths];}@@ -216,10 +218,18 @@ async function writeState(statePath, state) {await writeFile(statePath, `${JSON.stringify(state, null, 2)}\n`);}-async function pathExists(path) {+async function isRegularFile(path) {try {- await stat(path);- return true;+ return (await lstat(path)).isFile();+ } catch (error) {+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;+ throw error;+ }+}++async function isRegularDirectory(path) {+ try {+ return (await lstat(path)).isDirectory();} catch (error) {if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;throw error;diff --git a/plugins/omo/skills/rules/SKILL.md b/plugins/omo/skills/rules/SKILL.mdindex 3ac40130..b1c27c4c 100644--- a/plugins/omo/skills/rules/SKILL.md+++ b/plugins/omo/skills/rules/SKILL.md@@ -14,10 +14,8 @@ Dynamic `PostToolUse` output is injected as additional context and is deduplicatSupported project sources:-- `AGENTS.md`-- `CLAUDE.md`- `CONTEXT.md`-- `.sisyphus/rules/**/*.md`+- `.omo/rules/**/*.md`- `.claude/rules/**/*.md`- `.cursor/rules/**/*.md`- `.github/instructions/**/*.md`@@ -29,6 +27,6 @@ Supported environment knobs:- `CODEX_RULES_MODE=both|static|dynamic|off`- `CODEX_RULES_MAX_RULE_CHARS=<number>`- `CODEX_RULES_MAX_RESULT_CHARS=<number>`-- `CODEX_RULES_ENABLED_SOURCES=AGENTS.md,.sisyphus/rules`+- `CODEX_RULES_ENABLED_SOURCES=CONTEXT.md,.omo/rules`The legacy `PI_RULES_*` variables are accepted as fallbacks for users migrating from `pi-rules`.diff --git a/plugins/omo/skills/ulw-loop/references/full-workflow.md b/plugins/omo/skills/ulw-loop/references/full-workflow.mdindex f68c1cc6..2847532f 100644--- a/plugins/omo/skills/ulw-loop/references/full-workflow.md+++ b/plugins/omo/skills/ulw-loop/references/full-workflow.md@@ -172,7 +172,7 @@ Trigger only when one goal remains and all its criteria are passing.1. Run targeted verification for changed behavior.2. Run `ai-slop-cleaner` on changed files. If no relevant edits exist, record a passed no-op cleaner report.3. Rerun verification after cleanup.-4. Run `$code-review`.+4. Judge the change size. Spawn the `codex-ultrawork-reviewer` agent (`spawn_agent(agent_type="codex-ultrawork-reviewer", fork_turns="none", ...)`; fall back to `agent_type="worker"` with a scoped reviewer assignment if unavailable) only when the work is large or risky (multi-file, cross-cutting, new architecture, security/data surfaces, or you are unsure it is sound); for a small, local, low-risk change, do the review yourself and record `codeReview` with `evidence` starting `UNCONDITIONAL APPROVAL` plus a one-line justification of why the change was small enough to self-review.5. Clean review means `codeReview.recommendation == "APPROVE"` and `codeReview.architectStatus == "CLEAR"`.6. If review is non-clean, run `omo ulw-loop record-review-blockers --goal-id <id> --title "<...>" --objective "<...>" --evidence "<review findings>" --codex-goal-json <snapshot> --json`.7. If clean, checkpoint final completion:diff --git a/plugins/omo/test/migrate-codex-config.test.mjs b/plugins/omo/test/migrate-codex-config.test.mjsindex 76f78e22..3898ec26 100644--- a/plugins/omo/test/migrate-codex-config.test.mjs+++ b/plugins/omo/test/migrate-codex-config.test.mjs@@ -1,5 +1,5 @@import assert from "node:assert/strict";-import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";+import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { dirname, join } from "node:path";import test from "node:test";@@ -32,6 +32,66 @@ test("#given stale root reasoning config #when ensuring config #then replaces stassert.match(result, /\[features\]/);});+test("#given project .codex is a symlink #when migrating #then project config is skipped", async (t) => {+ if (!(await canCreateSymlink("dir"))) t.skip("symbolic links are unavailable in this environment");++ const root = await mkdtemp(join(tmpdir(), "lazycodex-config-symlink-dir-"));+ const codexHome = join(root, "codex-home");+ const project = join(root, "project");+ const projectNested = join(project, "nested");+ const projectCodexDirectory = join(root, "project-codex-real");+ const projectConfigTarget = join(projectCodexDirectory, "config.toml");+ const projectConfig = join(project, ".codex", "config.toml");++ await mkdir(codexHome, { recursive: true });+ await mkdir(projectCodexDirectory, { recursive: true });+ await mkdir(dirname(projectConfigTarget), { recursive: true });+ await mkdir(projectNested, { recursive: true });+ await writeFile(join(codexHome, "config.toml"), 'model = "gpt-5.2"\n');+ await writeFile(projectConfigTarget, 'model = "gpt-5.2"\nmodel_context_window = 272000\n');+ await rm(join(project, ".codex"), { recursive: true, force: true });+ await symlink(projectCodexDirectory, join(project, ".codex"), "dir");++ const result = await migrateCodexConfig({+ env: {+ CODEX_HOME: codexHome,+ LAZYCODEX_MODEL_CATALOG_STATE_PATH: join(root, "model-state.json"),+ },+ cwd: projectNested,+ });++ assert.deepEqual(result.changed, [join(codexHome, "config.toml")]);+ assert.match(await readFile(projectConfig, "utf8"), /model = "gpt-5\.2"/);+});++test("#given project config.toml is a symlink #when migrating #then project config is skipped", async (t) => {+ if (!(await canCreateSymlink("file"))) t.skip("symbolic links are unavailable in this environment");++ const root = await mkdtemp(join(tmpdir(), "lazycodex-config-symlink-file-"));+ const codexHome = join(root, "codex-home");+ const project = join(root, "project");+ const projectConfigDirectory = join(project, ".codex");+ const projectConfig = join(projectConfigDirectory, "config.toml");+ const realConfigSource = join(root, "shared-config.toml");++ await mkdir(codexHome, { recursive: true });+ await mkdir(projectConfigDirectory, { recursive: true });+ await writeFile(join(codexHome, "config.toml"), 'model = "gpt-5.2"\n');+ await writeFile(realConfigSource, 'model = "gpt-5.2"\nmodel_context_window = 272000\n');+ await symlink(realConfigSource, projectConfig, "file");++ const result = await migrateCodexConfig({+ env: {+ CODEX_HOME: codexHome,+ LAZYCODEX_MODEL_CATALOG_STATE_PATH: join(root, "model-state.json"),+ },+ cwd: project,+ });++ assert.deepEqual(result.changed, [join(codexHome, "config.toml")]);+ assert.match(await readFile(realConfigSource, "utf8"), /model = "gpt-5\.2"/);+});+test("#given global and project-local stale Codex configs #when migrating #then both configs are forced to current defaults", async () => {const root = await mkdtemp(join(tmpdir(), "lazycodex-config-migration-"));const codexHome = join(root, "codex-home");@@ -144,3 +204,29 @@ test("#given managed catalog state #when catalog version advances #then only preassert.match(content, /model = "gpt-5\.5"/);assert.match(content, /model_context_window = 400000/);});++async function canCreateSymlink(type) {+ const root = await mkdtemp(join(tmpdir(), "lazycodex-symlink-capability-"));+ const target = join(root, "target");+ const link = join(root, "link");++ try {+ if (type === "dir") {+ await mkdir(target, { recursive: true });+ await symlink(target, link, "dir");+ } else {+ await writeFile(target, "");+ await symlink(target, link, "file");+ }++ await rm(link);+ await rm(target, { recursive: true, force: true });+ await rm(root, { recursive: true, force: true });+ return true;+ } catch (error) {+ await rm(root, { recursive: true, force: true });+ if (!(error instanceof Error)) throw error;+ if (error.code === "EPERM" || error.code === "EEXIST") return false;+ return false;+ }+}