@a-company/paradigm 6.6.2 → 6.6.3

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.
Files changed (45) hide show
  1. package/dist/{accept-orchestration-TIXUQQGR.js → accept-orchestration-JHDCVHB2.js} +1 -1
  2. package/dist/{aggregate-A5S5MTCC.js → aggregate-KZICPVT3.js} +1 -1
  3. package/dist/arch-loader-G3AAM4E2.js +2 -0
  4. package/dist/{beacon-QVUD3MGP.js → beacon-52EWNZPK.js} +1 -1
  5. package/dist/chunk-4GC35IFF.js +2 -0
  6. package/dist/{chunk-AXQBUD3Q.js → chunk-FI66YM6G.js} +43 -43
  7. package/dist/{chunk-Y4P4SGZV.js → chunk-MBSY57RN.js} +1 -1
  8. package/dist/{chunk-IOVHF4SR.js → chunk-MU5YWTNE.js} +1 -1
  9. package/dist/{chunk-5NAF6CKU.js → chunk-QALPEMCU.js} +26 -26
  10. package/dist/{chunk-4PSD5R7N.js → chunk-QDP4G53M.js} +1 -1
  11. package/dist/{chunk-ARLB6YYW.js → chunk-RGSFU2YW.js} +1 -1
  12. package/dist/{chunk-TOYQ2QCB.js → chunk-S3UVQ5RV.js} +1 -1
  13. package/dist/chunk-TMDPDIWA.js +3 -0
  14. package/dist/{chunk-2AU5L333.js → chunk-XKNJSPB5.js} +1 -1
  15. package/dist/{commands-ANRJNG2W.js → commands-4ENQMHFO.js} +1 -1
  16. package/dist/{constellation-NWLXYATA.js → constellation-RHZAEFV7.js} +1 -1
  17. package/dist/{diff-75MABOSL.js → diff-ANKTFDRA.js} +1 -1
  18. package/dist/dist-RXYJK7AZ.js +2 -0
  19. package/dist/dist-TNE4GFT7.js +2 -0
  20. package/dist/index.js +5 -5
  21. package/dist/{init-V4KSEKPK.js → init-F4MSKZIW.js} +1 -1
  22. package/dist/{integrity-ROO3G43N.js → integrity-7TKX3DZ4.js} +1 -1
  23. package/dist/mcp.js +2 -2
  24. package/dist/{orchestrate-K4KBTBYK.js → orchestrate-UG5QXNAU.js} +1 -1
  25. package/dist/{probe-5HAXULAD.js → probe-27ARJKRO.js} +1 -1
  26. package/dist/reindex-F7BZCG4W.js +2 -0
  27. package/dist/review-BRO2UP4M.js +11 -0
  28. package/dist/{ripple-FNZI47SH.js → ripple-KCVDS3WE.js} +1 -1
  29. package/dist/sentinel.js +1 -1
  30. package/dist/{setup-ZSEC72BS.js → setup-5V2AGLQ6.js} +1 -1
  31. package/dist/{shift-QY3EXVF4.js → shift-TNA2E5O7.js} +2 -2
  32. package/dist/{snapshot-3IYB67D4.js → snapshot-YMX5QRBM.js} +1 -1
  33. package/dist/{status-DB3KNLW3.js → status-3GJXI4IK.js} +1 -1
  34. package/dist/{summary-WLI3NF4G.js → summary-RPU2BS3Q.js} +1 -1
  35. package/dist/{team-2LGZQRP4.js → team-PEGP6F7S.js} +1 -1
  36. package/dist/{tools-W5WRPSJF.js → tools-HQKF4Q3P.js} +1 -1
  37. package/dist/{workspace-VMSPYIBV.js → workspace-6POCBPDY.js} +1 -1
  38. package/package.json +1 -1
  39. package/dist/arch-loader-T3TARMSO.js +0 -2
  40. package/dist/chunk-LWAIVOSF.js +0 -2
  41. package/dist/chunk-SU5F5D4I.js +0 -3
  42. package/dist/dist-JZZJLVMR.js +0 -2
  43. package/dist/dist-OG6MM4VY.js +0 -2
  44. package/dist/reindex-2YTQP2EO.js +0 -2
  45. package/dist/review-VMSX2PKI.js +0 -11
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import {l}from'./chunk-SU5F5D4I.js';import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import*as i from'fs';import*as c from'path';import*as f from'js-yaml';b$1();var g=".paradigm/arch.yaml";function u(e){let n=c.join(e,g);if(!i.existsSync(n))return null;try{let t=i.readFileSync(n,"utf8");return f.load(t)}catch{return null}}function S(e,n){let t=c.join(e,g),r=c.dirname(t);i.existsSync(r)||i.mkdirSync(r,{recursive:true}),i.writeFileSync(t,f.dump(n,{lineWidth:-1,noRefs:true}),"utf8");}function b(e,n){let t=u(e);if(!t)return {unassigned:[],missing_purpose:[]};let r=new Set;for(let o of t.tiers)for(let p of o.components)r.add(p);let s=new Set;try{let o=l(n.index,"component");for(let p of o)s.add(p.symbol);}catch(o){a.component("#arch-loader").warn("Could not load symbol index for drift check",{error:String(o)});}let a$1=Array.from(s).filter(o=>!r.has(o)),h=Array.from(r).filter(o=>!s.has(o));return {unassigned:a$1,missing_purpose:h}}function k(e){let n=r=>r.replace(/[^a-zA-Z0-9_-]/g,"-"),t=["graph TD"];for(let r of e.tiers){let s=n(r.id);t.push(` ${s}["${r.label}\\n(${r.responsibility})"]`);}for(let r of e.links){let s=n(r.from),a=n(r.to);r.via?t.push(` ${s} -->|"${r.via}"| ${a}`):t.push(` ${s} --> ${a}`);}return t.join(`
2
+ import {l}from'./chunk-TMDPDIWA.js';import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import*as i from'fs';import*as c from'path';import*as f from'js-yaml';b$1();var g=".paradigm/arch.yaml";function u(e){let n=c.join(e,g);if(!i.existsSync(n))return null;try{let t=i.readFileSync(n,"utf8");return f.load(t)}catch{return null}}function S(e,n){let t=c.join(e,g),r=c.dirname(t);i.existsSync(r)||i.mkdirSync(r,{recursive:true}),i.writeFileSync(t,f.dump(n,{lineWidth:-1,noRefs:true}),"utf8");}function b(e,n){let t=u(e);if(!t)return {unassigned:[],missing_purpose:[]};let r=new Set;for(let o of t.tiers)for(let p of o.components)r.add(p);let s=new Set;try{let o=l(n.index,"component");for(let p of o)s.add(p.symbol);}catch(o){a.component("#arch-loader").warn("Could not load symbol index for drift check",{error:String(o)});}let a$1=Array.from(s).filter(o=>!r.has(o)),h=Array.from(r).filter(o=>!s.has(o));return {unassigned:a$1,missing_purpose:h}}function k(e){let n=r=>r.replace(/[^a-zA-Z0-9_-]/g,"-"),t=["graph TD"];for(let r of e.tiers){let s=n(r.id);t.push(` ${s}["${r.label}\\n(${r.responsibility})"]`);}for(let r of e.links){let s=n(r.from),a=n(r.to);r.via?t.push(` ${s} -->|"${r.via}"| ${a}`):t.push(` ${s} --> ${a}`);}return t.join(`
3
3
  `)}export{g as a,u as b,S as c,b as d,k as e};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-Y4P4SGZV.js';import {a}from'./chunk-LKAT7IAK.js';import*as r from'fs';import*as i from'path';import e from'chalk';import W from'ora';import*as u from'js-yaml';async function v(l={}){let c=process.cwd(),o=i.join(c,".paradigm-workspace");console.log(e.blue(`
2
+ import {b}from'./chunk-MBSY57RN.js';import {a}from'./chunk-LKAT7IAK.js';import*as r from'fs';import*as i from'path';import e from'chalk';import W from'ora';import*as u from'js-yaml';async function v(l={}){let c=process.cwd(),o=i.join(c,".paradigm-workspace");console.log(e.blue(`
3
3
  \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510`)),console.log(e.blue("\u2502")+e.white.bold(" paradigm workspace init ")+e.blue("\u2502")),console.log(e.blue("\u2502")+e.gray(" Create a multi-project workspace ")+e.blue("\u2502")),console.log(e.blue(`\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
4
4
  `));let n=a.command("workspace-init").start("Creating workspace",{cwd:c});if(r.existsSync(o)&&!l.force){console.log(e.yellow(` .paradigm-workspace already exists. Use --force to overwrite.
5
5
  `)),n.success("Workspace already exists");return}let s=c,t=r.readdirSync(s,{withFileTypes:true}),a$1=[];for(let p of t){if(!p.isDirectory()||p.name.startsWith(".")||p.name==="node_modules")continue;let g=i.join(s,p.name),k=r.existsSync(i.join(g,".paradigm")),y=r.existsSync(i.join(g,".purpose"));if(k||y){let w=j(p.name,g);a$1.push({name:p.name,path:`./${p.name}`,...w&&{role:w}});}}if(a$1.length===0){console.log(e.yellow(" No sibling projects with .paradigm/ or .purpose found.")),console.log(e.gray(` Create .purpose files in sibling directories first.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import*as P from'fs';import*as z from'js-yaml';import {z as z$1}from'zod';import*as b from'path';import {glob}from'glob';var T=z$1.object({description:z$1.string(),type:z$1.string().optional(),parent:z$1.string().optional(),anchors:z$1.array(z$1.string()).optional(),tags:z$1.array(z$1.string()).optional(),endpoints:z$1.array(z$1.string()).optional(),tests:z$1.array(z$1.string()).optional(),rules:z$1.record(z$1.unknown()).optional(),aspects:z$1.array(z$1.string()).optional(),flows:z$1.array(z$1.string()).optional(),gates:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional(),states:z$1.array(z$1.string()).optional(),components:z$1.array(z$1.string()).optional(),location:z$1.string().optional(),locations:z$1.array(z$1.string()).optional(),uses:z$1.array(z$1.string()).optional(),"used-by":z$1.array(z$1.string()).optional(),"used-for":z$1.array(z$1.string()).optional(),exports:z$1.array(z$1.string()).optional(),status:z$1.string().optional(),properties:z$1.record(z$1.unknown()).optional(),handles:z$1.array(z$1.string()).optional()}).passthrough(),Y=T.extend({id:z$1.string()}),de=z$1.object({description:z$1.string().optional(),category:z$1.string().optional(),severity:z$1.enum(["info","warn","error"]).optional(),emitters:z$1.array(z$1.string()).optional(),related:z$1.array(z$1.string()).optional(),data:z$1.record(z$1.unknown()).optional()}),me=z$1.union([de,z$1.string().transform(t=>({description:t}))]),he=z$1.object({from:z$1.string(),to:z$1.string(),type:z$1.string(),description:z$1.string().optional()}),ge=z$1.union([he,z$1.string()]),ye=z$1.object({component:z$1.string(),action:z$1.string(),description:z$1.string().optional()}),N=z$1.union([ye,z$1.string()]),$e=z$1.object({name:z$1.string(),description:z$1.string().optional(),steps:z$1.array(N)}),we=z$1.object({description:z$1.string().optional(),gates:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional(),components:z$1.array(z$1.string()).optional(),steps:z$1.array(N).optional()}),be=z$1.object({description:z$1.string().optional(),requires:z$1.array(z$1.string()).optional(),keys:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional()}),Se=z$1.object({description:z$1.string().optional(),default:z$1.unknown().optional(),type:z$1.string().optional()}),ve=z$1.object({description:z$1.string().optional(),tags:z$1.array(z$1.string()).optional(),anchors:z$1.array(z$1.string()).optional(),"applies-to":z$1.array(z$1.string()).optional(),enforcement:z$1.string().optional()}),xe=z$1.object({target:z$1.string(),type:z$1.string(),path:z$1.string()}),Pe=z$1.object({version:z$1.string().optional(),description:z$1.string().optional(),apiSpec:z$1.string().optional(),context:z$1.array(z$1.string()).optional(),rules:z$1.record(z$1.unknown()).optional(),features:z$1.union([z$1.array(Y),z$1.record(T)]).optional(),components:z$1.union([z$1.array(Y),z$1.record(T)]).optional(),gates:z$1.record(be).optional(),states:z$1.record(Se).optional(),signals:z$1.record(me).optional(),aspects:z$1.record(ve).optional(),relationships:z$1.array(ge).optional(),flows:z$1.union([z$1.array($e),z$1.record(we)]).optional(),references:z$1.array(xe).optional()});function ke(t){let s=je(t);return {data:s.data,errors:s.errors}}function je(t){let s=[],e=[],o;try{o=P.readFileSync(t,"utf8");}catch(c){let p=`Cannot read file: ${c.message}`;return s.push(p),e.push({message:p,type:"file"}),{data:null,errors:s,detailedErrors:e,rawContent:void 0,isYamlValid:false}}let a=o.replace(/^([#~!$^][\w-]+):/gm,'"$1":').replace(/^(\s*-\s+)([!#][\w-]+)$/gm,'$1"$2"'),i=null;try{i=z.load(a);}catch(c){let p=c,f=p.mark?.line?p.mark.line+1:void 0,u=`YAML syntax error: ${p.reason||c.message}`;return s.push(`${u}${f?` (line ${f})`:""}`),e.push({message:u,line:f,type:"yaml"}),{data:null,errors:s,detailedErrors:e,rawContent:o,isYamlValid:false}}if(i==null)return {data:{},errors:[],detailedErrors:[],rawContent:o,isYamlValid:true};if(typeof i=="object"&&i!==null){let c=i,p={"#":"components",$:"flows","^":"gates","!":"signals","~":"aspects"};for(let f of Object.keys(c)){let u=f[0],d=p[u];if(!d||f.length<2)continue;let g=f.slice(1),y=c[f];if(typeof y!="object"||y===null)continue;let S=c[d]||{};d in c||(c[d]=S),g in S||(S[g]=y),delete c[f];}}let r=Pe.safeParse(i);if(!r.success){for(let c of r.error.issues){let p=c.path.join("."),f=c.message;s.push(`Schema error at ${p||"/"}: ${f}`),e.push({message:f,path:p||"/",type:"schema"});}return {data:i,errors:s,detailedErrors:e,rawContent:o,isYamlValid:true}}return {data:r.data,errors:[],detailedErrors:[],rawContent:o,isYamlValid:true}}function He(t){return z.dump(t,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function D(t){return t?Array.isArray(t)?t.map(s=>[s.id,s]):Object.entries(t):[]}async function Ae(t){let s=b.resolve(t);return (await glob("**/.purpose",{cwd:s,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})).sort((o,a)=>{let i=o.split(b.sep).length,r=a.split(b.sep).length;return i-r})}async function K(t){let s=await Ae(t),e=[];for(let o of s){let{data:a,errors:i}=ke(o);a&&(e.push({filePath:o,data:a}),i.length>0&&console.warn(`Warnings parsing ${o}:`,i));}return e}function U(t){let s=new Map;for(let{filePath:e,data:o}of t){let a=D(o.features);for(let[i,r]of a)s.set(i,{item:r,filePath:e});}return s}function q(t){let s=new Map;for(let{filePath:e,data:o}of t){let a=D(o.components);for(let[i,r]of a)s.set(i,{item:r,filePath:e});}return s}function Z(t){let s=new Map;for(let{filePath:e,data:o}of t)if(o.gates)for(let[a,i]of Object.entries(o.gates))s.set(a,{item:i,filePath:e});return s}function X(t){let s=new Map;for(let{filePath:e,data:o}of t)if(o.states)for(let[a,i]of Object.entries(o.states))s.set(a,{item:i,filePath:e});return s}function H(t){let s=new Map;for(let{filePath:e,data:o}of t)if(o.flows)if(Array.isArray(o.flows))for(let a of o.flows)s.set(a.name,{item:{id:a.name,description:a.description,steps:a.steps},filePath:e});else for(let[a,i]of Object.entries(o.flows))s.set(a,{item:{id:a,description:i.description,gates:i.gates,signals:i.signals,components:i.components,steps:i.steps},filePath:e});return s}function J(t){let s=new Map;for(let{filePath:e,data:o}of t)if(o.signals)for(let[a,i]of Object.entries(o.signals))s.set(a,{item:i,filePath:e});return s}function Q(t){let s=new Map;for(let{filePath:e,data:o}of t)if(o.aspects)for(let[a,i]of Object.entries(o.aspects))s.set(a,{item:i,filePath:e});return s}function ee(t){let s=[],e=new Set;for(let{filePath:o,data:a}of t){let i=D(a.features);for(let[c,p]of i)B(`#${c}`,p,o,s,e);let r=D(a.components);for(let[c,p]of r)B(`#${c}`,p,o,s,e);}return s}function B(t,s,e,o,a){if(s.flows)for(let i of s.flows){let r=i.startsWith("$")?i:`$${i}`;a.has(r)||(a.add(r),o.push({symbol:r,type:"flow",sourceSymbol:t,filePath:e}));}if(s.gates)for(let i of s.gates){let r=i.startsWith("^")?i:`^${i}`;a.has(r)||(a.add(r),o.push({symbol:r,type:"gate",sourceSymbol:t,filePath:e}));}if(s.signals)for(let i of s.signals){let r=i.startsWith("!")?i:`!${i}`;a.has(r)||(a.add(r),o.push({symbol:r,type:"signal",sourceSymbol:t,filePath:e}));}if(s.states)for(let i of s.states){let r=i.startsWith("#")?i:i.startsWith("%")?`#${i.slice(1)}`:`#${i}`;a.has(r)||(a.add(r),o.push({symbol:r,type:"component",sourceSymbol:t,filePath:e}));}if(s.components)for(let i of s.components){let r=i.startsWith("#")?i:`#${i}`;a.has(r)||(a.add(r),o.push({symbol:r,type:"component",sourceSymbol:t,filePath:e}));}if(s.aspects)for(let i of s.aspects){let r=i.startsWith("~")?i:`~${i}`;a.has(r)||(a.add(r),o.push({symbol:r,type:"aspect",sourceSymbol:t,filePath:e}));}if(s.description){let i=De(s.description);for(let{symbol:r,type:c}of i)a.has(r)||(a.add(r),o.push({symbol:r,type:c,sourceSymbol:t,filePath:e}));}}var Ie=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function De(t){let s=[],e=/([$^!#~%])([a-zA-Z][a-zA-Z0-9._-]*)/g,o;for(;(o=e.exec(t))!==null;){let a=o[1],i=o[2],r,c;switch(a){case "#":c="component",r=`#${i}`;break;case "$":c="flow",r=`$${i}`;break;case "^":c="gate",r=`^${i}`;break;case "!":c="signal",r=`!${i}`;break;case "~":c="aspect",r=`~${i}`;break;case "%":c="component",r=`#${i}`;break;default:continue}Ie.has(r)||s.push({symbol:r,type:c});}return s}function k(t){return t?Array.isArray(t)?t.map(s=>[s.id,s]):Object.entries(t):[]}function F(t){return t?Array.isArray(t)?t.map(s=>s.id):Object.keys(t):[]}function Qe(t,s){let e=[],o=s?`${s}: `:"",a=k(t.features);for(let[r,c]of a)V(r,c,"feature",o,e);let i=k(t.components);for(let[r,c]of i)V(r,c,"component",o,e);if(t.relationships){let r=new Set([...F(t.features),...F(t.components)]);for(let c of t.relationships){if(typeof c=="string"||!c||!c.from||!c.to)continue;let p=c.from.replace(/^[@#$%~^!?]/,"");!r.has(p)&&!c.from.includes(".")&&e.push({type:"warning",message:`${o}Relationship references unknown source: "${c.from}"`,path:"relationships"});let f=c.to.replace(/^[@#$%~^!?]/,"");!r.has(f)&&!c.to.includes(".")&&e.push({type:"warning",message:`${o}Relationship references unknown target: "${c.to}"`,path:"relationships"});}}if(t.flows){let r=new Set(F(t.components));if(Array.isArray(t.flows)){for(let c of t.flows)if(!(!c||typeof c!="object")&&(c.name||e.push({type:"error",message:`${o}Flow missing required "name" field`,path:"flows"}),c.steps&&Array.isArray(c.steps)))for(let p of c.steps){if(typeof p=="string"||!p||!p.component)continue;let f=p.component.replace(/^#/,"");r.has(f)||e.push({type:"warning",message:`${o}Flow "${c.name}" references unknown component: "${p.component}"`,path:`flows.${c.name}`});}}else for(let[c,p]of Object.entries(t.flows))if(!(!p||typeof p!="object")&&p.steps&&Array.isArray(p.steps))for(let f of p.steps){if(typeof f=="string"||!f||!f.component)continue;let u=f.component.replace(/^#/,"");r.has(u)||e.push({type:"warning",message:`${o}Flow "${c}" references unknown component: "${f.component}"`,path:`flows.${c}`});}}return {valid:e.filter(r=>r.type==="error").length===0,issues:e}}function V(t,s,e,o,a){let i=`${e}s.${t}`;if(/^[a-zA-Z][a-zA-Z0-9-]*$/.test(t)||a.push({type:"warning",message:`${o}${e} ID "${t}" should use alphanumeric characters and hyphens`,path:i}),(!s.description||s.description.trim()==="")&&a.push({type:"warning",message:`${o}${e} "${t}" has no description`,path:i}),s.endpoints)for(let r of s.endpoints)/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+\//.test(r)||a.push({type:"warning",message:`${o}Endpoint "${r}" in ${e} "${t}" may not be in standard format (e.g., "GET /api/users")`,path:`${i}.endpoints`});}function et(t){let s=[],e=new Set;for(let{data:o}of t){let a=k(o.components);for(let[r]of a)e.add(`#${r}`),e.add(r);let i=k(o.features);for(let[r]of i)e.add(`#${r}`),e.add(r);if(o.gates)for(let r of Object.keys(o.gates))e.add(`^${r}`),e.add(r);if(o.signals)for(let r of Object.keys(o.signals))e.add(`!${r}`),e.add(r);if(o.flows)if(Array.isArray(o.flows))for(let r of o.flows)r?.name&&(e.add(`$${r.name}`),e.add(r.name));else for(let r of Object.keys(o.flows))e.add(`$${r}`),e.add(r);if(o.aspects)for(let r of Object.keys(o.aspects))e.add(`~${r}`),e.add(r);if(o.states)for(let r of Object.keys(o.states))e.add(`#${r}`),e.add(r);}for(let{filePath:o,data:a}of t){let i=o?`${o}: `:"",r=[...k(a.components),...k(a.features)];for(let[c,p]of r){if(p.parent){let u=p.parent.replace(/^["']|["']$/g,""),d=u.replace(/^[#$^!~@%?&]/,"");!e.has(u)&&!e.has(d)&&s.push({type:"warning",message:`${i}Component "${c}" references parent "${u}" which is not defined in any .purpose file`,path:`components.${c}.parent`});}let f=[{field:"gates",refs:p.gates},{field:"signals",refs:p.signals},{field:"flows",refs:p.flows},{field:"components",refs:p.components},{field:"aspects",refs:p.aspects}];for(let{field:u,refs:d}of f)if(d)for(let g of d){let y=g.replace(/^[#$^!~@%?&]/,"");!e.has(g)&&!e.has(y)&&s.push({type:"warning",message:`${i}Symbol "${c}" references ${u} "${g}" which is not defined`,path:`components.${c}.${u}`});}}if(a.flows){if(Array.isArray(a.flows)){for(let c of a.flows)if(c?.steps)for(let p of c.steps){if(typeof p=="string"||!p?.component)continue;let f=p.component.replace(/^#/,"");!e.has(p.component)&&!e.has(f)&&s.push({type:"warning",message:`${i}Flow "${c.name}" step references "${p.component}" which is not defined`,path:`flows.${c.name}.steps`});}}else for(let[c,p]of Object.entries(a.flows))if(p?.steps)for(let f of p.steps){if(typeof f=="string"||!f?.component)continue;let u=f.component.replace(/^#/,"");!e.has(f.component)&&!e.has(u)&&s.push({type:"warning",message:`${i}Flow "${c}" step references "${f.component}" which is not defined`,path:`flows.${c}.steps`});}}}return {valid:s.filter(o=>o.type==="error").length===0,issues:s}}var ze={visualizerPort:42195,watcherPort:42196,autoConnect:true};async function R(t){let s=b.resolve(t),e=b.dirname(s);if(!P.existsSync(s))throw new Error(`Gate config not found: ${s}`);let o=P.readFileSync(s,"utf8"),a=z.load(o);if(!a.version)throw new Error('Gate config missing required "version" field');let i=[],r=a,c=a.gates||r.portals;if(c)for(let[f,u]of Object.entries(c)){let d=f.startsWith("^")?f.slice(1):f;i.push(L(d,u));}if(a.include)for(let f of a.include){let u=b.join(e,f),d=await glob(u.replace(/\\/g,"/"));for(let g of d){let y=await Oe(g);i.push(...y);}}let p=[];if(a.flows)for(let[f,u]of Object.entries(a.flows))p.push(Fe(f,u));return {version:a.version,gates:i,flows:p,settings:{dev:{...ze,...a.settings?.dev}}}}async function Oe(t){let s=P.readFileSync(t,"utf8"),e=z.load(s);if(e.id){let o=e.id,a=o.startsWith("^")?o.slice(1):o;return [L(a,e)]}if(e.gates){let o=[];for(let[a,i]of Object.entries(e.gates)){let r=a.startsWith("^")?a.slice(1):a;o.push(L(r,i));}return o}return []}function L(t,s){let e=[];if(s.locks)for(let a of s.locks)e.push(Re(a));let o=[];if(s.prizes)for(let a of s.prizes)o.push(Ee(a));return {id:t,description:s.description,locks:e,prizes:o,position:s.position}}function Re(t){let s=t,e=[];if(s.keys){for(let o of s.keys)if(typeof o=="string")e.push({expression:o});else if(o.expression){let a=o;e.push({expression:a.expression,description:a.description});}}return {id:s.id,description:s.description,keys:e,mode:s.mode||"all"}}function Ee(t){let s=t;return {id:s.id,oneTime:s.oneTime??false,metadata:s.metadata}}function Fe(t,s){return {id:t,description:s.description,gates:s.gates||[],forkable:s.forkable}}async function se(t){let s=b.resolve(t);return await glob("**/portal.yaml",{cwd:s,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})}function ot(t){if(t instanceof z.YAMLException){let s=(t.reason||"").toLowerCase();return s.includes("duplicated mapping key")||s.includes("duplicate mapping key")?{errorClass:"duplicate-key",detail:"duplicate mapping key"}:["unexpected","expected","bad indentation","mapping values","cannot read a block mapping entry","end of the stream","while scanning","while parsing"].some(o=>s.includes(o))?{errorClass:"syntax",detail:"yaml syntax error"}:{errorClass:"other",detail:"yaml parse error"}}return {errorClass:"other",detail:"yaml parse error"}}var Te=z$1.object({x:z$1.number(),y:z$1.number()}),Le=z$1.object({x:z$1.number(),y:z$1.number(),zoom:z$1.number()}),ne=z$1.object({path:z$1.string(),include:z$1.array(z$1.string()).optional(),exclude:z$1.array(z$1.string()).optional()}),ae=z$1.object({id:z$1.string(),symbol:z$1.string(),type:z$1.enum(["feature","component","flow","state","aspect","gate","signal","idea"]),content:z$1.string().optional(),position:Te,tags:z$1.array(z$1.string()).optional(),created:z$1.string(),modified:z$1.string().optional()}),ie=z$1.object({from:z$1.string(),to:z$1.string(),label:z$1.string().optional(),type:z$1.string().optional()}),Me=z$1.object({id:z$1.string(),name:z$1.string(),nodes:z$1.array(z$1.string()),color:z$1.string().optional()}),ce=z$1.object({viewport:Le,groups:z$1.array(Me).optional()}),Ge=z$1.object({nodes:z$1.array(ae),connections:z$1.array(ie),layout:ce}),We=z$1.object({id:z$1.string(),name:z$1.string(),timestamp:z$1.string(),description:z$1.string().optional(),state:Ge});z$1.object({version:z$1.string(),metadata:z$1.object({name:z$1.string(),created:z$1.string(),modified:z$1.string()}),sources:z$1.object({purpose:z$1.array(ne).optional(),portal:z$1.array(ne).optional()}),nodes:z$1.array(ae),connections:z$1.array(ie),layout:ce,snapshots:z$1.array(We).optional()});async function Ye(t,s){let e=[],o=[],a=[],i=[];if(t.sources.purpose)for(let p of t.sources.purpose){let f=b.resolve(s,p.path);try{let u=await K(f);a.push(...u.map(m=>m.filePath));let d=U(u);for(let[m,{item:h,filePath:$}]of d){let C=["feature",...h.tags||[]];e.push(w({id:`purpose-feature-${m}`,symbol:`#${m}`,type:"component",source:"purpose",filePath:$,data:h,description:h.description,tags:C,componentType:h.type,parentSymbol:h.parent,anchors:h.anchors?.map(ue=>M(ue))}));}let g=q(u);for(let[m,{item:h,filePath:$}]of g)e.push(w({id:`purpose-component-${m}`,symbol:`#${m}`,type:"component",source:"purpose",filePath:$,data:h,description:h.description,tags:h.tags,componentType:h.type,parentSymbol:h.parent,anchors:h.anchors?.map(C=>M(C))}));let y=Z(u);for(let[m,{item:h,filePath:$}]of y)e.push(w({id:`purpose-gate-${m}`,symbol:`^${m}`,type:"gate",source:"purpose",filePath:$,data:h,description:h.description}));let S=X(u);for(let[m,{item:h,filePath:$}]of S)e.push(w({id:`purpose-state-${m}`,symbol:`#${m}`,type:"component",source:"purpose",filePath:$,data:h,description:h.description,tags:["state"]}));let G=H(u);for(let[m,{item:h,filePath:$}]of G)e.push(w({id:`purpose-flow-${m}`,symbol:`$${m}`,type:"flow",source:"purpose",filePath:$,data:h,description:h.description}));let pe=J(u);for(let[m,{item:h,filePath:$}]of pe)e.push(w({id:`purpose-signal-${m}`,symbol:`!${m}`,type:"signal",source:"purpose",filePath:$,data:h,description:h.description}));let fe=Q(u);for(let[m,{item:h,filePath:$}]of fe)e.push(w({id:`purpose-aspect-${m}`,symbol:`~${m}`,type:"aspect",source:"purpose",filePath:$,data:h,description:h.description,anchors:h.anchors?.map(C=>M(C)),appliesTo:h["applies-to"],tags:h.tags,enforcement:h.enforcement}));let le=ee(u),W=new Set(e.map(m=>m.symbol));for(let m of le)W.has(m.symbol)||(W.add(m.symbol),e.push(w({id:`purpose-ref-${m.type}-${m.symbol.slice(1)}`,symbol:m.symbol,type:m.type,source:"purpose",filePath:m.filePath,data:{referencedFrom:m.sourceSymbol},description:`Referenced from ${m.sourceSymbol}`})));}catch(u){o.push({source:"purpose",filePath:f,message:u.message});}}if(t.sources.portal)for(let p of t.sources.portal){let f=b.resolve(s,p.path);try{let u;if(f.endsWith(".yaml")||f.endsWith(".yml"))u=await R(f),i.push(f);else {let d=await se(f);if(i.push(...d),d.length>0){u=await R(d[0]);for(let g=1;g<d.length;g++){let y=await R(d[g]);u.gates.push(...y.gates),u.flows.push(...y.flows);}}else continue}for(let d of u.gates){e.push(Be(d,f));for(let g of d.prizes)e.push(w({id:`gate-signal-${d.id}-${g.id}`,symbol:`!${g.id}`,type:"signal",source:"portal",filePath:f,data:g,description:`Signal from gate ${d.id}`}));}for(let d of u.flows)e.push(Ve(d,f));}catch(u){o.push({source:"portal",filePath:f,message:u.message});}}for(let p of t.nodes){let f=p.tags?.includes("idea");if(!p.content&&!f){let u=e.find(d=>d.symbol===p.symbol);if(u){u.position=p.position,u.tags=p.tags;continue}}e.push(w({id:p.id,symbol:p.symbol,type:p.type,source:"premise",filePath:".premise",data:p,description:p.content,position:p.position,tags:p.tags,created:p.created,modified:p.modified}));}Ne(e);let r=new Map;for(let p of e){let f=r.get(p.symbol)||[];f.includes(p.filePath)||f.push(p.filePath),r.set(p.symbol,f);}let c=[];for(let[p,f]of r)f.length>1&&c.push({symbol:p,files:f});return {symbols:e,purposeFiles:a,portalFiles:i,errors:o,timestamp:Date.now(),...c.length>0?{duplicateSymbols:c}:{}}}function w(t){return {...t,data:t.data??null,references:t.references??[],referencedBy:t.referencedBy??[]}}function Be(t,s){let e=t.id.startsWith("^")?t.id.slice(1):t.id;return w({id:`gate-${e}`,symbol:`^${e}`,type:"gate",source:"portal",filePath:s,data:t,description:t.description,position:t.position})}function Ve(t,s){return w({id:`gate-flow-${t.id}`,symbol:`$${t.id}`,type:"flow",source:"portal",filePath:s,data:t,description:t.description})}function M(t){let s=t.lastIndexOf(":");if(s===-1||s===t.length-1)return {path:t,lines:0,raw:t};let e=t.slice(s+1),o=t.slice(0,s);if(!/^[\d,\- ]+$/.test(e))return {path:t,lines:0,raw:t};if(e.includes("-")){let[a,i]=e.split("-").map(Number);return {path:o,lines:[a,i],raw:t}}else if(e.includes(",")){let a=e.split(",").map(Number);return {path:o,lines:a,raw:t}}else return {path:o,lines:Number(e),raw:t}}var _e=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function Ne(t){let s=new Map(t.map(e=>[e.symbol,e]));for(let e of t){let o=JSON.stringify(e.data),a=/(?:\?[@#$%~^!]|[@#$%~^!?])[a-zA-Z][\w-]*/g,i=(o.match(a)||[]).filter(r=>!_e.has(r));for(let r of i)if(r!==e.symbol&&s.has(r)){e.references.includes(r)||e.references.push(r);let c=s.get(r);c&&!c.referencedBy.includes(e.symbol)&&c.referencedBy.push(e.symbol);}}}async function pt(t){let s={metadata:{name:b.basename(t),created:new Date().toISOString(),modified:new Date().toISOString()},sources:{purpose:[{path:"./"}],portal:[{path:"./"}]},nodes:[]};return Ye(s,t)}function Ke(){return {entries:new Map,byType:new Map,bySource:new Map,timestamp:0}}function ft(t){let s=Ke();s.timestamp=t.timestamp;for(let e of t.symbols)s.entries.set(e.id,e),s.byType.has(e.type)||s.byType.set(e.type,[]),s.byType.get(e.type).push(e),s.bySource.has(e.source)||s.bySource.set(e.source,[]),s.bySource.get(e.source).push(e);return s}function E(t,s){for(let e of t.entries.values())if(e.symbol===s)return e}function Ue(t,s){return t.byType.get(s)||[]}function lt(t,s){let e=s.toLowerCase(),o=[];for(let a of t.entries.values()){if(a.symbol.toLowerCase().includes(e)){o.push(a);continue}if(a.description?.toLowerCase().includes(e)){o.push(a);continue}if(a.tags?.some(i=>i.toLowerCase().includes(e))){o.push(a);continue}if(a.componentType?.toLowerCase().includes(e)){o.push(a);continue}}return o}function ut(t,s){let e=E(t,s);return e?e.referencedBy.map(o=>E(t,o)).filter(o=>o!==void 0):[]}function dt(t,s){let e=E(t,s);return e?e.references.map(o=>E(t,o)).filter(o=>o!==void 0):[]}function mt(t){let s={component:0,flow:0,gate:0,signal:0,aspect:0};for(let[e,o]of t.byType)e in s&&(s[e]=o.length);return s}function ht(t){return Array.from(t.entries.values())}function qe(t,s,e){if(b.isAbsolute(t))return {resolvedPath:t,baseUsed:"absolute",exists:P.existsSync(t)};let o=b.join(e,t);if(P.existsSync(o))return {resolvedPath:o,baseUsed:"project-root",exists:true};let a=b.resolve(s,t);return P.existsSync(a)?{resolvedPath:a,baseUsed:"purpose-dir",exists:true}:{resolvedPath:o,baseUsed:"project-root",exists:false}}function gt(t,s,e){if(b.isAbsolute(t)){let i=P.existsSync(t);return {rootResolves:i,purposeResolves:i,mismatch:false}}let o=P.existsSync(b.join(e,t)),a=P.existsSync(b.resolve(s,t));return {rootResolves:o,purposeResolves:a,mismatch:o!==a}}function Ze(t,s){return t.includes("*")?new RegExp("^"+t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(s):t===s}function yt(t,s,e){let o=[],a=Ue(t,"aspect"),i=new Set;for(let r of a){let c=r.appliesTo||[];if(c.length!==0)for(let p of c)for(let f of s){if(!Ze(p,f))continue;let u=r.anchors||[];if(u.length===0){let d=`${r.symbol}::__no-anchors__`;i.has(d)||(i.add(d),o.push({aspectSymbol:r.symbol,anchorRaw:null,kind:"no-anchors"}));}else {let d=r.filePath?b.isAbsolute(r.filePath)?r.filePath:b.resolve(e,r.filePath):e,g=r.filePath?b.dirname(d):e;for(let y of u){let S=`${r.symbol}::${y.raw}`;if(i.has(S))continue;qe(y.path,g,e).exists||(i.add(S),o.push({aspectSymbol:r.symbol,anchorRaw:y.raw,kind:"missing-file"}));}}}}return o}
3
+ export{ke as a,je as b,He as c,Ae as d,Qe as e,et as f,R as g,ot as h,pt as i,ft as j,E as k,Ue as l,lt as m,ut as n,dt as o,mt as p,ht as q,qe as r,gt as s,yt as t};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-IOVHF4SR.js';import {e,f,c,d,l,h,g,k,i,m as m$1,o,n,j,b as b$1,a as a$1}from'./chunk-TQOT2LBO.js';import {a}from'./chunk-Y4XFVDZC.js';import*as $ from'fs';import*as m from'path';import e$1 from'chalk';import E from'prompts';function F(){return process.env.CLAUDE_CODE==="1"||process.env.TERM_PROGRAM==="claude"?false:!!(process.env.TERM_PROGRAM==="cursor"||process.env.CURSOR_SESSION||process.env.CURSOR_TRACE_ID||process.env.VSCODE_CWD&&process.env.VSCODE_CWD.toLowerCase().includes("cursor")||process.env.VSCODE_NLS_CONFIG&&process.env.VSCODE_NLS_CONFIG.toLowerCase().includes("cursor")||process.env.TERM_PROGRAM==="vscode"&&process.env.VSCODE_GIT_ASKPASS_NODE?.toLowerCase().includes("cursor")||process.stdin.isTTY)}async function T(g){let n=new a(g),c=await n.discover();console.log(e$1.cyan(`
2
+ import {b}from'./chunk-MU5YWTNE.js';import {e,f,c,d,l,h,g,k,i,m as m$1,o,n,j,b as b$1,a as a$1}from'./chunk-TQOT2LBO.js';import {a}from'./chunk-Y4XFVDZC.js';import*as $ from'fs';import*as m from'path';import e$1 from'chalk';import E from'prompts';function F(){return process.env.CLAUDE_CODE==="1"||process.env.TERM_PROGRAM==="claude"?false:!!(process.env.TERM_PROGRAM==="cursor"||process.env.CURSOR_SESSION||process.env.CURSOR_TRACE_ID||process.env.VSCODE_CWD&&process.env.VSCODE_CWD.toLowerCase().includes("cursor")||process.env.VSCODE_NLS_CONFIG&&process.env.VSCODE_NLS_CONFIG.toLowerCase().includes("cursor")||process.env.TERM_PROGRAM==="vscode"&&process.env.VSCODE_GIT_ASKPASS_NODE?.toLowerCase().includes("cursor")||process.stdin.isTTY)}async function T(g){let n=new a(g),c=await n.discover();console.log(e$1.cyan(`
3
3
  Configure Agent Models
4
4
  `)),console.log(e$1.gray(` Environment: ${c.source}`)),console.log(e$1.gray(` Available: ${c.models.length} models
5
5
  `));let i={},o=n.groupByTier(c.models),a$2=t=>{let r=a$1[t],s=r.tier==="high"?o.high:r.tier==="medium"?o.medium:o.low,l=[];for(let f of s){let P=l.length===0;l.push({title:P?`${f.name} (recommended)`:f.name,value:f.id,description:`${f.provider} - ${r.tier} tier`});}let u=o.high.filter(f=>!s.includes(f)),y=o.medium.filter(f=>!s.includes(f)),v=o.low.filter(f=>!s.includes(f));for(let f of u)l.push({title:f.name,value:f.id,description:`${f.provider} - high tier`});for(let f of y)l.push({title:f.name,value:f.id,description:`${f.provider} - medium tier`});for(let f of v)l.push({title:f.name,value:f.id,description:`${f.provider} - low tier`});return l};for(let t of ["architect","builder","tester","reviewer","security"]){let r=a$1[t],s=t.charAt(0).toUpperCase()+t.slice(1),l=a$2(t),u=await E({type:"select",name:"model",message:`${s} (${r.description})`,choices:l,initial:0},{onCancel:()=>{console.log(e$1.yellow(`
@@ -421,7 +421,7 @@ import m from'chalk';import Ze from'sql.js';import {v4}from'uuid';import*as S fr
421
421
  SELECT id FROM events ORDER BY timestamp ASC LIMIT ?
422
422
  )`,[t]),this.save(),t}rowToGenericEvent(e,n){let t={};return e.forEach((s,r)=>{t[s]=n[r];}),{id:t.id,schemaId:t.schema_id,eventType:t.event_type,category:t.category,timestamp:t.timestamp,scopeValue:t.scope_value||void 0,scopeOrdinal:t.scope_ordinal!=null?t.scope_ordinal:void 0,sessionId:t.session_id||void 0,service:t.service,data:t.data_json?JSON.parse(t.data_json):void 0,severity:t.severity||"info",parentEventId:t.parent_event_id||void 0,depth:t.depth||0}}close(){this.db&&(this.save(),this.db.close(),this.db=null);}};var nt={minScore:30,maxResults:5,boostConfidence:true},q=class{constructor(e){this.storage=e;}match(e,n={}){let{minScore:t,maxResults:s,boostConfidence:r}={...nt,...n},i=this.storage.getAllPatterns({includePrivate:true}),a=[];for(let c of i){if(!this.matchEnvironment(c,e))continue;let{score:l,matchedCriteria:d}=this.scoreMatch(c,e);if(l>=t){let u=l;if(r){let g=c.confidence.score/100;u=l*(.5+.5*g);}a.push({pattern:c,score:l,matchedCriteria:d,confidence:Math.round(u)}),this.storage.updatePatternConfidence(c.id,"matched");}}return a.sort((c,l)=>l.confidence-c.confidence).slice(0,s)}testPattern(e,n=100){let t=this.storage.getRecentIncidents({limit:n}),s=[],r=0;for(let i of t){if(!this.matchEnvironment(e,i))continue;let{score:a}=this.scoreMatch(e,i);a>=30&&(s.push(i),r+=a);}return {wouldMatch:s,matchCount:s.length,avgScore:s.length>0?Math.round(r/s.length):0}}scoreMatch(e,n){let t=0,s={symbols:[],errorKeywords:[],missingSignals:[]},r=this.matchSymbols(e.pattern.symbols,n.symbols,s.symbols);t+=Math.min(r,50);let i=this.matchErrorText(e,n,s.errorKeywords);t+=Math.min(i,25);let a=this.matchMissingSignals(e,n,s.missingSignals);return t+=Math.min(a,25),t=Math.min(t,100),{score:t,matchedCriteria:s}}matchSymbols(e,n,t){let s=0,r=["feature","component","flow","gate","signal","state","integration"];for(let i of r){let a=e[i],c=n[i];if(!(!a||!c)){if(typeof a=="string")this.matchSingleSymbol(a,c)&&(s+=a.includes("*")?5:10,t.push(i));else if(Array.isArray(a)){for(let l of a)if(this.matchSingleSymbol(l,c)){s+=7,t.push(i);break}}}}return s}matchSingleSymbol(e,n){if(e==="*")return true;if(e.endsWith("*")){let t=e.slice(0,-1);return n.startsWith(t)}if(e.startsWith("*")){let t=e.slice(1);return n.endsWith(t)}return e.includes("*")?new RegExp("^"+e.replace(/\*/g,".*")+"$").test(n):e===n}matchErrorText(e,n,t){let s=0,r=n.error.message.toLowerCase(),i=n.error.type?.toLowerCase();if(e.pattern.errorContains)for(let a of e.pattern.errorContains)r.includes(a.toLowerCase())&&(s+=5,t.push(a));if(e.pattern.errorMatches)try{new RegExp(e.pattern.errorMatches,"i").test(n.error.message)&&(s+=10,t.push(`regex:${e.pattern.errorMatches}`));}catch{}if(e.pattern.errorType&&i)for(let a of e.pattern.errorType)i.includes(a.toLowerCase())&&(s+=5,t.push(`type:${a}`));return s}matchMissingSignals(e,n,t){if(!e.pattern.missingSignals||!n.flowPosition?.missing)return 0;let s=0;for(let r of e.pattern.missingSignals)for(let i of n.flowPosition.missing)if(this.matchSingleSymbol(r,i)){s+=12,t.push(i);break}return s}matchEnvironment(e,n){return !e.pattern.environment||e.pattern.environment.length===0?true:e.pattern.environment.includes(n.environment)}};var G=class{constructor(e){this.storage=e;}getStats(e=7){let n=new Date().toISOString(),t=new Date(Date.now()-e*24*60*60*1e3).toISOString();return this.storage.getStats({start:t,end:n})}getSymbolHealth(e){return this.storage.getSymbolHealth(e)}getTrendingIssues(e=7){let n=Date.now(),t=e*24*60*60*1e3/2,s=new Date(n-e*24*60*60*1e3).toISOString(),r=new Date(n-t).toISOString(),i=new Date(n).toISOString(),a=this.storage.getRecentIncidents({dateFrom:s,dateTo:r,limit:1e3}),c=this.storage.getRecentIncidents({dateFrom:r,dateTo:i,limit:1e3}),l=this.countSymbols(a),d=this.countSymbols(c),u=[],g=new Set([...l.keys(),...d.keys()]);for(let p of g){let y=l.get(p)||0,f=d.get(p)||0;if(y===0&&f>0)u.push({symbol:p,trend:f*100});else if(y>0){let T=(f-y)/y*100;u.push({symbol:p,trend:T});}}return u.filter(p=>p.trend>0).sort((p,y)=>y.trend-p.trend).slice(0,10)}getResolutionMetrics(){let e=this.getStats(30);return {avgTimeToResolve:e.resolution.avgTimeToResolve,resolvedWithPattern:e.resolution.resolvedWithPattern,resolvedManually:e.resolution.resolvedManually,totalResolved:e.incidents.resolved,resolutionRate:e.resolution.resolutionRate}}getPatternEffectiveness(){return this.storage.getAllPatterns({includePrivate:true}).filter(n=>n.confidence.timesMatched>0).map(n=>({patternId:n.id,name:n.name,matches:n.confidence.timesMatched,resolutions:n.confidence.timesResolved,recurrences:n.confidence.timesRecurred,effectiveness:n.confidence.timesMatched>0?Math.round((n.confidence.timesResolved-n.confidence.timesRecurred)/n.confidence.timesMatched*100):0})).sort((n,t)=>t.effectiveness-n.effectiveness)}getIncidentsByHour(e=7){let n=new Date(Date.now()-e*24*60*60*1e3).toISOString(),t=this.storage.getRecentIncidents({dateFrom:n,limit:1e4}),s=new Map;for(let r=0;r<24;r++)s.set(r,0);for(let r of t){let i=new Date(r.timestamp).getHours();s.set(i,(s.get(i)||0)+1);}return Array.from(s.entries()).map(([r,i])=>({hour:r,count:i}))}getIncidentsByEnvironment(){let e=this.getStats(30),n=e.incidents.total;return Object.entries(e.incidents.byEnvironment).map(([t,s])=>({environment:t,count:s,percentage:n>0?Math.round(s/n*100):0})).sort((t,s)=>s.count-t.count)}getSymbolCorrelation(){let e=this.storage.getRecentIncidents({limit:1e3}),n=new Map,t=new Map;for(let r of e){let i=this.getSymbolsFromIncident(r);for(let a of i)t.set(a,(t.get(a)||0)+1);for(let a=0;a<i.length;a++)for(let c=a+1;c<i.length;c++){let l=[i[a],i[c]].sort().join("|");n.set(l,(n.get(l)||0)+1);}}let s=[];for(let[r,i]of n){let[a,c]=r.split("|"),l=t.get(a)||1,d=t.get(c)||1,u=i/Math.max(l,d);u>.3&&s.push({symbol1:a,symbol2:c,correlation:Math.round(u*100)/100});}return s.sort((r,i)=>i.correlation-r.correlation).slice(0,20)}generateDashboard(e=7){let n=this.getStats(e),t=[];t.push("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),t.push("\u2551 PARADIGM SENTINEL DASHBOARD \u2551"),t.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");let s=n.incidents.byDay[n.incidents.byDay.length-1]?.count||0;t.push(`\u2551 Open: ${String(n.incidents.open).padEnd(4)} \u2502 Investigating: ${String(n.incidents.total-n.incidents.open-n.incidents.resolved).padEnd(3)} \u2502 Resolved: ${String(n.incidents.resolved).padEnd(4)} \u2502 Today: +${s} \u2551`),t.push("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),t.push(""),t.push("Incidents by Day (last 7 days):"),t.push("\u2500".repeat(50));let r=Math.max(...n.incidents.byDay.map(i=>i.count),1);for(let i of n.incidents.byDay.slice(-7)){let a=Math.round(i.count/r*30),c="\u2588".repeat(a);t.push(`${i.date.substring(5)} ${c} ${i.count}`);}t.push(""),t.push("Most Affected Symbols:"),t.push("\u2500".repeat(50));for(let{symbol:i,count:a}of n.symbols.mostIncidents.slice(0,5))t.push(` ${i.padEnd(25)} ${a} incidents`);t.push(""),t.push("Top Patterns:"),t.push("\u2500".repeat(50));for(let{patternId:i,resolvedCount:a}of n.patterns.mostEffective.slice(0,5))t.push(` ${i.padEnd(25)} ${a} resolved`);return t.push(""),t.push("Resolution Stats:"),t.push("\u2500".repeat(50)),t.push(` Resolution rate: ${Math.round(n.resolution.resolutionRate)}%`),t.push(` With pattern: ${n.resolution.resolvedWithPattern}`),t.push(` Manual: ${n.resolution.resolvedManually}`),t.join(`
423
423
  `)}countSymbols(e){let n=new Map;for(let t of e)for(let[,s]of Object.entries(t.symbols))s&&n.set(s,(n.get(s)||0)+1);return n}getSymbolsFromIncident(e){let n=[];for(let[,t]of Object.entries(e.symbols))t&&n.push(t);return n}};var W=class{build(e){if(!e.flowPosition)return null;let n=[],t=new Date(e.timestamp).getTime();n.push({timestamp:new Date(t-5e3).toISOString(),symbol:e.flowPosition.flowId,type:"flow-started"});let s=1e3;for(let i of e.flowPosition.actual){let a=this.inferEventType(i);n.push({timestamp:new Date(t-4e3+s).toISOString(),symbol:i,type:a}),s+=Math.random()*1e3+500;}let r=e.flowPosition.failedAt||e.flowPosition.missing[0]||e.symbols.gate||e.symbols.signal||"unknown";return n.push({timestamp:e.timestamp,symbol:r,type:"error",data:{message:e.error.message,missing:e.flowPosition.missing}}),{incidentId:e.id,flowId:e.flowPosition.flowId,events:n,failure:{at:e.timestamp,symbol:r,reason:e.error.message}}}renderAscii(e){let n=[];n.push(`${e.flowId} Timeline`),n.push("\u2550".repeat(40)),n.push("");for(let s of e.events){let r=this.formatTime(s.timestamp),i=this.getEventIcon(s.type),a=this.getEventStatus(s.type),c=`${r} ${i} ${s.symbol}`;a&&(c+=` (${a})`),n.push(c),s.type==="error"&&s.data&&(n.push(` \u2514\u2500 ${s.data.message}`),s.data.missing&&Array.isArray(s.data.missing)&&s.data.missing.length>0&&n.push(` \u2514\u2500 Expected: ${s.data.missing.join(", ")}`));}let t=e.events.find(s=>s.type==="error")?.data?.missing;return t&&t.length>0&&(n.push(""),n.push(`Missing signals: ${t.join(", ")}`)),n.join(`
424
- `)}renderStructured(e){return {incidentId:e.incidentId,flow:{id:e.flowId,eventCount:e.events.length},events:e.events.map(n=>({time:this.formatTime(n.timestamp),symbol:n.symbol,type:n.type,status:this.getEventStatus(n.type),data:n.data})),failure:{at:this.formatTime(e.failure.at),symbol:e.failure.symbol,reason:e.failure.reason}}}inferEventType(e){return e.startsWith("^")?"gate-passed":e.startsWith("!")?"signal-emitted":e.startsWith("%")?"state-changed":"signal-emitted"}getEventIcon(e){switch(e){case "flow-started":return "\u25B6";case "flow-ended":return "\u25A0";case "gate-passed":return "\u2713";case "gate-failed":return "\u2717";case "signal-emitted":return "\u26A1";case "state-changed":return "\u25C6";case "error":return "\u2717";default:return "\u2022"}}getEventStatus(e){switch(e){case "gate-passed":return "PASSED";case "gate-failed":return "FAILED";case "signal-emitted":return "EMITTED";case "state-changed":return "CHANGED";case "error":return "ERROR";default:return ""}}formatTime(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),s=String(n.getMinutes()).padStart(2,"0"),r=String(n.getSeconds()).padStart(2,"0"),i=String(n.getMilliseconds()).padStart(3,"0");return `${t}:${s}:${r}.${i}`}};var rt=fileURLToPath(import.meta.url),Ne=S.dirname(rt);function it(){let o=S.join(Ne,"universal-patterns.json"),e=E.readFileSync(o,"utf-8");return JSON.parse(e)}function ot(){let o=S.join(Ne,"paradigm-patterns.json"),e=E.readFileSync(o,"utf-8");return JSON.parse(e)}function Oe(){let o=it(),e=ot();return {version:"1.0.0",exportedAt:new Date().toISOString(),patterns:[...o.patterns,...e.patterns]}}var at=process.env.SENTINEL_LOG_LEVEL||process.env.LOG_LEVEL||"info",xe={debug:0,info:1,warn:2,error:3};function A(o){return xe[o]>=xe[at]}function P(o){if(!o)return "";let e=Object.entries(o).map(([n,t])=>`${n}=${typeof t=="string"?t:JSON.stringify(t)}`).join(" ");return m.gray(` ${e}`)}var v={component(o){let e=m.magenta(`#${o}`);return {debug:(n,t)=>{A("debug")&&console.log(`${m.gray("\u25CB")} ${e} ${n}${P(t)}`);},info:(n,t)=>{A("info")&&console.log(`${m.blue("\u2139")} ${e} ${n}${P(t)}`);},warn:(n,t)=>{A("warn")&&console.log(`${m.yellow("\u26A0")} ${e} ${n}${P(t)}`);},error:(n,t)=>{A("error")&&console.error(`${m.red("\u2716")} ${e} ${n}${P(t)}`);}}},flow(o){let e=m.yellow(`$${o}`);return {debug:(n,t)=>{A("debug")&&console.log(`${m.gray("\u25CB")} ${e} ${n}${P(t)}`);},info:(n,t)=>{A("info")&&console.log(`${m.blue("\u2139")} ${e} ${n}${P(t)}`);},warn:(n,t)=>{A("warn")&&console.log(`${m.yellow("\u26A0")} ${e} ${n}${P(t)}`);},error:(n,t)=>{A("error")&&console.error(`${m.red("\u2716")} ${e} ${n}${P(t)}`);}}}},Le=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);async function Q(o){let e=S.join(o,".paradigm","config.yaml");if(!E.existsSync(e)){let n=S.join(o,"package.json");if(E.existsSync(n))try{return {name:JSON.parse(E.readFileSync(n,"utf-8")).name}}catch{}return {}}try{let n=E.readFileSync(e,"utf-8"),t={},s=n.match(/^name:\s*(.+)$/m);s&&(t.name=s[1].trim().replace(/^["']|["']$/g,""));let r=n.match(/^discipline:\s*(.+)$/m);r&&(t.discipline=r[1].trim());let i=n.match(/^version:\s*(.+)$/m);return i&&(t.version=i[1].trim()),t}catch(n){return v.component("config-loader").error("Failed to load Paradigm config",{error:String(n)}),{}}}async function ct(o){try{let{aggregateFromDirectory:e}=await import('./dist-JZZJLVMR.js');v.flow("load-symbols").info("Using premise-core aggregator",{path:o});let n=await e(o),t={};for(let s of n.symbols)t[s.type]=(t[s.type]||0)+1;if(v.flow("load-symbols").info("Aggregation complete",{total:n.symbols.length,...t,purposeFiles:n.purposeFiles.length,portalFiles:n.portalFiles.length}),n.errors.length>0)for(let s of n.errors)v.component("aggregator").warn("Aggregation error",{source:s.source,file:s.filePath,message:s.message});for(let s of n.purposeFiles)v.component("purpose-loader").info("Loaded .purpose file",{file:S.relative(o,s)});for(let s of n.portalFiles)v.component("gate-loader").info("Loaded portal.yaml",{file:S.relative(o,s)});return n.symbols}catch(e){return v.component("premise-core").warn("premise-core not available, using fallback scanner",{error:e instanceof Error?e.message:String(e)}),null}}async function $(o){v.flow("load-symbols").info("Loading symbols",{projectDir:o});let e=S.join(o,".paradigm","index.json");if(E.existsSync(e))try{v.component("index-loader").info("Found cached index",{path:e});let t=E.readFileSync(e,"utf-8"),s=JSON.parse(t),r=Array.isArray(s.entries)?s.entries:Array.isArray(s)?s:null;if(r)return v.flow("load-symbols").info("Loaded from cached index",{count:r.length}),r}catch(t){v.component("index-loader").error("Failed to load cached index",{error:String(t)});}let n=await ct(o);return n||(v.flow("load-symbols").info("Using fallback scanner"),lt(o))}async function lt(o){let e=[],n=new Set,t=["src","lib","packages","apps","."];for(let r of t){let i=S.join(o,r);E.existsSync(i)&&await we(i,e,n,o);}let s=S.join(o,"portal.yaml");if(E.existsSync(s)){v.component("gate-loader").debug("Found portal.yaml",{path:"portal.yaml"});try{let i=E.readFileSync(s,"utf-8").match(/^gates:\s*\n((?: .+\n)*)/m);if(i){let a=i[1].matchAll(/^ ([a-z][a-z0-9-]*):/gm);for(let c of a){let l=c[1],d=`gate-${l}`;n.has(d)||(n.add(d),e.push({id:d,symbol:`^${l}`,type:"gate",source:"portal",filePath:"portal.yaml",data:{},references:[],referencedBy:[]}),v.component("gate-loader").debug("Extracted gate",{symbol:`^${l}`}));}}}catch(r){v.component("gate-loader").error("Failed to parse portal.yaml",{error:String(r)});}}return v.flow("load-symbols").info("Fallback scan complete",{count:e.length}),e}async function we(o,e,n,t){let s=["node_modules",".git","dist","build",".paradigm","coverage",".next",".svelte-kit"],r;try{r=E.readdirSync(o,{withFileTypes:!0});}catch{return}for(let i of r){let a=S.join(o,i.name);if(i.isDirectory())s.includes(i.name)||await we(a,e,n,t);else if(i.name===".purpose"){let c=S.relative(t,a);v.component("purpose-loader").debug("Scanning .purpose file",{path:c});try{let l=E.readFileSync(a,"utf-8"),d=ut(l,a,t);for(let u of d)n.has(u.id)||(n.add(u.id),e.push(u),v.component("purpose-loader").debug("Extracted symbol",{symbol:u.symbol,type:u.type,file:c}));}catch(l){v.component("purpose-loader").error("Failed to parse .purpose file",{path:c,error:String(l)});}}}}function ut(o,e,n){let t=[],s=S.relative(n,e),r=o.matchAll(/(?:^|\s)#([a-z][a-z0-9-]*)/gm);for(let d of r){let u=d[1];t.push({id:`component-${u}`,symbol:`#${u}`,type:"component",source:"purpose",filePath:s,data:{},description:dt(o,`#${u}`),references:mt(o),referencedBy:[],tags:gt(o)});}let i=o.matchAll(/\$([a-z][a-z0-9-]*)/gm);for(let d of i){let u=d[1],g=`$${u}`;if(Le.has(g)){v.component("purpose-loader").debug("Skipping blocklisted symbol",{symbol:g});continue}t.find(p=>p.symbol===g)||t.push({id:`flow-${u}`,symbol:g,type:"flow",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}let a=o.matchAll(/!([a-z][a-z0-9-]*)/gm);for(let d of a){let u=d[1];t.find(g=>g.symbol===`!${u}`)||t.push({id:`signal-${u}`,symbol:`!${u}`,type:"signal",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}let c=o.matchAll(/\^([a-z][a-z0-9-]*)/gm);for(let d of c){let u=d[1];t.find(g=>g.symbol===`^${u}`)||t.push({id:`gate-${u}`,symbol:`^${u}`,type:"gate",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}let l=o.matchAll(/~([a-z][a-z0-9-]*)/gm);for(let d of l){let u=d[1];t.find(g=>g.symbol===`~${u}`)||t.push({id:`aspect-${u}`,symbol:`~${u}`,type:"aspect",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}return t}function dt(o,e){let n=new RegExp(`${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[-:]?\\s*(.+)`,"m"),t=o.match(n);if(t&&t[1])return t[1].trim()}function mt(o){let e=new Set,n=o.matchAll(/[@#$!^~]([a-z][a-z0-9-]*)/g);for(let t of n){let s=t[0];Le.has(s)||e.add(s);}return Array.from(e)}function gt(o){let e=o.match(/tags:\s*\[([^\]]+)\]/);return e?e[1].split(",").map(n=>n.trim().replace(/^["']|["']$/g,"")):[]}async function Z(o){return (await $(o)).length}async function Ce(o,e,n){let s=(await $(o)).find(i=>i.id===e);if(!s)return {success:false,error:"Symbol not found"};let r=S.join(o,s.filePath);if(!E.existsSync(r))return {success:false,error:"Source file not found"};try{let i=E.readFileSync(r,"utf-8"),a=!1;if(n.description!==void 0){let c=s.symbol.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`(${c})\\s*[-:]?\\s*(.*)`,"m");if(i.match(l)){let u=n.description?`${s.symbol}: ${n.description}`:s.symbol;i=i.replace(l,u),a=!0;}}if(n.tags!==void 0){let c=n.tags.length>0?`tags: [${n.tags.map(d=>`"${d}"`).join(", ")}]`:"",l=/^tags:\s*\[[^\]]*\]\s*$/m;if(l.test(i))c?i=i.replace(l,c):i=i.replace(l,""),a=!0;else if(c){let d=s.symbol.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=new RegExp(`(${d}[^\\n]*\\n)`,"m");i.match(u)&&(i=i.replace(u,`$1${c}
424
+ `)}renderStructured(e){return {incidentId:e.incidentId,flow:{id:e.flowId,eventCount:e.events.length},events:e.events.map(n=>({time:this.formatTime(n.timestamp),symbol:n.symbol,type:n.type,status:this.getEventStatus(n.type),data:n.data})),failure:{at:this.formatTime(e.failure.at),symbol:e.failure.symbol,reason:e.failure.reason}}}inferEventType(e){return e.startsWith("^")?"gate-passed":e.startsWith("!")?"signal-emitted":e.startsWith("%")?"state-changed":"signal-emitted"}getEventIcon(e){switch(e){case "flow-started":return "\u25B6";case "flow-ended":return "\u25A0";case "gate-passed":return "\u2713";case "gate-failed":return "\u2717";case "signal-emitted":return "\u26A1";case "state-changed":return "\u25C6";case "error":return "\u2717";default:return "\u2022"}}getEventStatus(e){switch(e){case "gate-passed":return "PASSED";case "gate-failed":return "FAILED";case "signal-emitted":return "EMITTED";case "state-changed":return "CHANGED";case "error":return "ERROR";default:return ""}}formatTime(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),s=String(n.getMinutes()).padStart(2,"0"),r=String(n.getSeconds()).padStart(2,"0"),i=String(n.getMilliseconds()).padStart(3,"0");return `${t}:${s}:${r}.${i}`}};var rt=fileURLToPath(import.meta.url),Ne=S.dirname(rt);function it(){let o=S.join(Ne,"universal-patterns.json"),e=E.readFileSync(o,"utf-8");return JSON.parse(e)}function ot(){let o=S.join(Ne,"paradigm-patterns.json"),e=E.readFileSync(o,"utf-8");return JSON.parse(e)}function Oe(){let o=it(),e=ot();return {version:"1.0.0",exportedAt:new Date().toISOString(),patterns:[...o.patterns,...e.patterns]}}var at=process.env.SENTINEL_LOG_LEVEL||process.env.LOG_LEVEL||"info",xe={debug:0,info:1,warn:2,error:3};function A(o){return xe[o]>=xe[at]}function P(o){if(!o)return "";let e=Object.entries(o).map(([n,t])=>`${n}=${typeof t=="string"?t:JSON.stringify(t)}`).join(" ");return m.gray(` ${e}`)}var v={component(o){let e=m.magenta(`#${o}`);return {debug:(n,t)=>{A("debug")&&console.log(`${m.gray("\u25CB")} ${e} ${n}${P(t)}`);},info:(n,t)=>{A("info")&&console.log(`${m.blue("\u2139")} ${e} ${n}${P(t)}`);},warn:(n,t)=>{A("warn")&&console.log(`${m.yellow("\u26A0")} ${e} ${n}${P(t)}`);},error:(n,t)=>{A("error")&&console.error(`${m.red("\u2716")} ${e} ${n}${P(t)}`);}}},flow(o){let e=m.yellow(`$${o}`);return {debug:(n,t)=>{A("debug")&&console.log(`${m.gray("\u25CB")} ${e} ${n}${P(t)}`);},info:(n,t)=>{A("info")&&console.log(`${m.blue("\u2139")} ${e} ${n}${P(t)}`);},warn:(n,t)=>{A("warn")&&console.log(`${m.yellow("\u26A0")} ${e} ${n}${P(t)}`);},error:(n,t)=>{A("error")&&console.error(`${m.red("\u2716")} ${e} ${n}${P(t)}`);}}}},Le=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);async function Q(o){let e=S.join(o,".paradigm","config.yaml");if(!E.existsSync(e)){let n=S.join(o,"package.json");if(E.existsSync(n))try{return {name:JSON.parse(E.readFileSync(n,"utf-8")).name}}catch{}return {}}try{let n=E.readFileSync(e,"utf-8"),t={},s=n.match(/^name:\s*(.+)$/m);s&&(t.name=s[1].trim().replace(/^["']|["']$/g,""));let r=n.match(/^discipline:\s*(.+)$/m);r&&(t.discipline=r[1].trim());let i=n.match(/^version:\s*(.+)$/m);return i&&(t.version=i[1].trim()),t}catch(n){return v.component("config-loader").error("Failed to load Paradigm config",{error:String(n)}),{}}}async function ct(o){try{let{aggregateFromDirectory:e}=await import('./dist-RXYJK7AZ.js');v.flow("load-symbols").info("Using premise-core aggregator",{path:o});let n=await e(o),t={};for(let s of n.symbols)t[s.type]=(t[s.type]||0)+1;if(v.flow("load-symbols").info("Aggregation complete",{total:n.symbols.length,...t,purposeFiles:n.purposeFiles.length,portalFiles:n.portalFiles.length}),n.errors.length>0)for(let s of n.errors)v.component("aggregator").warn("Aggregation error",{source:s.source,file:s.filePath,message:s.message});for(let s of n.purposeFiles)v.component("purpose-loader").info("Loaded .purpose file",{file:S.relative(o,s)});for(let s of n.portalFiles)v.component("gate-loader").info("Loaded portal.yaml",{file:S.relative(o,s)});return n.symbols}catch(e){return v.component("premise-core").warn("premise-core not available, using fallback scanner",{error:e instanceof Error?e.message:String(e)}),null}}async function $(o){v.flow("load-symbols").info("Loading symbols",{projectDir:o});let e=S.join(o,".paradigm","index.json");if(E.existsSync(e))try{v.component("index-loader").info("Found cached index",{path:e});let t=E.readFileSync(e,"utf-8"),s=JSON.parse(t),r=Array.isArray(s.entries)?s.entries:Array.isArray(s)?s:null;if(r)return v.flow("load-symbols").info("Loaded from cached index",{count:r.length}),r}catch(t){v.component("index-loader").error("Failed to load cached index",{error:String(t)});}let n=await ct(o);return n||(v.flow("load-symbols").info("Using fallback scanner"),lt(o))}async function lt(o){let e=[],n=new Set,t=["src","lib","packages","apps","."];for(let r of t){let i=S.join(o,r);E.existsSync(i)&&await we(i,e,n,o);}let s=S.join(o,"portal.yaml");if(E.existsSync(s)){v.component("gate-loader").debug("Found portal.yaml",{path:"portal.yaml"});try{let i=E.readFileSync(s,"utf-8").match(/^gates:\s*\n((?: .+\n)*)/m);if(i){let a=i[1].matchAll(/^ ([a-z][a-z0-9-]*):/gm);for(let c of a){let l=c[1],d=`gate-${l}`;n.has(d)||(n.add(d),e.push({id:d,symbol:`^${l}`,type:"gate",source:"portal",filePath:"portal.yaml",data:{},references:[],referencedBy:[]}),v.component("gate-loader").debug("Extracted gate",{symbol:`^${l}`}));}}}catch(r){v.component("gate-loader").error("Failed to parse portal.yaml",{error:String(r)});}}return v.flow("load-symbols").info("Fallback scan complete",{count:e.length}),e}async function we(o,e,n,t){let s=["node_modules",".git","dist","build",".paradigm","coverage",".next",".svelte-kit"],r;try{r=E.readdirSync(o,{withFileTypes:!0});}catch{return}for(let i of r){let a=S.join(o,i.name);if(i.isDirectory())s.includes(i.name)||await we(a,e,n,t);else if(i.name===".purpose"){let c=S.relative(t,a);v.component("purpose-loader").debug("Scanning .purpose file",{path:c});try{let l=E.readFileSync(a,"utf-8"),d=ut(l,a,t);for(let u of d)n.has(u.id)||(n.add(u.id),e.push(u),v.component("purpose-loader").debug("Extracted symbol",{symbol:u.symbol,type:u.type,file:c}));}catch(l){v.component("purpose-loader").error("Failed to parse .purpose file",{path:c,error:String(l)});}}}}function ut(o,e,n){let t=[],s=S.relative(n,e),r=o.matchAll(/(?:^|\s)#([a-z][a-z0-9-]*)/gm);for(let d of r){let u=d[1];t.push({id:`component-${u}`,symbol:`#${u}`,type:"component",source:"purpose",filePath:s,data:{},description:dt(o,`#${u}`),references:mt(o),referencedBy:[],tags:gt(o)});}let i=o.matchAll(/\$([a-z][a-z0-9-]*)/gm);for(let d of i){let u=d[1],g=`$${u}`;if(Le.has(g)){v.component("purpose-loader").debug("Skipping blocklisted symbol",{symbol:g});continue}t.find(p=>p.symbol===g)||t.push({id:`flow-${u}`,symbol:g,type:"flow",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}let a=o.matchAll(/!([a-z][a-z0-9-]*)/gm);for(let d of a){let u=d[1];t.find(g=>g.symbol===`!${u}`)||t.push({id:`signal-${u}`,symbol:`!${u}`,type:"signal",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}let c=o.matchAll(/\^([a-z][a-z0-9-]*)/gm);for(let d of c){let u=d[1];t.find(g=>g.symbol===`^${u}`)||t.push({id:`gate-${u}`,symbol:`^${u}`,type:"gate",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}let l=o.matchAll(/~([a-z][a-z0-9-]*)/gm);for(let d of l){let u=d[1];t.find(g=>g.symbol===`~${u}`)||t.push({id:`aspect-${u}`,symbol:`~${u}`,type:"aspect",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}return t}function dt(o,e){let n=new RegExp(`${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[-:]?\\s*(.+)`,"m"),t=o.match(n);if(t&&t[1])return t[1].trim()}function mt(o){let e=new Set,n=o.matchAll(/[@#$!^~]([a-z][a-z0-9-]*)/g);for(let t of n){let s=t[0];Le.has(s)||e.add(s);}return Array.from(e)}function gt(o){let e=o.match(/tags:\s*\[([^\]]+)\]/);return e?e[1].split(",").map(n=>n.trim().replace(/^["']|["']$/g,"")):[]}async function Z(o){return (await $(o)).length}async function Ce(o,e,n){let s=(await $(o)).find(i=>i.id===e);if(!s)return {success:false,error:"Symbol not found"};let r=S.join(o,s.filePath);if(!E.existsSync(r))return {success:false,error:"Source file not found"};try{let i=E.readFileSync(r,"utf-8"),a=!1;if(n.description!==void 0){let c=s.symbol.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`(${c})\\s*[-:]?\\s*(.*)`,"m");if(i.match(l)){let u=n.description?`${s.symbol}: ${n.description}`:s.symbol;i=i.replace(l,u),a=!0;}}if(n.tags!==void 0){let c=n.tags.length>0?`tags: [${n.tags.map(d=>`"${d}"`).join(", ")}]`:"",l=/^tags:\s*\[[^\]]*\]\s*$/m;if(l.test(i))c?i=i.replace(l,c):i=i.replace(l,""),a=!0;else if(c){let d=s.symbol.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=new RegExp(`(${d}[^\\n]*\\n)`,"m");i.match(u)&&(i=i.replace(u,`$1${c}
425
425
  `),a=!0);}}if(a){i=i.replace(/\n{3,}/g,`
426
426
 
427
427
  `),E.writeFileSync(r,i,"utf-8"),v.component("symbol-updater").info("Updated symbol",{symbol:s.symbol,file:s.filePath});let c=S.join(o,".paradigm","index.json");if(E.existsSync(c))try{let l=E.readFileSync(c,"utf-8"),d=JSON.parse(l),u=Array.isArray(d.entries)?d.entries:d,g=u.findIndex(p=>p.id===e);g>=0&&(n.description!==void 0&&(u[g].description=n.description),n.tags!==void 0&&(u[g].tags=n.tags),Array.isArray(d.entries)?(d.entries=u,E.writeFileSync(c,JSON.stringify(d,null,2),"utf-8")):E.writeFileSync(c,JSON.stringify(u,null,2),"utf-8"));}catch{}return {success:!0}}return {success:!0}}catch(i){return v.component("symbol-updater").error("Failed to update symbol",{error:String(i)}),{success:false,error:"Failed to write file"}}}var ft=process.env.SENTINEL_LOG_LEVEL||process.env.LOG_LEVEL||"info",Ae=o=>{let e={debug:0,info:1,warn:2,error:3};return e[o]>=e[ft]},M={gate(o){let e=m.cyan(`^${o}`);return {info:(n,t)=>{if(Ae("info")){let s=t?m.gray(` ${Object.entries(t).map(([r,i])=>`${r}=${i}`).join(" ")}`):"";console.log(`${m.blue("\u2139")} ${e} ${n}${s}`);}},error:(n,t)=>{if(Ae("error")){let s=t?m.gray(` ${Object.entries(t).map(([r,i])=>`${r}=${i}`).join(" ")}`):"";console.error(`${m.red("\u2716")} ${e} ${n}${s}`);}}}}};function ee(o){let e=Router();return e.get("/",async(n,t)=>{try{let s=await $(o);M.gate("api-symbols").info("Symbols loaded",{count:s.length}),t.json({symbols:s});}catch(s){M.gate("api-symbols").error("Failed to load symbols",{error:String(s)}),t.status(500).json({error:"Failed to load symbols"});}}),e.put("/:id",async(n,t)=>{try{let{id:s}=n.params,r=n.body;if(M.gate("api-symbols").info("Update requested",{id:s,updates:JSON.stringify(r)}),r.tags&&!Array.isArray(r.tags)){t.status(400).json({error:"Tags must be an array"});return}let i=await Ce(o,s,r);if(i.success){let c=(await $(o)).find(l=>l.id===s);M.gate("api-symbols").info("Symbol updated",{id:s}),t.json({success:!0,symbol:c});}else M.gate("api-symbols").error("Update failed",{id:s,error:i.error}),t.status(400).json({success:!1,error:i.error});}catch(s){M.gate("api-symbols").error("Failed to update symbol",{error:String(s)}),t.status(500).json({error:"Failed to update symbol"});}}),e}function te(o){let e=Router();return e.get("/",async(n,t)=>{try{let s=await Q(o),r=await Z(o);t.json({projectName:s.name||null,discipline:s.discipline||null,symbolCount:r,projectDir:o});}catch(s){console.error("Failed to load project info:",s),t.status(500).json({error:"Failed to load project info"});}}),e}function vt(o){let e=new Set;for(let n of o){if(n.endsWith(".purpose")){let r=S.dirname(n),i=S.basename(r);r.includes("features/")||r.includes("routes/")||r.includes("api/")?e.add(`@${i}`):r.includes("components/")||r.includes("lib/")||r.includes("utils/")?e.add(`#${i}`):r.includes("middleware/")||r.includes("auth/")||r.includes("guards/")?e.add(`^${i}`):(r.includes("flows/")||r.includes("workflows/"))&&e.add(`$${i}`);}n.includes("portal.yaml")&&e.add("^portal");let t=n.match(/features\/([^/]+)/);t&&e.add(`@${t[1]}`);let s=n.match(/components\/([^/]+)/);s&&e.add(`#${s[1]}`);}return Array.from(e)}async function ne(o,e={}){let n=ht(o);if(!await n.checkIsRepo())return [];try{let s={maxCount:e.limit||100};e.since&&(s["--since"]=e.since);let r=await n.log(s),i=[];for(let a of r.all){let c=[],l=[];try{c=(await n.diffSummary([`${a.hash}^`,a.hash])).files.map(u=>u.file),l=vt(c);}catch{}i.push({hash:a.hash,shortHash:a.hash.slice(0,7),date:a.date,author:a.author_name,message:a.message.split(`
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {m as m$1,o,C,B,r}from'./chunk-LWAIVOSF.js';import'./chunk-JIXHEBGK.js';import'./chunk-ZJQY5PPP.js';import {a}from'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';import*as u from'fs';import*as m from'path';import e from'chalk';import F from'ora';function I(t){let o={gates:[],signals:[],components:[],flows:[],aspects:[]};for(let r of t){if(!r||r.length<2)continue;switch(r[0]){case "^":o.gates.push(r);break;case "!":o.signals.push(r);break;case "#":o.components.push(r);break;case "$":o.flows.push(r);break;case "~":o.aspects.push(r);break}}return o}function T(t,o){let r$1={},g={},l=B(t),a=C(t);for(let s of a){let n=I(s.references),i={type:s.type,path:s.filePath,references:s.references,referencedBy:s.referencedBy};s.description&&(i.description=s.description),s.tags&&s.tags.length>0&&(i.tags=s.tags),n.gates.length>0&&(i.gates=n.gates),n.signals.length>0&&(i.signals=n.signals),n.components.length>0&&(i.components=n.components),n.flows.length>0&&(i.flows=n.flows),n.aspects.length>0&&(i.aspects=n.aspects),r$1[s.symbol]=i;}let y=r(t,"flow");for(let s of y){let n=s.data,i=n?.sequence||n?.gates||s.references;g[s.symbol]={description:s.description,sequence:i};}return {version:"1.0",generated:new Date().toISOString(),project:o,stats:{components:l.component,flows:l.flow,gates:l.gate,signals:l.signal,aspects:l.aspect,total:Object.values(l).reduce((s,n)=>s+n,0)},stars:r$1,orbits:g}}async function z(t,o$1={}){let r=process.cwd(),g=t?m.resolve(r,t):r,l=m.basename(g),a$1=o$1.format||"json";o$1.quiet||console.log(e.blue(`
2
+ import {m as m$1,o,C,B,r}from'./chunk-4GC35IFF.js';import'./chunk-JIXHEBGK.js';import'./chunk-ZJQY5PPP.js';import {a}from'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';import*as u from'fs';import*as m from'path';import e from'chalk';import F from'ora';function I(t){let o={gates:[],signals:[],components:[],flows:[],aspects:[]};for(let r of t){if(!r||r.length<2)continue;switch(r[0]){case "^":o.gates.push(r);break;case "!":o.signals.push(r);break;case "#":o.components.push(r);break;case "$":o.flows.push(r);break;case "~":o.aspects.push(r);break}}return o}function T(t,o){let r$1={},g={},l=B(t),a=C(t);for(let s of a){let n=I(s.references),i={type:s.type,path:s.filePath,references:s.references,referencedBy:s.referencedBy};s.description&&(i.description=s.description),s.tags&&s.tags.length>0&&(i.tags=s.tags),n.gates.length>0&&(i.gates=n.gates),n.signals.length>0&&(i.signals=n.signals),n.components.length>0&&(i.components=n.components),n.flows.length>0&&(i.flows=n.flows),n.aspects.length>0&&(i.aspects=n.aspects),r$1[s.symbol]=i;}let y=r(t,"flow");for(let s of y){let n=s.data,i=n?.sequence||n?.gates||s.references;g[s.symbol]={description:s.description,sequence:i};}return {version:"1.0",generated:new Date().toISOString(),project:o,stats:{components:l.component,flows:l.flow,gates:l.gate,signals:l.signal,aspects:l.aspect,total:Object.values(l).reduce((s,n)=>s+n,0)},stars:r$1,orbits:g}}async function z(t,o$1={}){let r=process.cwd(),g=t?m.resolve(r,t):r,l=m.basename(g),a$1=o$1.format||"json";o$1.quiet||console.log(e.blue(`
3
3
  \u2728 Building Constellation...
4
4
  `));let y=F("Aggregating symbols...").start(),s=a.command("constellation").start("Building constellation",{project:l});try{let n=await m$1(g),i=o(n);a.operation("aggregate").debug("Symbols aggregated",{count:C(i).length}),y.text="Building constellation...";let p=T(i,l),$=m.join(g,".paradigm");u.existsSync($)||u.mkdirSync($,{recursive:!0});let h=o$1.output||m.join($,`constellation.${a$1}`),S;if(a$1==="yaml"?S=d(p):S=JSON.stringify(p,null,2),u.writeFileSync(h,S,"utf8"),a.component("constellation-file").success("Constellation written",{path:h,format:a$1}),y.succeed("Constellation built"),s.success("Constellation built",{path:h,stars:Object.keys(p.stars).length}),!o$1.quiet){console.log(e.white(`
5
5
  Constellation Stats`)),console.log(e.gray("\u2500".repeat(40)));let f=p.stats,q=[{symbol:"#",name:"Components",count:f.components,color:e.green},{symbol:"$",name:"Flows",count:f.flows,color:e.yellow},{symbol:"^",name:"Gates",count:f.gates,color:e.red},{symbol:"!",name:"Signals",count:f.signals,color:e.cyan},{symbol:"~",name:"Aspects",count:f.aspects,color:e.magenta}];for(let{symbol:c,name:R,count:O,color:E}of q)O>0&&console.log(` ${E(c)} ${R.padEnd(12)} ${e.cyan(O.toString())}`);console.log(e.gray("\u2500".repeat(40))),console.log(` Total stars: ${e.cyan(f.total.toString())}`),console.log(` Total orbits: ${e.cyan(Object.keys(p.orbits).length.toString())}`),console.log(e.gray(`
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-IOVHF4SR.js';import'./chunk-TYWB5IQJ.js';import'./chunk-AMLD7IYC.js';import'./chunk-FYDRENK7.js';import'./chunk-HXGYVS2N.js';import'./chunk-TQOT2LBO.js';import'./chunk-EKZDFEJW.js';import'./chunk-LPBCQM5Y.js';import'./chunk-LWAIVOSF.js';import'./chunk-JIXHEBGK.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as i from'fs';import*as a from'path';import o from'chalk';async function D(l,f,t){let d=f?a.resolve(f):process.cwd();if(!l){t.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(o.red(`
2
+ import {b}from'./chunk-MU5YWTNE.js';import'./chunk-TYWB5IQJ.js';import'./chunk-AMLD7IYC.js';import'./chunk-FYDRENK7.js';import'./chunk-HXGYVS2N.js';import'./chunk-TQOT2LBO.js';import'./chunk-EKZDFEJW.js';import'./chunk-LPBCQM5Y.js';import'./chunk-4GC35IFF.js';import'./chunk-JIXHEBGK.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as i from'fs';import*as a from'path';import o from'chalk';async function D(l,f,t){let d=f?a.resolve(f):process.cwd();if(!l){t.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(o.red(`
3
3
  Orchestration ID required.`)),console.log(o.gray(`Usage: paradigm team diff <orchestration-id>
4
4
  `)));return}let e=new b(d).getOrchestration(l);if(!e){t.json?console.log(JSON.stringify({error:"Orchestration not found",id:l})):console.log(o.red(`
5
5
  Orchestration not found: ${l}
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import*as P from'fs';import*as z from'js-yaml';import {z as z$1}from'zod';import*as b from'path';import {glob}from'glob';var F=z$1.object({description:z$1.string(),type:z$1.string().optional(),parent:z$1.string().optional(),anchors:z$1.array(z$1.string()).optional(),tags:z$1.array(z$1.string()).optional(),endpoints:z$1.array(z$1.string()).optional(),tests:z$1.array(z$1.string()).optional(),rules:z$1.record(z$1.unknown()).optional(),aspects:z$1.array(z$1.string()).optional(),flows:z$1.array(z$1.string()).optional(),gates:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional(),states:z$1.array(z$1.string()).optional(),components:z$1.array(z$1.string()).optional(),location:z$1.string().optional(),locations:z$1.array(z$1.string()).optional(),uses:z$1.array(z$1.string()).optional(),"used-by":z$1.array(z$1.string()).optional(),"used-for":z$1.array(z$1.string()).optional(),exports:z$1.array(z$1.string()).optional(),status:z$1.string().optional(),properties:z$1.record(z$1.unknown()).optional(),handles:z$1.array(z$1.string()).optional()}).passthrough(),Y=F.extend({id:z$1.string()}),de=z$1.object({description:z$1.string().optional(),category:z$1.string().optional(),severity:z$1.enum(["info","warn","error"]).optional(),emitters:z$1.array(z$1.string()).optional(),related:z$1.array(z$1.string()).optional(),data:z$1.record(z$1.unknown()).optional()}),me=z$1.union([de,z$1.string().transform(e=>({description:e}))]),he=z$1.object({from:z$1.string(),to:z$1.string(),type:z$1.string(),description:z$1.string().optional()}),ge=z$1.union([he,z$1.string()]),ye=z$1.object({component:z$1.string(),action:z$1.string(),description:z$1.string().optional()}),_=z$1.union([ye,z$1.string()]),$e=z$1.object({name:z$1.string(),description:z$1.string().optional(),steps:z$1.array(_)}),we=z$1.object({description:z$1.string().optional(),gates:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional(),components:z$1.array(z$1.string()).optional(),steps:z$1.array(_).optional()}),be=z$1.object({description:z$1.string().optional(),requires:z$1.array(z$1.string()).optional(),keys:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional()}),Se=z$1.object({description:z$1.string().optional(),default:z$1.unknown().optional(),type:z$1.string().optional()}),ve=z$1.object({description:z$1.string().optional(),tags:z$1.array(z$1.string()).optional(),anchors:z$1.array(z$1.string()).optional(),"applies-to":z$1.array(z$1.string()).optional(),enforcement:z$1.string().optional()}),xe=z$1.object({target:z$1.string(),type:z$1.string(),path:z$1.string()}),Pe=z$1.object({version:z$1.string().optional(),description:z$1.string().optional(),apiSpec:z$1.string().optional(),context:z$1.array(z$1.string()).optional(),rules:z$1.record(z$1.unknown()).optional(),features:z$1.union([z$1.array(Y),z$1.record(F)]).optional(),components:z$1.union([z$1.array(Y),z$1.record(F)]).optional(),gates:z$1.record(be).optional(),states:z$1.record(Se).optional(),signals:z$1.record(me).optional(),aspects:z$1.record(ve).optional(),relationships:z$1.array(ge).optional(),flows:z$1.union([z$1.array($e),z$1.record(we)]).optional(),references:z$1.array(xe).optional()});function ke(e){let t=je(e);return {data:t.data,errors:t.errors}}function je(e){let t=[],s=[],o;try{o=P.readFileSync(e,"utf8");}catch(l){let p=`Cannot read file: ${l.message}`;return t.push(p),s.push({message:p,type:"file"}),{data:null,errors:t,detailedErrors:s,rawContent:void 0,isYamlValid:false}}let r=o.replace(/^([#~!$^][\w-]+):/gm,'"$1":').replace(/^(\s*-\s+)([!#][\w-]+)$/gm,'$1"$2"'),a=null;try{a=z.load(r);}catch(l){let p=l,f=p.mark?.line?p.mark.line+1:void 0,u=`YAML syntax error: ${p.reason||l.message}`;return t.push(`${u}${f?` (line ${f})`:""}`),s.push({message:u,line:f,type:"yaml"}),{data:null,errors:t,detailedErrors:s,rawContent:o,isYamlValid:false}}if(a==null)return {data:{},errors:[],detailedErrors:[],rawContent:o,isYamlValid:true};if(typeof a=="object"&&a!==null){let l=a,p={"#":"components",$:"flows","^":"gates","!":"signals","~":"aspects"};for(let f of Object.keys(l)){let u=f[0],h=p[u];if(!h||f.length<2)continue;let g=f.slice(1),y=l[f];if(typeof y!="object"||y===null)continue;let S=l[h]||{};h in l||(l[h]=S),g in S||(S[g]=y),delete l[f];}}let i=Pe.safeParse(a);if(!i.success){for(let l of i.error.issues){let p=l.path.join("."),f=l.message;t.push(`Schema error at ${p||"/"}: ${f}`),s.push({message:f,path:p||"/",type:"schema"});}return {data:a,errors:t,detailedErrors:s,rawContent:o,isYamlValid:true}}return {data:i.data,errors:[],detailedErrors:[],rawContent:o,isYamlValid:true}}function D(e){return e?Array.isArray(e)?e.map(t=>[t.id,t]):Object.entries(e):[]}async function Ae(e){let t=b.resolve(e);return (await glob("**/.purpose",{cwd:t,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})).sort((o,r)=>{let a=o.split(b.sep).length,i=r.split(b.sep).length;return a-i})}async function N(e){let t=await Ae(e),s=[];for(let o of t){let{data:r,errors:a}=ke(o);r&&(s.push({filePath:o,data:r}),a.length>0&&console.warn(`Warnings parsing ${o}:`,a));}return s}function K(e){let t=new Map;for(let{filePath:s,data:o}of e){let r=D(o.features);for(let[a,i]of r)t.set(a,{item:i,filePath:s});}return t}function U(e){let t=new Map;for(let{filePath:s,data:o}of e){let r=D(o.components);for(let[a,i]of r)t.set(a,{item:i,filePath:s});}return t}function q(e){let t=new Map;for(let{filePath:s,data:o}of e)if(o.gates)for(let[r,a]of Object.entries(o.gates))t.set(r,{item:a,filePath:s});return t}function Z(e){let t=new Map;for(let{filePath:s,data:o}of e)if(o.states)for(let[r,a]of Object.entries(o.states))t.set(r,{item:a,filePath:s});return t}function X(e){let t=new Map;for(let{filePath:s,data:o}of e)if(o.flows)if(Array.isArray(o.flows))for(let r of o.flows)t.set(r.name,{item:{id:r.name,description:r.description,steps:r.steps},filePath:s});else for(let[r,a]of Object.entries(o.flows))t.set(r,{item:{id:r,description:a.description,gates:a.gates,signals:a.signals,components:a.components,steps:a.steps},filePath:s});return t}function H(e){let t=new Map;for(let{filePath:s,data:o}of e)if(o.signals)for(let[r,a]of Object.entries(o.signals))t.set(r,{item:a,filePath:s});return t}function J(e){let t=new Map;for(let{filePath:s,data:o}of e)if(o.aspects)for(let[r,a]of Object.entries(o.aspects))t.set(r,{item:a,filePath:s});return t}function Q(e){let t=[],s=new Set;for(let{filePath:o,data:r}of e){let a=D(r.features);for(let[l,p]of a)B(`#${l}`,p,o,t,s);let i=D(r.components);for(let[l,p]of i)B(`#${l}`,p,o,t,s);}return t}function B(e,t,s,o,r){if(t.flows)for(let a of t.flows){let i=a.startsWith("$")?a:`$${a}`;r.has(i)||(r.add(i),o.push({symbol:i,type:"flow",sourceSymbol:e,filePath:s}));}if(t.gates)for(let a of t.gates){let i=a.startsWith("^")?a:`^${a}`;r.has(i)||(r.add(i),o.push({symbol:i,type:"gate",sourceSymbol:e,filePath:s}));}if(t.signals)for(let a of t.signals){let i=a.startsWith("!")?a:`!${a}`;r.has(i)||(r.add(i),o.push({symbol:i,type:"signal",sourceSymbol:e,filePath:s}));}if(t.states)for(let a of t.states){let i=a.startsWith("#")?a:a.startsWith("%")?`#${a.slice(1)}`:`#${a}`;r.has(i)||(r.add(i),o.push({symbol:i,type:"component",sourceSymbol:e,filePath:s}));}if(t.components)for(let a of t.components){let i=a.startsWith("#")?a:`#${a}`;r.has(i)||(r.add(i),o.push({symbol:i,type:"component",sourceSymbol:e,filePath:s}));}if(t.aspects)for(let a of t.aspects){let i=a.startsWith("~")?a:`~${a}`;r.has(i)||(r.add(i),o.push({symbol:i,type:"aspect",sourceSymbol:e,filePath:s}));}if(t.description){let a=De(t.description);for(let{symbol:i,type:l}of a)r.has(i)||(r.add(i),o.push({symbol:i,type:l,sourceSymbol:e,filePath:s}));}}var Ie=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function De(e){let t=[],s=/([$^!#~%])([a-zA-Z][a-zA-Z0-9._-]*)/g,o;for(;(o=s.exec(e))!==null;){let r=o[1],a=o[2],i,l;switch(r){case "#":l="component",i=`#${a}`;break;case "$":l="flow",i=`$${a}`;break;case "^":l="gate",i=`^${a}`;break;case "!":l="signal",i=`!${a}`;break;case "~":l="aspect",i=`~${a}`;break;case "%":l="component",i=`#${a}`;break;default:continue}Ie.has(i)||t.push({symbol:i,type:l});}return t}var ze={visualizerPort:42195,watcherPort:42196,autoConnect:true};async function O(e){let t=b.resolve(e),s=b.dirname(t);if(!P.existsSync(t))throw new Error(`Gate config not found: ${t}`);let o=P.readFileSync(t,"utf8"),r=z.load(o);if(!r.version)throw new Error('Gate config missing required "version" field');let a=[],i=r,l=r.gates||i.portals;if(l)for(let[f,u]of Object.entries(l)){let h=f.startsWith("^")?f.slice(1):f;a.push(L(h,u));}if(r.include)for(let f of r.include){let u=b.join(s,f),h=await glob(u.replace(/\\/g,"/"));for(let g of h){let y=await Oe(g);a.push(...y);}}let p=[];if(r.flows)for(let[f,u]of Object.entries(r.flows))p.push(Fe(f,u));return {version:r.version,gates:a,flows:p,settings:{dev:{...ze,...r.settings?.dev}}}}async function Oe(e){let t=P.readFileSync(e,"utf8"),s=z.load(t);if(s.id){let o=s.id,r=o.startsWith("^")?o.slice(1):o;return [L(r,s)]}if(s.gates){let o=[];for(let[r,a]of Object.entries(s.gates)){let i=r.startsWith("^")?r.slice(1):r;o.push(L(i,a));}return o}return []}function L(e,t){let s=[];if(t.locks)for(let r of t.locks)s.push(Re(r));let o=[];if(t.prizes)for(let r of t.prizes)o.push(Ee(r));return {id:e,description:t.description,locks:s,prizes:o,position:t.position}}function Re(e){let t=e,s=[];if(t.keys){for(let o of t.keys)if(typeof o=="string")s.push({expression:o});else if(o.expression){let r=o;s.push({expression:r.expression,description:r.description});}}return {id:t.id,description:t.description,keys:s,mode:t.mode||"all"}}function Ee(e){let t=e;return {id:t.id,oneTime:t.oneTime??false,metadata:t.metadata}}function Fe(e,t){return {id:e,description:t.description,gates:t.gates||[],forkable:t.forkable}}async function te(e){let t=b.resolve(e);return await glob("**/portal.yaml",{cwd:t,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})}var Le={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},Me={"#":"component",$:"flow","^":"gate","!":"signal","~":"aspect"},Ge=["#","$","^","!","~"];function We(e){return Ge.includes(e)}var Ye=z$1.object({x:z$1.number(),y:z$1.number()}),Be=z$1.object({x:z$1.number(),y:z$1.number(),zoom:z$1.number()}),se=z$1.object({path:z$1.string(),include:z$1.array(z$1.string()).optional(),exclude:z$1.array(z$1.string()).optional()}),ne=z$1.object({id:z$1.string(),symbol:z$1.string(),type:z$1.enum(["feature","component","flow","state","aspect","gate","signal","idea"]),content:z$1.string().optional(),position:Ye,tags:z$1.array(z$1.string()).optional(),created:z$1.string(),modified:z$1.string().optional()}),re=z$1.object({from:z$1.string(),to:z$1.string(),label:z$1.string().optional(),type:z$1.string().optional()}),Ve=z$1.object({id:z$1.string(),name:z$1.string(),nodes:z$1.array(z$1.string()),color:z$1.string().optional()}),ae=z$1.object({viewport:Be,groups:z$1.array(Ve).optional()}),_e=z$1.object({nodes:z$1.array(ne),connections:z$1.array(re),layout:ae}),Ne=z$1.object({id:z$1.string(),name:z$1.string(),timestamp:z$1.string(),description:z$1.string().optional(),state:_e}),Ke=z$1.object({version:z$1.string(),metadata:z$1.object({name:z$1.string(),created:z$1.string(),modified:z$1.string()}),sources:z$1.object({purpose:z$1.array(se).optional(),portal:z$1.array(se).optional()}),nodes:z$1.array(ne),connections:z$1.array(re),layout:ae,snapshots:z$1.array(Ne).optional()});function ft(e){let t=[],s;try{s=P.readFileSync(e,"utf8");}catch(o){return t.push(`Cannot read file: ${o.message}`),{data:null,errors:t,rawContent:void 0}}return Ue(s)}function Ue(e){let t=[],s=null;try{s=z.load(e);}catch(r){let a=r,i=a.mark?.line?a.mark.line+1:void 0;return t.push(`YAML syntax error: ${a.reason||r.message}${i?` (line ${i})`:""}`),{data:null,errors:t,rawContent:e}}if(s==null)return {data:ie(),errors:[],rawContent:e};let o=Ke.safeParse(s);if(!o.success){for(let r of o.error.issues){let a=r.path.join(".");t.push(`Schema error at ${a||"/"}: ${r.message}`);}return {data:s,errors:t,rawContent:e}}return {data:o.data,errors:[],rawContent:e}}function ie(e="Untitled"){let t=new Date().toISOString();return {version:"1.0.0",metadata:{name:e,created:t,modified:t},sources:{purpose:[{path:"./"}],portal:[{path:"./portal.yaml"}]},nodes:[],connections:[],layout:{viewport:{x:0,y:0,zoom:1}}}}function qe(e){return e.metadata.modified=new Date().toISOString(),z.dump(e,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function lt(e="My Project"){return qe(ie(e))}function ut(e,t){return {...e,nodes:[...e.nodes,t],metadata:{...e.metadata,modified:new Date().toISOString()}}}function dt(e,t,s){return {...e,nodes:e.nodes.map(o=>o.id===t?{...o,position:s,modified:new Date().toISOString()}:o),metadata:{...e.metadata,modified:new Date().toISOString()}}}function mt(e,t){return e.connections.some(o=>o.from===t.from&&o.to===t.to)?e:{...e,connections:[...e.connections,t],metadata:{...e.metadata,modified:new Date().toISOString()}}}function ht(e,t,s){let o={id:`snap-${Date.now()}`,name:t,timestamp:new Date().toISOString(),description:s,state:{nodes:[...e.nodes],connections:[...e.connections],layout:{...e.layout}}};return {...e,snapshots:[...e.snapshots||[],o],metadata:{...e.metadata,modified:new Date().toISOString()}}}async function Ze(e,t){let s=[],o=[],r=[],a=[];if(e.sources.purpose)for(let p of e.sources.purpose){let f=b.resolve(t,p.path);try{let u=await N(f);r.push(...u.map(d=>d.filePath));let h=K(u);for(let[d,{item:m,filePath:$}]of h){let j=["feature",...m.tags||[]];s.push(w({id:`purpose-feature-${d}`,symbol:`#${d}`,type:"component",source:"purpose",filePath:$,data:m,description:m.description,tags:j,componentType:m.type,parentSymbol:m.parent,anchors:m.anchors?.map(ue=>M(ue))}));}let g=U(u);for(let[d,{item:m,filePath:$}]of g)s.push(w({id:`purpose-component-${d}`,symbol:`#${d}`,type:"component",source:"purpose",filePath:$,data:m,description:m.description,tags:m.tags,componentType:m.type,parentSymbol:m.parent,anchors:m.anchors?.map(j=>M(j))}));let y=q(u);for(let[d,{item:m,filePath:$}]of y)s.push(w({id:`purpose-gate-${d}`,symbol:`^${d}`,type:"gate",source:"purpose",filePath:$,data:m,description:m.description}));let S=Z(u);for(let[d,{item:m,filePath:$}]of S)s.push(w({id:`purpose-state-${d}`,symbol:`#${d}`,type:"component",source:"purpose",filePath:$,data:m,description:m.description,tags:["state"]}));let G=X(u);for(let[d,{item:m,filePath:$}]of G)s.push(w({id:`purpose-flow-${d}`,symbol:`$${d}`,type:"flow",source:"purpose",filePath:$,data:m,description:m.description}));let pe=H(u);for(let[d,{item:m,filePath:$}]of pe)s.push(w({id:`purpose-signal-${d}`,symbol:`!${d}`,type:"signal",source:"purpose",filePath:$,data:m,description:m.description}));let fe=J(u);for(let[d,{item:m,filePath:$}]of fe)s.push(w({id:`purpose-aspect-${d}`,symbol:`~${d}`,type:"aspect",source:"purpose",filePath:$,data:m,description:m.description,anchors:m.anchors?.map(j=>M(j)),appliesTo:m["applies-to"],tags:m.tags,enforcement:m.enforcement}));let le=Q(u),W=new Set(s.map(d=>d.symbol));for(let d of le)W.has(d.symbol)||(W.add(d.symbol),s.push(w({id:`purpose-ref-${d.type}-${d.symbol.slice(1)}`,symbol:d.symbol,type:d.type,source:"purpose",filePath:d.filePath,data:{referencedFrom:d.sourceSymbol},description:`Referenced from ${d.sourceSymbol}`})));}catch(u){o.push({source:"purpose",filePath:f,message:u.message});}}if(e.sources.portal)for(let p of e.sources.portal){let f=b.resolve(t,p.path);try{let u;if(f.endsWith(".yaml")||f.endsWith(".yml"))u=await O(f),a.push(f);else {let h=await te(f);if(a.push(...h),h.length>0){u=await O(h[0]);for(let g=1;g<h.length;g++){let y=await O(h[g]);u.gates.push(...y.gates),u.flows.push(...y.flows);}}else continue}for(let h of u.gates){s.push(Xe(h,f));for(let g of h.prizes)s.push(w({id:`gate-signal-${h.id}-${g.id}`,symbol:`!${g.id}`,type:"signal",source:"portal",filePath:f,data:g,description:`Signal from gate ${h.id}`}));}for(let h of u.flows)s.push(He(h,f));}catch(u){o.push({source:"portal",filePath:f,message:u.message});}}for(let p of e.nodes){let f=p.tags?.includes("idea");if(!p.content&&!f){let u=s.find(h=>h.symbol===p.symbol);if(u){u.position=p.position,u.tags=p.tags;continue}}s.push(w({id:p.id,symbol:p.symbol,type:p.type,source:"premise",filePath:".premise",data:p,description:p.content,position:p.position,tags:p.tags,created:p.created,modified:p.modified}));}Qe(s);let i=new Map;for(let p of s){let f=i.get(p.symbol)||[];f.includes(p.filePath)||f.push(p.filePath),i.set(p.symbol,f);}let l=[];for(let[p,f]of i)f.length>1&&l.push({symbol:p,files:f});return {symbols:s,purposeFiles:r,portalFiles:a,errors:o,timestamp:Date.now(),...l.length>0?{duplicateSymbols:l}:{}}}function w(e){return {...e,data:e.data??null,references:e.references??[],referencedBy:e.referencedBy??[]}}function Xe(e,t){let s=e.id.startsWith("^")?e.id.slice(1):e.id;return w({id:`gate-${s}`,symbol:`^${s}`,type:"gate",source:"portal",filePath:t,data:e,description:e.description,position:e.position})}function He(e,t){return w({id:`gate-flow-${e.id}`,symbol:`$${e.id}`,type:"flow",source:"portal",filePath:t,data:e,description:e.description})}function M(e){let t=e.lastIndexOf(":");if(t===-1||t===e.length-1)return {path:e,lines:0,raw:e};let s=e.slice(t+1),o=e.slice(0,t);if(!/^[\d,\- ]+$/.test(s))return {path:e,lines:0,raw:e};if(s.includes("-")){let[r,a]=s.split("-").map(Number);return {path:o,lines:[r,a],raw:e}}else if(s.includes(",")){let r=s.split(",").map(Number);return {path:o,lines:r,raw:e}}else return {path:o,lines:Number(s),raw:e}}var Je=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function Qe(e){let t=new Map(e.map(s=>[s.symbol,s]));for(let s of e){let o=JSON.stringify(s.data),r=/(?:\?[@#$%~^!]|[@#$%~^!?])[a-zA-Z][\w-]*/g,a=(o.match(r)||[]).filter(i=>!Je.has(i));for(let i of a)if(i!==s.symbol&&t.has(i)){s.references.includes(i)||s.references.push(i);let l=t.get(i);l&&!l.referencedBy.includes(s.symbol)&&l.referencedBy.push(s.symbol);}}}async function $t(e){let t={metadata:{name:b.basename(e),created:new Date().toISOString(),modified:new Date().toISOString()},sources:{purpose:[{path:"./"}],portal:[{path:"./"}]},nodes:[]};return Ze(t,e)}function et(){return {entries:new Map,byType:new Map,bySource:new Map,timestamp:0}}function wt(e){let t=et();t.timestamp=e.timestamp;for(let s of e.symbols)t.entries.set(s.id,s),t.byType.has(s.type)||t.byType.set(s.type,[]),t.byType.get(s.type).push(s),t.bySource.has(s.source)||t.bySource.set(s.source,[]),t.bySource.get(s.source).push(s);return t}function R(e,t){for(let s of e.entries.values())if(s.symbol===t)return s}function bt(e,t){return e.entries.get(t)}function I(e,t){return e.byType.get(t)||[]}function St(e,t){return e.bySource.get(t)||[]}function tt(e,t){let s=t.toLowerCase(),o=[];for(let r of e.entries.values()){if(r.symbol.toLowerCase().includes(s)){o.push(r);continue}if(r.description?.toLowerCase().includes(s)){o.push(r);continue}if(r.tags?.some(a=>a.toLowerCase().includes(s))){o.push(r);continue}if(r.componentType?.toLowerCase().includes(s)){o.push(r);continue}}return o}function vt(e,t){return I(e,"component").filter(o=>o.componentType===t)}function xt(e){let t=new Set,s=I(e,"component");for(let o of s)o.componentType&&t.add(o.componentType);return Array.from(t).sort()}function Pt(e,t){return I(e,"component").filter(o=>o.parentSymbol===t)}function kt(e,t){let s=R(e,t);return s?s.referencedBy.map(o=>R(e,o)).filter(o=>o!==void 0):[]}function jt(e,t){let s=R(e,t);return s?s.references.map(o=>R(e,o)).filter(o=>o!==void 0):[]}function Ct(e,t){let s=[];for(let o of e.entries.values())o.tags?.includes(t)&&s.push(o);return s}function At(e){let t=new Set;for(let s of e.entries.values())for(let o of s.tags||[])t.add(o);return Array.from(t).sort()}function It(e){let t={component:0,flow:0,gate:0,signal:0,aspect:0};for(let[s,o]of e.byType)s in t&&(t[s]=o.length);return t}function Dt(e){return Array.from(e.entries.values())}function ce(e){if(e.length<2)return null;let t=e[0],s=e.slice(1);return We(t)?{type:Me[t],name:s}:null}function zt(e,t){return `${Le[e]}${t}`}function Ot(e){return ce(e)!==null}function Rt(e,t,s=10){let o=t.toLowerCase(),r=ce(t);return r?I(e,r.type).filter(i=>i.symbol.toLowerCase().includes(o)).slice(0,s):tt(e,t).slice(0,s)}function st(e,t,s){if(b.isAbsolute(e))return {resolvedPath:e,baseUsed:"absolute",exists:P.existsSync(e)};let o=b.join(s,e);if(P.existsSync(o))return {resolvedPath:o,baseUsed:"project-root",exists:true};let r=b.resolve(t,e);return P.existsSync(r)?{resolvedPath:r,baseUsed:"purpose-dir",exists:true}:{resolvedPath:o,baseUsed:"project-root",exists:false}}function Et(e,t,s){if(b.isAbsolute(e)){let a=P.existsSync(e);return {rootResolves:a,purposeResolves:a,mismatch:false}}let o=P.existsSync(b.join(s,e)),r=P.existsSync(b.resolve(t,e));return {rootResolves:o,purposeResolves:r,mismatch:o!==r}}function ot(e,t){return e.includes("*")?new RegExp("^"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(t):e===t}function Ft(e,t,s){let o=[],r=I(e,"aspect"),a=new Set;for(let i of r){let l=i.appliesTo||[];if(l.length!==0)for(let p of l)for(let f of t){if(!ot(p,f))continue;let u=i.anchors||[];if(u.length===0){let h=`${i.symbol}::__no-anchors__`;a.has(h)||(a.add(h),o.push({aspectSymbol:i.symbol,anchorRaw:null,kind:"no-anchors"}));}else {let h=i.filePath?b.isAbsolute(i.filePath)?i.filePath:b.resolve(s,i.filePath):s,g=i.filePath?b.dirname(h):s;for(let y of u){let S=`${i.symbol}::${y.raw}`;if(a.has(S))continue;st(y.path,g,s).exists||(a.add(S),o.push({aspectSymbol:i.symbol,anchorRaw:y.raw,kind:"missing-file"}));}}}}return o}export{Me as PREFIX_TO_TYPE,Le as SYMBOL_PREFIXES,mt as addConnection,ut as addPremiseNode,$t as aggregateFromDirectory,Ze as aggregateFromPremise,wt as buildSymbolIndex,Ft as checkAspectAnchors,ie as createEmptyPremiseFile,ht as createSnapshot,et as createSymbolIndex,zt as createSymbolString,Et as detectAnchorBaseMismatch,xt as getAllComponentTypes,Dt as getAllSymbols,At as getAllTags,Rt as getAutocompleteSuggestions,Pt as getChildComponents,vt as getComponentsByType,lt as getDefaultPremiseContent,jt as getReferencesFrom,kt as getReferencesTo,R as getSymbol,bt as getSymbolById,It as getSymbolCounts,St as getSymbolsBySource,Ct as getSymbolsByTag,I as getSymbolsByType,Ot as isValidSymbol,Ue as parsePremiseContent,ft as parsePremiseFile,ce as parseSymbol,st as resolveAnchorPath,tt as searchSymbols,qe as serializePremiseFile,dt as updateNodePosition};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export{b as PREFIX_TO_TYPE,a as SYMBOL_PREFIXES,j as addConnection,h as addPremiseNode,m as aggregateFromDirectory,l as aggregateFromPremise,o as buildSymbolIndex,J as checkAspectAnchors,e as createEmptyPremiseFile,k as createSnapshot,n as createSymbolIndex,E as createSymbolString,I as detectAnchorBaseMismatch,v as getAllComponentTypes,C as getAllSymbols,A as getAllTags,G as getAutocompleteSuggestions,w as getChildComponents,u as getComponentsByType,g as getDefaultPremiseContent,y as getReferencesFrom,x as getReferencesTo,p as getSymbol,q as getSymbolById,B as getSymbolCounts,s as getSymbolsBySource,z as getSymbolsByTag,r as getSymbolsByType,F as isValidSymbol,d as parsePremiseContent,c as parsePremiseFile,D as parseSymbol,H as resolveAnchorPath,t as searchSymbols,f as serializePremiseFile,i as updateNodePosition}from'./chunk-4GC35IFF.js';import'./chunk-JIXHEBGK.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';