@directive-run/cli 1.20.2 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,7 @@ CLI for [Directive](https://directive.run) – project scaffolding, system intro
4
4
 
5
5
  ## Quick: install AI rules for your assistant
6
6
 
7
- If you found this package looking for "how do I get Directive knowledge into my AI assistant?" one command:
7
+ If you found this package looking for "how do I get Directive knowledge into my AI assistant?" one command:
8
8
 
9
9
  ```bash
10
10
  npx directive ai-rules init
@@ -260,8 +260,8 @@ const tools = detectTools("./my-project");
260
260
 
261
261
  ## Composes with
262
262
 
263
- - [`@directive-run/knowledge`](../knowledge) the source-of-truth knowledge package the CLI reads from. Every rules-file generator pulls from here, so a knowledge update reaches every assistant on the next `ai-rules update`.
264
- - [`@directive-run/claude-plugin`](../claude-plugin) the Claude Code plugin built from the same knowledge. Use the plugin for Claude Code; use `directive ai-rules init` for everything else.
263
+ - [`@directive-run/knowledge`](../knowledge) the source-of-truth knowledge package the CLI reads from. Every rules-file generator pulls from here, so a knowledge update reaches every assistant on the next `ai-rules update`.
264
+ - [`@directive-run/claude-plugin`](../claude-plugin) the Claude Code plugin built from the same knowledge. Use the plugin for Claude Code; use `directive ai-rules init` for everything else.
265
265
 
266
266
  ## Contributing
267
267
 
package/dist/cli.js CHANGED
@@ -292,12 +292,12 @@ const result = await orchestrator.run(agent, "analyze this");
292
292
  - Subpath imports: \`from '@directive-run/ai/anthropic'\` not \`from '@directive-run/ai'\`
293
293
  - Token usage normalized: \`{ inputTokens, outputTokens }\` (not provider-specific)
294
294
  - \`facts.cache = [...facts.cache, item]\` not \`facts.cache.push(item)\`
295
- `}function at(){return ae()}function ct(){return ae()}var fr={cursor:Se,claude:it,copilot:ae,windsurf:ct,cline:at};function me(e){let t=fr[e];if(!t)throw new Error(`No template for tool: ${e}`);return t()}function Ue(e){let t={force:false,merge:false,tools:[],dir:process.cwd()};for(let r=0;r<e.length;r++)switch(e[r]){case "--force":t.force=true;break;case "--merge":t.merge=true;break;case "--tool":{let n=e[++r];n&&t.tools.push(n);break}case "--dir":{let n=e[++r];n&&(t.dir=n);break}}return t}async function lt(e){let t=Ue(e);g.intro(m.bgCyan(m.black(" directive ai-rules ")));let r=We(t.dir),s=t.dir;if(r.isMonorepo&&r.rootDir!==t.dir){let c=await g.select({message:"Monorepo detected. Where should AI rules be installed?",options:[{value:"root",label:`Monorepo root (${relative(t.dir,r.rootDir)||"."})`,hint:"recommended"},{value:"workspace",label:`Current workspace (${relative(r.rootDir,t.dir)})`}]});g.isCancel(c)&&(g.cancel("Cancelled."),process.exit(0)),c==="root"&&(s=r.rootDir);}let n;if(t.tools.length>0)n=t.tools.map(c=>{let a=ie(c);return {name:a.name,id:a.id,outputPath:join(s,a.outputPath)}});else {let c=nt(s);if(c.length>0){let a=await g.multiselect({message:`Detected ${c.length} AI tool(s). Which should get Directive rules?`,options:c.map(i=>({value:i.id,label:i.name,hint:relative(s,i.outputPath)})),initialValues:c.map(i=>i.id),required:true});g.isCancel(a)&&(g.cancel("Cancelled."),process.exit(0)),n=a.map(i=>{let l=ie(i);return {name:l.name,id:l.id,outputPath:join(s,l.outputPath)}});}else {let a=await g.multiselect({message:"No AI tools detected. Which tools do you use?",options:qe().map(i=>{let l=ie(i);return {value:i,label:l.name}}),required:true});g.isCancel(a)&&(g.cancel("Cancelled."),process.exit(0)),n=a.map(i=>{let l=ie(i);return {name:l.name,id:l.id,outputPath:join(s,l.outputPath)}});}}n.length===0&&(g.cancel("No tools selected."),process.exit(0));let o=g.spinner();for(let c of n){o.start(`Generating ${c.name} rules...`);let a=me(c.id),i=c.outputPath,l=existsSync(i);if(o.stop(`Generated ${c.name} rules.`),l&&!t.force){let u=readFileSync(i,"utf-8");if(t.merge){U(i,X(u,a)),g.log.success(`${m.green("Merged")} Directive section into ${m.dim(relative(s,i))}`);continue}if(V(u)){let d=await g.select({message:`${relative(s,i)} already has a Directive section. What should we do?`,options:[{value:"merge",label:"Update Directive section only",hint:"recommended"},{value:"overwrite",label:"Overwrite entire file"},{value:"skip",label:"Skip this file"}]});g.isCancel(d)&&(g.cancel("Cancelled."),process.exit(0)),d==="merge"?(U(i,X(u,a)),g.log.success(`${m.green("Updated")} ${m.dim(relative(s,i))}`)):d==="overwrite"?(U(i,a),g.log.success(`${m.green("Wrote")} ${m.dim(relative(s,i))}`)):g.log.info(`Skipped ${m.dim(relative(s,i))}`);}else {let d=await g.select({message:`${relative(s,i)} already exists. What should we do?`,options:[{value:"append",label:"Append Directive section",hint:"preserves existing content"},{value:"overwrite",label:"Overwrite entire file"},{value:"skip",label:"Skip this file"}]});g.isCancel(d)&&(g.cancel("Cancelled."),process.exit(0)),d==="append"?(U(i,X(u,a)),g.log.success(`${m.green("Appended")} to ${m.dim(relative(s,i))}`)):d==="overwrite"?(U(i,a),g.log.success(`${m.green("Wrote")} ${m.dim(relative(s,i))}`)):g.log.info(`Skipped ${m.dim(relative(s,i))}`);}}else U(i,a),g.log.success(`${m.green("Created")} ${m.dim(relative(s,i))}`);}g.outro(`Done! Run ${m.cyan(`${O} ai-rules init --merge`)} anytime to update.`);}function U(e,t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true}),writeFileSync(e,t,"utf-8");}function gr(e){let t={dir:process.cwd(),force:false};for(let r=0;r<e.length;r++){let s=e[r];if(s==="--force")t.force=true;else if(s==="--dir"){let n=e[++r];n&&(t.dir=n);}}return t}async function Le(e){let t=gr(e),r=We(t.dir),s=r.isMonorepo&&r.rootDir!==t.dir?r.rootDir:t.dir;s!==t.dir&&console.log(m.dim(`Monorepo detected \u2014 installing at root (${relative(t.dir,s)||"."})`));let o=qe().map(l=>{let u=ie(l);return {id:u.id,name:u.name,outputPath:join(s,u.outputPath)}}),c=0,a=0,i=0;for(let l of o){let u=me(l.id),d=`${oe}
295
+ `}function at(){return ae()}function ct(){return ae()}var fr={cursor:Se,claude:it,copilot:ae,windsurf:ct,cline:at};function me(e){let t=fr[e];if(!t)throw new Error(`No template for tool: ${e}`);return t()}function Le(e){let t={force:false,merge:false,tools:[],dir:process.cwd()};for(let r=0;r<e.length;r++)switch(e[r]){case "--force":t.force=true;break;case "--merge":t.merge=true;break;case "--tool":{let n=e[++r];n&&t.tools.push(n);break}case "--dir":{let n=e[++r];n&&(t.dir=n);break}}return t}async function lt(e){let t=Le(e);g.intro(m.bgCyan(m.black(" directive ai-rules ")));let r=We(t.dir),s=t.dir;if(r.isMonorepo&&r.rootDir!==t.dir){let c=await g.select({message:"Monorepo detected. Where should AI rules be installed?",options:[{value:"root",label:`Monorepo root (${relative(t.dir,r.rootDir)||"."})`,hint:"recommended"},{value:"workspace",label:`Current workspace (${relative(r.rootDir,t.dir)})`}]});g.isCancel(c)&&(g.cancel("Cancelled."),process.exit(0)),c==="root"&&(s=r.rootDir);}let n;if(t.tools.length>0)n=t.tools.map(c=>{let a=ie(c);return {name:a.name,id:a.id,outputPath:join(s,a.outputPath)}});else {let c=nt(s);if(c.length>0){let a=await g.multiselect({message:`Detected ${c.length} AI tool(s). Which should get Directive rules?`,options:c.map(i=>({value:i.id,label:i.name,hint:relative(s,i.outputPath)})),initialValues:c.map(i=>i.id),required:true});g.isCancel(a)&&(g.cancel("Cancelled."),process.exit(0)),n=a.map(i=>{let l=ie(i);return {name:l.name,id:l.id,outputPath:join(s,l.outputPath)}});}else {let a=await g.multiselect({message:"No AI tools detected. Which tools do you use?",options:qe().map(i=>{let l=ie(i);return {value:i,label:l.name}}),required:true});g.isCancel(a)&&(g.cancel("Cancelled."),process.exit(0)),n=a.map(i=>{let l=ie(i);return {name:l.name,id:l.id,outputPath:join(s,l.outputPath)}});}}n.length===0&&(g.cancel("No tools selected."),process.exit(0));let o=g.spinner();for(let c of n){o.start(`Generating ${c.name} rules...`);let a=me(c.id),i=c.outputPath,l=existsSync(i);if(o.stop(`Generated ${c.name} rules.`),l&&!t.force){let u=readFileSync(i,"utf-8");if(t.merge){L(i,X(u,a)),g.log.success(`${m.green("Merged")} Directive section into ${m.dim(relative(s,i))}`);continue}if(V(u)){let d=await g.select({message:`${relative(s,i)} already has a Directive section. What should we do?`,options:[{value:"merge",label:"Update Directive section only",hint:"recommended"},{value:"overwrite",label:"Overwrite entire file"},{value:"skip",label:"Skip this file"}]});g.isCancel(d)&&(g.cancel("Cancelled."),process.exit(0)),d==="merge"?(L(i,X(u,a)),g.log.success(`${m.green("Updated")} ${m.dim(relative(s,i))}`)):d==="overwrite"?(L(i,a),g.log.success(`${m.green("Wrote")} ${m.dim(relative(s,i))}`)):g.log.info(`Skipped ${m.dim(relative(s,i))}`);}else {let d=await g.select({message:`${relative(s,i)} already exists. What should we do?`,options:[{value:"append",label:"Append Directive section",hint:"preserves existing content"},{value:"overwrite",label:"Overwrite entire file"},{value:"skip",label:"Skip this file"}]});g.isCancel(d)&&(g.cancel("Cancelled."),process.exit(0)),d==="append"?(L(i,X(u,a)),g.log.success(`${m.green("Appended")} to ${m.dim(relative(s,i))}`)):d==="overwrite"?(L(i,a),g.log.success(`${m.green("Wrote")} ${m.dim(relative(s,i))}`)):g.log.info(`Skipped ${m.dim(relative(s,i))}`);}}else L(i,a),g.log.success(`${m.green("Created")} ${m.dim(relative(s,i))}`);}g.outro(`Done! Run ${m.cyan(`${O} ai-rules init --merge`)} anytime to update.`);}function L(e,t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true}),writeFileSync(e,t,"utf-8");}function gr(e){let t={dir:process.cwd(),force:false};for(let r=0;r<e.length;r++){let s=e[r];if(s==="--force")t.force=true;else if(s==="--dir"){let n=e[++r];n&&(t.dir=n);}}return t}async function Ue(e){let t=gr(e),r=We(t.dir),s=r.isMonorepo&&r.rootDir!==t.dir?r.rootDir:t.dir;s!==t.dir&&console.log(m.dim(`Monorepo detected \u2014 installing at root (${relative(t.dir,s)||"."})`));let o=qe().map(l=>{let u=ie(l);return {id:u.id,name:u.name,outputPath:join(s,u.outputPath)}}),c=0,a=0,i=0;for(let l of o){let u=me(l.id),d=`${oe}
296
296
  ${u}
297
- ${Y}`,f=l.outputPath,h=relative(s,f);if(!existsSync(f)){U(f,`${d}
298
- `),console.log(`${m.green("\u2713")} ${l.name.padEnd(20)} ${m.dim(h)}`),c++;continue}let $=readFileSync(f,"utf-8");if(t.force){U(f,`${d}
299
- `),console.log(`${m.yellow("\u21BB")} ${l.name.padEnd(20)} ${m.dim(h)} ${m.dim("(overwrote)")}`),c++;continue}if(V($)){U(f,X($,u)),console.log(`${m.green("\u2713")} ${l.name.padEnd(20)} ${m.dim(h)} ${m.dim("(merged section)")}`),a++;continue}console.log(`${m.dim("\xB7")} ${l.name.padEnd(20)} ${m.dim(h)} ${m.dim("(exists, no Directive section \u2014 pass --force to overwrite)")}`),i++;}console.log(""),console.log(m.green(`Installed Directive AI rules for ${o.length} tools.`)),console.log(m.dim(` ${c} written \xB7 ${a} merged \xB7 ${i} skipped (existing non-Directive content preserved)`)),console.log(""),console.log(m.dim("Next steps:")),console.log(m.dim(" \u2022 Restart your AI assistant so it picks up the new rules file.")),console.log(m.dim(` \u2022 Run ${m.cyan(`${O} ai-rules update`)} after each ${m.cyan("@directive-run/*")} version bump.`)),console.log(m.dim(` \u2022 For Claude Code, the plugin (${m.cyan("/plugin install directive@directive-plugins")}) is the canonical install \u2014 these files are the fallback for non-Claude editors.`));}async function ut(e){let r=Ue(e).dir,s=[{id:"cursor",path:join(r,".cursorrules")},{id:"claude",path:join(r,".claude/CLAUDE.md")},{id:"copilot",path:join(r,".github/copilot-instructions.md")},{id:"windsurf",path:join(r,".windsurfrules")},{id:"cline",path:join(r,".clinerules")}],n=0;for(let o of s){if(!existsSync(o.path))continue;let c=readFileSync(o.path,"utf-8");if(!V(c))continue;let a=me(o.id),i=X(c,a);U(o.path,i),console.log(`${m.green("Updated")} ${m.dim(relative(r,o.path))}`),n++;}console.log(n===0?m.dim(`No existing rule files found. Run ${m.cyan(`${O} ai-rules init`)} first.`):m.green(`
300
- Updated ${n} file(s) to latest knowledge version.`));}async function dt(e){let r=Ue(e).dir,s=[{id:"cursor",path:join(r,".cursorrules"),name:"Cursor"},{id:"claude",path:join(r,".claude/CLAUDE.md"),name:"Claude Code"},{id:"copilot",path:join(r,".github/copilot-instructions.md"),name:"GitHub Copilot"},{id:"windsurf",path:join(r,".windsurfrules"),name:"Windsurf"},{id:"cline",path:join(r,".clinerules"),name:"Cline"}],n=0,o=0;for(let c of s){if(!existsSync(c.path))continue;let a=readFileSync(c.path,"utf-8");if(!V(a))continue;n++;let i=me(c.id);X(a,i)!==a?(console.log(`${m.red("\u2717")} ${c.name} rules are ${m.yellow("stale")}`),o++):console.log(`${m.green("\u2713")} ${c.name} rules are ${m.green("current")}`);}if(n===0){console.log(m.dim("No rule files found to check."));return}o>0?(console.log(`
297
+ ${Y}`,f=l.outputPath,h=relative(s,f);if(!existsSync(f)){L(f,`${d}
298
+ `),console.log(`${m.green("\u2713")} ${l.name.padEnd(20)} ${m.dim(h)}`),c++;continue}let $=readFileSync(f,"utf-8");if(t.force){L(f,`${d}
299
+ `),console.log(`${m.yellow("\u21BB")} ${l.name.padEnd(20)} ${m.dim(h)} ${m.dim("(overwrote)")}`),c++;continue}if(V($)){L(f,X($,u)),console.log(`${m.green("\u2713")} ${l.name.padEnd(20)} ${m.dim(h)} ${m.dim("(merged section)")}`),a++;continue}console.log(`${m.dim("\xB7")} ${l.name.padEnd(20)} ${m.dim(h)} ${m.dim("(exists, no Directive section \u2014 pass --force to overwrite)")}`),i++;}console.log(""),console.log(m.green(`Installed Directive AI rules for ${o.length} tools.`)),console.log(m.dim(` ${c} written \xB7 ${a} merged \xB7 ${i} skipped (existing non-Directive content preserved)`)),console.log(""),console.log(m.dim("Next steps:")),console.log(m.dim(" \u2022 Restart your AI assistant so it picks up the new rules file.")),console.log(m.dim(` \u2022 Run ${m.cyan(`${O} ai-rules update`)} after each ${m.cyan("@directive-run/*")} version bump.`)),console.log(m.dim(` \u2022 For Claude Code, the plugin (${m.cyan("/plugin install directive@directive-plugins")}) is the canonical install \u2014 these files are the fallback for non-Claude editors.`));}async function ut(e){let r=Le(e).dir,s=[{id:"cursor",path:join(r,".cursorrules")},{id:"claude",path:join(r,".claude/CLAUDE.md")},{id:"copilot",path:join(r,".github/copilot-instructions.md")},{id:"windsurf",path:join(r,".windsurfrules")},{id:"cline",path:join(r,".clinerules")}],n=0;for(let o of s){if(!existsSync(o.path))continue;let c=readFileSync(o.path,"utf-8");if(!V(c))continue;let a=me(o.id),i=X(c,a);L(o.path,i),console.log(`${m.green("Updated")} ${m.dim(relative(r,o.path))}`),n++;}console.log(n===0?m.dim(`No existing rule files found. Run ${m.cyan(`${O} ai-rules init`)} first.`):m.green(`
300
+ Updated ${n} file(s) to latest knowledge version.`));}async function dt(e){let r=Le(e).dir,s=[{id:"cursor",path:join(r,".cursorrules"),name:"Cursor"},{id:"claude",path:join(r,".claude/CLAUDE.md"),name:"Claude Code"},{id:"copilot",path:join(r,".github/copilot-instructions.md"),name:"GitHub Copilot"},{id:"windsurf",path:join(r,".windsurfrules"),name:"Windsurf"},{id:"cline",path:join(r,".clinerules"),name:"Cline"}],n=0,o=0;for(let c of s){if(!existsSync(c.path))continue;let a=readFileSync(c.path,"utf-8");if(!V(a))continue;n++;let i=me(c.id);X(a,i)!==a?(console.log(`${m.red("\u2717")} ${c.name} rules are ${m.yellow("stale")}`),o++):console.log(`${m.green("\u2713")} ${c.name} rules are ${m.green("current")}`);}if(n===0){console.log(m.dim("No rule files found to check."));return}o>0?(console.log(`
301
301
  ${m.yellow(`${o} file(s) are stale.`)} Run ${m.cyan(`${O} ai-rules update`)} to refresh.`),process.exit(1)):console.log(m.green(`
302
302
  All rule files are current.`));}async function z(e){let t=resolve(e);if(!existsSync(t))throw new Error(`File not found: ${t}`);try{let r=await import(t);if(r.default&&Z(r.default))return r.default;if(r.system&&Z(r.system))return r.system;for(let s of Object.keys(r))if(Z(r[s]))return r[s];throw new Error(`No Directive system found in ${m.dim(e)}
303
303
  Export a system as default or named "system":
@@ -384,7 +384,7 @@ Current requirements:`),n.unmet.length===0)console.log(m.dim(" (no unmet requir
384
384
  `)}function _r(e,t){let r=[],s=[],i=Object.keys(t);for(let p=0;p<i.length;p++){let v=i[p];r.push({id:`fact-${v}`,label:v,type:"fact",x:40,y:60+p*50,color:"#3b82f6"});}for(let p=0;p<e.constraints.length;p++){let v=e.constraints[p];r.push({id:`constraint-${v.id}`,label:v.id,type:"constraint",x:260,y:60+p*50,color:v.active?"#22c55e":"#6b7280"});}let l=new Set;for(let p of e.unmet)l.add(p.requirement.type);let u=0;for(let p of l)r.push({id:`req-${p}`,label:p,type:"requirement",x:480,y:60+u*50,color:"#eab308"}),u++;for(let p=0;p<e.resolverDefs.length;p++){let v=e.resolverDefs[p];r.push({id:`resolver-${v.id}`,label:v.id,type:"resolver",x:700,y:60+p*50,color:"#a855f7"});}for(let p of e.unmet)s.push({from:`constraint-${p.fromConstraint}`,to:`req-${p.requirement.type}`});for(let p of e.resolverDefs)l.has(p.requirement)&&s.push({from:`req-${p.requirement}`,to:`resolver-${p.id}`});let d=new Map(r.map(p=>[p.id,p])),f=960,h=Math.max(...r.map(p=>p.y))+50+20,$=s.map(p=>{let v=d.get(p.from),D=d.get(p.to);return !v||!D?"":`<line x1="${v.x+90}" y1="${v.y+15}" x2="${D.x}" y2="${D.y+15}" stroke="#94a3b8" stroke-width="1.5" marker-end="url(#arrow)"/>`}).join(`
385
385
  `),w=r.map(p=>`<g>
386
386
  <rect x="${p.x}" y="${p.y}" width="180" height="30" rx="6" fill="${p.color}" opacity="0.15" stroke="${p.color}" stroke-width="1.5"/>
387
- <text x="${p.x+90}" y="${p.y+19}" text-anchor="middle" font-size="12" font-family="monospace" fill="${p.color}">${Ur(p.label)}</text>
387
+ <text x="${p.x+90}" y="${p.y+19}" text-anchor="middle" font-size="12" font-family="monospace" fill="${p.color}">${Lr(p.label)}</text>
388
388
  </g>`).join(`
389
389
  `),W=["Facts","Constraints","Requirements","Resolvers"].map((p,v)=>`<text x="${40+v*220+90}" y="35" text-anchor="middle" font-size="14" font-weight="bold" font-family="system-ui" fill="#e2e8f0">${p}</text>`).join(`
390
390
  `);return `<!DOCTYPE html>
@@ -408,7 +408,7 @@ Current requirements:`),n.unmet.length===0)console.log(m.dim(" (no unmet requir
408
408
  ${w}
409
409
  </svg>
410
410
  </body>
411
- </html>`}function Ur(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function At(e){let{filePath:t,opts:r}=Fr(e);t||(console.error("Usage: directive graph <file> [--ascii] [--no-open] [--output <path>]"),process.exit(1));let s=await z(t);s.isRunning||s.start();let n=s.inspect();if(r.ascii){console.log(Wr(n)),s.stop();return}let o={};if(s.facts)for(let i of Object.keys(s.facts))try{o[i]=s.facts[i];}catch{o[i]=null;}let c=_r(n,o),a=r.output||join(process.cwd(),".directive-graph.html");if(writeFileSync(a,c,"utf-8"),console.log(`${m.green("Generated")} ${m.dim(a)}`),r.open)try{let{execFile:i}=await import('child_process'),l=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";i(l,[a]),console.log(m.dim("Opened in browser."));}catch{console.log(m.dim(`Open ${a} in your browser to view the graph.`));}s.stop();}function Gr(e){let t={dir:process.cwd(),noInteractive:false};for(let r=0;r<e.length;r++)switch(e[r]){case "--template":{let n=e[++r];n&&(t.template=n);break}case "--dir":{let n=e[++r];n&&(t.dir=n);break}case "--no-interactive":t.noInteractive=true;break}return t}function Br(e){return existsSync(join(e,"pnpm-lock.yaml"))?"pnpm":existsSync(join(e,"bun.lockb"))||existsSync(join(e,"bun.lock"))?"bun":existsSync(join(e,"yarn.lock"))?"yarn":"npm"}function Hr(e,t){switch(e){case "pnpm":return `pnpm add ${t}`;case "yarn":return `yarn add ${t}`;case "bun":return `bun add ${t}`;default:return `npm install ${t}`}}function ze(e){return {counter:{id:"counter",label:"Counter (minimal)",hint:"schema + init + derive + events \u2014 simplest starting point",files:[{path:`src/${e}.ts`,content:Qr(e)},{path:"src/main.ts",content:Yr(e)}],deps:["@directive-run/core"]},"auth-flow":{id:"auth-flow",label:"Auth flow (constraints + resolvers)",hint:"login flow with constraints, resolvers, retry, and effects",files:[{path:`src/${e}.ts`,content:Xr(e)},{path:"src/main.ts",content:Vr(e)}],deps:["@directive-run/core"]},"ai-orchestrator":{id:"ai-orchestrator",label:"AI orchestrator",hint:"agent orchestrator with guardrails and streaming",files:[{path:`src/${e}.ts`,content:Zr(e)},{path:"src/main.ts",content:en(e)}],deps:["@directive-run/core","@directive-run/ai"]}}}function Qr(e){return `import { type ModuleSchema, createModule, t } from "@directive-run/core";
411
+ </html>`}function Lr(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function At(e){let{filePath:t,opts:r}=Fr(e);t||(console.error("Usage: directive graph <file> [--ascii] [--no-open] [--output <path>]"),process.exit(1));let s=await z(t);s.isRunning||s.start();let n=s.inspect();if(r.ascii){console.log(Wr(n)),s.stop();return}let o={};if(s.facts)for(let i of Object.keys(s.facts))try{o[i]=s.facts[i];}catch{o[i]=null;}let c=_r(n,o),a=r.output||join(process.cwd(),".directive-graph.html");if(writeFileSync(a,c,"utf-8"),console.log(`${m.green("Generated")} ${m.dim(a)}`),r.open)try{let{execFile:i}=await import('child_process'),l=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";i(l,[a]),console.log(m.dim("Opened in browser."));}catch{console.log(m.dim(`Open ${a} in your browser to view the graph.`));}s.stop();}function Gr(e){let t={dir:process.cwd(),noInteractive:false};for(let r=0;r<e.length;r++)switch(e[r]){case "--template":{let n=e[++r];n&&(t.template=n);break}case "--dir":{let n=e[++r];n&&(t.dir=n);break}case "--no-interactive":t.noInteractive=true;break}return t}function Br(e){return existsSync(join(e,"pnpm-lock.yaml"))?"pnpm":existsSync(join(e,"bun.lockb"))||existsSync(join(e,"bun.lock"))?"bun":existsSync(join(e,"yarn.lock"))?"yarn":"npm"}function Hr(e,t){switch(e){case "pnpm":return `pnpm add ${t}`;case "yarn":return `yarn add ${t}`;case "bun":return `bun add ${t}`;default:return `npm install ${t}`}}function ze(e){return {counter:{id:"counter",label:"Counter (minimal)",hint:"schema + init + derive + events \u2014 simplest starting point",files:[{path:`src/${e}.ts`,content:Qr(e)},{path:"src/main.ts",content:Yr(e)}],deps:["@directive-run/core"]},"auth-flow":{id:"auth-flow",label:"Auth flow (constraints + resolvers)",hint:"login flow with constraints, resolvers, retry, and effects",files:[{path:`src/${e}.ts`,content:Xr(e)},{path:"src/main.ts",content:Vr(e)}],deps:["@directive-run/core"]},"ai-orchestrator":{id:"ai-orchestrator",label:"AI orchestrator",hint:"agent orchestrator with guardrails and streaming",files:[{path:`src/${e}.ts`,content:Zr(e)},{path:"src/main.ts",content:en(e)}],deps:["@directive-run/core","@directive-run/ai"]}}}function Qr(e){return `import { type ModuleSchema, createModule, t } from "@directive-run/core";
412
412
 
413
413
  const schema = {
414
414
  facts: {
@@ -746,7 +746,7 @@ export default system;
746
746
  `);for(let r of e)t.push(` ${m.yellow(r.requirement.type)} (id: ${m.dim(r.id)}) from ${m.dim(r.fromConstraint)}`);return t.join(`
747
747
  `)}function cn(e){let t=[];if(t.push(m.bold("Inflight:")),e.length===0)return t.push(` ${m.green("(none)")}`),t.join(`
748
748
  `);let r=Date.now();for(let s of e){let n=r-s.startedAt;t.push(` ${m.cyan(s.resolverId)} \u2192 req ${m.dim(s.id)} ${m.yellow(`${n}ms`)}`);}return t.join(`
749
- `)}function ln(e,t,r){let s=r!==void 0?` ${r}ms`:"";switch(e){case "resolved":return m.green(`resolved${s}`);case "errored":return m.red(`errored${s}${t?` \u2014 ${t}`:""}`);case "inflight":return m.yellow("inflight");case "cancelled":return m.dim("cancelled");default:return m.dim(e)}}function un(e){return e===null?m.dim("null"):e===void 0?m.dim("undefined"):typeof e=="string"?e.length>60?`"${e.slice(0,57)}..."`:`"${e}"`:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`[${e.length} items]`:JSON.stringify(e).slice(0,60)}function dn(e){let t=[];new Set(e.unmet.map(o=>o.requirement.type));new Set(e.resolverDefs.map(o=>o.requirement));for(let o of e.resolverDefs)o.requirement;for(let o of e.unmet)e.resolverDefs.some(a=>a.requirement===o.requirement.type||a.requirement==="(predicate)")||t.push(`No resolver for requirement type "${o.requirement.type}"`);return t}async function Et(e){let{filePath:t,opts:r}=rn(e);t||(console.error("Usage: directive inspect <file> [--json] [--module <name>]"),process.exit(1));let s=await z(t);s.isRunning||s.start();let n=s.inspect();if(r.json){let a={};if(s.facts)for(let i of Object.keys(s.facts))try{a[i]=s.facts[i];}catch{a[i]="(error reading)";}console.log(JSON.stringify({facts:a,...n},null,2)),s.stop();return}console.log(),console.log(m.bold(m.cyan("Directive System Inspection"))),console.log(m.dim("\u2500".repeat(40))),console.log();let o={};if(s.facts)for(let a of Object.keys(s.facts))try{o[a]=s.facts[a];}catch{o[a]="(error reading)";}console.log(nn(o)),console.log(),console.log(sn(n.constraints)),console.log(),console.log(on(n.resolverDefs,n.resolvers)),console.log(),console.log(an(n.unmet)),console.log(),n.inflight.length>0&&(console.log(cn(n.inflight)),console.log());let c=dn(n);if(c.length>0){console.log(m.bold(m.yellow("Warnings:")));for(let a of c)console.log(` ${m.yellow("\u26A0")} ${a}`);console.log();}s.stop();}function Ct(e){let t={with:[],minimal:false,dir:process.cwd()};for(let r=0;r<e.length;r++)switch(e[r]){case "--with":{let n=e[++r];n&&(t.with=n.split(",").map(o=>o.trim()));break}case "--minimal":t.minimal=true;break;case "--dir":{let n=e[++r];n&&(t.dir=n);break}}return t}function Rt(e,t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true}),writeFileSync(e,t,"utf-8");}function Tt(e){return join(e,"src")}function Mt(e,t){let r=validateModuleName(t),s=r===true?"":`: ${r}`;console.error(`Invalid ${e} name: ${t||"(none)"}${s}`),console.error("Must start with a lowercase letter, use lowercase letters, numbers, and hyphens."),process.exit(1);}async function Nt(e,t){let r=Ct(t);if(validateModuleName(e)!==true){Mt("module",e);return}let s;r.minimal?s=[]:r.with.length>0?s=r.with.filter(l=>MODULE_SECTIONS.includes(l)):s=[...MODULE_SECTIONS];let{sourceFileName:n}=suggestFileNames(e,"module"),o=Tt(r.dir),c=join(o,n);existsSync(c)&&(console.error(`File already exists: ${relative(r.dir,c)}`),process.exit(1));let{moduleSource:a}=generateModule(e,s);Rt(c,a);let i=relative(r.dir,c);console.log(`${m.green("Created")} ${m.dim(i)}`),s.length===0?console.log(m.dim(" Minimal module (schema + init only)")):console.log(m.dim(` Sections: ${s.join(", ")}`));}async function Pt(e,t){let r=Ct(t);if(validateModuleName(e)!==true){Mt("orchestrator",e);return}let{sourceFileName:s}=suggestFileNames(e,"orchestrator"),n=Tt(r.dir),o=join(n,s);existsSync(o)&&(console.error(`File already exists: ${relative(r.dir,o)}`),process.exit(1));let{moduleSource:c}=generateOrchestrator(e);Rt(o,c);let a=relative(r.dir,o);console.log(`${m.green("Created")} ${m.dim(a)}`),console.log(m.dim(" AI orchestrator with memory, guardrails, and streaming"));}var ge=typeof process<"u"&&process.env?.NODE_ENV!=="production";function de(e,t=50){let r=new WeakSet;function s(i){if(i===null)return "null";if(i===void 0)return "undefined";let l=typeof i;if(l==="string")return JSON.stringify(i);if(l==="number"||l==="boolean")return String(i);if(l==="function")return '"[function]"';if(l==="symbol")return '"[symbol]"'}function n(i,l){if(r.has(i))return '"[circular]"';r.add(i);let u=l();return r.delete(i),u}function o(i,l){return n(i,()=>`[${i.map(u=>a(u,l+1)).join(",")}]`)}function c(i,l){return n(i,()=>`{${Object.keys(i).sort().map(u=>`${JSON.stringify(u)}:${a(i[u],l+1)}`).join(",")}}`)}function a(i,l){if(l>t)return '"[max depth exceeded]"';if(typeof i=="bigint")return `${i.toString()}n`;let u=s(i);if(u!==void 0)return u;if(i instanceof Date)return `D:${i.toISOString()}`;if(i instanceof RegExp)return `R:${i.source}:${i.flags}`;if(i instanceof Map){let d=[...i.entries()].sort();return `M:${a(d,l+1)}`}if(i instanceof Set){let d=[...i].sort();return `S:${a(d,l+1)}`}return Array.isArray(i)?o(i,l):typeof i=="object"?c(i,l):'"[unknown]"'}return a(e,0)}var K=new Set(["$eq","$ne","$in","$nin","$exists","$gt","$gte","$lt","$lte","$between","$matches","$startsWith","$endsWith","$contains","$changed"]),It=new Set(["$all","$any","$not"]);var G=64;function I(e){return typeof e!="object"||e===null||Array.isArray(e)?false:!(e instanceof Date)&&!(e instanceof RegExp)}function De(e){if(typeof e!="object"||e===null||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function He(e){if(!I(e))return false;let t=0,r=false;for(let s of Object.keys(e)){if(s.startsWith("$"))r=true,K.has(s)||$e(`predicate: unknown operator "${s}" \u2014 looks like a typo. Known operators: ${[...K].join(", ")}`);else if(r||t===0)return false;t++;}return r?t>0:false}function Ft(e){return e===null?false:Array.isArray(e)?e.every(t=>De(t)&&"fact"in t&&"op"in t):De(e)}function ye(e,t,r="",s=new WeakSet,n=0){if(n>G){ge&&console.warn(`[Directive] predicate depth limit (${G}) exceeded \u2014 flatten the predicate or split it into multiple constraints. If this is unexpected, check for a cyclic spec object.`),t.bail?.("depth");return}if(Array.isArray(e)){e.forEach((c,a)=>{if(!I(c))return;let i=c;if(typeof i.fact=="string"&&typeof i.op=="string"){let l=r?`${r}[${a}]`:`[${a}]`;t.operator?.(r?`${r}.${i.fact}`:i.fact,i.op,i.value,`${l}.value`);}});return}if(!I(e))return;if(s.has(e)){ge&&console.warn("[Directive] walkPredicate: cyclic predicate spec"),t.bail?.("cycle");return}s.add(e);let o=e;for(let c of ["$all","$any","$not"])if(c in o){if(t.combinator?.(c)===false)return;let a=c==="$not"?[o.$not]:o[c]??[];for(let i of a)ye(i,t,r,s,n+1);return}for(let c of Object.keys(o)){let a=r?`${r}.${c}`:c;if(c.startsWith("$")){t.strayOperatorKey?.(c,a);continue}let i=o[c];if(He(i)){let l=i;for(let u of Object.keys(l))t.operator?.(a,u,l[u],`${a}.${u}`);continue}if(De(i)){if(t.nested?.(c)===false)continue;ye(i,t,a,s,n+1);continue}t.literal?.(a,i);}}function Wt(e,t=""){function r(n,o,c,a){if(typeof n=="bigint")throw new Error(`[Directive] validatePredicate: bigint operand at "${o}" is not JSON-serializable (JSON.stringify throws on bigint).`);if(n instanceof Set)throw new Error(`[Directive] validatePredicate: Set operand at "${o}" is not JSON-serializable (serializes to {} and loses all members).`);if(n instanceof Map)throw new Error(`[Directive] validatePredicate: Map operand at "${o}" is not JSON-serializable (serializes to {} and loses all entries).`);if(n instanceof RegExp)throw new Error(`[Directive] validatePredicate: RegExp operand at "${o}" is not JSON-serializable (a regex lost to JSON.parse becomes {}). Only a direct $matches operand may be a RegExp.`);if(!(n===null||typeof n!="object")&&!(a>G)&&!c.has(n)){if(c.add(n),Array.isArray(n)){n.forEach((i,l)=>{r(i,`${o}[${l}]`,c,a+1);});return}for(let i of Object.keys(n))r(n[i],o?`${o}.${i}`:i,c,a+1);}}function s(n,o,c){if(typeof n=="bigint")throw new Error(`[Directive] validatePredicate: bigint operand at "${c}" is not JSON-serializable (JSON.stringify throws on bigint).`);if(n instanceof Set)throw new Error(`[Directive] validatePredicate: Set operand at "${c}" is not JSON-serializable (serializes to {} and loses all members).`);if(n instanceof Map)throw new Error(`[Directive] validatePredicate: Map operand at "${c}" is not JSON-serializable (serializes to {} and loses all entries).`);if(o==="$matches"&&!(n instanceof RegExp))throw new Error(`[Directive] validatePredicate: $matches operand at "${c}" must be a RegExp; got ${n===null?"null":typeof n}. A regex lost to JSON.parse becomes {} \u2014 reify with new RegExp(pattern, flags) before installing.`);if(Array.isArray(n))n.forEach((a,i)=>{r(a,`${c}[${i}]`,new WeakSet,1);});else if(De(n))for(let a of Object.keys(n))r(n[a],`${c}.${a}`,new WeakSet,1);}if(e instanceof Set)throw new Error(`[Directive] validatePredicate: Set operand${t?` at "${t}"`:""} is not JSON-serializable (serializes to {} and loses all members).`);if(e instanceof Map)throw new Error(`[Directive] validatePredicate: Map operand${t?` at "${t}"`:""} is not JSON-serializable (serializes to {} and loses all entries).`);ye(e,{operator(n,o,c,a){s(c,o,t?`${t}.${a}`:a);},literal(n,o){s(o,"",t?`${t}.${n}`:n);}});}function yn(){return {ids:new WeakMap,next:{v:1},pairs:new Set}}function qt(e,t){let r=e.ids.get(t);return r===void 0&&(r=e.next.v++,e.ids.set(t,r)),r}function q(e,t,r){if(Object.is(e,t))return true;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(typeof e!="object"||typeof t!="object"||e===null||t===null)return false;let s=r??yn(),n=`${qt(s,e)}:${qt(s,t)}`;if(s.pairs.has(n))return true;if(s.pairs.add(n),Array.isArray(e)||Array.isArray(t))return !Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?false:e.every((a,i)=>q(a,t[i],s));if(e instanceof Set||t instanceof Set){if(!(e instanceof Set)||!(t instanceof Set)||e.size!==t.size)return false;let a=[...t];return [...e].every(i=>a.some(l=>q(i,l,s)))}if(e instanceof Map||t instanceof Map){if(!(e instanceof Map)||!(t instanceof Map)||e.size!==t.size)return false;let a=[...t.entries()],i=new Array(a.length).fill(false);for(let[l,u]of e){let d=false;for(let f=0;f<a.length;f++){if(i[f])continue;let[h,$]=a[f];if(q(l,h,s)&&q(u,$,s)){i[f]=true,d=true;break}}if(!d)return false}return true}let o=Object.keys(e),c=Object.keys(t);return o.length!==c.length?false:o.every(a=>Object.hasOwn(t,a)&&q(e[a],t[a],s))}function Ce(e){if(e instanceof Date)return e.getTime();if(typeof e=="number"||typeof e=="bigint"||typeof e=="string")return e}function Be(e,t,r){let s=Ce(t),n=Ce(r);if(s===void 0||n===void 0||typeof s!=typeof n)return false;switch(e){case "$gt":return s>n;case "$gte":return s>=n;case "$lt":return s<n;case "$lte":return s<=n;default:return false}}function Re(e,t,r,s){switch(e){case "$eq":return q(t,r);case "$ne":return !q(t,r);case "$in":return Array.isArray(r)&&r.some(n=>q(t,n));case "$nin":return Array.isArray(r)&&!r.some(n=>q(t,n));case "$exists":return r===(t!==void 0);case "$changed":return !q(t,s);case "$gt":case "$gte":case "$lt":case "$lte":return Be(e,t,r);case "$between":{if(!Array.isArray(r)||r.length!==2)return false;let n=Ce(r[0]),o=Ce(r[1]);return n!==void 0&&o!==void 0&&typeof n==typeof o&&n>o?($e("$between: reversed pair \u2014 [min, max] required"),false):Be("$gte",t,r[0])&&Be("$lte",t,r[1])}case "$matches":{if(!(r instanceof RegExp))throw new Error("[Directive] $matches: operand must be a RegExp (string operands are no longer accepted; pass /pattern/flags directly).");return typeof t!="string"?false:r.test(t)}case "$startsWith":return typeof t!="string"?false:t.startsWith(String(r));case "$endsWith":return typeof t!="string"?false:t.endsWith(String(r));case "$contains":return typeof t=="string"?t.includes(String(r)):Array.isArray(t)?t.some(n=>q(n,r)):t instanceof Set?t.has(r):false;default:return false}}function $e(e){ge&&console.warn(`[Directive] ${e}`);}function $n(e,t,r,s){if(He(e)){let n=Object.keys(e);n.length>1&&$e(`predicate: operator object has ${n.length} operators (${n.join(", ")}) \u2014 write the array form or $all instead. The runtime ANDs them as a best-effort fallback.`);for(let o of n)if(!Re(o,t,e[o],r))return false;return true}return I(e)?se(e,I(t)?t:Object.create(null),I(r)?r:void 0,s+1):q(t,e)}function se(e,t,r,s=0){if(s>G)return $e(`predicate depth limit (${G}) exceeded \u2014 flatten the predicate or split it into multiple constraints. If this is unexpected, check for a cyclic spec object.`),false;if(Array.isArray(e))return e.every(n=>{if(!I(n))return false;let{fact:o,op:c,value:a}=n;return Re(c,t?.[o],a,r?.[o])});if(!I(e))return !!e;if("$all"in e)return e.$all.every(n=>se(n,t,r,s+1));if("$any"in e)return e.$any.some(n=>se(n,t,r,s+1));if("$not"in e)return !se(e.$not,t,r,s+1);for(let n of Object.keys(e)){if(K.has(n))return $e(`predicate: operator "${n}" mixed with fact keys \u2014 wrap operators in a per-fact object`),false;if(!$n(e[n],t?.[n],r?.[n],s))return false}return true}function ve(e,t,r,s=""){let n=[];if(Array.isArray(e)){for(let o of e){if(!I(o))continue;let{fact:c,op:a,value:i}=o,l=t?.[c];n.push({path:s+c,op:a,expected:i,actual:l,pass:Re(a,l,i,r?.[c])});}return n}if(!I(e))return n;for(let o of ["$all","$any","$not"])if(o in e){let c=o==="$not"?[e.$not]:e[o],a=[];for(let u of c)a.push(...ve(u,t,r,s));let i=a.filter(u=>u.pass).length,l;return o==="$all"?l=a.length===0||i===a.length:o==="$any"?l=a.length>0&&i>0:l=!a.every(u=>u.pass),n.push({path:s||o,op:o,expected:c.length,actual:i,pass:l,children:a}),n}for(let o of Object.keys(e)){if(K.has(o))continue;let c=e[o],a=t?.[o],i=s+o;if(He(c))for(let l of Object.keys(c))n.push({path:i,op:l,expected:c[l],actual:a,pass:Re(l,a,c[l],r?.[o])});else I(c)?n.push(...ve(c,I(a)?a:Object.create(null),I(r?.[o])?r?.[o]:void 0,`${i}.`)):n.push({path:i,op:"$eq",expected:c,actual:a,pass:q(a,c)});}return n}var fe=1e6;function _t(e,t){try{Wt(e);}catch(s){let n=s instanceof Error?s.message:String(s);throw new Error(`[Directive] replayUnder: the ${t} predicate is invalid \u2014 ${n}`)}if(!Ft(e)){let s=e===null||typeof e!="object"?`${typeof e} \u2014 ${JSON.stringify(e)}`:JSON.stringify(e).slice(0,80);throw new Error(`[Directive] replayUnder: the ${t} predicate is not a valid FactPredicate (got ${s})`)}let r;if(ye(e,{operator(s,n){r===void 0&&n.startsWith("$")&&!K.has(n)&&(r=n);},strayOperatorKey(s){r===void 0&&!K.has(s)&&!It.has(s)&&(r=s);}}),r!==void 0)throw new Error(`[Directive] replayUnder: the ${t} predicate uses an unknown operator "${r}" \u2014 known operators: ${[...K].join(", ")}`)}function we(e){if(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.snapshots))return vn(e);let t=Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.frames)?e.frames:null;if(!t)throw new Error("[Directive] toReplayFrames: history must be a JSON array of frames, an object with a `frames` array, or a history export with a `snapshots` array");if(t.length>fe)throw new Error(`[Directive] toReplayFrames: history has ${t.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${fe}) \u2014 split or down-sample the history`);return t.map((r,s)=>{if(r&&typeof r=="object"&&"facts"in r){let n=r,o={id:n.id??`#${s}`,facts:n.facts??{}};return typeof n.timestamp=="number"&&(o.timestamp=n.timestamp),o}return {id:`#${s}`,facts:r??{}}})}function vn(e){let t=typeof e=="string"?JSON.parse(e):e;if(Array.isArray(t))return Ut(t);if(!t||typeof t!="object")throw new Error("[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())");let r=t;if(r.version!==void 0&&r.version!==1)throw new Error(`[Directive] framesFromHistory: unsupported history export version ${JSON.stringify(r.version)} \u2014 expected 1`);if(!Array.isArray(r.snapshots))throw new Error("[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())");return Ut(r.snapshots)}function Ut(e){if(!Array.isArray(e))throw new Error("[Directive] framesFromSnapshots: expected an array of fact-state snapshots");if(e.length>fe)throw new Error(`[Directive] framesFromSnapshots: history has ${e.length} snapshots, exceeds the MAX_REPLAY_FRAMES limit (${fe}) \u2014 split or down-sample the history`);for(let t=0;t<e.length;t++){let r=e[t];if(!r||typeof r!="object"||!("facts"in r))throw new Error(`[Directive] framesFromSnapshots: snapshot at index ${t} is not a { facts, ... } object`)}return we(e)}function Te(e){let{frames:t,original:r,proposed:s,entityKey:n}=e,o=e.maxSamples??20,c=o>0?o:0;if(t.length>fe)throw new Error(`[Directive] replayUnder: history has ${t.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${fe}) \u2014 split or down-sample the history`);_t(r,"original"),_t(s,"proposed");let a=0,i=0,l=0,u=0,d=0,f=[],h=[],$=n?new Set:void 0,w=n?new Set:void 0,F;for(let p of t){let v=p.facts,D=se(r,v,F),_=se(s,v,F);D&&(a++,$?.add(v[n])),_&&(i++,w?.add(v[n])),D===_?d++:!D&&_?(l++,f.length<c&&f.push(Lt(p,r,s,F))):(u++,h.length<c&&h.push(Lt(p,r,s,F))),F=v;}let W={framesEvaluated:t.length,original:{matched:a},proposed:{matched:i},delta:i-a,newMatchCount:l,lostMatchCount:u,unchanged:d,newMatches:f,lostMatches:h};return $&&w&&(W.original.matchedEntities=$.size,W.proposed.matchedEntities=w.size),W}function Lt(e,t,r,s){let n=e.facts,o={frameId:e.id,facts:n,originalExplain:ve(t,n,s),proposedExplain:ve(r,n,s)};return e.timestamp!==void 0&&(o.timestamp=e.timestamp),o}var zt=1e4,Jt=5e7;function wn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===1&&typeof e.$hole=="string"}function Qe(e,t,r=new Set,s=0){if(s>G)throw new Error(`[Directive] sweepUnder: template exceeds MAX_PREDICATE_DEPTH (${G}) \u2014 flatten the template or split the sweep`);if(wn(e)){let n=e.$hole;if(!(n in t))throw new Error(`[Directive] sweepUnder: template references hole "${n}" but sweep has no values for it`);return t[n]}if(e===null||typeof e!="object")return e;if(r.has(e))throw new Error("[Directive] sweepUnder: template contains a cycle \u2014 predicate templates must be a tree");r.add(e);try{if(Array.isArray(e))return e.map(o=>Qe(o,t,r,s+1));let n={};for(let[o,c]of Object.entries(e))n[o]=Qe(c,t,r,s+1);return n}finally{r.delete(e);}}function*Gt(e,t){if(e.length===0){yield {};return}let r=e[0],s=e.slice(1),n=t[r]??[];for(let o of n)for(let c of Gt(s,t))yield {[r]:o,...c};}function bn(e){let t=1;for(let r of Object.values(e))t*=r.length;return t}function Bt(e){let{frames:t,original:r,template:s,sweep:n,objective:o=v=>v.proposed.matched,entityKey:c,maxSamples:a=0}=e,i=Object.keys(n);if(i.length===0)throw new Error("[Directive] sweepUnder: `sweep` must contain at least one hole name");let l=bn(n);if(l>zt)throw new Error(`[Directive] sweepUnder: grid has ${l} points, exceeds the MAX_SWEEP_POINTS limit (${zt}) \u2014 narrow the sweep ranges or split the run`);if(l===0)throw new Error("[Directive] sweepUnder: at least one hole has zero candidate values");let u=l*t.length;if(u>Jt)throw new Error(`[Directive] sweepUnder: ${l} points \xD7 ${t.length} frames = ${u} per-frame evaluations, exceeds the MAX_SWEEP_EVALUATIONS limit (${Jt}) \u2014 narrow the sweep, down-sample the history, or split the run`);let d=false,f=v=>{let D;try{D=o(v);}catch(_){return d||(d=true,console.warn(`[Directive] sweepUnder: objective threw \u2014 point will not rank (${_.message})`)),Number.NEGATIVE_INFINITY}return typeof D!="number"||!Number.isFinite(D)?(d||(d=true,console.warn(`[Directive] sweepUnder: objective returned a non-finite number (${String(D)}) \u2014 point will not rank`)),Number.NEGATIVE_INFINITY):D},h=Te({frames:t,original:r,proposed:r,entityKey:c,maxSamples:a}),$={values:{},report:h,score:f(h)},w=[],F=0,W=Number.NEGATIVE_INFINITY;for(let v of Gt(i,n)){let D=Qe(s,v),_=Te({frames:t,original:r,proposed:D,entityKey:c,maxSamples:a}),Ne=f(_);Ne>W&&(W=Ne,F=w.length),w.push({values:v,report:_,score:Ne});}let p=w[F];return {points:w,bestIndex:F,best:p,baseline:$}}function Kt(e){let t=e&&typeof e=="object"&&!Array.isArray(e)&&"constraints"in e?e.constraints:e;if(Array.isArray(t)){let r={};for(let s of t){if(!s||typeof s!="object"||!("id"in s))throw new Error("[Directive] diffRules: array entries must be `{ id, whenSpec }` objects");let n=s;if(typeof n.id!="string")throw new Error("[Directive] diffRules: constraint `id` must be a string");r[n.id]=n.whenSpec;}return r}if(t&&typeof t=="object")return t;throw new Error("[Directive] diffRules: expected a `{ id: whenSpec }` map, an array of `{ id, whenSpec }`, or `{ constraints: ... }`")}var kn=new Set(["$eq","$ne","$in","$nin","$exists","$gt","$gte","$lt","$lte","$between","$matches","$startsWith","$endsWith","$contains","$changed"]),xn=new Set(["$all","$any","$not"]);function Ht(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Sn(e){if(!Ht(e))return false;let t=Object.keys(e);if(t.length===0)return false;let r=false;for(let s of t){if(!s.startsWith("$"))return false;kn.has(s)&&(r=true);}return r}function H(e,t="",r=[]){if(e===null||typeof e!="object")return r;if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"&&"fact"in s&&"op"in s){let n=s;r.push({path:t?`${t}.${String(n.fact)}`:String(n.fact),op:String(n.op),value:n.value});}return r}if("$all"in e&&Array.isArray(e.$all))return e.$all.forEach((s,n)=>{H(s,`${t}$all[${n}]`,r);}),r;if("$any"in e&&Array.isArray(e.$any))return e.$any.forEach((s,n)=>{H(s,`${t}$any[${n}]`,r);}),r;if("$not"in e)return H(e.$not,`${t}$not`,r),r;for(let[s,n]of Object.entries(e)){let o=t?`${t}.${s}`:s;if(Sn(n))for(let[c,a]of Object.entries(n))r.push({path:o,op:c,value:a});else Ht(n)&&!xn.has(s)?H(n,o,r):r.push({path:o,op:"$eq",value:n});}return r}function B(e){return typeof e=="number"&&Number.isFinite(e)}function An(e,t,r){switch(e){case "$gte":case "$gt":if(B(t)&&B(r)){if(r<t)return "relaxed";if(r>t)return "tightened"}return null;case "$lte":case "$lt":if(B(t)&&B(r)){if(r>t)return "relaxed";if(r<t)return "tightened"}return null;case "$between":{if(Array.isArray(t)&&Array.isArray(r)&&t.length===2&&r.length===2&&B(t[0])&&B(t[1])&&B(r[0])&&B(r[1])){let s=t[1]-t[0],n=r[1]-r[0];if(n>s)return "relaxed";if(n<s)return "tightened"}return null}case "$in":case "$nin":{if(Array.isArray(t)&&Array.isArray(r))if(e==="$in"){if(r.length>t.length)return "relaxed";if(r.length<t.length)return "tightened"}else {if(r.length>t.length)return "tightened";if(r.length<t.length)return "relaxed"}return null}case "$contains":{if(Array.isArray(t)&&Array.isArray(r)){if(r.length>t.length)return "relaxed";if(r.length<t.length)return "tightened"}return null}default:return null}}function Qt(e){let t=Kt(e.before),r=Kt(e.after),s=[...new Set([...Object.keys(t),...Object.keys(r)])].sort(),n=[],o={added:0,removed:0,changed:0,unchanged:0,totalClauseChanges:0};for(let c of s){let a=t[c],i=r[c],l=c in t,u=c in r;if(l&&!u){let f=H(a),h=f.length===0?[{path:"(function-form predicate)",kind:"removed"}]:f.map($=>({path:$.path,kind:"removed",before:{op:$.op,value:$.value}}));Ye(h),n.push({id:c,status:"removed",changes:h}),o.removed++,o.totalClauseChanges+=h.length;continue}if(!l&&u){let f=H(i),h=f.length===0?[{path:"(function-form predicate)",kind:"added"}]:f.map($=>({path:$.path,kind:"added",after:{op:$.op,value:$.value}}));Ye(h),n.push({id:c,status:"added",changes:h}),o.added++,o.totalClauseChanges+=h.length;continue}let d=jn(a,i);d.length===0?(n.push({id:c,status:"unchanged",changes:[]}),o.unchanged++):(n.push({id:c,status:"changed",changes:d}),o.changed++,o.totalClauseChanges+=d.length);}return {constraints:n,summary:o}}function jn(e,t){if(e!==void 0&&t!==void 0&&(e===null||t===null||typeof e!="object"||typeof t!="object"))return de(e)===de(t)?[]:[{path:"",kind:"changed",before:{op:"$eq",value:e},after:{op:"$eq",value:t}}];let r=e===void 0?[]:H(e),s=t===void 0?[]:H(t),n=l=>`${l.path}::${l.op}`,o=new Map(r.map(l=>[n(l),l])),c=new Map(s.map(l=>[n(l),l])),a=new Set([...o.keys(),...c.keys()]),i=[];for(let l of a){let u=o.get(l),d=c.get(l);if(u&&!d){i.push({path:u.path,kind:"removed",before:{op:u.op,value:u.value}});continue}if(!u&&d){i.push({path:d.path,kind:"added",after:{op:d.op,value:d.value}});continue}if(u&&d){if(de(u.value)===de(d.value))continue;let f=An(u.op,u.value,d.value);i.push({path:u.path,kind:f??"changed",before:{op:u.op,value:u.value},after:{op:d.op,value:d.value}});}}return Ye(i),i}function Ye(e){e.sort((t,r)=>{let s=t.path.localeCompare(r.path);if(s!==0)return s;let n=t.before?.op??t.after?.op??"",o=r.before?.op??r.after?.op??"";return n.localeCompare(o)});}function Cn(e){let t={maxSamples:20,json:false};for(let r=0;r<e.length;r++)switch(e[r]){case "--history":{let n=e[++r];n&&(t.historyPath=n);break}case "--proposed":case "-p":{let n=e[++r];n&&(t.proposedPath=n);break}case "--original":case "-o":{let n=e[++r];n&&(t.originalPath=n);break}case "--max-samples":{let n=e[++r],o=n?Number.parseInt(n,10):Number.NaN;Number.isFinite(o)&&o>=0&&(t.maxSamples=o);break}case "--entity-key":{let n=e[++r];n&&(t.entityKey=n);break}case "--json":t.json=true;break}return t}function Me(){console.error(`
749
+ `)}function ln(e,t,r){let s=r!==void 0?` ${r}ms`:"";switch(e){case "resolved":return m.green(`resolved${s}`);case "errored":return m.red(`errored${s}${t?` \u2014 ${t}`:""}`);case "inflight":return m.yellow("inflight");case "cancelled":return m.dim("cancelled");default:return m.dim(e)}}function un(e){return e===null?m.dim("null"):e===void 0?m.dim("undefined"):typeof e=="string"?e.length>60?`"${e.slice(0,57)}..."`:`"${e}"`:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`[${e.length} items]`:JSON.stringify(e).slice(0,60)}function dn(e){let t=[];new Set(e.unmet.map(o=>o.requirement.type));new Set(e.resolverDefs.map(o=>o.requirement));for(let o of e.resolverDefs)o.requirement;for(let o of e.unmet)e.resolverDefs.some(a=>a.requirement===o.requirement.type||a.requirement==="(predicate)")||t.push(`No resolver for requirement type "${o.requirement.type}"`);return t}async function Et(e){let{filePath:t,opts:r}=rn(e);t||(console.error("Usage: directive inspect <file> [--json] [--module <name>]"),process.exit(1));let s=await z(t);s.isRunning||s.start();let n=s.inspect();if(r.json){let a={};if(s.facts)for(let i of Object.keys(s.facts))try{a[i]=s.facts[i];}catch{a[i]="(error reading)";}console.log(JSON.stringify({facts:a,...n},null,2)),s.stop();return}console.log(),console.log(m.bold(m.cyan("Directive System Inspection"))),console.log(m.dim("\u2500".repeat(40))),console.log();let o={};if(s.facts)for(let a of Object.keys(s.facts))try{o[a]=s.facts[a];}catch{o[a]="(error reading)";}console.log(nn(o)),console.log(),console.log(sn(n.constraints)),console.log(),console.log(on(n.resolverDefs,n.resolvers)),console.log(),console.log(an(n.unmet)),console.log(),n.inflight.length>0&&(console.log(cn(n.inflight)),console.log());let c=dn(n);if(c.length>0){console.log(m.bold(m.yellow("Warnings:")));for(let a of c)console.log(` ${m.yellow("\u26A0")} ${a}`);console.log();}s.stop();}function Ct(e){let t={with:[],minimal:false,dir:process.cwd()};for(let r=0;r<e.length;r++)switch(e[r]){case "--with":{let n=e[++r];n&&(t.with=n.split(",").map(o=>o.trim()));break}case "--minimal":t.minimal=true;break;case "--dir":{let n=e[++r];n&&(t.dir=n);break}}return t}function Rt(e,t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true}),writeFileSync(e,t,"utf-8");}function Tt(e){return join(e,"src")}function Mt(e,t){let r=validateModuleName(t),s=r===true?"":`: ${r}`;console.error(`Invalid ${e} name: ${t||"(none)"}${s}`),console.error("Must start with a lowercase letter, use lowercase letters, numbers, and hyphens."),process.exit(1);}async function Nt(e,t){let r=Ct(t);if(validateModuleName(e)!==true){Mt("module",e);return}let s;r.minimal?s=[]:r.with.length>0?s=r.with.filter(l=>MODULE_SECTIONS.includes(l)):s=[...MODULE_SECTIONS];let{sourceFileName:n}=suggestFileNames(e,"module"),o=Tt(r.dir),c=join(o,n);existsSync(c)&&(console.error(`File already exists: ${relative(r.dir,c)}`),process.exit(1));let{moduleSource:a}=generateModule(e,s);Rt(c,a);let i=relative(r.dir,c);console.log(`${m.green("Created")} ${m.dim(i)}`),s.length===0?console.log(m.dim(" Minimal module (schema + init only)")):console.log(m.dim(` Sections: ${s.join(", ")}`));}async function Pt(e,t){let r=Ct(t);if(validateModuleName(e)!==true){Mt("orchestrator",e);return}let{sourceFileName:s}=suggestFileNames(e,"orchestrator"),n=Tt(r.dir),o=join(n,s);existsSync(o)&&(console.error(`File already exists: ${relative(r.dir,o)}`),process.exit(1));let{moduleSource:c}=generateOrchestrator(e);Rt(o,c);let a=relative(r.dir,o);console.log(`${m.green("Created")} ${m.dim(a)}`),console.log(m.dim(" AI orchestrator with memory, guardrails, and streaming"));}var ge=typeof process<"u"&&process.env?.NODE_ENV!=="production";function de(e,t=50){let r=new WeakSet;function s(i){if(i===null)return "null";if(i===void 0)return "undefined";let l=typeof i;if(l==="string")return JSON.stringify(i);if(l==="number"||l==="boolean")return String(i);if(l==="function")return '"[function]"';if(l==="symbol")return '"[symbol]"'}function n(i,l){if(r.has(i))return '"[circular]"';r.add(i);let u=l();return r.delete(i),u}function o(i,l){return n(i,()=>`[${i.map(u=>a(u,l+1)).join(",")}]`)}function c(i,l){return n(i,()=>`{${Object.keys(i).sort().map(u=>`${JSON.stringify(u)}:${a(i[u],l+1)}`).join(",")}}`)}function a(i,l){if(l>t)return '"[max depth exceeded]"';if(typeof i=="bigint")return `${i.toString()}n`;let u=s(i);if(u!==void 0)return u;if(i instanceof Date)return `D:${i.toISOString()}`;if(i instanceof RegExp)return `R:${i.source}:${i.flags}`;if(i instanceof Map){let d=[...i.entries()].sort();return `M:${a(d,l+1)}`}if(i instanceof Set){let d=[...i].sort();return `S:${a(d,l+1)}`}return Array.isArray(i)?o(i,l):typeof i=="object"?c(i,l):'"[unknown]"'}return a(e,0)}var K=new Set(["$eq","$ne","$in","$nin","$exists","$gt","$gte","$lt","$lte","$between","$matches","$startsWith","$endsWith","$contains","$changed"]),It=new Set(["$all","$any","$not"]);var G=64;function I(e){return typeof e!="object"||e===null||Array.isArray(e)?false:!(e instanceof Date)&&!(e instanceof RegExp)}function De(e){if(typeof e!="object"||e===null||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function He(e){if(!I(e))return false;let t=0,r=false;for(let s of Object.keys(e)){if(s.startsWith("$"))r=true,K.has(s)||$e(`predicate: unknown operator "${s}" \u2014 looks like a typo. Known operators: ${[...K].join(", ")}`);else if(r||t===0)return false;t++;}return r?t>0:false}function Ft(e){return e===null?false:Array.isArray(e)?e.every(t=>De(t)&&"fact"in t&&"op"in t):De(e)}function ye(e,t,r="",s=new WeakSet,n=0){if(n>G){ge&&console.warn(`[Directive] predicate depth limit (${G}) exceeded \u2014 flatten the predicate or split it into multiple constraints. If this is unexpected, check for a cyclic spec object.`),t.bail?.("depth");return}if(Array.isArray(e)){e.forEach((c,a)=>{if(!I(c))return;let i=c;if(typeof i.fact=="string"&&typeof i.op=="string"){let l=r?`${r}[${a}]`:`[${a}]`;t.operator?.(r?`${r}.${i.fact}`:i.fact,i.op,i.value,`${l}.value`);}});return}if(!I(e))return;if(s.has(e)){ge&&console.warn("[Directive] walkPredicate: cyclic predicate spec"),t.bail?.("cycle");return}s.add(e);let o=e;for(let c of ["$all","$any","$not"])if(c in o){if(t.combinator?.(c)===false)return;let a=c==="$not"?[o.$not]:o[c]??[];for(let i of a)ye(i,t,r,s,n+1);return}for(let c of Object.keys(o)){let a=r?`${r}.${c}`:c;if(c.startsWith("$")){t.strayOperatorKey?.(c,a);continue}let i=o[c];if(He(i)){let l=i;for(let u of Object.keys(l))t.operator?.(a,u,l[u],`${a}.${u}`);continue}if(De(i)){if(t.nested?.(c)===false)continue;ye(i,t,a,s,n+1);continue}t.literal?.(a,i);}}function Wt(e,t=""){function r(n,o,c,a){if(typeof n=="bigint")throw new Error(`[Directive] validatePredicate: bigint operand at "${o}" is not JSON-serializable (JSON.stringify throws on bigint).`);if(n instanceof Set)throw new Error(`[Directive] validatePredicate: Set operand at "${o}" is not JSON-serializable (serializes to {} and loses all members).`);if(n instanceof Map)throw new Error(`[Directive] validatePredicate: Map operand at "${o}" is not JSON-serializable (serializes to {} and loses all entries).`);if(n instanceof RegExp)throw new Error(`[Directive] validatePredicate: RegExp operand at "${o}" is not JSON-serializable (a regex lost to JSON.parse becomes {}). Only a direct $matches operand may be a RegExp.`);if(!(n===null||typeof n!="object")&&!(a>G)&&!c.has(n)){if(c.add(n),Array.isArray(n)){n.forEach((i,l)=>{r(i,`${o}[${l}]`,c,a+1);});return}for(let i of Object.keys(n))r(n[i],o?`${o}.${i}`:i,c,a+1);}}function s(n,o,c){if(typeof n=="bigint")throw new Error(`[Directive] validatePredicate: bigint operand at "${c}" is not JSON-serializable (JSON.stringify throws on bigint).`);if(n instanceof Set)throw new Error(`[Directive] validatePredicate: Set operand at "${c}" is not JSON-serializable (serializes to {} and loses all members).`);if(n instanceof Map)throw new Error(`[Directive] validatePredicate: Map operand at "${c}" is not JSON-serializable (serializes to {} and loses all entries).`);if(o==="$matches"&&!(n instanceof RegExp))throw new Error(`[Directive] validatePredicate: $matches operand at "${c}" must be a RegExp; got ${n===null?"null":typeof n}. A regex lost to JSON.parse becomes {} \u2014 reify with new RegExp(pattern, flags) before installing.`);if(Array.isArray(n))n.forEach((a,i)=>{r(a,`${c}[${i}]`,new WeakSet,1);});else if(De(n))for(let a of Object.keys(n))r(n[a],`${c}.${a}`,new WeakSet,1);}if(e instanceof Set)throw new Error(`[Directive] validatePredicate: Set operand${t?` at "${t}"`:""} is not JSON-serializable (serializes to {} and loses all members).`);if(e instanceof Map)throw new Error(`[Directive] validatePredicate: Map operand${t?` at "${t}"`:""} is not JSON-serializable (serializes to {} and loses all entries).`);ye(e,{operator(n,o,c,a){s(c,o,t?`${t}.${a}`:a);},literal(n,o){s(o,"",t?`${t}.${n}`:n);}});}function yn(){return {ids:new WeakMap,next:{v:1},pairs:new Set}}function qt(e,t){let r=e.ids.get(t);return r===void 0&&(r=e.next.v++,e.ids.set(t,r)),r}function q(e,t,r){if(Object.is(e,t))return true;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(typeof e!="object"||typeof t!="object"||e===null||t===null)return false;let s=r??yn(),n=`${qt(s,e)}:${qt(s,t)}`;if(s.pairs.has(n))return true;if(s.pairs.add(n),Array.isArray(e)||Array.isArray(t))return !Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?false:e.every((a,i)=>q(a,t[i],s));if(e instanceof Set||t instanceof Set){if(!(e instanceof Set)||!(t instanceof Set)||e.size!==t.size)return false;let a=[...t];return [...e].every(i=>a.some(l=>q(i,l,s)))}if(e instanceof Map||t instanceof Map){if(!(e instanceof Map)||!(t instanceof Map)||e.size!==t.size)return false;let a=[...t.entries()],i=new Array(a.length).fill(false);for(let[l,u]of e){let d=false;for(let f=0;f<a.length;f++){if(i[f])continue;let[h,$]=a[f];if(q(l,h,s)&&q(u,$,s)){i[f]=true,d=true;break}}if(!d)return false}return true}let o=Object.keys(e),c=Object.keys(t);return o.length!==c.length?false:o.every(a=>Object.hasOwn(t,a)&&q(e[a],t[a],s))}function Ce(e){if(e instanceof Date)return e.getTime();if(typeof e=="number"||typeof e=="bigint"||typeof e=="string")return e}function Be(e,t,r){let s=Ce(t),n=Ce(r);if(s===void 0||n===void 0||typeof s!=typeof n)return false;switch(e){case "$gt":return s>n;case "$gte":return s>=n;case "$lt":return s<n;case "$lte":return s<=n;default:return false}}function Re(e,t,r,s){switch(e){case "$eq":return q(t,r);case "$ne":return !q(t,r);case "$in":return Array.isArray(r)&&r.some(n=>q(t,n));case "$nin":return Array.isArray(r)&&!r.some(n=>q(t,n));case "$exists":return r===(t!==void 0);case "$changed":return !q(t,s);case "$gt":case "$gte":case "$lt":case "$lte":return Be(e,t,r);case "$between":{if(!Array.isArray(r)||r.length!==2)return false;let n=Ce(r[0]),o=Ce(r[1]);return n!==void 0&&o!==void 0&&typeof n==typeof o&&n>o?($e("$between: reversed pair \u2014 [min, max] required"),false):Be("$gte",t,r[0])&&Be("$lte",t,r[1])}case "$matches":{if(!(r instanceof RegExp))throw new Error("[Directive] $matches: operand must be a RegExp (string operands are no longer accepted; pass /pattern/flags directly).");return typeof t!="string"?false:r.test(t)}case "$startsWith":return typeof t!="string"?false:t.startsWith(String(r));case "$endsWith":return typeof t!="string"?false:t.endsWith(String(r));case "$contains":return typeof t=="string"?t.includes(String(r)):Array.isArray(t)?t.some(n=>q(n,r)):t instanceof Set?t.has(r):false;default:return false}}function $e(e){ge&&console.warn(`[Directive] ${e}`);}function $n(e,t,r,s){if(He(e)){let n=Object.keys(e);n.length>1&&$e(`predicate: operator object has ${n.length} operators (${n.join(", ")}) \u2014 write the array form or $all instead. The runtime ANDs them as a best-effort fallback.`);for(let o of n)if(!Re(o,t,e[o],r))return false;return true}return I(e)?se(e,I(t)?t:Object.create(null),I(r)?r:void 0,s+1):q(t,e)}function se(e,t,r,s=0){if(s>G)return $e(`predicate depth limit (${G}) exceeded \u2014 flatten the predicate or split it into multiple constraints. If this is unexpected, check for a cyclic spec object.`),false;if(Array.isArray(e))return e.every(n=>{if(!I(n))return false;let{fact:o,op:c,value:a}=n;return Re(c,t?.[o],a,r?.[o])});if(!I(e))return !!e;if("$all"in e)return e.$all.every(n=>se(n,t,r,s+1));if("$any"in e)return e.$any.some(n=>se(n,t,r,s+1));if("$not"in e)return !se(e.$not,t,r,s+1);for(let n of Object.keys(e)){if(K.has(n))return $e(`predicate: operator "${n}" mixed with fact keys \u2014 wrap operators in a per-fact object`),false;if(!$n(e[n],t?.[n],r?.[n],s))return false}return true}function ve(e,t,r,s=""){let n=[];if(Array.isArray(e)){for(let o of e){if(!I(o))continue;let{fact:c,op:a,value:i}=o,l=t?.[c];n.push({path:s+c,op:a,expected:i,actual:l,pass:Re(a,l,i,r?.[c])});}return n}if(!I(e))return n;for(let o of ["$all","$any","$not"])if(o in e){let c=o==="$not"?[e.$not]:e[o],a=[];for(let u of c)a.push(...ve(u,t,r,s));let i=a.filter(u=>u.pass).length,l;return o==="$all"?l=a.length===0||i===a.length:o==="$any"?l=a.length>0&&i>0:l=!a.every(u=>u.pass),n.push({path:s||o,op:o,expected:c.length,actual:i,pass:l,children:a}),n}for(let o of Object.keys(e)){if(K.has(o))continue;let c=e[o],a=t?.[o],i=s+o;if(He(c))for(let l of Object.keys(c))n.push({path:i,op:l,expected:c[l],actual:a,pass:Re(l,a,c[l],r?.[o])});else I(c)?n.push(...ve(c,I(a)?a:Object.create(null),I(r?.[o])?r?.[o]:void 0,`${i}.`)):n.push({path:i,op:"$eq",expected:c,actual:a,pass:q(a,c)});}return n}var fe=1e6;function _t(e,t){try{Wt(e);}catch(s){let n=s instanceof Error?s.message:String(s);throw new Error(`[Directive] replayUnder: the ${t} predicate is invalid \u2014 ${n}`)}if(!Ft(e)){let s=e===null||typeof e!="object"?`${typeof e} \u2014 ${JSON.stringify(e)}`:JSON.stringify(e).slice(0,80);throw new Error(`[Directive] replayUnder: the ${t} predicate is not a valid FactPredicate (got ${s})`)}let r;if(ye(e,{operator(s,n){r===void 0&&n.startsWith("$")&&!K.has(n)&&(r=n);},strayOperatorKey(s){r===void 0&&!K.has(s)&&!It.has(s)&&(r=s);}}),r!==void 0)throw new Error(`[Directive] replayUnder: the ${t} predicate uses an unknown operator "${r}" \u2014 known operators: ${[...K].join(", ")}`)}function we(e){if(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.snapshots))return vn(e);let t=Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.frames)?e.frames:null;if(!t)throw new Error("[Directive] toReplayFrames: history must be a JSON array of frames, an object with a `frames` array, or a history export with a `snapshots` array");if(t.length>fe)throw new Error(`[Directive] toReplayFrames: history has ${t.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${fe}) \u2014 split or down-sample the history`);return t.map((r,s)=>{if(r&&typeof r=="object"&&"facts"in r){let n=r,o={id:n.id??`#${s}`,facts:n.facts??{}};return typeof n.timestamp=="number"&&(o.timestamp=n.timestamp),o}return {id:`#${s}`,facts:r??{}}})}function vn(e){let t=typeof e=="string"?JSON.parse(e):e;if(Array.isArray(t))return Lt(t);if(!t||typeof t!="object")throw new Error("[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())");let r=t;if(r.version!==void 0&&r.version!==1)throw new Error(`[Directive] framesFromHistory: unsupported history export version ${JSON.stringify(r.version)} \u2014 expected 1`);if(!Array.isArray(r.snapshots))throw new Error("[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())");return Lt(r.snapshots)}function Lt(e){if(!Array.isArray(e))throw new Error("[Directive] framesFromSnapshots: expected an array of fact-state snapshots");if(e.length>fe)throw new Error(`[Directive] framesFromSnapshots: history has ${e.length} snapshots, exceeds the MAX_REPLAY_FRAMES limit (${fe}) \u2014 split or down-sample the history`);for(let t=0;t<e.length;t++){let r=e[t];if(!r||typeof r!="object"||!("facts"in r))throw new Error(`[Directive] framesFromSnapshots: snapshot at index ${t} is not a { facts, ... } object`)}return we(e)}function Te(e){let{frames:t,original:r,proposed:s,entityKey:n}=e,o=e.maxSamples??20,c=o>0?o:0;if(t.length>fe)throw new Error(`[Directive] replayUnder: history has ${t.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${fe}) \u2014 split or down-sample the history`);_t(r,"original"),_t(s,"proposed");let a=0,i=0,l=0,u=0,d=0,f=[],h=[],$=n?new Set:void 0,w=n?new Set:void 0,F;for(let p of t){let v=p.facts,D=se(r,v,F),_=se(s,v,F);D&&(a++,$?.add(v[n])),_&&(i++,w?.add(v[n])),D===_?d++:!D&&_?(l++,f.length<c&&f.push(Ut(p,r,s,F))):(u++,h.length<c&&h.push(Ut(p,r,s,F))),F=v;}let W={framesEvaluated:t.length,original:{matched:a},proposed:{matched:i},delta:i-a,newMatchCount:l,lostMatchCount:u,unchanged:d,newMatches:f,lostMatches:h};return $&&w&&(W.original.matchedEntities=$.size,W.proposed.matchedEntities=w.size),W}function Ut(e,t,r,s){let n=e.facts,o={frameId:e.id,facts:n,originalExplain:ve(t,n,s),proposedExplain:ve(r,n,s)};return e.timestamp!==void 0&&(o.timestamp=e.timestamp),o}var zt=1e4,Jt=5e7;function wn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===1&&typeof e.$hole=="string"}function Qe(e,t,r=new Set,s=0){if(s>G)throw new Error(`[Directive] sweepUnder: template exceeds MAX_PREDICATE_DEPTH (${G}) \u2014 flatten the template or split the sweep`);if(wn(e)){let n=e.$hole;if(!(n in t))throw new Error(`[Directive] sweepUnder: template references hole "${n}" but sweep has no values for it`);return t[n]}if(e===null||typeof e!="object")return e;if(r.has(e))throw new Error("[Directive] sweepUnder: template contains a cycle \u2014 predicate templates must be a tree");r.add(e);try{if(Array.isArray(e))return e.map(o=>Qe(o,t,r,s+1));let n={};for(let[o,c]of Object.entries(e))n[o]=Qe(c,t,r,s+1);return n}finally{r.delete(e);}}function*Gt(e,t){if(e.length===0){yield {};return}let r=e[0],s=e.slice(1),n=t[r]??[];for(let o of n)for(let c of Gt(s,t))yield {[r]:o,...c};}function bn(e){let t=1;for(let r of Object.values(e))t*=r.length;return t}function Bt(e){let{frames:t,original:r,template:s,sweep:n,objective:o=v=>v.proposed.matched,entityKey:c,maxSamples:a=0}=e,i=Object.keys(n);if(i.length===0)throw new Error("[Directive] sweepUnder: `sweep` must contain at least one hole name");let l=bn(n);if(l>zt)throw new Error(`[Directive] sweepUnder: grid has ${l} points, exceeds the MAX_SWEEP_POINTS limit (${zt}) \u2014 narrow the sweep ranges or split the run`);if(l===0)throw new Error("[Directive] sweepUnder: at least one hole has zero candidate values");let u=l*t.length;if(u>Jt)throw new Error(`[Directive] sweepUnder: ${l} points \xD7 ${t.length} frames = ${u} per-frame evaluations, exceeds the MAX_SWEEP_EVALUATIONS limit (${Jt}) \u2014 narrow the sweep, down-sample the history, or split the run`);let d=false,f=v=>{let D;try{D=o(v);}catch(_){return d||(d=true,console.warn(`[Directive] sweepUnder: objective threw \u2014 point will not rank (${_.message})`)),Number.NEGATIVE_INFINITY}return typeof D!="number"||!Number.isFinite(D)?(d||(d=true,console.warn(`[Directive] sweepUnder: objective returned a non-finite number (${String(D)}) \u2014 point will not rank`)),Number.NEGATIVE_INFINITY):D},h=Te({frames:t,original:r,proposed:r,entityKey:c,maxSamples:a}),$={values:{},report:h,score:f(h)},w=[],F=0,W=Number.NEGATIVE_INFINITY;for(let v of Gt(i,n)){let D=Qe(s,v),_=Te({frames:t,original:r,proposed:D,entityKey:c,maxSamples:a}),Ne=f(_);Ne>W&&(W=Ne,F=w.length),w.push({values:v,report:_,score:Ne});}let p=w[F];return {points:w,bestIndex:F,best:p,baseline:$}}function Kt(e){let t=e&&typeof e=="object"&&!Array.isArray(e)&&"constraints"in e?e.constraints:e;if(Array.isArray(t)){let r={};for(let s of t){if(!s||typeof s!="object"||!("id"in s))throw new Error("[Directive] diffRules: array entries must be `{ id, whenSpec }` objects");let n=s;if(typeof n.id!="string")throw new Error("[Directive] diffRules: constraint `id` must be a string");r[n.id]=n.whenSpec;}return r}if(t&&typeof t=="object")return t;throw new Error("[Directive] diffRules: expected a `{ id: whenSpec }` map, an array of `{ id, whenSpec }`, or `{ constraints: ... }`")}var kn=new Set(["$eq","$ne","$in","$nin","$exists","$gt","$gte","$lt","$lte","$between","$matches","$startsWith","$endsWith","$contains","$changed"]),xn=new Set(["$all","$any","$not"]);function Ht(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Sn(e){if(!Ht(e))return false;let t=Object.keys(e);if(t.length===0)return false;let r=false;for(let s of t){if(!s.startsWith("$"))return false;kn.has(s)&&(r=true);}return r}function H(e,t="",r=[]){if(e===null||typeof e!="object")return r;if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"&&"fact"in s&&"op"in s){let n=s;r.push({path:t?`${t}.${String(n.fact)}`:String(n.fact),op:String(n.op),value:n.value});}return r}if("$all"in e&&Array.isArray(e.$all))return e.$all.forEach((s,n)=>{H(s,`${t}$all[${n}]`,r);}),r;if("$any"in e&&Array.isArray(e.$any))return e.$any.forEach((s,n)=>{H(s,`${t}$any[${n}]`,r);}),r;if("$not"in e)return H(e.$not,`${t}$not`,r),r;for(let[s,n]of Object.entries(e)){let o=t?`${t}.${s}`:s;if(Sn(n))for(let[c,a]of Object.entries(n))r.push({path:o,op:c,value:a});else Ht(n)&&!xn.has(s)?H(n,o,r):r.push({path:o,op:"$eq",value:n});}return r}function B(e){return typeof e=="number"&&Number.isFinite(e)}function An(e,t,r){switch(e){case "$gte":case "$gt":if(B(t)&&B(r)){if(r<t)return "relaxed";if(r>t)return "tightened"}return null;case "$lte":case "$lt":if(B(t)&&B(r)){if(r>t)return "relaxed";if(r<t)return "tightened"}return null;case "$between":{if(Array.isArray(t)&&Array.isArray(r)&&t.length===2&&r.length===2&&B(t[0])&&B(t[1])&&B(r[0])&&B(r[1])){let s=t[1]-t[0],n=r[1]-r[0];if(n>s)return "relaxed";if(n<s)return "tightened"}return null}case "$in":case "$nin":{if(Array.isArray(t)&&Array.isArray(r))if(e==="$in"){if(r.length>t.length)return "relaxed";if(r.length<t.length)return "tightened"}else {if(r.length>t.length)return "tightened";if(r.length<t.length)return "relaxed"}return null}case "$contains":{if(Array.isArray(t)&&Array.isArray(r)){if(r.length>t.length)return "relaxed";if(r.length<t.length)return "tightened"}return null}default:return null}}function Qt(e){let t=Kt(e.before),r=Kt(e.after),s=[...new Set([...Object.keys(t),...Object.keys(r)])].sort(),n=[],o={added:0,removed:0,changed:0,unchanged:0,totalClauseChanges:0};for(let c of s){let a=t[c],i=r[c],l=c in t,u=c in r;if(l&&!u){let f=H(a),h=f.length===0?[{path:"(function-form predicate)",kind:"removed"}]:f.map($=>({path:$.path,kind:"removed",before:{op:$.op,value:$.value}}));Ye(h),n.push({id:c,status:"removed",changes:h}),o.removed++,o.totalClauseChanges+=h.length;continue}if(!l&&u){let f=H(i),h=f.length===0?[{path:"(function-form predicate)",kind:"added"}]:f.map($=>({path:$.path,kind:"added",after:{op:$.op,value:$.value}}));Ye(h),n.push({id:c,status:"added",changes:h}),o.added++,o.totalClauseChanges+=h.length;continue}let d=jn(a,i);d.length===0?(n.push({id:c,status:"unchanged",changes:[]}),o.unchanged++):(n.push({id:c,status:"changed",changes:d}),o.changed++,o.totalClauseChanges+=d.length);}return {constraints:n,summary:o}}function jn(e,t){if(e!==void 0&&t!==void 0&&(e===null||t===null||typeof e!="object"||typeof t!="object"))return de(e)===de(t)?[]:[{path:"",kind:"changed",before:{op:"$eq",value:e},after:{op:"$eq",value:t}}];let r=e===void 0?[]:H(e),s=t===void 0?[]:H(t),n=l=>`${l.path}::${l.op}`,o=new Map(r.map(l=>[n(l),l])),c=new Map(s.map(l=>[n(l),l])),a=new Set([...o.keys(),...c.keys()]),i=[];for(let l of a){let u=o.get(l),d=c.get(l);if(u&&!d){i.push({path:u.path,kind:"removed",before:{op:u.op,value:u.value}});continue}if(!u&&d){i.push({path:d.path,kind:"added",after:{op:d.op,value:d.value}});continue}if(u&&d){if(de(u.value)===de(d.value))continue;let f=An(u.op,u.value,d.value);i.push({path:u.path,kind:f??"changed",before:{op:u.op,value:u.value},after:{op:d.op,value:d.value}});}}return Ye(i),i}function Ye(e){e.sort((t,r)=>{let s=t.path.localeCompare(r.path);if(s!==0)return s;let n=t.before?.op??t.after?.op??"",o=r.before?.op??r.after?.op??"";return n.localeCompare(o)});}function Cn(e){let t={maxSamples:20,json:false};for(let r=0;r<e.length;r++)switch(e[r]){case "--history":{let n=e[++r];n&&(t.historyPath=n);break}case "--proposed":case "-p":{let n=e[++r];n&&(t.proposedPath=n);break}case "--original":case "-o":{let n=e[++r];n&&(t.originalPath=n);break}case "--max-samples":{let n=e[++r],o=n?Number.parseInt(n,10):Number.NaN;Number.isFinite(o)&&o>=0&&(t.maxSamples=o);break}case "--entity-key":{let n=e[++r];n&&(t.entityKey=n);break}case "--json":t.json=true;break}return t}function Me(){console.error(`
750
750
  Usage: directive replay-under --history <frames.json> --proposed <spec.json>
751
751
 
752
752
  Replay a recorded fact-frame history through a proposed constraint
@@ -825,10 +825,10 @@ Or pull one from a git ref:
825
825
  git show HEAD~1:path/to/snapshot.json > before.json
826
826
  git show HEAD:path/to/snapshot.json > after.json
827
827
  directive rules-diff --before before.json --after after.json
828
- `);}function er(e,t){let r=resolve(e);existsSync(r)||(console.error(m.red(`error: ${t} file not found: ${r}`)),process.exit(1));try{return JSON.parse(readFileSync(r,"utf8"))}catch(s){console.error(m.red(`error: failed to parse ${t} (${r}): `)+s.message),process.exit(1);}}function Un(e){switch(e){case "added":return m.green("+");case "removed":return m.red("-");case "relaxed":return m.green("\u25B2");case "tightened":return m.red("\u25BD");default:return m.yellow("~")}}function Q(e){return e?e.op==="$eq"?JSON.stringify(e.value):`${e.op} ${JSON.stringify(e.value)}`:"\u2014"}function be(e){return e.replace(/\|/g,"\\|").replace(/`/g,"'").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ln(e){let{summary:t,constraints:r}=e;console.log(`
828
+ `);}function er(e,t){let r=resolve(e);existsSync(r)||(console.error(m.red(`error: ${t} file not found: ${r}`)),process.exit(1));try{return JSON.parse(readFileSync(r,"utf8"))}catch(s){console.error(m.red(`error: failed to parse ${t} (${r}): `)+s.message),process.exit(1);}}function Ln(e){switch(e){case "added":return m.green("+");case "removed":return m.red("-");case "relaxed":return m.green("\u25B2");case "tightened":return m.red("\u25BD");default:return m.yellow("~")}}function Q(e){return e?e.op==="$eq"?JSON.stringify(e.value):`${e.op} ${JSON.stringify(e.value)}`:"\u2014"}function be(e){return e.replace(/\|/g,"\\|").replace(/`/g,"'").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Un(e){let{summary:t,constraints:r}=e;console.log(`
829
829
  ${m.bold("rules-diff")} \u2014 structural predicate diff
830
830
  `),console.log(` ${m.green(`+${t.added}`)} added ${m.red(`-${t.removed}`)} removed ${m.yellow(`~${t.changed}`)} changed ${m.dim(`\xB7${t.unchanged} unchanged`)}`),console.log(` ${t.totalClauseChanges} clause-level change${t.totalClauseChanges===1?"":"s"}
831
- `);for(let s of r){if(s.status==="unchanged")continue;let n=s.status==="added"?m.green("ADDED"):s.status==="removed"?m.red("REMOVED"):m.yellow("CHANGED");console.log(` ${m.bold(s.id)} ${n}`);for(let o of s.changes){let c=m.cyan(o.path||"(predicate)"),a=Un(o.kind);if(o.kind==="added")console.log(` ${a} ${c} ${Q(o.after)}`);else if(o.kind==="removed")console.log(` ${a} ${c} ${Q(o.before)}`);else {let i=o.kind==="relaxed"?m.green("relaxed"):o.kind==="tightened"?m.red("tightened"):m.yellow("changed");console.log(` ${a} ${c} ${Q(o.before)} ${m.dim("\u2192")} ${Q(o.after)} ${m.dim(`[${i}]`)}`);}}console.log("");}}function zn(e){let{summary:t,constraints:r}=e;console.log("## \u{1F4CB} Rules diff"),console.log(""),console.log(`**+${t.added} added \xB7 -${t.removed} removed \xB7 ~${t.changed} changed \xB7 \xB7${t.unchanged} unchanged** \u2014 ${t.totalClauseChanges} clause change${t.totalClauseChanges===1?"":"s"}`),console.log("");for(let s of r){if(s.status==="unchanged")continue;let n=s.status==="added"?"\u{1F195} ADDED":s.status==="removed"?"\u{1F5D1} REMOVED":"\u270F\uFE0F CHANGED";console.log(`### \`${s.id}\` \u2014 ${n}`),console.log(""),console.log("| | path | change |"),console.log("|---|---|---|");for(let o of s.changes){let c=`\`${be(o.path||"(predicate)")}\``,a;o.kind==="added"?a=`| \u2795 | ${c} | ${be(Q(o.after))} |`:o.kind==="removed"?a=`| \u2796 | ${c} | ${be(Q(o.before))} |`:a=`| ${o.kind==="relaxed"?"\u25B2 relaxed":o.kind==="tightened"?"\u25BD tightened":"\u2194 changed"} | ${c} | ${be(Q(o.before))} \u2192 ${be(Q(o.after))} |`,console.log(a);}console.log("");}}async function tr(e){(e.includes("--help")||e.length===0)&&(Ze(),process.exit(e.length===0?1:0));let t=_n(e);t.beforePath||(console.error(m.red("error: --before <a.json> is required")),Ze(),process.exit(1)),t.afterPath||(console.error(m.red("error: --after <b.json> is required")),Ze(),process.exit(1));let r=er(t.beforePath,"--before"),s=er(t.afterPath,"--after"),n;try{n=Qt({before:r,after:s});}catch(o){console.error(m.red(`error: ${o.message}`)),process.exit(1);}if(t.json){console.log(JSON.stringify(n,null,2));return}if(t.markdown){zn(n);return}Ln(n);}function Bn(e){let t={json:false,verbose:false},r=[];for(let s=0;s<e.length;s++){let n=e[s];switch(n){case "--json":t.json=true;break;case "--verbose":case "-v":t.verbose=true;break;default:n&&!n.startsWith("-")&&r.push(n);}}return {aPath:r[0]??"",bPath:r[1]??"",opts:t}}function rr(){console.error(`
831
+ `);for(let s of r){if(s.status==="unchanged")continue;let n=s.status==="added"?m.green("ADDED"):s.status==="removed"?m.red("REMOVED"):m.yellow("CHANGED");console.log(` ${m.bold(s.id)} ${n}`);for(let o of s.changes){let c=m.cyan(o.path||"(predicate)"),a=Ln(o.kind);if(o.kind==="added")console.log(` ${a} ${c} ${Q(o.after)}`);else if(o.kind==="removed")console.log(` ${a} ${c} ${Q(o.before)}`);else {let i=o.kind==="relaxed"?m.green("relaxed"):o.kind==="tightened"?m.red("tightened"):m.yellow("changed");console.log(` ${a} ${c} ${Q(o.before)} ${m.dim("\u2192")} ${Q(o.after)} ${m.dim(`[${i}]`)}`);}}console.log("");}}function zn(e){let{summary:t,constraints:r}=e;console.log("## \u{1F4CB} Rules diff"),console.log(""),console.log(`**+${t.added} added \xB7 -${t.removed} removed \xB7 ~${t.changed} changed \xB7 \xB7${t.unchanged} unchanged** \u2014 ${t.totalClauseChanges} clause change${t.totalClauseChanges===1?"":"s"}`),console.log("");for(let s of r){if(s.status==="unchanged")continue;let n=s.status==="added"?"\u{1F195} ADDED":s.status==="removed"?"\u{1F5D1} REMOVED":"\u270F\uFE0F CHANGED";console.log(`### \`${s.id}\` \u2014 ${n}`),console.log(""),console.log("| | path | change |"),console.log("|---|---|---|");for(let o of s.changes){let c=`\`${be(o.path||"(predicate)")}\``,a;o.kind==="added"?a=`| \u2795 | ${c} | ${be(Q(o.after))} |`:o.kind==="removed"?a=`| \u2796 | ${c} | ${be(Q(o.before))} |`:a=`| ${o.kind==="relaxed"?"\u25B2 relaxed":o.kind==="tightened"?"\u25BD tightened":"\u2194 changed"} | ${c} | ${be(Q(o.before))} \u2192 ${be(Q(o.after))} |`,console.log(a);}console.log("");}}async function tr(e){(e.includes("--help")||e.length===0)&&(Ze(),process.exit(e.length===0?1:0));let t=_n(e);t.beforePath||(console.error(m.red("error: --before <a.json> is required")),Ze(),process.exit(1)),t.afterPath||(console.error(m.red("error: --after <b.json> is required")),Ze(),process.exit(1));let r=er(t.beforePath,"--before"),s=er(t.afterPath,"--after"),n;try{n=Qt({before:r,after:s});}catch(o){console.error(m.red(`error: ${o.message}`)),process.exit(1);}if(t.json){console.log(JSON.stringify(n,null,2));return}if(t.markdown){zn(n);return}Un(n);}function Bn(e){let t={json:false,verbose:false},r=[];for(let s=0;s<e.length;s++){let n=e[s];switch(n){case "--json":t.json=true;break;case "--verbose":case "-v":t.verbose=true;break;default:n&&!n.startsWith("-")&&r.push(n);}}return {aPath:r[0]??"",bPath:r[1]??"",opts:t}}function rr(){console.error(`
832
832
  Usage: directive timeline diff <a.json> <b.json>
833
833
 
834
834
  Compare two serialized Directive timelines as a structured causal-graph
@@ -958,7 +958,7 @@ examples options:
958
958
  --dest <dir> Destination directory for copy
959
959
  `.trim();async function ss(){let e=process.argv.slice(2),t=e[0];if((e.length===0||t==="--help"||t==="-h")&&(console.log(ns),process.exit(0)),t==="--version"||t==="-v"){let{readFileSync:n}=await import('fs'),{fileURLToPath:o}=await import('url'),{dirname:c,join:a}=await import('path'),i=c(o(import.meta.url)),l=JSON.parse(n(a(i,"..","package.json"),"utf-8"));console.log(l.version),process.exit(0);}let s=e[0];switch(s){case "init":{await jt(e.slice(1));break}case "new":{let n=e[1],o=e[2];n==="module"?(o||(console.error("Usage: directive new module <name>"),process.exit(1)),await Nt(o,e.slice(3))):n==="orchestrator"?(o||(console.error("Usage: directive new orchestrator <name>"),process.exit(1)),await Pt(o,e.slice(3))):(console.error(`Unknown subcommand: ${n??"(none)"}
960
960
  Usage: ${O} new module <name>
961
- ${O} new orchestrator <name>`),process.exit(1));break}case "inspect":{await Et(e.slice(1));break}case "explain":{await St(e.slice(1));break}case "graph":{await At(e.slice(1));break}case "doctor":{await yt(e.slice(1));break}case "install":{await Le(e.slice(1));break}case "ai-rules":{let n=e[1];n==="init"?await lt(e.slice(2)):n==="install"?await Le(e.slice(2)):n==="update"?await ut(e.slice(2)):n==="check"?await dt(e.slice(2)):(console.error(`Unknown subcommand: ${n??"(none)"}
961
+ ${O} new orchestrator <name>`),process.exit(1));break}case "inspect":{await Et(e.slice(1));break}case "explain":{await St(e.slice(1));break}case "graph":{await At(e.slice(1));break}case "doctor":{await yt(e.slice(1));break}case "install":{await Ue(e.slice(1));break}case "ai-rules":{let n=e[1];n==="init"?await lt(e.slice(2)):n==="install"?await Ue(e.slice(2)):n==="update"?await ut(e.slice(2)):n==="check"?await dt(e.slice(2)):(console.error(`Unknown subcommand: ${n??"(none)"}
962
962
  Usage: ${O} ai-rules install
963
963
  ${O} ai-rules init
964
964
  ${O} ai-rules update