#!/usr/bin/env node
import {b as b$1,c}from'./chunk-WS2N27RX.js';import {a}from'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';import*as l from'fs';import*as y from'path';import b from'chalk';import M from'ora';import*as $ from'js-yaml';import {glob}from'glob';var _=new Set(["node_modules","dist",".git",".next","build","coverage","__pycache__","target"]),L=new Set([".ts",".tsx",".js",".jsx",".py",".rs",".go",".java",".rb",".ex",".exs"]),P=14,O=90;function j(){return new Date().toISOString().slice(0,10)}function R(c){return !c.dry&&!c.skipFix}function W(c){let o=[];function u(e){let s;try{s=l.readdirSync(e,{withFileTypes:!0});}catch{return}for(let f of s){if(_.has(f.name))continue;let i=y.join(e,f.name);f.isDirectory()?u(i):f.name===".purpose"&&o.push(i);}}return u(c),o}function H(c){let o=new Set;function u(e){let s;try{s=l.readdirSync(e,{withFileTypes:!0});}catch{return}let f=false;for(let i of s){if(_.has(i.name))continue;let h=y.join(e,i.name);i.isDirectory()?u(h):L.has(y.extname(i.name))&&(f=true);}f&&o.add(e);}return u(c),[...o]}function z(c){let o=y.join(c,".paradigm","scan-index.json");if(!l.existsSync(o))return null;try{return JSON.parse(l.readFileSync(o,"utf8"))}catch{return null}}function B(c){let o=y.join(c,".paradigm","flow-index.json");if(!l.existsSync(o))return null;try{return JSON.parse(l.readFileSync(o,"utf8"))}catch{return null}}function I(c){let o=new Map,u=["components","features","flows","state","gates","signals","aspects"];for(let e of u){let s=c[e];if(!(!s||typeof s!="object"))for(let f of Object.values(s))f.symbol&&o.set(f.symbol,f);}return o}function G(c,o,u){let e=0;for(let s of o)if(s!==u)try{l.readFileSync(s,"utf8").includes(c)&&e++;}catch{}return e}function q(c,o,u,e){let s=[];if(!o)return s.push({check:"orphaned-symbols",category:"orphaned",status:"ok",message:"Skipped \u2014 no scan-index.json"}),s;let f=I(o),i=0,h=0;for(let[a,t]of f)if(G(a,u,t.path)===0){if(i++,R(e)){let n=t.path.endsWith(".purpose")?t.path:y.join(t.path,".purpose");if(l.existsSync(n))try{let r=l.readFileSync(n,"utf8");if(!r.includes("# orphan-detected:")||!r.includes(a)){r+=`
# orphan-detected: ${j()} \u2014 ${a} has 0 cross-references
`,l.writeFileSync(n,r,"utf8"),h++,s.push({check:"orphaned-symbols",category:"orphaned",status:"fixed",symbol:a,file:n,message:`${a} \u2014 0 cross-references, marked orphan`,fixAction:"Added orphan-detected comment"});continue}}catch{}}s.push({check:"orphaned-symbols",category:"orphaned",status:"entropy",symbol:a,file:t.path,message:`${a} \u2014 0 cross-references from other .purpose files`});}return i===0&&s.push({check:"orphaned-symbols",category:"orphaned",status:"ok",message:`All ${f.size} symbols have cross-references`}),s}function Y(c,o,u){let e=[],s=0;for(let f of o){let i=y.dirname(f),h;try{h=l.statSync(f).mtime.getTime();}catch{continue}let a=0,t="";try{let n=l.readdirSync(i,{withFileTypes:!0});for(let r of n){if(!r.isFile()||!L.has(y.extname(r.name)))continue;let g=l.statSync(y.join(i,r.name));g.mtime.getTime()>a&&(a=g.mtime.getTime(),t=r.name);}}catch{continue}if(a===0)continue;let d=(a-h)/(1e3*60*60*24);if(d>P){s++;let n=y.relative(c,f),r=Math.floor(d);if(R(u))try{let g=l.readFileSync(f,"utf8");if(!g.includes("# stale-since:")){g+=`
# stale-since: ${j()} \u2014 code in ${t} is ${r} days newer
`,l.writeFileSync(f,g,"utf8"),e.push({check:"stale-purpose",category:"stale",status:"fixed",file:n,message:`${n} \u2014 ${r} days behind ${t}`,fixAction:"Added stale-since marker"});continue}}catch{}e.push({check:"stale-purpose",category:"stale",status:"entropy",file:n,message:`${n} \u2014 ${r} days behind ${t}`});}}return s===0&&e.push({check:"stale-purpose",category:"stale",status:"ok",message:`All ${o.length} .purpose files are fresh (within ${P} days)`}),e}async function J(c,o){let u=[],e=y.join(c,"portal.yaml");if(!l.existsSync(e))return u.push({check:"phantom-gates",category:"phantom",status:"ok",message:"No portal.yaml \u2014 skipped"}),u;let s;try{s=l.readFileSync(e,"utf8");}catch{return u.push({check:"phantom-gates",category:"phantom",status:"ok",message:"Could not read portal.yaml \u2014 skipped"}),u}let f=$.load(s);if(!f?.gates)return u.push({check:"phantom-gates",category:"phantom",status:"ok",message:"No gates defined in portal.yaml"}),u;let i=Object.keys(f.gates),h=0,a=await glob("**/*.{ts,tsx,js,jsx,py,rs,go,java,rb}",{cwd:c,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**","**/build/**","**/coverage/**"]});for(let t of i){let d=t.startsWith("^")?t.slice(1):t,n=false;for(let r of a)try{if(l.readFileSync(r,"utf8").includes(d)){n=!0;break}}catch{continue}if(!n){h++;let r=t.startsWith("^")?t:`^${t}`;if(R(o))try{let g=l.readFileSync(e,"utf8"),p=$.load(g);if(p.gates&&p.gates[t]&&delete p.gates[t],p.routes){for(let[m,S]of Object.entries(p.routes))if(Array.isArray(S)&&S.includes(r)){let w=S.filter(k=>k!==r);w.length===0?delete p.routes[m]:p.routes[m]=w;}}l.writeFileSync(e,$.dump(p,{lineWidth:-1,noRefs:!0}),"utf8"),u.push({check:"phantom-gates",category:"phantom",status:"fixed",symbol:r,file:"portal.yaml",message:`${r} \u2014 no code implementation found`,fixAction:"Removed from portal.yaml"});continue}catch{}u.push({check:"phantom-gates",category:"phantom",status:"entropy",symbol:r,file:"portal.yaml",message:`${r} \u2014 defined in portal.yaml but no code references "${d}"`});}}return h===0&&u.push({check:"phantom-gates",category:"phantom",status:"ok",message:`All ${i.length} gates have code references`}),u}async function V(c,o,u,e){let s=[];if(!o)return s.push({check:"dead-signals",category:"dead",status:"ok",message:"Skipped \u2014 no scan-index.json"}),s;let f=o.signals||{},i=Object.values(f);if(i.length===0)return s.push({check:"dead-signals",category:"dead",status:"ok",message:"No signals defined"}),s;let h=await glob("**/*.{ts,tsx,js,jsx,py,rs,go,java,rb}",{cwd:c,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**","**/build/**","**/coverage/**"]}),a=0;for(let t of i){let d=t.id,n=false;for(let r of h)try{if(l.readFileSync(r,"utf8").includes(d)){n=!0;break}}catch{continue}if(!n){a++;let r=t.symbol;if(R(e)){let g=t.path.endsWith(".purpose")?t.path:y.join(t.path,".purpose");if(l.existsSync(g))try{let p=l.readFileSync(g,"utf8");if(!p.includes(`# dead-signal: ${r}`)){p+=`
# dead-signal: ${r} \u2014 no handler/listener found (${j()})
`,l.writeFileSync(g,p,"utf8"),s.push({check:"dead-signals",category:"dead",status:"fixed",symbol:r,file:g,message:`${r} \u2014 no handler or listener in codebase`,fixAction:"Added dead-signal marker"});continue}}catch{}}s.push({check:"dead-signals",category:"dead",status:"entropy",symbol:r,file:t.path,message:`${r} \u2014 no handler or listener references in codebase`});}}return a===0&&s.push({check:"dead-signals",category:"dead",status:"ok",message:`All ${i.length} signals have code references`}),s}function K(c,o,u,e){let s=[];if(!u)return s.push({check:"broken-flows",category:"broken",status:"ok",message:"No flow-index.json \u2014 skipped"}),s;if(!o)return s.push({check:"broken-flows",category:"broken",status:"ok",message:"No scan-index.json \u2014 skipped"}),s;let f=I(o),i=0;for(let[h,a]of Object.entries(u.flows))for(let t of a.steps)if(t.symbol&&!f.has(t.symbol)){if(i++,R(e)){let d=y.join(c,a.definedIn);if(l.existsSync(d))try{let n=l.readFileSync(d,"utf8");if(!n.includes(`# broken: ${t.symbol}`)){n+=`
# broken: ${t.symbol} not found \u2014 ${h} step ${t.id} (${j()})
`,l.writeFileSync(d,n,"utf8"),s.push({check:"broken-flows",category:"broken",status:"fixed",symbol:t.symbol,file:a.definedIn,message:`${h} step ${t.id} references ${t.symbol} \u2014 not found`,fixAction:"Added broken step comment"});continue}}catch{}}s.push({check:"broken-flows",category:"broken",status:"entropy",symbol:t.symbol,file:a.definedIn,message:`${h} step ${t.id} references ${t.symbol} \u2014 symbol not in scan-index`});}return i===0&&s.push({check:"broken-flows",category:"broken",status:"ok",message:`All flow steps reference valid symbols (${Object.keys(u.flows).length} flows)`}),s}function U(c,o,u){let e=[],s=y.join(c,".paradigm","lore","entries");if(!l.existsSync(s))return e.push({check:"lore-rot",category:"lore-rot",status:"ok",message:"No lore entries \u2014 skipped"}),e;let f=o?I(o):new Map,i=0,h;try{h=l.readdirSync(s).filter(t=>{let d=y.join(s,t);return l.statSync(d).isDirectory()});}catch{return e.push({check:"lore-rot",category:"lore-rot",status:"ok",message:"Could not read lore directory \u2014 skipped"}),e}let a=0;for(let t of h){let d=y.join(s,t),n;try{n=l.readdirSync(d).filter(r=>r.endsWith(".yaml")||r.endsWith(".lore"));}catch{continue}for(let r of n){a++;let g=y.join(d,r),p;try{p=$.load(l.readFileSync(g,"utf8"));}catch{continue}let m=p.symbols_touched||[],S=p.files_modified||[],w=p.files_created||[],k=p.tags||[],v=[];if(o)for(let x of m)f.has(x)||v.push(x);let F=[];for(let x of [...S,...w]){let A=y.isAbsolute(x)?x:y.join(c,x);l.existsSync(A)||F.push(x);}if(v.length>0||F.length>0){i++;let x=p.id||r,A=[...v.length>0?[`dead symbols: ${v.join(", ")}`]:[],...F.length>0?[`missing files: ${F.length}`]:[]].join("; ");if(R(u))try{if(!k.includes("stale")){let N=[...k,"stale"];p.tags=N,l.writeFileSync(g,$.dump(p,{lineWidth:-1,noRefs:!0}),"utf8"),e.push({check:"lore-rot",category:"lore-rot",status:"fixed",symbol:x,file:g,message:`${x} \u2014 ${A}`,fixAction:"Added stale tag"});continue}}catch{}e.push({check:"lore-rot",category:"lore-rot",status:"entropy",symbol:x,file:g,message:`${x} \u2014 ${A}`});}}}return i===0&&e.push({check:"lore-rot",category:"lore-rot",status:"ok",message:`All ${a} lore entries have valid references`}),e}function X(c,o,u){let e=[],s=y.join(c,".paradigm","tags.yaml");if(!l.existsSync(s))return e.push({check:"tag-orphans",category:"tag-orphan",status:"ok",message:"No tags.yaml \u2014 skipped"}),e;let f;try{f=$.load(l.readFileSync(s,"utf8"));}catch{return e.push({check:"tag-orphans",category:"tag-orphan",status:"ok",message:"Could not parse tags.yaml \u2014 skipped"}),e}let i=new Set;for(let d of ["core","project"]){let n=f[d];if(n&&typeof n=="object")for(let r of Object.keys(n))i.add(r);}if(i.size===0)return e.push({check:"tag-orphans",category:"tag-orphan",status:"ok",message:"No tags defined"}),e;let h=new Set;for(let d of o)try{let n=l.readFileSync(d,"utf8"),r=n.matchAll(/tags:\s*\[([^\]]*)\]/g);for(let p of r){let m=p[1].split(",").map(S=>S.trim().replace(/['"]/g,"")).filter(Boolean);for(let S of m)h.add(S);}let g=$.load(n);if(g){let p=function(m){if(Array.isArray(m))for(let S of m)p(S);else if(m&&typeof m=="object"){let S=m;if(Array.isArray(S.tags))for(let w of S.tags)typeof w=="string"&&h.add(w);for(let w of Object.values(S))p(w);}};var t=p;p(g);}}catch{continue}let a=0;for(let d of i)if(!h.has(d)){if(a++,R(u))try{let n=$.load(l.readFileSync(s,"utf8")),r=!1;for(let g of ["core","project"])n[g]&&n[g][d]&&(delete n[g][d],r=!0);if(r){l.writeFileSync(s,$.dump(n,{lineWidth:-1,noRefs:!0}),"utf8"),e.push({check:"tag-orphans",category:"tag-orphan",status:"fixed",symbol:d,file:"tags.yaml",message:`Tag "${d}" \u2014 not used in any .purpose file`,fixAction:"Removed from tags.yaml"});continue}}catch{}e.push({check:"tag-orphans",category:"tag-orphan",status:"entropy",symbol:d,file:".paradigm/tags.yaml",message:`Tag "${d}" \u2014 defined in tag bank but not used in any .purpose file`});}return a===0&&e.push({check:"tag-orphans",category:"tag-orphan",status:"ok",message:`All ${i.size} tags are in use`}),e}function Q(c,o,u){let e=[],s=y.join(c,".paradigm","aspect-graph.db");if(!l.existsSync(s))return e.push({check:"aspect-semantic-drift",category:"semantic-drift",status:"ok",message:"No aspect-graph.db \u2014 skipped"}),e;if(!o||!o.aspects)return e.push({check:"aspect-semantic-drift",category:"semantic-drift",status:"ok",message:"No aspects in scan-index \u2014 skipped"}),e;let f=o.aspects,i=0;for(let[,h]of Object.entries(f)){let a=h.path.endsWith(".purpose")?h.path:y.join(h.path,".purpose");if(l.existsSync(a))try{let t=l.readFileSync(a,"utf8"),n=/anchors?:\s*\n((?:\s+-\s+.+\n?)*)/g.exec(t);if(!n)continue;let r=n[1].split(`
`).filter(g=>g.trim().startsWith("-"));for(let g of r){let p=g.match(/- (.+):(\d+)(?:-(\d+))?/);if(!p)continue;let m=p[1].trim(),S=parseInt(p[2],10),w=p[3]?parseInt(p[3],10):S,k=y.isAbsolute(m)?m:y.join(c,m);if(l.existsSync(k))try{let F=l.readFileSync(k,"utf8").split(`
`).length;(S>F||w>F)&&i++;}catch{}}}catch{continue}}return i>0?e.push({check:"aspect-semantic-drift",category:"semantic-drift",status:"entropy",message:`${i} aspect anchor(s) reference lines beyond file bounds \u2014 run "paradigm drift check" to repair`}):e.push({check:"aspect-semantic-drift",category:"semantic-drift",status:"ok",message:'Aspect anchors stable (use "paradigm drift check" for deep analysis)'}),e}function Z(c,o,u){let e=[],s=H(c);if(s.length===0)return e.push({check:"coverage-decay",category:"coverage-decay",status:"ok",message:"No source directories found"}),e;let f=new Set(o.map(a=>y.dirname(a))),i=[];for(let a of s){let t=false,d=a;for(;d.startsWith(c);){if(f.has(d)){t=true;break}let n=y.dirname(d);if(n===d)break;d=n;}t||i.push(a);}let h=s.length>0?Math.round((s.length-i.length)/s.length*100):100;if(h<O){if(R(u)){let a=0;for(let t of i){let d=y.join(t,".purpose");if(!l.existsSync(d))try{let n=y.basename(t),r=y.relative(c,t),g=[`# ${n}`,`# Auto-generated by paradigm sweep \u2014 ${j()}`,"# TODO: Add component descriptions and symbol declarations","",`#${n}:`,`  description: "${r}"`,"  tags: []",""].join(`
`);l.writeFileSync(d,g,"utf8"),a++;}catch{}}if(a>0)return e.push({check:"coverage-decay",category:"coverage-decay",status:"fixed",message:`Coverage at ${h}% (threshold: ${O}%) \u2014 generated ${a} skeleton .purpose files`,fixAction:`Generated ${a} skeleton .purpose files`}),e}e.push({check:"coverage-decay",category:"coverage-decay",status:"entropy",message:`Coverage at ${h}% \u2014 below ${O}% threshold (${i.length} directories uncovered)`});}else e.push({check:"coverage-decay",category:"coverage-decay",status:"ok",message:`Coverage at ${h}% (${s.length} source dirs, ${o.length} .purpose files)`});return e}async function ee(c$1,o){let u=o.filter(t=>t.status==="entropy"),e=o.filter(t=>t.status==="fixed"),s=o.filter(t=>t.status==="ok"),f=new Set(o.map(t=>t.category)),i=o.filter(t=>t.symbol).map(t=>t.symbol).filter((t,d,n)=>n.indexOf(t)===d).slice(0,20),h=[`Sweep completed: ${f.size} categories checked.`,u.length>0?`${u.length} entropy issue(s) found.`:"",e.length>0?`${e.length} issue(s) auto-resolved.`:"",`${s.length} categories healthy.`].filter(Boolean).join(" "),a={id:"",type:"insight",timestamp:new Date().toISOString(),author:b$1(),title:`Sweep: ${u.length+e.length} issues, ${e.length} fixed`,summary:h,symbols_touched:i,tags:["arc:sweep","automated"]};try{return await c(c$1,a),a.id}catch{return null}}async function ae(c){let o=c.rootDir||process.cwd(),u=c.quiet,e=M(),s=a.command("sweep").start("Running entropy detection");u||(console.log(b.blue(`
Paradigm Sweep Report`)+b.gray(` \u2014 ${j()}`)),console.log(b.gray("===================================")),(c.dry||c.skipFix)&&console.log(b.yellow(`  Mode: dry run (no fixes applied)
`))),e.start("Loading project data...");let f=W(o),i=z(o),h=B(o);e.succeed(`Loaded: ${f.length} .purpose files, scan-index ${i?"present":"absent"}`);let a$1=[],t=[{name:"Orphaned symbols",run:()=>q(o,i,f,c)},{name:"Stale purpose files",run:()=>Y(o,f,c)},{name:"Phantom gates",run:()=>J(o,c)},{name:"Dead signals",run:()=>V(o,i,f,c)},{name:"Broken flows",run:()=>K(o,i,h,c)},{name:"Lore rot",run:()=>U(o,i,c)},{name:"Tag orphans",run:()=>X(o,f,c)},{name:"Aspect semantic drift",run:()=>Q(o,i)},{name:"Coverage decay",run:()=>Z(o,f,c)}];for(let n of t){e.start(`Checking: ${n.name}...`);let r=await n.run();a$1.push(...r);let g=r.some(m=>m.status==="entropy"),p=r.some(m=>m.status==="fixed");g?e.warn(b.yellow(`${n.name}`)):p?e.succeed(b.green(`${n.name} (auto-fixed)`)):e.succeed(b.green(n.name));}if(!u){let n=i?I(i).size:0;console.log(b.gray(`
Checked: 9 categories, ${n} symbols, ${f.length} .purpose files
`));let r=a$1.filter(k=>k.status==="entropy");if(r.length>0){console.log(b.red.bold("ENTROPY FOUND:"));for(let k of r)console.log(`  ${b.red(`[${k.category}]`)}  ${k.message}`);console.log();}let g=a$1.filter(k=>k.status==="ok");if(g.length>0){console.log(b.green.bold("HEALTHY:"));for(let k of g)console.log(`  ${b.green("[ok]")} ${k.check} \u2014 ${k.message}`);console.log();}let p=a$1.filter(k=>k.status==="fixed");if(p.length>0){console.log(b.cyan.bold("RESOLVED (auto-fixed):"));for(let k of p)console.log(`  ${b.cyan("[fixed]")}  ${k.message}`),k.fixAction&&console.log(b.gray(`           ${k.fixAction}`));console.log();}let m=await ee(o,a$1),S=r.length+p.length,w=[`${S} issue${S!==1?"s":""} found`,p.length>0?`${p.length} auto-resolved`:null,m?`Lore recorded: ${m}`:null].filter(Boolean).join(", ");console.log(b.gray(`Summary: ${w}`)),console.log();}a$1.some(n=>n.status==="entropy")?s.error("Entropy detected",{entropy:a$1.filter(n=>n.status==="entropy").length,fixed:a$1.filter(n=>n.status==="fixed").length}):s.success("Clean sweep",{fixed:a$1.filter(n=>n.status==="fixed").length,ok:a$1.filter(n=>n.status==="ok").length});}export{ae as sweepCommand};