Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(plugins): add native Codex adapters for ADR DDD and SPARC mods

Stuart Kerrb968e34970e5
diff --git a/plugins/ruflo-adr/.codex-plugin/plugin.json b/plugins/ruflo-adr/.codex-plugin/plugin.json
new file mode 100644
index 0000000000..ca9da01fb7
--- /dev/null
+++ b/plugins/ruflo-adr/.codex-plugin/plugin.json
@@ -0,0 +1,12 @@
+{
+ "name": "ruflo-adr",
+ "description": "ADR lifecycle management \u2014 create, index, reconcile, supersede, check compliance, and link Architecture Decision Records to code via AgentDB hierarchical store + causal edges (supersedes/amends/depends-on/related)",
+ "version": "0.5.3",
+ "author": {
+ "name": "ruvnet",
+ "url": "https://github.com/ruvnet"
+ },
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "license": "MIT",
+ "hooks": "./hooks/codex-hooks.json"
+}
diff --git a/plugins/ruflo-adr/README.md b/plugins/ruflo-adr/README.md
index 8716f3028d..1adb9f7f90 100644
--- a/plugins/ruflo-adr/README.md
+++ b/plugins/ruflo-adr/README.md
@@ -104,3 +104,32 @@ ADR also ships as a function-hook mod (ADR-445 pattern; hooks in `hooks/`, loade
- **Options** (`userConfig`): `guard` (`on` by default).
Test: `claude plugin validate plugins/ruflo-adr`, `claude plugin test plugins/ruflo-adr`, and `bash plugins/ruflo-adr/scripts/smoke.sh`.
+
+## Native Codex hooks
+
+The separate `.codex-plugin/plugin.json` selects `hooks/codex-hooks.json`, replacing
+the Claude-only module entry for Codex. Claude's manifest and `register.ts` remain
+unchanged. The synchronous native `PreToolUse` adapter bundles the existing pure
+guard and shared secret screen; it preserves their tool/namespace scope and emits
+the native permission-denial envelope before a guarded write. `SessionStart` and
+guarded calls maintain private per-session counters in `PLUGIN_DATA`; the existing
+version-1 project status file remains a best-effort courtesy view. Status failure
+does not permit a denied write. Guarding is enabled for the native adapter.
+
+Existing skills and command files remain available. Claude's dynamic
+`$.command.register` / `command.run` mod interception has no native command-hook
+equivalent: Codex does **not** get that interception. The same deterministic local
+command helpers are available explicitly via
+`node <plugin-root>/hooks/codex-hook.cjs --command status` (and the helper's existing
+subcommands). This is guard/status compatibility, not full SDK-mod parity.
+
+Maintainers rebuild the committed standalone bundles with
+`ESBUILD=<esbuild executable> node scripts/build-codex-mod-hooks.mjs`, then run
+`node --test tests/plugins/codex-mod-hooks.test.mjs`. Set `ESBUILD` in that test run
+to check byte reproducibility using the same installed builder. Run
+`scripts/sync-mod-screen.mjs --check` before bundling when the shared screen changes.
+The adapters need Node.js and contain no runtime SDK dependency.
+
+This source change requires a released upstream package or an explicitly owned
+source projection to reach installations. It does not patch foreign cache entries,
+pin upstream updates, disable plugins, or claim an already published repair.
diff --git a/plugins/ruflo-adr/hooks/codex-hook.cjs b/plugins/ruflo-adr/hooks/codex-hook.cjs
new file mode 100644
index 0000000000..b361a02a26
--- /dev/null
+++ b/plugins/ruflo-adr/hooks/codex-hook.cjs
@@ -0,0 +1,11 @@
+// Generated by scripts/build-codex-mod-hooks.mjs; edit codex.ts or shared runtime, not this bundle.
+"use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var import_node_fs=__toESM(require("node:fs"),1);var import_node_path=__toESM(require("node:path"),1);var import_node_os=__toESM(require("node:os"),1);var import_node_crypto=__toESM(require("node:crypto"),1);var hash=text=>import_node_crypto.default.createHash("sha256").update(text).digest("hex");var plain=value=>value!==null&&typeof value==="object"&&!Array.isArray(value);var MAX_INPUT=8*1024*1024;function directory(target){const absolute=import_node_path.default.resolve(target);let current=import_node_path.default.parse(absolute).root;for(const segment of absolute.slice(current.length).split(import_node_path.default.sep).filter(Boolean)){current=import_node_path.default.join(current,segment);try{import_node_fs.default.mkdirSync(current,{mode:448})}catch(error){if(error.code!=="EEXIST")throw error}const stat=import_node_fs.default.lstatSync(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Unsafe status directory")}return absolute}function snapshot(file){try{const stat=import_node_fs.default.lstatSync(file);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>65536)return void 0;return JSON.parse(import_node_fs.default.readFileSync(file,"utf8"))}catch{return void 0}}function write(file,bytes){if(import_node_fs.default.existsSync(file)&&import_node_fs.default.lstatSync(file).isSymbolicLink())throw new Error("Unsafe status file");const tmp=`${file}.${import_node_crypto.default.randomUUID()}.tmp`;try{const fd=import_node_fs.default.openSync(tmp,"wx",384);try{import_node_fs.default.writeFileSync(fd,bytes);import_node_fs.default.fsyncSync(fd)}finally{import_node_fs.default.closeSync(fd)}import_node_fs.default.renameSync(tmp,file)}finally{if(import_node_fs.default.existsSync(tmp))import_node_fs.default.unlinkSync(tmp)}}function updateStatus(plugin,event,change){const data=directory(process.env.PLUGIN_DATA??import_node_path.default.join(import_node_os.default.homedir(),".cache","ruflo-codex",plugin.name));const sessions=directory(import_node_path.default.join(data,"sessions"));const file=import_node_path.default.join(sessions,`${hash(`${event.cwd}\0${event.session_id}`)}.json`);const lock=`${file}.lock`;let acquired=false;for(let attempt=0;attempt<25;attempt++){try{import_node_fs.default.mkdirSync(lock,{mode:448});acquired=true;break}catch(error){if(error.code!=="EEXIST")throw error;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}}if(!acquired)throw new Error("Status writer busy");try{const old=snapshot(file);const stats=old?.version===1&&old.host==="codex"&&old.sessionId===event.session_id&&plain(old.stats)?old.stats:plugin.newStats();change(stats);const now=Date.now();const body={version:1,host:"codex",sessionId:event.session_id,stats,updatedMs:now};write(file,`${JSON.stringify(body)}
+`);try{const courtesy=import_node_path.default.join(directory(import_node_path.default.join(event.cwd,import_node_path.default.dirname(plugin.statusPath))),import_node_path.default.basename(plugin.statusPath));const view=JSON.parse(plugin.statusText(stats,now));write(courtesy,`${JSON.stringify({...view,host:"codex",sessionId:event.session_id},null,2)}
+`)}catch{}return stats}finally{import_node_fs.default.rmdirSync(lock)}}function validEvent(event){return plain(event)&&typeof event.cwd==="string"&&import_node_path.default.isAbsolute(event.cwd)&&typeof event.session_id==="string"&&event.session_id.length>0&&event.session_id.length<=512}async function runCodexHook(plugin){const mode=process.argv[2];if(mode==="--command"){const cwd=process.cwd();const view=snapshot(import_node_path.default.join(cwd,plugin.statusPath));const text=await plugin.answer(process.argv.slice(3).join(" "),{opts:{guard:true},guard:true,stats:view?.host==="codex"?view:plugin.newStats(),tools:async()=>[],list:async relative=>import_node_fs.default.readdirSync(import_node_path.default.join(cwd,relative),{withFileTypes:true}).map(entry=>({name:entry.name,kind:entry.isDirectory()?"dir":"file"}))});process.stdout.write(`${text}
+`);return}const chunks=[];let bytes=0;for await(const chunk of process.stdin){bytes+=chunk.length;if(bytes>MAX_INPUT)throw new Error("Hook input exceeds bound");chunks.push(chunk)}const event=JSON.parse(Buffer.concat(chunks).toString("utf8"));if(!validEvent(event)||event.hook_event_name!==mode)throw new Error("Invalid hook envelope");if(mode==="SessionStart"){try{updateStatus(plugin,event,stats=>{if("startedMs"in stats&&!stats.startedMs)stats.startedMs=Date.now()})}catch{process.stderr.write(`${plugin.name}: courtesy status unavailable
+`)}return}if(mode!=="PreToolUse"||typeof event.tool_name!=="string"||!plain(event.tool_input))throw new Error("Invalid native tool event");const reason=plugin.verdict(event.tool_name,event.tool_input);try{updateStatus(plugin,event,stats=>plugin.count(stats,event.tool_name,event.tool_input,reason))}catch{process.stderr.write(`${plugin.name}: courtesy status unavailable
+`)}if(reason!==void 0)process.stdout.write(`${JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:reason}})}
+`)}function hookFailure(plugin){process.stderr.write(`${plugin}: native hook input or adapter failed
+`);process.exitCode=2}var newStats=()=>({calls:0,blocked:0,startedMs:0});var STATUS_PATH=".claude-flow/adr-mod/status.json";function statusText(stats,mode,nowMs){return`${JSON.stringify({version:1,updatedMs:nowMs,mod:"adr",guard:mode.guard,...stats},null,2)}
+`}var COMMON_SECRETS=[["private key",/-----BEGIN [A-Z ]*PRIVATE KEY-----/],["aws access key",/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/],["github token",/\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})\b/],["slack token",/\bxox[abprs]-[A-Za-z0-9-]{10,}/],["slack webhook",/\bhooks\.slack\.com\/services\/T[A-Z0-9]{6,}\/B[A-Z0-9]{6,}\/[A-Za-z0-9]{16,}/],["google api key",/\bAIza[0-9A-Za-z_-]{35}\b/],["anthropic or openai key",/\bsk-(?:(?:ant|proj|svcacct|admin)-[A-Za-z0-9_-]{20,}|(?=[A-Za-z]{0,40}\d)[A-Za-z0-9]{32,})/],["stripe key",/\b[rs]k_live_[A-Za-z0-9]{16,}/],["npm token",/\bnpm_[A-Za-z0-9]{36}\b/],["huggingface token",/\bhf_[A-Za-z0-9]{30,}\b/],["sendgrid key",/\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/],["twilio key",/\bSK[0-9a-f]{32}\b/],["jwt",/\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/],["bearer token",/\bBearer\s+([A-Za-z0-9._~+/=-]{24,})/],["database url with credentials",/\b[a-z][a-z0-9+.-]{1,20}:\/\/[^\s:@/]+:[^\s@/]{3,}@[^\s/]+/i]];var INJECTION=[["override instructions",/\b(?:ignore|disregard|forget|override)\b[^.\n]{0,40}\b(?:previous|prior|above|earlier|all|any|system)\b[^.\n]{0,30}\b(?:instructions?|rules?|prompts?|guidelines?)\b/i],["role reassignment",/\byou are (?:now|no longer)\b|\bact as (?:an? )?(?:unrestricted|jailbroken)\b/i],["new instructions",/\b(?:new|updated|real) (?:system )?instructions?\s*:/i],["fake role tags",/<\/?\s*(?:system|assistant|developer|instructions?)\s*>|^\s*(?:system|assistant)\s*:/im],["concealment",/\bdo not (?:tell|inform|mention|reveal)[^.\n]{0,30}\b(?:user|human|operator)\b/i],["exfiltration",/\b(?:exfiltrate|send|post|upload)\b[^.\n]{0,50}\b(?:secrets?|credentials?|tokens?|api keys?|\.env)\b/i],["shell pipe",/\b(?:curl|wget)\b[^|\n]{0,200}\|\s*(?:sudo\s+)?(?:ba|z)?sh\b/i]];var INVISIBLE=new RegExp("[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u00ad\\u034f\\u061c\\u115f\\u1160\\u17b4\\u17b5\\u180b-\\u180e\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u206f\\u3164\\ufe00-\\ufe0f\\ufeff\\uffa0\\ufff9-\\ufffb]","g");var MAX_SCAN=2e5;var bare=text=>(text.length>MAX_SCAN?text.slice(0,MAX_SCAN/2)+"\n"+text.slice(-MAX_SCAN/2):text).replace(INVISIBLE,"");var PLACEHOLDER=/placeholder|your[-_ ]|example|changeme|change[-_]?me|redacted|dummy|replace[-_]?me|insert[-_]|\*{3,}|x{5,}|\.{3}|^(?:none|null|undefined|true|false)$/i;var REFERENCE=/^(?:\$(?:\{[^}]*\}|\(|[A-Za-z_]\w*$)|%[^%]*%$|<[^>]*>$|\{\{|process\.env|os\.environ|env[.[]|import\.meta|System\.getenv|secrets?\.|vault:|op:\/\/|ref\+|arn:|projects\/[^/]+\/secrets\/|gcp:|kms:|aws:|file:)/i;var CALL=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\(|^[A-Za-z_$][\w$]*\[/;var IDENT_PATH=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/;var UUID=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;var NAME_LIKE=/^[a-z][a-z0-9]*(?:[-_./][a-z0-9]+){2,}$/;function entropy(v){const counts=new Map;for(const ch of v)counts.set(ch,(counts.get(ch)??0)+1);let h=0;for(const n of counts.values())h-=n/v.length*Math.log2(n/v.length);return h}function isReference(v){if(PLACEHOLDER.test(v)||REFERENCE.test(v)||CALL.test(v)||IDENT_PATH.test(v)||URL_NO_CREDS.test(v))return true;return NAME_LIKE.test(v)&&v.replace(/\D/g,"").length/v.length<.15}function plausibleSecret(v){if(v.length<8||v.length>256||/\s/.test(v)||UUID.test(v)||isReference(v))return false;const symbol=/[^A-Za-z0-9]/.test(v);const digit=/\d/.test(v);const classes=[/[a-z]/.test(v),/[A-Z]/.test(v),digit,symbol].filter(Boolean).length;return classes>=2&&(digit||symbol)&&entropy(v)>=2.5}var KEYED_MIN=20;var PLACEHOLDER_WORD=/(?:^|[^a-z])(?:your|placeholder|changeme|change[-_]?me|example|redacted|dummy|replace[-_]?me|insert)(?:[^a-z]|$)|\*{3,}|x{5,}|\.{3}|^(?:none|null|undefined|true|false)$/i;var URL_NO_CREDS=/^[a-z][a-z0-9+.-]{1,20}:\/\/[^\s@]*$/i;function hyphenName(v){const parts=v.split("-");return parts.length>=3&&parts.every(p=>/^[a-z0-9]{2,}$/.test(p)&&!/^[0-9a-f]{8,}$/.test(p))&&v.replace(/\D/g,"").length/v.length<.15}function keyedSecret(v){if(v.length<KEYED_MIN||v.length>256||/\s/.test(v))return false;return!(PLACEHOLDER_WORD.test(v)||REFERENCE.test(v)||CALL.test(v)||IDENT_PATH.test(v)||URL_NO_CREDS.test(v)||!UUID.test(v)&&hyphenName(v))}var KEY_NAME=/(?:api[_-]?key|secret|token|passw(?:or)?d|passwd|pwd|credential|private[_-]?key|auth(?!or))s?[A-Za-z0-9_-]{0,40}["']?\s*[:=]\s*/gi;var QUOTED=/(["'\x60])((?:(?!\1)[^\n]){1,256})\1/y;var BARE_VALUE=/[^\s"'\x60,;]{1,256}/y;var QUERY_VALUE=/[^\s"'\x60,;&]{1,256}/y;function assignmentSecret(text){let valueEnd=0;for(const m of text.matchAll(KEY_NAME)){if(m.index<valueEnd)continue;const at=m.index+m[0].length;let back=m.index;while(back>0&&m.index-back<64&&/[A-Za-z0-9_.-]/.test(text.charAt(back-1)))back--;const re=/["'\x60]/.test(text.charAt(at))?QUOTED:/[?&]/.test(text.charAt(back-1))?QUERY_VALUE:BARE_VALUE;re.lastIndex=at;const hit=re.exec(text);const v=hit&&(hit[2]??hit[0]);valueEnd=hit?at+hit[0].length:at;if(v&&(plausibleSecret(v)||keyedSecret(v)))return true}return false}function urlCredential(url){const pass=/^[^:]+:\/\/[^\s:@/]+:([^\s@/]+)@/.exec(url)?.[1];if(!pass||/\$\{|\{\{|%\(|%s/.test(pass))return false;return!/^(?:password|passwd|pass|pwd|secret|changeme|dbpassword|db_password|\$\w*|<.*>|\{.*\}|\*+|x+)$/i.test(pass)&&!PLACEHOLDER.test(pass)}var CHECKS={"bearer token":m=>!isReference(m[1]??""),"database url with credentials":m=>urlCredential(m[0]),"database url with password":m=>urlCredential(m[0])};var globals=new WeakMap;function matches(name,re,text){if(name==="key assignment")return assignmentSecret(text);const check=CHECKS[name];if(!check)return re.test(text);let g=globals.get(re);if(!g)globals.set(re,g=new RegExp(re.source,re.flags.includes("g")?re.flags:re.flags+"g"));for(const m of text.matchAll(g))if(check(m))return true;return false}var TRUNCATED="ruflo-screen: input exceeded the screening budget";var TRUNCATED_NAME="input too large to screen";var names=(rules,text)=>text===TRUNCATED?[TRUNCATED_NAME]:rules.filter(([name,re])=>matches(name,re,text)).map(([name])=>name);function screenWith(secrets,text){const bounded=bare(text);return{secrets:names(secrets,bounded),injection:names(INJECTION,bounded)}}var hasSecretIn=(secrets,text)=>names(secrets,bare(text)).length>0;var NODES=2e4;var CHARS=2e6;var PER_STRING=15e5;var OVERLAP=2048;var BARE_KEY_MIN=8;function windows(text,out){if(text.length<=MAX_SCAN){out.push(text);return}for(let at=0;;at+=MAX_SCAN-OVERLAP){out.push(text.slice(at,at+MAX_SCAN));if(at+MAX_SCAN>=text.length)return}}function textsOf(input,limits={}){const out=[];let slots=limits.nodes??NODES;let chars=limits.chars??CHARS;const perString=limits.perString??PER_STRING;let truncated=false;const take=text=>{if(chars<=0){truncated=true;return}if(text.length<=Math.min(perString,chars)){chars-=text.length;windows(text,out);return}truncated=true;const half=Math.floor(Math.min(perString,chars)/2);chars-=2*half;windows(text.slice(0,half),out);windows(text.slice(-half),out)};const queue=[input];let head=0;for(;head<queue.length&&chars>0;head++){const node=queue[head];if(typeof node==="string")take(node);else if(Array.isArray(node)){let i=0;for(;i<node.length&&slots>0;i++,slots--)if(i in node)queue.push(node[i]);if(i<node.length)truncated=true}else if(typeof node==="object"&&node!==null){for(const k in node){if(slots--<=0){truncated=true;break}if(!Object.prototype.hasOwnProperty.call(node,k))continue;const v=node[k];if(typeof v==="string")queue.push(k+"="+v);else{if(k.length>=BARE_KEY_MIN)take(k);queue.push(v)}}}}if(queue.length>head)truncated=true;if(truncated)out.push(TRUNCATED);return out}var SECRETS=[...COMMON_SECRETS,["key assignment",/\b(?:api[_-]?key|secret|token|passw(?:or)?d|credential)s?["']?\s*[:=]\s*["']?[A-Za-z0-9/+=_.-]{16,}/i]];var scan=text=>screenWith(SECRETS,text);var hasSecret=text=>hasSecretIn(SECRETS,text);var HELP=["/adr-mod status","/adr-mod scan <text>","/adr-mod format"].join("\n");function answer(args,deps){const[verb="",...rest]=args.trim().split(/\s+/);const arg=rest.join(" ");const{opts,stats}=deps;if(verb===""||verb==="help")return HELP;if(verb==="status"){return`guard ${opts.guard?"on":"off"} \xB7 calls guarded ${stats.calls} \xB7 blocked ${stats.blocked}`}if(verb==="scan"){if(arg==="")return"usage: /adr-mod scan <text>";const found=scan(arg);const parts=[found.secrets.length?`secrets: ${found.secrets.join(", ")}`:"",found.injection.length?`injection phrasing: ${found.injection.join(", ")}`:""].filter(Boolean);return parts.length?`The guard would refuse a write of that (${parts.join("; ")}).`:"Nothing found: the guard would let that through."}if(verb==="format")return"An ADR carries: Status (proposed, accepted, deprecated, superseded), Context, Decision, Consequences. Relations: supersedes, amends, depends-on, related. Create with /adr-create, index with /adr-index.";return`Unknown: ${verb}
+${HELP}`}function splitName(name){if(!name.startsWith("mcp__"))return void 0;const at=name.lastIndexOf("__");return at>5?{server:name.slice(5,at),tool:name.slice(at+2)}:void 0}var namespaceOf=input=>{const ns=input?.namespace;return typeof ns==="string"?ns:""};var ADR_ID=/^(?:mem:)?ADR-/i;var field=(input,key)=>{const v=input?.[key];return typeof v==="string"?v:""};function owns(tool,input){const parts=splitName(tool);const name=parts?.tool??tool;const adrNamespace=/adr/i.test(namespaceOf(input));if(name==="memory_store")return adrNamespace;if(name==="agentdb_hierarchical-store")return adrNamespace||ADR_ID.test(field(input,"key"));if(name==="agentdb_causal-edge")return adrNamespace||ADR_ID.test(field(input,"sourceId"))||ADR_ID.test(field(input,"targetId"));return false}function verdict(tool,input){if(!owns(tool,input))return void 0;return textsOf(input).some(hasSecret)?"ruflo-adr: this ADR write holds what looks like a secret (a key, token or password). An ADR records a decision; name where the secret lives, not its value.":void 0}runCodexHook({name:"ruflo-adr",verdict,newStats,statusPath:STATUS_PATH,answer,statusText:(stats,now)=>statusText(stats,{guard:true},now),count:(stats,tool,input,reason)=>{if(owns(tool,input)){stats.calls++;if(reason!==void 0)stats.blocked++}}}).catch(()=>hookFailure("ruflo-adr"));
diff --git a/plugins/ruflo-adr/hooks/codex-hooks.json b/plugins/ruflo-adr/hooks/codex-hooks.json
new file mode 100644
index 0000000000..29b2acd0f1
--- /dev/null
+++ b/plugins/ruflo-adr/hooks/codex-hooks.json
@@ -0,0 +1,27 @@
+{
+ "description": "Native Codex ADR secret guard and session status; Claude module hooks remain separate.",
+ "hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/hooks/codex-hook.cjs\" SessionStart",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "PreToolUse": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/hooks/codex-hook.cjs\" PreToolUse",
+ "timeout": 5
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/plugins/ruflo-adr/hooks/codex.ts b/plugins/ruflo-adr/hooks/codex.ts
new file mode 100644
index 0000000000..1a3f4ae4a4
--- /dev/null
+++ b/plugins/ruflo-adr/hooks/codex.ts
@@ -0,0 +1,9 @@
+import { runCodexHook, hookFailure } from '../../../scripts/lib/codex-mod-runtime.mjs'
+import { newStats, STATUS_PATH, statusText } from './status'
+import { answer } from './command'
+import { verdict, owns } from './guard'
+
+runCodexHook({ name: 'ruflo-adr', verdict, newStats, statusPath: STATUS_PATH, answer,
+ statusText: (stats, now) => statusText(stats, { guard: true }, now),
+ count: (stats, tool, input, reason) => { if (owns(tool, input)) { stats.calls++; if (reason !== undefined) stats.blocked++; } },
+}).catch(() => hookFailure('ruflo-adr'))
diff --git a/plugins/ruflo-ddd/.codex-plugin/plugin.json b/plugins/ruflo-ddd/.codex-plugin/plugin.json
new file mode 100644
index 0000000000..afe6a9aa0c
--- /dev/null
+++ b/plugins/ruflo-ddd/.codex-plugin/plugin.json
@@ -0,0 +1,12 @@
+{
+ "name": "ruflo-ddd",
+ "description": "Domain-Driven Design scaffolding \u2014 bounded contexts, aggregate roots, domain events, value objects, repositories, and anti-corruption layers; navigable domain graph stored in AgentDB",
+ "version": "0.3.3",
+ "author": {
+ "name": "ruvnet",
+ "url": "https://github.com/ruvnet"
+ },
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "license": "MIT",
+ "hooks": "./hooks/codex-hooks.json"
+}
diff --git a/plugins/ruflo-ddd/README.md b/plugins/ruflo-ddd/README.md
index f6814c80fc..bb0adec0d5 100644
--- a/plugins/ruflo-ddd/README.md
+++ b/plugins/ruflo-ddd/README.md
@@ -104,3 +104,32 @@ Since this version the plugin is also a function-hook mod (ADR-445 pattern; need
- **Option**: `guard` (`on` | `off`, default `on`) in the plugin's `userConfig`.
Test it: `claude plugin test plugins/ruflo-ddd` and `bash plugins/ruflo-ddd/scripts/smoke.sh`.
+
+## Native Codex hooks
+
+The separate `.codex-plugin/plugin.json` selects `hooks/codex-hooks.json`, replacing
+the Claude-only module entry for Codex. Claude's manifest and `register.ts` remain
+unchanged. The synchronous native `PreToolUse` adapter bundles the existing pure
+guard and shared secret screen; it preserves their tool/namespace scope and emits
+the native permission-denial envelope before a guarded write. `SessionStart` and
+guarded calls maintain private per-session counters in `PLUGIN_DATA`; the existing
+version-1 project status file remains a best-effort courtesy view. Status failure
+does not permit a denied write. Guarding is enabled for the native adapter.
+
+Existing skills and command files remain available. Claude's dynamic
+`$.command.register` / `command.run` mod interception has no native command-hook
+equivalent: Codex does **not** get that interception. The same deterministic local
+command helpers are available explicitly via
+`node <plugin-root>/hooks/codex-hook.cjs --command status` (and the helper's existing
+subcommands). This is guard/status compatibility, not full SDK-mod parity.
+
+Maintainers rebuild the committed standalone bundles with
+`ESBUILD=<esbuild executable> node scripts/build-codex-mod-hooks.mjs`, then run
+`node --test tests/plugins/codex-mod-hooks.test.mjs`. Set `ESBUILD` in that test run
+to check byte reproducibility using the same installed builder. Run
+`scripts/sync-mod-screen.mjs --check` before bundling when the shared screen changes.
+The adapters need Node.js and contain no runtime SDK dependency.
+
+This source change requires a released upstream package or an explicitly owned
+source projection to reach installations. It does not patch foreign cache entries,
+pin upstream updates, disable plugins, or claim an already published repair.
diff --git a/plugins/ruflo-ddd/hooks/codex-hook.cjs b/plugins/ruflo-ddd/hooks/codex-hook.cjs
new file mode 100644
index 0000000000..73eaf29e5e
--- /dev/null
+++ b/plugins/ruflo-ddd/hooks/codex-hook.cjs
@@ -0,0 +1,12 @@
+// Generated by scripts/build-codex-mod-hooks.mjs; edit codex.ts or shared runtime, not this bundle.
+"use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var import_node_fs=__toESM(require("node:fs"),1);var import_node_path=__toESM(require("node:path"),1);var import_node_os=__toESM(require("node:os"),1);var import_node_crypto=__toESM(require("node:crypto"),1);var hash=text=>import_node_crypto.default.createHash("sha256").update(text).digest("hex");var plain=value=>value!==null&&typeof value==="object"&&!Array.isArray(value);var MAX_INPUT=8*1024*1024;function directory(target){const absolute=import_node_path.default.resolve(target);let current=import_node_path.default.parse(absolute).root;for(const segment of absolute.slice(current.length).split(import_node_path.default.sep).filter(Boolean)){current=import_node_path.default.join(current,segment);try{import_node_fs.default.mkdirSync(current,{mode:448})}catch(error){if(error.code!=="EEXIST")throw error}const stat=import_node_fs.default.lstatSync(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Unsafe status directory")}return absolute}function snapshot(file){try{const stat=import_node_fs.default.lstatSync(file);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>65536)return void 0;return JSON.parse(import_node_fs.default.readFileSync(file,"utf8"))}catch{return void 0}}function write(file,bytes){if(import_node_fs.default.existsSync(file)&&import_node_fs.default.lstatSync(file).isSymbolicLink())throw new Error("Unsafe status file");const tmp=`${file}.${import_node_crypto.default.randomUUID()}.tmp`;try{const fd=import_node_fs.default.openSync(tmp,"wx",384);try{import_node_fs.default.writeFileSync(fd,bytes);import_node_fs.default.fsyncSync(fd)}finally{import_node_fs.default.closeSync(fd)}import_node_fs.default.renameSync(tmp,file)}finally{if(import_node_fs.default.existsSync(tmp))import_node_fs.default.unlinkSync(tmp)}}function updateStatus(plugin,event,change){const data=directory(process.env.PLUGIN_DATA??import_node_path.default.join(import_node_os.default.homedir(),".cache","ruflo-codex",plugin.name));const sessions=directory(import_node_path.default.join(data,"sessions"));const file=import_node_path.default.join(sessions,`${hash(`${event.cwd}\0${event.session_id}`)}.json`);const lock=`${file}.lock`;let acquired=false;for(let attempt=0;attempt<25;attempt++){try{import_node_fs.default.mkdirSync(lock,{mode:448});acquired=true;break}catch(error){if(error.code!=="EEXIST")throw error;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}}if(!acquired)throw new Error("Status writer busy");try{const old=snapshot(file);const stats=old?.version===1&&old.host==="codex"&&old.sessionId===event.session_id&&plain(old.stats)?old.stats:plugin.newStats();change(stats);const now=Date.now();const body={version:1,host:"codex",sessionId:event.session_id,stats,updatedMs:now};write(file,`${JSON.stringify(body)}
+`);try{const courtesy=import_node_path.default.join(directory(import_node_path.default.join(event.cwd,import_node_path.default.dirname(plugin.statusPath))),import_node_path.default.basename(plugin.statusPath));const view=JSON.parse(plugin.statusText(stats,now));write(courtesy,`${JSON.stringify({...view,host:"codex",sessionId:event.session_id},null,2)}
+`)}catch{}return stats}finally{import_node_fs.default.rmdirSync(lock)}}function validEvent(event){return plain(event)&&typeof event.cwd==="string"&&import_node_path.default.isAbsolute(event.cwd)&&typeof event.session_id==="string"&&event.session_id.length>0&&event.session_id.length<=512}async function runCodexHook(plugin){const mode=process.argv[2];if(mode==="--command"){const cwd=process.cwd();const view=snapshot(import_node_path.default.join(cwd,plugin.statusPath));const text=await plugin.answer(process.argv.slice(3).join(" "),{opts:{guard:true},guard:true,stats:view?.host==="codex"?view:plugin.newStats(),tools:async()=>[],list:async relative=>import_node_fs.default.readdirSync(import_node_path.default.join(cwd,relative),{withFileTypes:true}).map(entry=>({name:entry.name,kind:entry.isDirectory()?"dir":"file"}))});process.stdout.write(`${text}
+`);return}const chunks=[];let bytes=0;for await(const chunk of process.stdin){bytes+=chunk.length;if(bytes>MAX_INPUT)throw new Error("Hook input exceeds bound");chunks.push(chunk)}const event=JSON.parse(Buffer.concat(chunks).toString("utf8"));if(!validEvent(event)||event.hook_event_name!==mode)throw new Error("Invalid hook envelope");if(mode==="SessionStart"){try{updateStatus(plugin,event,stats=>{if("startedMs"in stats&&!stats.startedMs)stats.startedMs=Date.now()})}catch{process.stderr.write(`${plugin.name}: courtesy status unavailable
+`)}return}if(mode!=="PreToolUse"||typeof event.tool_name!=="string"||!plain(event.tool_input))throw new Error("Invalid native tool event");const reason=plugin.verdict(event.tool_name,event.tool_input);try{updateStatus(plugin,event,stats=>plugin.count(stats,event.tool_name,event.tool_input,reason))}catch{process.stderr.write(`${plugin.name}: courtesy status unavailable
+`)}if(reason!==void 0)process.stdout.write(`${JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:reason}})}
+`)}function hookFailure(plugin){process.stderr.write(`${plugin}: native hook input or adapter failed
+`);process.exitCode=2}var newStats=()=>({blocked:0});var STATUS_PATH=".claude-flow/ddd-mod/status.json";var statusText=(stats,guard,nowMs)=>`${JSON.stringify({version:1,updatedMs:nowMs,guard,...stats},null,2)}
+`;var COMMON_SECRETS=[["private key",/-----BEGIN [A-Z ]*PRIVATE KEY-----/],["aws access key",/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/],["github token",/\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})\b/],["slack token",/\bxox[abprs]-[A-Za-z0-9-]{10,}/],["slack webhook",/\bhooks\.slack\.com\/services\/T[A-Z0-9]{6,}\/B[A-Z0-9]{6,}\/[A-Za-z0-9]{16,}/],["google api key",/\bAIza[0-9A-Za-z_-]{35}\b/],["anthropic or openai key",/\bsk-(?:(?:ant|proj|svcacct|admin)-[A-Za-z0-9_-]{20,}|(?=[A-Za-z]{0,40}\d)[A-Za-z0-9]{32,})/],["stripe key",/\b[rs]k_live_[A-Za-z0-9]{16,}/],["npm token",/\bnpm_[A-Za-z0-9]{36}\b/],["huggingface token",/\bhf_[A-Za-z0-9]{30,}\b/],["sendgrid key",/\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/],["twilio key",/\bSK[0-9a-f]{32}\b/],["jwt",/\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/],["bearer token",/\bBearer\s+([A-Za-z0-9._~+/=-]{24,})/],["database url with credentials",/\b[a-z][a-z0-9+.-]{1,20}:\/\/[^\s:@/]+:[^\s@/]{3,}@[^\s/]+/i]];var INVISIBLE=new RegExp("[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u00ad\\u034f\\u061c\\u115f\\u1160\\u17b4\\u17b5\\u180b-\\u180e\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u206f\\u3164\\ufe00-\\ufe0f\\ufeff\\uffa0\\ufff9-\\ufffb]","g");var MAX_SCAN=2e5;var bare=text=>(text.length>MAX_SCAN?text.slice(0,MAX_SCAN/2)+"\n"+text.slice(-MAX_SCAN/2):text).replace(INVISIBLE,"");var PLACEHOLDER=/placeholder|your[-_ ]|example|changeme|change[-_]?me|redacted|dummy|replace[-_]?me|insert[-_]|\*{3,}|x{5,}|\.{3}|^(?:none|null|undefined|true|false)$/i;var REFERENCE=/^(?:\$(?:\{[^}]*\}|\(|[A-Za-z_]\w*$)|%[^%]*%$|<[^>]*>$|\{\{|process\.env|os\.environ|env[.[]|import\.meta|System\.getenv|secrets?\.|vault:|op:\/\/|ref\+|arn:|projects\/[^/]+\/secrets\/|gcp:|kms:|aws:|file:)/i;var CALL=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\(|^[A-Za-z_$][\w$]*\[/;var IDENT_PATH=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/;var UUID=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;var NAME_LIKE=/^[a-z][a-z0-9]*(?:[-_./][a-z0-9]+){2,}$/;function entropy(v){const counts=new Map;for(const ch of v)counts.set(ch,(counts.get(ch)??0)+1);let h=0;for(const n of counts.values())h-=n/v.length*Math.log2(n/v.length);return h}function isReference(v){if(PLACEHOLDER.test(v)||REFERENCE.test(v)||CALL.test(v)||IDENT_PATH.test(v)||URL_NO_CREDS.test(v))return true;return NAME_LIKE.test(v)&&v.replace(/\D/g,"").length/v.length<.15}function plausibleSecret(v){if(v.length<8||v.length>256||/\s/.test(v)||UUID.test(v)||isReference(v))return false;const symbol=/[^A-Za-z0-9]/.test(v);const digit=/\d/.test(v);const classes=[/[a-z]/.test(v),/[A-Z]/.test(v),digit,symbol].filter(Boolean).length;return classes>=2&&(digit||symbol)&&entropy(v)>=2.5}var KEYED_MIN=20;var PLACEHOLDER_WORD=/(?:^|[^a-z])(?:your|placeholder|changeme|change[-_]?me|example|redacted|dummy|replace[-_]?me|insert)(?:[^a-z]|$)|\*{3,}|x{5,}|\.{3}|^(?:none|null|undefined|true|false)$/i;var URL_NO_CREDS=/^[a-z][a-z0-9+.-]{1,20}:\/\/[^\s@]*$/i;function hyphenName(v){const parts=v.split("-");return parts.length>=3&&parts.every(p=>/^[a-z0-9]{2,}$/.test(p)&&!/^[0-9a-f]{8,}$/.test(p))&&v.replace(/\D/g,"").length/v.length<.15}function keyedSecret(v){if(v.length<KEYED_MIN||v.length>256||/\s/.test(v))return false;return!(PLACEHOLDER_WORD.test(v)||REFERENCE.test(v)||CALL.test(v)||IDENT_PATH.test(v)||URL_NO_CREDS.test(v)||!UUID.test(v)&&hyphenName(v))}var KEY_NAME=/(?:api[_-]?key|secret|token|passw(?:or)?d|passwd|pwd|credential|private[_-]?key|auth(?!or))s?[A-Za-z0-9_-]{0,40}["']?\s*[:=]\s*/gi;var QUOTED=/(["'\x60])((?:(?!\1)[^\n]){1,256})\1/y;var BARE_VALUE=/[^\s"'\x60,;]{1,256}/y;var QUERY_VALUE=/[^\s"'\x60,;&]{1,256}/y;function assignmentSecret(text){let valueEnd=0;for(const m of text.matchAll(KEY_NAME)){if(m.index<valueEnd)continue;const at=m.index+m[0].length;let back=m.index;while(back>0&&m.index-back<64&&/[A-Za-z0-9_.-]/.test(text.charAt(back-1)))back--;const re=/["'\x60]/.test(text.charAt(at))?QUOTED:/[?&]/.test(text.charAt(back-1))?QUERY_VALUE:BARE_VALUE;re.lastIndex=at;const hit=re.exec(text);const v=hit&&(hit[2]??hit[0]);valueEnd=hit?at+hit[0].length:at;if(v&&(plausibleSecret(v)||keyedSecret(v)))return true}return false}function urlCredential(url){const pass=/^[^:]+:\/\/[^\s:@/]+:([^\s@/]+)@/.exec(url)?.[1];if(!pass||/\$\{|\{\{|%\(|%s/.test(pass))return false;return!/^(?:password|passwd|pass|pwd|secret|changeme|dbpassword|db_password|\$\w*|<.*>|\{.*\}|\*+|x+)$/i.test(pass)&&!PLACEHOLDER.test(pass)}var CHECKS={"bearer token":m=>!isReference(m[1]??""),"database url with credentials":m=>urlCredential(m[0]),"database url with password":m=>urlCredential(m[0])};var globals=new WeakMap;function matches(name,re,text){if(name==="key assignment")return assignmentSecret(text);const check=CHECKS[name];if(!check)return re.test(text);let g=globals.get(re);if(!g)globals.set(re,g=new RegExp(re.source,re.flags.includes("g")?re.flags:re.flags+"g"));for(const m of text.matchAll(g))if(check(m))return true;return false}var TRUNCATED="ruflo-screen: input exceeded the screening budget";var TRUNCATED_NAME="input too large to screen";var names=(rules,text)=>text===TRUNCATED?[TRUNCATED_NAME]:rules.filter(([name,re])=>matches(name,re,text)).map(([name])=>name);var hasSecretIn=(secrets,text)=>names(secrets,bare(text)).length>0;var NODES=2e4;var CHARS=2e6;var PER_STRING=15e5;var OVERLAP=2048;var BARE_KEY_MIN=8;function windows(text,out){if(text.length<=MAX_SCAN){out.push(text);return}for(let at=0;;at+=MAX_SCAN-OVERLAP){out.push(text.slice(at,at+MAX_SCAN));if(at+MAX_SCAN>=text.length)return}}function textsOf(input,limits={}){const out=[];let slots=limits.nodes??NODES;let chars=limits.chars??CHARS;const perString=limits.perString??PER_STRING;let truncated=false;const take=text=>{if(chars<=0){truncated=true;return}if(text.length<=Math.min(perString,chars)){chars-=text.length;windows(text,out);return}truncated=true;const half=Math.floor(Math.min(perString,chars)/2);chars-=2*half;windows(text.slice(0,half),out);windows(text.slice(-half),out)};const queue=[input];let head=0;for(;head<queue.length&&chars>0;head++){const node=queue[head];if(typeof node==="string")take(node);else if(Array.isArray(node)){let i=0;for(;i<node.length&&slots>0;i++,slots--)if(i in node)queue.push(node[i]);if(i<node.length)truncated=true}else if(typeof node==="object"&&node!==null){for(const k in node){if(slots--<=0){truncated=true;break}if(!Object.prototype.hasOwnProperty.call(node,k))continue;const v=node[k];if(typeof v==="string")queue.push(k+"="+v);else{if(k.length>=BARE_KEY_MIN)take(k);queue.push(v)}}}}if(queue.length>head)truncated=true;if(truncated)out.push(TRUNCATED);return out}var SECRETS=[...COMMON_SECRETS,["key assignment",/\b(?:api[_-]?key|secret|token|passw(?:or)?d|credential)s?["']?\s*[:=]\s*["']?[A-Za-z0-9/+=_.-]{16,}/i]];var secretNames=text=>names(SECRETS,bare(text));var hasSecret=text=>hasSecretIn(SECRETS,text);var HELP=["/ddd-mod status","/ddd-mod scan <text>","/ddd-mod contexts"].join("\n");async function answer(args,deps){const[verb="",...rest]=args.trim().split(/\s+/);const arg=rest.join(" ");if(verb===""||verb==="help")return HELP;if(verb==="status")return`guard ${deps.guard?"on":"off"} \xB7 calls blocked ${deps.stats.blocked}`;if(verb==="scan"){if(arg==="")return"usage: /ddd-mod scan <text>";const found=secretNames(arg);return found.length?`The guard would refuse that (${found.join(", ")}).`:"Nothing found: the guard would let that through."}if(verb==="contexts"){const found=[];for(const base of["src","src/contexts","src/modules"]){let entries;try{entries=await deps.list(base)}catch{continue}if(entries.some(e=>e.kind==="dir"&&e.name==="domain")&&base==="src")found.push("src (single domain)");for(const dir of entries.filter(e=>e.kind==="dir"&&e.name!=="domain").slice(0,40)){try{if((await deps.list(`${base}/${dir.name}`)).some(e=>e.kind==="dir"&&e.name==="domain"))found.push(`${base}/${dir.name}`)}catch{}}}return found.length?`${found.length} bounded context${found.length===1?"":"s"} (a folder with a domain/ layer):
+${found.map(f=>`- ${f}`).join("\n")}`:"No bounded context found under src/, src/contexts or src/modules."}return`Unknown: ${verb}
+${HELP}`}var tail=name=>name.startsWith("mcp__")?name.slice(name.lastIndexOf("__")+2):name;var WRITERS=new Set(["memory_store","agentdb_hierarchical-store"]);var DOMAIN=/^(?:ddd|domain)-|^(?:context|aggregate):/;function isDomainWrite(input){const o=typeof input==="object"&&input!==null?input:{};return["key","parent","child"].some(k=>typeof o[k]==="string"&&DOMAIN.test(o[k]))}function verdict(tool,input){if(!WRITERS.has(tail(tool))||!isDomainWrite(input))return void 0;return textsOf(input).some(hasSecret)?"ruflo-ddd: this domain-model entry holds what looks like a secret (a key, token or password). The model records contexts and aggregates, not credentials.":void 0}runCodexHook({name:"ruflo-ddd",verdict,newStats,statusPath:STATUS_PATH,answer,statusText:(stats,now)=>statusText(stats,true,now),count:(stats,tool,input,reason)=>{if(reason!==void 0)stats.blocked++}}).catch(()=>hookFailure("ruflo-ddd"));
diff --git a/plugins/ruflo-ddd/hooks/codex-hooks.json b/plugins/ruflo-ddd/hooks/codex-hooks.json
new file mode 100644
index 0000000000..4b0c58fb1e
--- /dev/null
+++ b/plugins/ruflo-ddd/hooks/codex-hooks.json
@@ -0,0 +1,27 @@
+{
+ "description": "Native Codex DDD secret guard and session status; Claude module hooks remain separate.",
+ "hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/hooks/codex-hook.cjs\" SessionStart",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "PreToolUse": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/hooks/codex-hook.cjs\" PreToolUse",
+ "timeout": 5
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/plugins/ruflo-ddd/hooks/codex.ts b/plugins/ruflo-ddd/hooks/codex.ts
new file mode 100644
index 0000000000..e38b1a0f1a
--- /dev/null
+++ b/plugins/ruflo-ddd/hooks/codex.ts
@@ -0,0 +1,9 @@
+import { runCodexHook, hookFailure } from '../../../scripts/lib/codex-mod-runtime.mjs'
+import { newStats, STATUS_PATH, statusText } from './status'
+import { answer } from './command'
+import { verdict } from './guard'
+
+runCodexHook({ name: 'ruflo-ddd', verdict, newStats, statusPath: STATUS_PATH, answer,
+ statusText: (stats, now) => statusText(stats, true, now),
+ count: (stats, tool, input, reason) => { if (reason !== undefined) stats.blocked++; },
+}).catch(() => hookFailure('ruflo-ddd'))
diff --git a/plugins/ruflo-sparc/.codex-plugin/plugin.json b/plugins/ruflo-sparc/.codex-plugin/plugin.json
new file mode 100644
index 0000000000..a1958395c2
--- /dev/null
+++ b/plugins/ruflo-sparc/.codex-plugin/plugin.json
@@ -0,0 +1,12 @@
+{
+ "name": "ruflo-sparc",
+ "description": "SPARC methodology \u2014 Specification, Pseudocode, Architecture, Refinement, Completion phases with gate checks",
+ "version": "0.3.3",
+ "author": {
+ "name": "ruvnet",
+ "url": "https://github.com/ruvnet"
+ },
+ "homepage": "https://github.com/ruvnet/ruflo",
+ "license": "MIT",
+ "hooks": "./hooks/codex-hooks.json"
+}
diff --git a/plugins/ruflo-sparc/README.md b/plugins/ruflo-sparc/README.md
index 828d1af167..e7dc328083 100644
--- a/plugins/ruflo-sparc/README.md
+++ b/plugins/ruflo-sparc/README.md
@@ -120,3 +120,32 @@ This plugin also loads as a function-hook mod (ADR-445 pattern, `hooks/hooks.jso
- **Option.** `guard` (`on` | `off`, default `on`) in the plugin's `userConfig`.
Test it: `claude plugin validate plugins/ruflo-sparc`, `claude plugin test plugins/ruflo-sparc`, `bash plugins/ruflo-sparc/scripts/smoke.sh`.
+
+## Native Codex hooks
+
+The separate `.codex-plugin/plugin.json` selects `hooks/codex-hooks.json`, replacing
+the Claude-only module entry for Codex. Claude's manifest and `register.ts` remain
+unchanged. The synchronous native `PreToolUse` adapter bundles the existing pure
+guard and shared secret screen; it preserves their tool/namespace scope and emits
+the native permission-denial envelope before a guarded write. `SessionStart` and
+guarded calls maintain private per-session counters in `PLUGIN_DATA`; the existing
+version-1 project status file remains a best-effort courtesy view. Status failure
+does not permit a denied write. Guarding is enabled for the native adapter.
+
+Existing skills and command files remain available. Claude's dynamic
+`$.command.register` / `command.run` mod interception has no native command-hook
+equivalent: Codex does **not** get that interception. The same deterministic local
+command helpers are available explicitly via
+`node <plugin-root>/hooks/codex-hook.cjs --command status` (and the helper's existing
+subcommands). This is guard/status compatibility, not full SDK-mod parity.
+
+Maintainers rebuild the committed standalone bundles with
+`ESBUILD=<esbuild executable> node scripts/build-codex-mod-hooks.mjs`, then run
+`node --test tests/plugins/codex-mod-hooks.test.mjs`. Set `ESBUILD` in that test run
+to check byte reproducibility using the same installed builder. Run
+`scripts/sync-mod-screen.mjs --check` before bundling when the shared screen changes.
+The adapters need Node.js and contain no runtime SDK dependency.
+
+This source change requires a released upstream package or an explicitly owned
+source projection to reach installations. It does not patch foreign cache entries,
+pin upstream updates, disable plugins, or claim an already published repair.
diff --git a/plugins/ruflo-sparc/hooks/codex-hook.cjs b/plugins/ruflo-sparc/hooks/codex-hook.cjs
new file mode 100644
index 0000000000..d8d36a3fdf
--- /dev/null
+++ b/plugins/ruflo-sparc/hooks/codex-hook.cjs
@@ -0,0 +1,11 @@
+// Generated by scripts/build-codex-mod-hooks.mjs; edit codex.ts or shared runtime, not this bundle.
+"use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var import_node_fs=__toESM(require("node:fs"),1);var import_node_path=__toESM(require("node:path"),1);var import_node_os=__toESM(require("node:os"),1);var import_node_crypto=__toESM(require("node:crypto"),1);var hash=text=>import_node_crypto.default.createHash("sha256").update(text).digest("hex");var plain=value=>value!==null&&typeof value==="object"&&!Array.isArray(value);var MAX_INPUT=8*1024*1024;function directory(target){const absolute=import_node_path.default.resolve(target);let current=import_node_path.default.parse(absolute).root;for(const segment of absolute.slice(current.length).split(import_node_path.default.sep).filter(Boolean)){current=import_node_path.default.join(current,segment);try{import_node_fs.default.mkdirSync(current,{mode:448})}catch(error){if(error.code!=="EEXIST")throw error}const stat=import_node_fs.default.lstatSync(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Unsafe status directory")}return absolute}function snapshot(file){try{const stat=import_node_fs.default.lstatSync(file);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>65536)return void 0;return JSON.parse(import_node_fs.default.readFileSync(file,"utf8"))}catch{return void 0}}function write(file,bytes){if(import_node_fs.default.existsSync(file)&&import_node_fs.default.lstatSync(file).isSymbolicLink())throw new Error("Unsafe status file");const tmp=`${file}.${import_node_crypto.default.randomUUID()}.tmp`;try{const fd=import_node_fs.default.openSync(tmp,"wx",384);try{import_node_fs.default.writeFileSync(fd,bytes);import_node_fs.default.fsyncSync(fd)}finally{import_node_fs.default.closeSync(fd)}import_node_fs.default.renameSync(tmp,file)}finally{if(import_node_fs.default.existsSync(tmp))import_node_fs.default.unlinkSync(tmp)}}function updateStatus(plugin,event,change){const data=directory(process.env.PLUGIN_DATA??import_node_path.default.join(import_node_os.default.homedir(),".cache","ruflo-codex",plugin.name));const sessions=directory(import_node_path.default.join(data,"sessions"));const file=import_node_path.default.join(sessions,`${hash(`${event.cwd}\0${event.session_id}`)}.json`);const lock=`${file}.lock`;let acquired=false;for(let attempt=0;attempt<25;attempt++){try{import_node_fs.default.mkdirSync(lock,{mode:448});acquired=true;break}catch(error){if(error.code!=="EEXIST")throw error;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}}if(!acquired)throw new Error("Status writer busy");try{const old=snapshot(file);const stats=old?.version===1&&old.host==="codex"&&old.sessionId===event.session_id&&plain(old.stats)?old.stats:plugin.newStats();change(stats);const now=Date.now();const body={version:1,host:"codex",sessionId:event.session_id,stats,updatedMs:now};write(file,`${JSON.stringify(body)}
+`);try{const courtesy=import_node_path.default.join(directory(import_node_path.default.join(event.cwd,import_node_path.default.dirname(plugin.statusPath))),import_node_path.default.basename(plugin.statusPath));const view=JSON.parse(plugin.statusText(stats,now));write(courtesy,`${JSON.stringify({...view,host:"codex",sessionId:event.session_id},null,2)}
+`)}catch{}return stats}finally{import_node_fs.default.rmdirSync(lock)}}function validEvent(event){return plain(event)&&typeof event.cwd==="string"&&import_node_path.default.isAbsolute(event.cwd)&&typeof event.session_id==="string"&&event.session_id.length>0&&event.session_id.length<=512}async function runCodexHook(plugin){const mode=process.argv[2];if(mode==="--command"){const cwd=process.cwd();const view=snapshot(import_node_path.default.join(cwd,plugin.statusPath));const text=await plugin.answer(process.argv.slice(3).join(" "),{opts:{guard:true},guard:true,stats:view?.host==="codex"?view:plugin.newStats(),tools:async()=>[],list:async relative=>import_node_fs.default.readdirSync(import_node_path.default.join(cwd,relative),{withFileTypes:true}).map(entry=>({name:entry.name,kind:entry.isDirectory()?"dir":"file"}))});process.stdout.write(`${text}
+`);return}const chunks=[];let bytes=0;for await(const chunk of process.stdin){bytes+=chunk.length;if(bytes>MAX_INPUT)throw new Error("Hook input exceeds bound");chunks.push(chunk)}const event=JSON.parse(Buffer.concat(chunks).toString("utf8"));if(!validEvent(event)||event.hook_event_name!==mode)throw new Error("Invalid hook envelope");if(mode==="SessionStart"){try{updateStatus(plugin,event,stats=>{if("startedMs"in stats&&!stats.startedMs)stats.startedMs=Date.now()})}catch{process.stderr.write(`${plugin.name}: courtesy status unavailable
+`)}return}if(mode!=="PreToolUse"||typeof event.tool_name!=="string"||!plain(event.tool_input))throw new Error("Invalid native tool event");const reason=plugin.verdict(event.tool_name,event.tool_input);try{updateStatus(plugin,event,stats=>plugin.count(stats,event.tool_name,event.tool_input,reason))}catch{process.stderr.write(`${plugin.name}: courtesy status unavailable
+`)}if(reason!==void 0)process.stdout.write(`${JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:reason}})}
+`)}function hookFailure(plugin){process.stderr.write(`${plugin}: native hook input or adapter failed
+`);process.exitCode=2}var newStats=()=>({checked:0,blocked:0,seen:{}});var STATUS_PATH=".claude-flow/sparc-mod/status.json";function statusText(stats,mode,nowMs){return`${JSON.stringify({version:1,updatedMs:nowMs,guard:mode.guard,...stats},null,2)}
+`}var COMMON_SECRETS=[["private key",/-----BEGIN [A-Z ]*PRIVATE KEY-----/],["aws access key",/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/],["github token",/\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})\b/],["slack token",/\bxox[abprs]-[A-Za-z0-9-]{10,}/],["slack webhook",/\bhooks\.slack\.com\/services\/T[A-Z0-9]{6,}\/B[A-Z0-9]{6,}\/[A-Za-z0-9]{16,}/],["google api key",/\bAIza[0-9A-Za-z_-]{35}\b/],["anthropic or openai key",/\bsk-(?:(?:ant|proj|svcacct|admin)-[A-Za-z0-9_-]{20,}|(?=[A-Za-z]{0,40}\d)[A-Za-z0-9]{32,})/],["stripe key",/\b[rs]k_live_[A-Za-z0-9]{16,}/],["npm token",/\bnpm_[A-Za-z0-9]{36}\b/],["huggingface token",/\bhf_[A-Za-z0-9]{30,}\b/],["sendgrid key",/\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/],["twilio key",/\bSK[0-9a-f]{32}\b/],["jwt",/\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/],["bearer token",/\bBearer\s+([A-Za-z0-9._~+/=-]{24,})/],["database url with credentials",/\b[a-z][a-z0-9+.-]{1,20}:\/\/[^\s:@/]+:[^\s@/]{3,}@[^\s/]+/i]];var INVISIBLE=new RegExp("[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u00ad\\u034f\\u061c\\u115f\\u1160\\u17b4\\u17b5\\u180b-\\u180e\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u206f\\u3164\\ufe00-\\ufe0f\\ufeff\\uffa0\\ufff9-\\ufffb]","g");var MAX_SCAN=2e5;var bare=text=>(text.length>MAX_SCAN?text.slice(0,MAX_SCAN/2)+"\n"+text.slice(-MAX_SCAN/2):text).replace(INVISIBLE,"");var PLACEHOLDER=/placeholder|your[-_ ]|example|changeme|change[-_]?me|redacted|dummy|replace[-_]?me|insert[-_]|\*{3,}|x{5,}|\.{3}|^(?:none|null|undefined|true|false)$/i;var REFERENCE=/^(?:\$(?:\{[^}]*\}|\(|[A-Za-z_]\w*$)|%[^%]*%$|<[^>]*>$|\{\{|process\.env|os\.environ|env[.[]|import\.meta|System\.getenv|secrets?\.|vault:|op:\/\/|ref\+|arn:|projects\/[^/]+\/secrets\/|gcp:|kms:|aws:|file:)/i;var CALL=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\(|^[A-Za-z_$][\w$]*\[/;var IDENT_PATH=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/;var UUID=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;var NAME_LIKE=/^[a-z][a-z0-9]*(?:[-_./][a-z0-9]+){2,}$/;function entropy(v){const counts=new Map;for(const ch of v)counts.set(ch,(counts.get(ch)??0)+1);let h=0;for(const n of counts.values())h-=n/v.length*Math.log2(n/v.length);return h}function isReference(v){if(PLACEHOLDER.test(v)||REFERENCE.test(v)||CALL.test(v)||IDENT_PATH.test(v)||URL_NO_CREDS.test(v))return true;return NAME_LIKE.test(v)&&v.replace(/\D/g,"").length/v.length<.15}function plausibleSecret(v){if(v.length<8||v.length>256||/\s/.test(v)||UUID.test(v)||isReference(v))return false;const symbol=/[^A-Za-z0-9]/.test(v);const digit=/\d/.test(v);const classes=[/[a-z]/.test(v),/[A-Z]/.test(v),digit,symbol].filter(Boolean).length;return classes>=2&&(digit||symbol)&&entropy(v)>=2.5}var KEYED_MIN=20;var PLACEHOLDER_WORD=/(?:^|[^a-z])(?:your|placeholder|changeme|change[-_]?me|example|redacted|dummy|replace[-_]?me|insert)(?:[^a-z]|$)|\*{3,}|x{5,}|\.{3}|^(?:none|null|undefined|true|false)$/i;var URL_NO_CREDS=/^[a-z][a-z0-9+.-]{1,20}:\/\/[^\s@]*$/i;function hyphenName(v){const parts=v.split("-");return parts.length>=3&&parts.every(p=>/^[a-z0-9]{2,}$/.test(p)&&!/^[0-9a-f]{8,}$/.test(p))&&v.replace(/\D/g,"").length/v.length<.15}function keyedSecret(v){if(v.length<KEYED_MIN||v.length>256||/\s/.test(v))return false;return!(PLACEHOLDER_WORD.test(v)||REFERENCE.test(v)||CALL.test(v)||IDENT_PATH.test(v)||URL_NO_CREDS.test(v)||!UUID.test(v)&&hyphenName(v))}var KEY_NAME=/(?:api[_-]?key|secret|token|passw(?:or)?d|passwd|pwd|credential|private[_-]?key|auth(?!or))s?[A-Za-z0-9_-]{0,40}["']?\s*[:=]\s*/gi;var QUOTED=/(["'\x60])((?:(?!\1)[^\n]){1,256})\1/y;var BARE_VALUE=/[^\s"'\x60,;]{1,256}/y;var QUERY_VALUE=/[^\s"'\x60,;&]{1,256}/y;function assignmentSecret(text){let valueEnd=0;for(const m of text.matchAll(KEY_NAME)){if(m.index<valueEnd)continue;const at=m.index+m[0].length;let back=m.index;while(back>0&&m.index-back<64&&/[A-Za-z0-9_.-]/.test(text.charAt(back-1)))back--;const re=/["'\x60]/.test(text.charAt(at))?QUOTED:/[?&]/.test(text.charAt(back-1))?QUERY_VALUE:BARE_VALUE;re.lastIndex=at;const hit=re.exec(text);const v=hit&&(hit[2]??hit[0]);valueEnd=hit?at+hit[0].length:at;if(v&&(plausibleSecret(v)||keyedSecret(v)))return true}return false}function urlCredential(url){const pass=/^[^:]+:\/\/[^\s:@/]+:([^\s@/]+)@/.exec(url)?.[1];if(!pass||/\$\{|\{\{|%\(|%s/.test(pass))return false;return!/^(?:password|passwd|pass|pwd|secret|changeme|dbpassword|db_password|\$\w*|<.*>|\{.*\}|\*+|x+)$/i.test(pass)&&!PLACEHOLDER.test(pass)}var CHECKS={"bearer token":m=>!isReference(m[1]??""),"database url with credentials":m=>urlCredential(m[0]),"database url with password":m=>urlCredential(m[0])};var globals=new WeakMap;function matches(name,re,text){if(name==="key assignment")return assignmentSecret(text);const check=CHECKS[name];if(!check)return re.test(text);let g=globals.get(re);if(!g)globals.set(re,g=new RegExp(re.source,re.flags.includes("g")?re.flags:re.flags+"g"));for(const m of text.matchAll(g))if(check(m))return true;return false}var TRUNCATED="ruflo-screen: input exceeded the screening budget";var TRUNCATED_NAME="input too large to screen";var names=(rules,text)=>text===TRUNCATED?[TRUNCATED_NAME]:rules.filter(([name,re])=>matches(name,re,text)).map(([name])=>name);var hasSecretIn=(secrets,text)=>names(secrets,bare(text)).length>0;var NODES=2e4;var CHARS=2e6;var PER_STRING=15e5;var OVERLAP=2048;var BARE_KEY_MIN=8;function windows(text,out){if(text.length<=MAX_SCAN){out.push(text);return}for(let at=0;;at+=MAX_SCAN-OVERLAP){out.push(text.slice(at,at+MAX_SCAN));if(at+MAX_SCAN>=text.length)return}}function textsOf(input,limits={}){const out=[];let slots=limits.nodes??NODES;let chars=limits.chars??CHARS;const perString=limits.perString??PER_STRING;let truncated=false;const take=text=>{if(chars<=0){truncated=true;return}if(text.length<=Math.min(perString,chars)){chars-=text.length;windows(text,out);return}truncated=true;const half=Math.floor(Math.min(perString,chars)/2);chars-=2*half;windows(text.slice(0,half),out);windows(text.slice(-half),out)};const queue=[input];let head=0;for(;head<queue.length&&chars>0;head++){const node=queue[head];if(typeof node==="string")take(node);else if(Array.isArray(node)){let i=0;for(;i<node.length&&slots>0;i++,slots--)if(i in node)queue.push(node[i]);if(i<node.length)truncated=true}else if(typeof node==="object"&&node!==null){for(const k in node){if(slots--<=0){truncated=true;break}if(!Object.prototype.hasOwnProperty.call(node,k))continue;const v=node[k];if(typeof v==="string")queue.push(k+"="+v);else{if(k.length>=BARE_KEY_MIN)take(k);queue.push(v)}}}}if(queue.length>head)truncated=true;if(truncated)out.push(TRUNCATED);return out}var SECRETS=[...COMMON_SECRETS,["key assignment",/\b(?:api[_-]?key|secret|token|passw(?:or)?d|credential)s?["']?\s*[:=]\s*["']?[A-Za-z0-9/+=_.-]{16,}/i]];var secretsIn=text=>names(SECRETS,bare(text));var hasSecret=text=>hasSecretIn(SECRETS,text);var HELP=["/sparc-mod status","/sparc-mod scan <text>","/sparc-mod phases"].join("\n");async function answer(args,deps){const[verb="",...rest]=args.trim().split(/\s+/);const arg=rest.join(" ");const{opts,stats}=deps;if(verb===""||verb==="help")return HELP;if(verb==="status"){const seen=Object.entries(stats.seen).map(([k,n])=>`${k} ${n}`).join(" \xB7 ");return[`guard ${opts.guard?"on":"off"} \xB7 checked ${stats.checked} \xB7 blocked ${stats.blocked}`,seen===""?"no sparc-artifact calls this session":seen].join("\n")}if(verb==="scan"){if(arg==="")return"usage: /sparc-mod scan <text>";const found=secretsIn(arg);return found.length?`The guard would refuse that (looks like: ${found.join(", ")}).`:"Nothing found: the guard would let that through."}if(verb==="phases")return["S specification","P pseudocode","A architecture","R refinement","C completion","Artifacts go in memory namespaces starting with sparc; the guard screens them for secrets."].join("\n");return`Unknown: ${verb}
+${HELP}`}var shortName=name=>name.startsWith("mcp__")&&name.lastIndexOf("__")>5?name.slice(name.lastIndexOf("__")+2):name;var field=(input,key)=>{const v=typeof input==="object"&&input!==null?input[key]:void 0;return typeof v==="string"?v:""};var NS=/^sparc/i;var WRITERS=new Set(["memory_store","agentdb_hierarchical-store","agentdb_pattern-store"]);function watched(tool,input){if(!WRITERS.has(shortName(tool)))return void 0;return NS.test(field(input,"namespace"))?"sparc artifact write":void 0}function verdict(tool,input){if(watched(tool,input)===void 0)return void 0;return textsOf(input).some(hasSecret)?"ruflo-sparc: this spec or artifact holds what looks like a secret (a key, token or password). Write a placeholder and name where the real value lives.":void 0}runCodexHook({name:"ruflo-sparc",verdict,newStats,statusPath:STATUS_PATH,answer,statusText:(stats,now)=>statusText(stats,{guard:true},now),count:(stats,tool,input,reason)=>{const label=watched(tool,input);if(label!==void 0){stats.checked++;stats.seen[label]=(stats.seen[label]??0)+1;if(reason!==void 0){stats.blocked++;stats.lastReason=reason.slice(0,160)}}}}).catch(()=>hookFailure("ruflo-sparc"));
diff --git a/plugins/ruflo-sparc/hooks/codex-hooks.json b/plugins/ruflo-sparc/hooks/codex-hooks.json
new file mode 100644
index 0000000000..a5558e5b04
--- /dev/null
+++ b/plugins/ruflo-sparc/hooks/codex-hooks.json
@@ -0,0 +1,27 @@
+{
+ "description": "Native Codex SPARC secret guard and session status; Claude module hooks remain separate.",
+ "hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/hooks/codex-hook.cjs\" SessionStart",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "PreToolUse": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/hooks/codex-hook.cjs\" PreToolUse",
+ "timeout": 5
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/plugins/ruflo-sparc/hooks/codex.ts b/plugins/ruflo-sparc/hooks/codex.ts
new file mode 100644
index 0000000000..86b1288bba
--- /dev/null
+++ b/plugins/ruflo-sparc/hooks/codex.ts
@@ -0,0 +1,9 @@
+import { runCodexHook, hookFailure } from '../../../scripts/lib/codex-mod-runtime.mjs'
+import { newStats, STATUS_PATH, statusText } from './status'
+import { answer } from './command'
+import { verdict, watched } from './guard'
+
+runCodexHook({ name: 'ruflo-sparc', verdict, newStats, statusPath: STATUS_PATH, answer,
+ statusText: (stats, now) => statusText(stats, { guard: true }, now),
+ count: (stats, tool, input, reason) => { const label = watched(tool, input); if (label !== undefined) { stats.checked++; stats.seen[label] = (stats.seen[label] ?? 0) + 1; if (reason !== undefined) { stats.blocked++; stats.lastReason = reason.slice(0, 160); } } },
+}).catch(() => hookFailure('ruflo-sparc'))
diff --git a/scripts/build-codex-mod-hooks.mjs b/scripts/build-codex-mod-hooks.mjs
new file mode 100644
index 0000000000..2e965eb7a5
--- /dev/null
+++ b/scripts/build-codex-mod-hooks.mjs
@@ -0,0 +1,22 @@
+#!/usr/bin/env node
+// Bundle exact existing pure guard/screen/status functions, never a second secret detector.
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import { execFileSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const esbuild = process.env.ESBUILD ?? path.join(root, 'node_modules', '.bin', 'esbuild');
+const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'ruflo-codex-mod-build-'));
+try {
+ for (const name of ['adr', 'ddd', 'sparc']) {
+ const target = path.join(root, `plugins/ruflo-${name}/hooks/codex-hook.cjs`);
+ const output = path.join(temp, `${name}.cjs`);
+ execFileSync(esbuild, [path.join(root, `plugins/ruflo-${name}/hooks/codex.ts`), '--bundle', '--platform=node', '--target=node20', '--format=cjs', '--minify-whitespace', `--outfile=${output}`], { stdio: 'pipe' });
+ const bytes = `// Generated by scripts/build-codex-mod-hooks.mjs; edit codex.ts or shared runtime, not this bundle.\n${fs.readFileSync(output, 'utf8')}`;
+ if (process.argv.includes('--check')) {
+ if (!fs.existsSync(target) || fs.readFileSync(target, 'utf8') !== bytes) throw new Error(`${name}: native bundle drift; rebuild before release`);
+ } else fs.writeFileSync(target, bytes);
+ }
+ console.log('codex-mod-hooks: three bundles match their shared sources');
+} finally { fs.rmSync(temp, { recursive: true, force: true }); }
diff --git a/scripts/lib/codex-mod-runtime.d.mts b/scripts/lib/codex-mod-runtime.d.mts
new file mode 100644
index 0000000000..55ea2ca38f
--- /dev/null
+++ b/scripts/lib/codex-mod-runtime.d.mts
@@ -0,0 +1,11 @@
+export type NativePlugin<Stats extends object> = {
+ name: string;
+ verdict(tool: string, input: unknown): string | undefined;
+ newStats(): Stats;
+ statusPath: string;
+ statusText(stats: Stats, now: number): string;
+ answer: Function;
+ count(stats: Stats, tool: string, input: unknown, reason: string | undefined): void;
+};
+export function runCodexHook<Stats extends object>(plugin: NativePlugin<Stats>): Promise<void>;
+export function hookFailure(plugin: string): void;
diff --git a/scripts/lib/codex-mod-runtime.mjs b/scripts/lib/codex-mod-runtime.mjs
new file mode 100644
index 0000000000..9078f28e79
--- /dev/null
+++ b/scripts/lib/codex-mod-runtime.mjs
@@ -0,0 +1,107 @@
+// Shared command-hook transport. Bundled into each plugin; no dependency outside its root.
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import crypto from 'node:crypto';
+
+const hash = (text) => crypto.createHash('sha256').update(text).digest('hex');
+const plain = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
+const MAX_INPUT = 8 * 1024 * 1024;
+function directory(target) {
+ const absolute = path.resolve(target);
+ let current = path.parse(absolute).root;
+ for (const segment of absolute.slice(current.length).split(path.sep).filter(Boolean)) {
+ current = path.join(current, segment);
+ try { fs.mkdirSync(current, { mode: 0o700 }); } catch (error) { if (error.code !== 'EEXIST') throw error; }
+ const stat = fs.lstatSync(current);
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('Unsafe status directory');
+ }
+ return absolute;
+}
+function snapshot(file) {
+ try {
+ const stat = fs.lstatSync(file);
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 65536) return undefined;
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
+ } catch { return undefined; }
+}
+function write(file, bytes) {
+ if (fs.existsSync(file) && fs.lstatSync(file).isSymbolicLink()) throw new Error('Unsafe status file');
+ const tmp = `${file}.${crypto.randomUUID()}.tmp`;
+ try {
+ const fd = fs.openSync(tmp, 'wx', 0o600);
+ try { fs.writeFileSync(fd, bytes); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
+ fs.renameSync(tmp, file);
+ } finally { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); }
+}
+function updateStatus(plugin, event, change) {
+ const data = directory(process.env.PLUGIN_DATA ?? path.join(os.homedir(), '.cache', 'ruflo-codex', plugin.name));
+ const sessions = directory(path.join(data, 'sessions'));
+ const file = path.join(sessions, `${hash(`${event.cwd}\0${event.session_id}`)}.json`);
+ const lock = `${file}.lock`;
+ let acquired = false;
+ for (let attempt = 0; attempt < 25; attempt++) {
+ try { fs.mkdirSync(lock, { mode: 0o700 }); acquired = true; break; }
+ catch (error) { if (error.code !== 'EEXIST') throw error; Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10); }
+ }
+ if (!acquired) throw new Error('Status writer busy'); // Never reap another writer's lock.
+ try {
+ const old = snapshot(file);
+ const stats = old?.version === 1 && old.host === 'codex' && old.sessionId === event.session_id && plain(old.stats)
+ ? old.stats : plugin.newStats();
+ change(stats);
+ const now = Date.now();
+ const body = { version: 1, host: 'codex', sessionId: event.session_id, stats, updatedMs: now };
+ write(file, `${JSON.stringify(body)}\n`);
+ // Same version-1 courtesy view as the Claude mod; last writer wins across sessions/hosts.
+ // Session-specific counters above are independent. Failure of the courtesy view cannot allow a denied write.
+ try {
+ const courtesy = path.join(directory(path.join(event.cwd, path.dirname(plugin.statusPath))), path.basename(plugin.statusPath));
+ const view = JSON.parse(plugin.statusText(stats, now));
+ write(courtesy, `${JSON.stringify({ ...view, host: 'codex', sessionId: event.session_id }, null, 2)}\n`);
+ } catch { /* courtesy status is not guard authority */ }
+ return stats;
+ } finally { fs.rmdirSync(lock); }
+}
+function validEvent(event) {
+ return plain(event) && typeof event.cwd === 'string' && path.isAbsolute(event.cwd)
+ && typeof event.session_id === 'string' && event.session_id.length > 0 && event.session_id.length <= 512;
+}
+export async function runCodexHook(plugin) {
+ const mode = process.argv[2];
+ if (mode === '--command') {
+ const cwd = process.cwd();
+ const view = snapshot(path.join(cwd, plugin.statusPath));
+ const text = await plugin.answer(process.argv.slice(3).join(' '), {
+ opts: { guard: true }, guard: true, stats: view?.host === 'codex' ? view : plugin.newStats(), tools: async () => [],
+ list: async (relative) => fs.readdirSync(path.join(cwd, relative), { withFileTypes: true })
+ .map((entry) => ({ name: entry.name, kind: entry.isDirectory() ? 'dir' : 'file' })),
+ });
+ process.stdout.write(`${text}\n`); return;
+ }
+ const chunks = []; let bytes = 0;
+ for await (const chunk of process.stdin) {
+ bytes += chunk.length;
+ if (bytes > MAX_INPUT) throw new Error('Hook input exceeds bound');
+ chunks.push(chunk);
+ }
+ const event = JSON.parse(Buffer.concat(chunks).toString('utf8'));
+ if (!validEvent(event) || event.hook_event_name !== mode) throw new Error('Invalid hook envelope');
+ if (mode === 'SessionStart') {
+ try { updateStatus(plugin, event, (stats) => { if ('startedMs' in stats && !stats.startedMs) stats.startedMs = Date.now(); }); }
+ catch { process.stderr.write(`${plugin.name}: courtesy status unavailable\n`); }
+ return; // No extra instructions or model turn.
+ }
+ if (mode !== 'PreToolUse' || typeof event.tool_name !== 'string' || !plain(event.tool_input)) throw new Error('Invalid native tool event');
+ const reason = plugin.verdict(event.tool_name, event.tool_input);
+ try { updateStatus(plugin, event, (stats) => plugin.count(stats, event.tool_name, event.tool_input, reason)); }
+ catch { process.stderr.write(`${plugin.name}: courtesy status unavailable\n`); }
+ if (reason !== undefined) process.stdout.write(`${JSON.stringify({ hookSpecificOutput: {
+ hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason,
+ } })}\n`);
+ // A permitted call emits nothing. Never emit unsupported continue/stopReason fields for PreToolUse.
+}
+export function hookFailure(plugin) {
+ process.stderr.write(`${plugin}: native hook input or adapter failed\n`);
+ process.exitCode = 2; // Native PreToolUse blocks before execution; no secret or raw input in diagnostics.
+}
diff --git a/tests/plugins/codex-mod-hooks.test.mjs b/tests/plugins/codex-mod-hooks.test.mjs
new file mode 100644
index 0000000000..d428653229
--- /dev/null
+++ b/tests/plugins/codex-mod-hooks.test.mjs
@@ -0,0 +1,128 @@
+import { test, after } from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import { execFileSync, spawnSync, spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
+const temporary = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'codex-mod-hooks-')));
+const cwd = path.join(temporary, 'project'); fs.mkdirSync(cwd);
+after(() => fs.rmSync(temporary, { recursive: true, force: true }));
+const token = `ghp_${'a1B2'.repeat(10)}`;
+const fixtures = {
+ adr: { tool: 'memory_store', input: { namespace: 'adr-patterns', key: 'ADR-007', value: token }, benign: { namespace: 'notes', value: token } },
+ ddd: { tool: 'agentdb_hierarchical-store', input: { key: 'ddd-order', value: token }, benign: { key: 'personal-note', value: token } },
+ sparc: { tool: 'agentdb_pattern-store', input: { namespace: 'sparc-specification', value: token }, benign: { namespace: 'notes', value: token } },
+};
+function run(name, mode, input, extra = {}) {
+ const data = path.join(temporary, name); fs.mkdirSync(data, { recursive: true });
+ return spawnSync(process.execPath, [path.join(root, `plugins/ruflo-${name}/hooks/codex-hook.cjs`), mode], {
+ cwd, encoding: 'utf8', timeout: 5000,
+ input: typeof input === 'string' ? input : JSON.stringify({ cwd, session_id: `native-${name}`, hook_event_name: mode, ...input }),
+ env: { ...process.env, PLUGIN_DATA: data, ...extra },
+ });
+}
+const event = (fixture, input = fixture.input) => ({ tool_name: `mcp__ruflo__${fixture.tool}`, tool_input: input });
+for (const [name, fixture] of Object.entries(fixtures)) {
+ test(`${name}: host-specific manifest replaces Claude modules with real synchronous guard/status hooks`, () => {
+ const manifest = JSON.parse(fs.readFileSync(path.join(root, `plugins/ruflo-${name}/.codex-plugin/plugin.json`)));
+ const original = JSON.parse(fs.readFileSync(path.join(root, `plugins/ruflo-${name}/.claude-plugin/plugin.json`)));
+ assert.equal(manifest.name, original.name); assert.equal(manifest.version, original.version);
+ assert.equal(manifest.hooks, './hooks/codex-hooks.json');
+ const hooks = JSON.parse(fs.readFileSync(path.join(root, `plugins/ruflo-${name}/hooks/codex-hooks.json`)));
+ assert.deepEqual(Object.keys(hooks.hooks).sort(), ['PreToolUse', 'SessionStart']);
+ assert.ok(hooks.hooks.PreToolUse[0].hooks[0].command.includes('${PLUGIN_ROOT}/hooks/codex-hook.cjs'));
+ assert.equal(hooks.hooks.PreToolUse[0].hooks[0].type, 'command');
+ assert.equal(hooks.hooks.PreToolUse[0].hooks[0].async, undefined);
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(root, `plugins/ruflo-${name}/hooks/hooks.json`))).modules, ['./register.ts']);
+ });
+ test(`${name}: native envelope blocks owned secret write with exact supported deny output and no echoed secret`, () => {
+ const out = run(name, 'PreToolUse', event(fixture)); assert.equal(out.status, 0, out.stderr);
+ const parsed = JSON.parse(out.stdout);
+ assert.deepEqual(Object.keys(parsed), ['hookSpecificOutput']);
+ assert.deepEqual(Object.keys(parsed.hookSpecificOutput).sort(), ['hookEventName', 'permissionDecision', 'permissionDecisionReason']);
+ assert.equal(parsed.hookSpecificOutput.hookEventName, 'PreToolUse'); assert.equal(parsed.hookSpecificOutput.permissionDecision, 'deny');
+ assert.equal(typeof parsed.hookSpecificOutput.permissionDecisionReason, 'string'); assert.ok(parsed.hookSpecificOutput.permissionDecisionReason.includes('secret'));
+ assert.ok(!`${out.stdout}${out.stderr}`.includes(token));
+ });
+ test(`${name}: clean/placeholder and unrelated writes allow silently`, () => {
+ for (const input of [fixture.benign, { ...fixture.input, value: 'process.env.EXAMPLE_KEY' }]) {
+ const out = run(name, 'PreToolUse', event(fixture, input)); assert.equal(out.status, 0, out.stderr); assert.equal(out.stdout, '');
+ }
+ const wrongTool = run(name, 'PreToolUse', { tool_name: 'mcp__ruflo__memory_search', tool_input: fixture.input });
+ assert.equal(wrongTool.status, 0); assert.equal(wrongTool.stdout, '');
+ });
+ test(`${name}: session counters persist across processes, initialize courtesy view, never retain tool input`, () => {
+ const started = run(name, 'SessionStart', {}); assert.equal(started.status, 0); assert.equal(started.stdout, '');
+ const denied = run(name, 'PreToolUse', event(fixture)); assert.equal(denied.status, 0);
+ const file = path.join(cwd, `.claude-flow/${name}-mod/status.json`);
+ const status = JSON.parse(fs.readFileSync(file, 'utf8')); assert.equal(status.version, 1); assert.equal(status.host, 'codex'); assert.equal(status.guard, true);
+ assert.ok(status.blocked >= 1); assert.ok(!fs.readFileSync(file, 'utf8').includes(token));
+ if (name === 'adr') { assert.ok(status.calls >= status.blocked); assert.ok(status.startedMs > 0); }
+ if (name === 'sparc') { assert.ok(status.checked >= status.blocked); assert.ok(status.seen['sparc artifact write'] >= 1); }
+ });
+ test(`${name}: malformed/oversized input fails closed without echoed data`, () => {
+ for (const input of ['bad JSON', '{"tool_name":"missing envelope"}', ' '.repeat(8 * 1024 * 1024 + 1)]) {
+ const out = run(name, 'PreToolUse', input); assert.equal(out.status, 2); assert.equal(out.stdout, '');
+ assert.equal(out.stderr, `ruflo-${name}: native hook input or adapter failed\n`);
+ }
+ });
+ test(`${name}: courtesy failure never converts secret denial to an allowed call`, () => {
+ const blockedData = path.join(temporary, `${name}-blocked-data`); fs.writeFileSync(blockedData, 'not a directory');
+ const out = run(name, 'PreToolUse', event(fixture), { PLUGIN_DATA: blockedData });
+ assert.equal(out.status, 0); assert.equal(JSON.parse(out.stdout).hookSpecificOutput.permissionDecision, 'deny');
+ assert.ok(!out.stderr.includes(token));
+ });
+ test(`${name}: bundled adapter runs standalone without source imports or SDK installation`, () => {
+ const isolated = path.join(temporary, `${name}-standalone.cjs`);
+ fs.copyFileSync(path.join(root, `plugins/ruflo-${name}/hooks/codex-hook.cjs`), isolated);
+ const out = spawnSync(process.execPath, [isolated, '--command', 'scan', token], { encoding: 'utf8', cwd, timeout: 5000 });
+ assert.equal(out.status, 0, out.stderr); assert.ok(out.stdout.includes('refuse')); assert.ok(!out.stdout.includes(token));
+ });
+}
+test('ADR causal-edge and DDD parent/child forms remain guarded; SPARC scope is namespace-only', () => {
+ const adr = run('adr', 'PreToolUse', { tool_name: 'mcp__any__agentdb_causal-edge', tool_input: { sourceId: 'mem:ADR-008', metadata: { token } } });
+ assert.equal(JSON.parse(adr.stdout).hookSpecificOutput.permissionDecision, 'deny');
+ const ddd = run('ddd', 'PreToolUse', { tool_name: 'mcp__any__memory_store', tool_input: { parent: 'context:payments', value: token } });
+ assert.equal(JSON.parse(ddd.stdout).hookSpecificOutput.permissionDecision, 'deny');
+ const sparc = run('sparc', 'PreToolUse', { tool_name: 'mcp__any__memory_store', tool_input: { key: 'sparc-spec', value: token } }); assert.equal(sparc.stdout, '');
+});
+test('generated bundles match exact existing guard/screen/status source inputs', { skip: !process.env.ESBUILD }, () => {
+ execFileSync(process.execPath, [path.join(root, 'scripts/build-codex-mod-hooks.mjs'), '--check'], { env: process.env });
+});
+
+// Opt-in real loader acceptance; private home only, no auth and no model turn.
+test('native Codex loads six candidate hooks without module warnings (no inference)', { skip: !process.env.CODEX_NATIVE_LOADER, timeout: 30000 }, async () => {
+ const binary = process.env.CODEX_NATIVE_LOADER;
+ const home = path.join(temporary, 'native-home'); fs.mkdirSync(home, { mode: 0o700 });
+ const env = { ...process.env, CODEX_HOME: home };
+ execFileSync(binary, ['plugin', 'marketplace', 'add', root, '--json'], { env, timeout: 10000 });
+ for (const name of Object.keys(fixtures)) execFileSync(binary, ['plugin', 'add', `ruflo-${name}@ruflo`, '--json'], { env, timeout: 10000 });
+ const child = spawn(binary, ['app-server', '--listen', 'stdio://'], { env, stdio: ['pipe', 'pipe', 'pipe'] });
+ let buffer = ''; let sequence = 0; const pending = new Map();
+ child.stderr.resume();
+ child.stdout.on('data', (chunk) => {
+ buffer += chunk.toString('utf8'); let at;
+ while ((at = buffer.indexOf('\n')) >= 0) {
+ const line = buffer.slice(0, at); buffer = buffer.slice(at + 1);
+ const message = JSON.parse(line);
+ if (pending.has(message.id)) { pending.get(message.id).resolve(message); pending.delete(message.id); }
+ }
+ });
+ const call = (method, params) => new Promise((resolve, reject) => {
+ const id = ++sequence; pending.set(id, { resolve, reject }); child.stdin.write(`${JSON.stringify({ id, method, params })}\n`);
+ });
+ const timer = setTimeout(() => { for (const request of pending.values()) request.reject(new Error('Native loader timed out')); child.kill('SIGKILL'); }, 20000);
+ child.on('exit', () => { for (const request of pending.values()) request.reject(new Error('Native loader exited')); });
+ try {
+ const init = await call('initialize', { clientInfo: { name: 'ruflo_native_mod_test', version: '1' }, capabilities: { experimentalApi: true } });
+ assert.ok(init.result); child.stdin.write(`${JSON.stringify({ method: 'initialized' })}\n`);
+ const result = await call('hooks/list', { cwds: [root] }); const row = result.result.data[0];
+ assert.deepEqual(row.warnings, []); assert.deepEqual(row.errors, []); assert.equal(row.hooks.length, 6);
+ for (const hook of row.hooks) {
+ assert.equal(hook.handlerType, 'command'); assert.equal(hook.async, false); assert.equal(hook.enabled, true);
+ assert.ok(hook.sourcePath.startsWith(home)); assert.ok(hook.sourcePath.endsWith('/hooks/codex-hooks.json'));
+ }
+ } finally { clearTimeout(timer); child.kill(); }
+});