@a-company/paradigm 6.1.0 → 6.2.1

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 (29) hide show
  1. package/dist/arch-5UVPSOG2.js +3 -0
  2. package/dist/arch-loader-T3TARMSO.js +2 -0
  3. package/dist/chunk-ARLB6YYW.js +3 -0
  4. package/dist/chunk-EMGJWT7D.js +111 -0
  5. package/dist/chunk-MA75GS7J.js +635 -0
  6. package/dist/chunk-SU5F5D4I.js +3 -0
  7. package/dist/index.js +6 -6
  8. package/dist/mcp.js +3 -52
  9. package/dist/reindex-PJVOMN57.js +2 -0
  10. package/dist/tools-BPEKRC2U.js +2 -0
  11. package/dist/university-content/notes/.purpose +14 -0
  12. package/dist/university-content/notes/N-para-701-arch-mcp-tools.md +149 -0
  13. package/dist/university-content/notes/N-para-701-arch-yaml-format.md +123 -0
  14. package/dist/university-content/notes/N-para-701-atlas-agent.md +83 -0
  15. package/dist/university-content/paths/.purpose +12 -0
  16. package/dist/university-content/paths/LP-para-701.yaml +15 -0
  17. package/dist/university-content/quizzes/.purpose +14 -0
  18. package/dist/university-content/quizzes/Q-para-701-arch-mcp-tools.yaml +66 -0
  19. package/dist/university-content/quizzes/Q-para-701-arch-yaml-format.yaml +66 -0
  20. package/dist/university-content/quizzes/Q-para-701-atlas-agent.yaml +66 -0
  21. package/dist/university-content/quizzes/Q-plsat-v3.yaml +126 -1
  22. package/dist/university-ui/assets/{index-CkgaxOXi.js → index-SNyIB61M.js} +2 -2
  23. package/dist/university-ui/assets/{index-CkgaxOXi.js.map → index-SNyIB61M.js.map} +1 -1
  24. package/dist/university-ui/index.html +1 -1
  25. package/package.json +1 -1
  26. package/dist/chunk-K7EQHFZP.js +0 -111
  27. package/dist/chunk-MOVDVBU7.js +0 -605
  28. package/dist/reindex-GSRV4MQO.js +0 -2
  29. package/dist/tools-VNDXOFXR.js +0 -2
@@ -8,7 +8,7 @@
8
8
  <link rel="preconnect" href="https://fonts.googleapis.com">
9
9
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
10
10
  <link href="https://fonts.googleapis.com/css2?family=Crimson+Pro:ital,wght@0,400;0,500;0,600;0,700;1,400&family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
11
- <script type="module" crossorigin src="/assets/index-CkgaxOXi.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-SNyIB61M.js"></script>
12
12
  <link rel="stylesheet" crossorigin href="/assets/index-CMrxD7y5.css">
13
13
  </head>
14
14
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a-company/paradigm",
3
- "version": "6.1.0",
3
+ "version": "6.2.1",
4
4
  "description": "Unified CLI for Paradigm developer tools",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,111 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a as a$2,b as b$4,c as c$2}from'./chunk-M4UMM6DC.js';import {j,b as b$3,a as a$3}from'./chunk-GRZQIKST.js';import {j as j$1,a,c as c$1,b as b$2,k}from'./chunk-6QXBXZF6.js';import {b as b$1,a as a$1}from'./chunk-EK4ZRIFJ.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as w from'fs';import*as P from'path';import*as ie from'crypto';import {execSync}from'child_process';import*as z from'js-yaml';import {z as z$1}from'zod';import {glob}from'glob';import*as Ce from'os';import Xn from'sql.js';var rs={};c(rs,{contentSearch:()=>Bn,detectFileRename:()=>ss,generateFingerprint:()=>Zt,levenshteinDistance:()=>ts,levenshteinSimilarity:()=>Ze,searchSiblingFiles:()=>ns,slidingWindowSearch:()=>je});function Zt(t){let e=t.split(`
3
- `).filter(n=>n.trim()!=="");return {firstLine:Ae(e[0]||""),lastLine:Ae(e[e.length-1]||""),lineCount:e.length,structuralHash:es(e)}}function es(t){let e=t.map(n=>n.trim()).filter(n=>Jt.test(n)).map(n=>{let s=n.match(Jt);return s?s[1].trim():""}).join("|");return ie.createHash("sha256").update(e).digest("hex").slice(0,16)}function Ae(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function ts(t,e){if(t===e)return 0;if(t.length===0)return e.length;if(e.length===0)return t.length;t.length>e.length&&([t,e]=[e,t]);let n=t.length,s=e.length;if(n>5e3||s>5e3)return Math.abs(n-s);let r=new Array(n+1),o=new Array(n+1);for(let i=0;i<=n;i++)r[i]=i;for(let i=1;i<=s;i++){o[0]=i;for(let a=1;a<=n;a++){let c=t[a-1]===e[i-1]?0:1;o[a]=Math.min(r[a]+1,o[a-1]+1,r[a-1]+c);}[r,o]=[o,r];}return r[n]}function Ze(t,e){if(t.length===0&&e.length===0)return 1;let n=Math.max(t.length,e.length);return 1-ts(t,e)/n}function je(t,e,n,s=3){let{lineCount:r}=e,o=Math.max(1,Math.floor(r*.8)),i=Math.ceil(r*1.2),a=[],c=Qe(n);for(let d of [r,o,i])if(!(d>t.length))for(let u=0;u<=t.length-d;u++){let p=t.slice(u,u+d),g=Gn(p,e,c);if(g>=.5){let m=p.join(`
4
- `);a.push({windowStart:u+1,windowEnd:u+d,similarity:Ze(Qe(m),c),score:g});}}let l=new Map;for(let d of a){let u=l.get(d.windowStart);(!u||d.score>u.score)&&l.set(d.windowStart,d);}return Array.from(l.values()).sort((d,u)=>u.score-d.score).slice(0,s)}function Gn(t,e,n){let s=t.filter(p=>p.trim()!=="");if(s.length===0)return 0;let r=0,o=Ae(s[0]),i=Ae(s[s.length-1]),a=0;o===e.firstLine&&(a+=.5),i===e.lastLine&&(a+=.5),r+=a*Un,es(s)===e.structuralHash&&(r+=zn);let l=s.join(`
5
- `),d=Ze(Qe(l),n);d>=.8&&(r+=(d-.8)/.2*Hn);let u=s.length/e.lineCount;if(u>=.8&&u<=1.2){let p=1-Math.abs(1-u)/.2;r+=p*Wn;}return r}function Qe(t){return t.split(`
6
- `).map(e=>e.trim()).filter(e=>e!=="").join(`
7
- `)}function ss(t,e){try{let n=execSync(`git log --follow --diff-filter=R --name-status --format="" -- "${e}"`,{cwd:t,encoding:"utf8",timeout:5e3}).trim();if(!n)return null;let s=n.split(`
8
- `);for(let r of s){let o=r.split(" ");if(o.length>=3&&o[0].startsWith("R"))return o[2]}return null}catch{return null}}function ns(t,e,n,s,r=10){let o=P.isAbsolute(e)?e:P.join(t,e);if(!w.existsSync(o))return [];let i=[];try{let a=w.readdirSync(o).filter(c=>!c.startsWith(".")&&w.statSync(P.join(o,c)).isFile()).slice(0,r);for(let c of a)try{let d=w.readFileSync(P.join(o,c),"utf8").split(`
9
- `),u=je(d,n,s,1);if(u.length>0&&u[0].score>=.7){let p=P.relative(t,P.join(o,c));i.push({file:p,score:u[0].score,start:u[0].windowStart,end:u[0].windowEnd});}}catch{}}catch{return []}return i.sort((a,c)=>c.score-a.score)}function Bn(t,e,n,s=true){let r=Zt(n),o=P.isAbsolute(e)?e:P.join(t,e);if(w.existsSync(o)){let d=w.readFileSync(o,"utf8").split(`
10
- `),u=je(d,r,n);if(u.length>0){let p=u[0];return {found:p.score>=.7,score:p.score,suggestedStart:p.windowStart,suggestedEnd:p.windowEnd,similarity:p.similarity}}}let i=ss(t,e);if(i){let l=P.join(t,i);if(w.existsSync(l)){let u=w.readFileSync(l,"utf8").split(`
11
- `),p=je(u,r,n);if(p.length>0&&p[0].score>=.7)return {found:true,score:p[0].score,suggestedStart:p[0].windowStart,suggestedEnd:p[0].windowEnd,suggestedPath:i,similarity:p[0].similarity}}}let a=P.dirname(e),c=ns(t,a,r,n);if(c.length>0&&c[0].score>=.7){let l=c[0];return {found:true,score:l.score,suggestedStart:l.start,suggestedEnd:l.end,suggestedPath:l.file!==e?l.file:void 0,similarity:l.score}}return {found:false,score:0}}var Jt,Un,zn,Hn,Wn,os=b(()=>{Jt=/^\s*(function |class |if |else |for |while |switch |case |return |export |import |const |let |var |async |await |try |catch |throw |struct |enum |protocol |guard |def |fn )/;Un=.4,zn=.3,Hn=.2,Wn=.1;});var We=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(),xt=We.extend({id:z$1.string()}),Hs=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()}),Ws=z$1.union([Hs,z$1.string().transform(t=>({description:t}))]),Gs=z$1.object({from:z$1.string(),to:z$1.string(),type:z$1.string(),description:z$1.string().optional()}),Bs=z$1.union([Gs,z$1.string()]),Xs=z$1.object({component:z$1.string(),action:z$1.string(),description:z$1.string().optional()}),kt=z$1.union([Xs,z$1.string()]),qs=z$1.object({name:z$1.string(),description:z$1.string().optional(),steps:z$1.array(kt)}),Vs=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(kt).optional()}),Ys=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()}),Ks=z$1.object({description:z$1.string().optional(),default:z$1.unknown().optional(),type:z$1.string().optional()}),Js=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()}),Qs=z$1.object({target:z$1.string(),type:z$1.string(),path:z$1.string()}),Zs=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(xt),z$1.record(We)]).optional(),components:z$1.union([z$1.array(xt),z$1.record(We)]).optional(),gates:z$1.record(Ys).optional(),states:z$1.record(Ks).optional(),signals:z$1.record(Ws).optional(),aspects:z$1.record(Js).optional(),relationships:z$1.array(Bs).optional(),flows:z$1.union([z$1.array(qs),z$1.record(Vs)]).optional(),references:z$1.array(Qs).optional()});function Ge(t){let e=en(t);return {data:e.data,errors:e.errors}}function en(t){let e=[],n=[],s;try{s=w.readFileSync(t,"utf8");}catch(a){let c=`Cannot read file: ${a.message}`;return e.push(c),n.push({message:c,type:"file"}),{data:null,errors:e,detailedErrors:n,rawContent:void 0,isYamlValid:false}}let r=s.replace(/^([#~!$^][\w-]+):/gm,'"$1":').replace(/^(\s*-\s+)([!#][\w-]+)$/gm,'$1"$2"'),o=null;try{o=z.load(r);}catch(a){let c=a,l=c.mark?.line?c.mark.line+1:void 0,d=`YAML syntax error: ${c.reason||a.message}`;return e.push(`${d}${l?` (line ${l})`:""}`),n.push({message:d,line:l,type:"yaml"}),{data:null,errors:e,detailedErrors:n,rawContent:s,isYamlValid:false}}if(o==null)return {data:{},errors:[],detailedErrors:[],rawContent:s,isYamlValid:true};if(typeof o=="object"&&o!==null){let a=o,c={"#":"components",$:"flows","^":"gates","!":"signals","~":"aspects"};for(let l of Object.keys(a)){let d=l[0],u=c[d];if(!u||l.length<2)continue;let p=l.slice(1),g=a[l];if(typeof g!="object"||g===null)continue;let m=a[u]||{};u in a||(a[u]=m),p in m||(m[p]=g),delete a[l];}}let i=Zs.safeParse(o);if(!i.success){for(let a of i.error.issues){let c=a.path.join("."),l=a.message;e.push(`Schema error at ${c||"/"}: ${l}`),n.push({message:l,path:c||"/",type:"schema"});}return {data:o,errors:e,detailedErrors:n,rawContent:s,isYamlValid:true}}return {data:i.data,errors:[],detailedErrors:[],rawContent:s,isYamlValid:true}}function eo(t){return z.dump(t,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function _e(t){return t?Array.isArray(t)?t.map(e=>[e.id,e]):Object.entries(t):[]}async function sn(t){let e=P.resolve(t);return (await glob("**/.purpose",{cwd:e,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})).sort((s,r)=>{let o=s.split(P.sep).length,i=r.split(P.sep).length;return o-i})}async function _t(t){let e=await sn(t),n=[];for(let s of e){let{data:r,errors:o}=Ge(s);r&&(n.push({filePath:s,data:r}),o.length>0&&console.warn(`Warnings parsing ${s}:`,o));}return n}function Pt(t){let e=new Map;for(let{filePath:n,data:s}of t){let r=_e(s.features);for(let[o,i]of r)e.set(o,{item:i,filePath:n});}return e}function Rt(t){let e=new Map;for(let{filePath:n,data:s}of t){let r=_e(s.components);for(let[o,i]of r)e.set(o,{item:i,filePath:n});}return e}function It(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.gates)for(let[r,o]of Object.entries(s.gates))e.set(r,{item:o,filePath:n});return e}function $t(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.states)for(let[r,o]of Object.entries(s.states))e.set(r,{item:o,filePath:n});return e}function Ct(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.flows)if(Array.isArray(s.flows))for(let r of s.flows)e.set(r.name,{item:{id:r.name,description:r.description,steps:r.steps},filePath:n});else for(let[r,o]of Object.entries(s.flows))e.set(r,{item:{id:r,description:o.description,gates:o.gates,signals:o.signals,components:o.components,steps:o.steps},filePath:n});return e}function At(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.signals)for(let[r,o]of Object.entries(s.signals))e.set(r,{item:o,filePath:n});return e}function jt(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.aspects)for(let[r,o]of Object.entries(s.aspects))e.set(r,{item:o,filePath:n});return e}function Lt(t){let e=[],n=new Set;for(let{filePath:s,data:r}of t){let o=_e(r.features);for(let[a,c]of o)vt(`#${a}`,c,s,e,n);let i=_e(r.components);for(let[a,c]of i)vt(`#${a}`,c,s,e,n);}return e}function vt(t,e,n,s,r){if(e.flows)for(let o of e.flows){let i=o.startsWith("$")?o:`$${o}`;r.has(i)||(r.add(i),s.push({symbol:i,type:"flow",sourceSymbol:t,filePath:n}));}if(e.gates)for(let o of e.gates){let i=o.startsWith("^")?o:`^${o}`;r.has(i)||(r.add(i),s.push({symbol:i,type:"gate",sourceSymbol:t,filePath:n}));}if(e.signals)for(let o of e.signals){let i=o.startsWith("!")?o:`!${o}`;r.has(i)||(r.add(i),s.push({symbol:i,type:"signal",sourceSymbol:t,filePath:n}));}if(e.states)for(let o of e.states){let i=o.startsWith("#")?o:o.startsWith("%")?`#${o.slice(1)}`:`#${o}`;r.has(i)||(r.add(i),s.push({symbol:i,type:"component",sourceSymbol:t,filePath:n}));}if(e.components)for(let o of e.components){let i=o.startsWith("#")?o:`#${o}`;r.has(i)||(r.add(i),s.push({symbol:i,type:"component",sourceSymbol:t,filePath:n}));}if(e.aspects)for(let o of e.aspects){let i=o.startsWith("~")?o:`~${o}`;r.has(i)||(r.add(i),s.push({symbol:i,type:"aspect",sourceSymbol:t,filePath:n}));}if(e.description){let o=rn(e.description);for(let{symbol:i,type:a}of o)r.has(i)||(r.add(i),s.push({symbol:i,type:a,sourceSymbol:t,filePath:n}));}}var nn=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function rn(t){let e=[],n=/([$^!#~%])([a-zA-Z][a-zA-Z0-9._-]*)/g,s;for(;(s=n.exec(t))!==null;){let r=s[1],o=s[2],i,a;switch(r){case "#":a="component",i=`#${o}`;break;case "$":a="flow",i=`$${o}`;break;case "^":a="gate",i=`^${o}`;break;case "!":a="signal",i=`!${o}`;break;case "~":a="aspect",i=`~${o}`;break;case "%":a="component",i=`#${o}`;break;default:continue}nn.has(i)||e.push({symbol:i,type:a});}return e}function me(t){return t?Array.isArray(t)?t.map(e=>[e.id,e]):Object.entries(t):[]}function He(t){return t?Array.isArray(t)?t.map(e=>e.id):Object.keys(t):[]}function so(t,e){let n=[],s=e?`${e}: `:"",r=me(t.features);for(let[i,a]of r)Et(i,a,"feature",s,n);let o=me(t.components);for(let[i,a]of o)Et(i,a,"component",s,n);if(t.relationships){let i=new Set([...He(t.features),...He(t.components)]);for(let a of t.relationships){if(typeof a=="string"||!a||!a.from||!a.to)continue;let c=a.from.replace(/^[@#$%~^!?]/,"");!i.has(c)&&!a.from.includes(".")&&n.push({type:"warning",message:`${s}Relationship references unknown source: "${a.from}"`,path:"relationships"});let l=a.to.replace(/^[@#$%~^!?]/,"");!i.has(l)&&!a.to.includes(".")&&n.push({type:"warning",message:`${s}Relationship references unknown target: "${a.to}"`,path:"relationships"});}}if(t.flows){let i=new Set(He(t.components));if(Array.isArray(t.flows)){for(let a of t.flows)if(!(!a||typeof a!="object")&&(a.name||n.push({type:"error",message:`${s}Flow missing required "name" field`,path:"flows"}),a.steps&&Array.isArray(a.steps)))for(let c of a.steps){if(typeof c=="string"||!c||!c.component)continue;let l=c.component.replace(/^#/,"");i.has(l)||n.push({type:"warning",message:`${s}Flow "${a.name}" references unknown component: "${c.component}"`,path:`flows.${a.name}`});}}else for(let[a,c]of Object.entries(t.flows))if(!(!c||typeof c!="object")&&c.steps&&Array.isArray(c.steps))for(let l of c.steps){if(typeof l=="string"||!l||!l.component)continue;let d=l.component.replace(/^#/,"");i.has(d)||n.push({type:"warning",message:`${s}Flow "${a}" references unknown component: "${l.component}"`,path:`flows.${a}`});}}return {valid:n.filter(i=>i.type==="error").length===0,issues:n}}function Et(t,e,n,s,r){let o=`${n}s.${t}`;if(/^[a-zA-Z][a-zA-Z0-9-]*$/.test(t)||r.push({type:"warning",message:`${s}${n} ID "${t}" should use alphanumeric characters and hyphens`,path:o}),(!e.description||e.description.trim()==="")&&r.push({type:"warning",message:`${s}${n} "${t}" has no description`,path:o}),e.endpoints)for(let i of e.endpoints)/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+\//.test(i)||r.push({type:"warning",message:`${s}Endpoint "${i}" in ${n} "${t}" may not be in standard format (e.g., "GET /api/users")`,path:`${o}.endpoints`});}function Ot(t){let e=[],n=new Set;for(let{data:s}of t){let r=me(s.components);for(let[i]of r)n.add(`#${i}`),n.add(i);let o=me(s.features);for(let[i]of o)n.add(`#${i}`),n.add(i);if(s.gates)for(let i of Object.keys(s.gates))n.add(`^${i}`),n.add(i);if(s.signals)for(let i of Object.keys(s.signals))n.add(`!${i}`),n.add(i);if(s.flows)if(Array.isArray(s.flows))for(let i of s.flows)i?.name&&(n.add(`$${i.name}`),n.add(i.name));else for(let i of Object.keys(s.flows))n.add(`$${i}`),n.add(i);if(s.aspects)for(let i of Object.keys(s.aspects))n.add(`~${i}`),n.add(i);if(s.states)for(let i of Object.keys(s.states))n.add(`#${i}`),n.add(i);}for(let{filePath:s,data:r}of t){let o=s?`${s}: `:"",i=[...me(r.components),...me(r.features)];for(let[a,c]of i){if(c.parent){let d=c.parent.replace(/^["']|["']$/g,""),u=d.replace(/^[#$^!~@%?&]/,"");!n.has(d)&&!n.has(u)&&e.push({type:"warning",message:`${o}Component "${a}" references parent "${d}" which is not defined in any .purpose file`,path:`components.${a}.parent`});}let l=[{field:"gates",refs:c.gates},{field:"signals",refs:c.signals},{field:"flows",refs:c.flows},{field:"components",refs:c.components},{field:"aspects",refs:c.aspects}];for(let{field:d,refs:u}of l)if(u)for(let p of u){let g=p.replace(/^[#$^!~@%?&]/,"");!n.has(p)&&!n.has(g)&&e.push({type:"warning",message:`${o}Symbol "${a}" references ${d} "${p}" which is not defined`,path:`components.${a}.${d}`});}}if(r.flows){if(Array.isArray(r.flows)){for(let a of r.flows)if(a?.steps)for(let c of a.steps){if(typeof c=="string"||!c?.component)continue;let l=c.component.replace(/^#/,"");!n.has(c.component)&&!n.has(l)&&e.push({type:"warning",message:`${o}Flow "${a.name}" step references "${c.component}" which is not defined`,path:`flows.${a.name}.steps`});}}else for(let[a,c]of Object.entries(r.flows))if(c?.steps)for(let l of c.steps){if(typeof l=="string"||!l?.component)continue;let d=l.component.replace(/^#/,"");!n.has(l.component)&&!n.has(d)&&e.push({type:"warning",message:`${o}Flow "${a}" step references "${l.component}" which is not defined`,path:`flows.${a}.steps`});}}}return {valid:e.filter(s=>s.type==="error").length===0,issues:e}}var on={visualizerPort:42195,watcherPort:42196,autoConnect:true};async function Ie(t){let e=P.resolve(t),n=P.dirname(e);if(!w.existsSync(e))throw new Error(`Gate config not found: ${e}`);let s=w.readFileSync(e,"utf8"),r=z.load(s);if(!r.version)throw new Error('Gate config missing required "version" field');let o=[],i=r,a=r.gates||i.portals;if(a)for(let[l,d]of Object.entries(a)){let u=l.startsWith("^")?l.slice(1):l;o.push(Be(u,d));}if(r.include)for(let l of r.include){let d=P.join(n,l),u=await glob(d.replace(/\\/g,"/"));for(let p of u){let g=await an(p);o.push(...g);}}let c=[];if(r.flows)for(let[l,d]of Object.entries(r.flows))c.push(dn(l,d));return {version:r.version,gates:o,flows:c,settings:{dev:{...on,...r.settings?.dev}}}}async function an(t){let e=w.readFileSync(t,"utf8"),n=z.load(e);if(n.id){let s=n.id,r=s.startsWith("^")?s.slice(1):s;return [Be(r,n)]}if(n.gates){let s=[];for(let[r,o]of Object.entries(n.gates)){let i=r.startsWith("^")?r.slice(1):r;s.push(Be(i,o));}return s}return []}function Be(t,e){let n=[];if(e.locks)for(let r of e.locks)n.push(cn(r));let s=[];if(e.prizes)for(let r of e.prizes)s.push(ln(r));return {id:t,description:e.description,locks:n,prizes:s,position:e.position}}function cn(t){let e=t,n=[];if(e.keys){for(let s of e.keys)if(typeof s=="string")n.push({expression:s});else if(s.expression){let r=s;n.push({expression:r.expression,description:r.description});}}return {id:e.id,description:e.description,keys:n,mode:e.mode||"all"}}function ln(t){let e=t;return {id:e.id,oneTime:e.oneTime??false,metadata:e.metadata}}function dn(t,e){return {id:t,description:e.description,gates:e.gates||[],forkable:e.forkable}}async function Nt(t){let e=P.resolve(t);return await glob("**/portal.yaml",{cwd:e,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})}function Dt(t){if(t instanceof z.YAMLException){let e=(t.reason||"").toLowerCase();return e.includes("duplicated mapping key")||e.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(s=>e.includes(s))?{errorClass:"syntax",detail:"yaml syntax error"}:{errorClass:"other",detail:"yaml parse error"}}return {errorClass:"other",detail:"yaml parse error"}}var un=z$1.object({x:z$1.number(),y:z$1.number()}),pn=z$1.object({x:z$1.number(),y:z$1.number(),zoom:z$1.number()}),Ut=z$1.object({path:z$1.string(),include:z$1.array(z$1.string()).optional(),exclude:z$1.array(z$1.string()).optional()}),Ht=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:un,tags:z$1.array(z$1.string()).optional(),created:z$1.string(),modified:z$1.string().optional()}),Wt=z$1.object({from:z$1.string(),to:z$1.string(),label:z$1.string().optional(),type:z$1.string().optional()}),fn=z$1.object({id:z$1.string(),name:z$1.string(),nodes:z$1.array(z$1.string()),color:z$1.string().optional()}),Gt=z$1.object({viewport:pn,groups:z$1.array(fn).optional()}),mn=z$1.object({nodes:z$1.array(Ht),connections:z$1.array(Wt),layout:Gt}),gn=z$1.object({id:z$1.string(),name:z$1.string(),timestamp:z$1.string(),description:z$1.string().optional(),state:mn});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(Ut).optional(),portal:z$1.array(Ut).optional()}),nodes:z$1.array(Ht),connections:z$1.array(Wt),layout:Gt,snapshots:z$1.array(gn).optional()});async function hn(t,e){let n=[],s=[],r=[],o=[];if(t.sources.purpose)for(let c of t.sources.purpose){let l=P.resolve(e,c.path);try{let d=await _t(l);r.push(...d.map(b=>b.filePath));let u=Pt(d);for(let[b,{item:S,filePath:x}]of u){let k=["feature",...S.tags||[]];n.push(G({id:`purpose-feature-${b}`,symbol:`#${b}`,type:"component",source:"purpose",filePath:x,data:S,description:S.description,tags:k,componentType:S.type,parentSymbol:S.parent,anchors:S.anchors?.map(E=>Xe(E))}));}let p=Rt(d);for(let[b,{item:S,filePath:x}]of p)n.push(G({id:`purpose-component-${b}`,symbol:`#${b}`,type:"component",source:"purpose",filePath:x,data:S,description:S.description,tags:S.tags,componentType:S.type,parentSymbol:S.parent,anchors:S.anchors?.map(k=>Xe(k))}));let g=It(d);for(let[b,{item:S,filePath:x}]of g)n.push(G({id:`purpose-gate-${b}`,symbol:`^${b}`,type:"gate",source:"purpose",filePath:x,data:S,description:S.description}));let m=$t(d);for(let[b,{item:S,filePath:x}]of m)n.push(G({id:`purpose-state-${b}`,symbol:`#${b}`,type:"component",source:"purpose",filePath:x,data:S,description:S.description,tags:["state"]}));let h=Ct(d);for(let[b,{item:S,filePath:x}]of h)n.push(G({id:`purpose-flow-${b}`,symbol:`$${b}`,type:"flow",source:"purpose",filePath:x,data:S,description:S.description}));let v=At(d);for(let[b,{item:S,filePath:x}]of v)n.push(G({id:`purpose-signal-${b}`,symbol:`!${b}`,type:"signal",source:"purpose",filePath:x,data:S,description:S.description}));let T=jt(d);for(let[b,{item:S,filePath:x}]of T)n.push(G({id:`purpose-aspect-${b}`,symbol:`~${b}`,type:"aspect",source:"purpose",filePath:x,data:S,description:S.description,anchors:S.anchors?.map(k=>Xe(k)),appliesTo:S["applies-to"],tags:S.tags,enforcement:S.enforcement}));let C=Lt(d),N=new Set(n.map(b=>b.symbol));for(let b of C)N.has(b.symbol)||(N.add(b.symbol),n.push(G({id:`purpose-ref-${b.type}-${b.symbol.slice(1)}`,symbol:b.symbol,type:b.type,source:"purpose",filePath:b.filePath,data:{referencedFrom:b.sourceSymbol},description:`Referenced from ${b.sourceSymbol}`})));}catch(d){s.push({source:"purpose",filePath:l,message:d.message});}}if(t.sources.portal)for(let c of t.sources.portal){let l=P.resolve(e,c.path);try{let d;if(l.endsWith(".yaml")||l.endsWith(".yml"))d=await Ie(l),o.push(l);else {let u=await Nt(l);if(o.push(...u),u.length>0){d=await Ie(u[0]);for(let p=1;p<u.length;p++){let g=await Ie(u[p]);d.gates.push(...g.gates),d.flows.push(...g.flows);}}else continue}for(let u of d.gates){n.push(yn(u,l));for(let p of u.prizes)n.push(G({id:`gate-signal-${u.id}-${p.id}`,symbol:`!${p.id}`,type:"signal",source:"portal",filePath:l,data:p,description:`Signal from gate ${u.id}`}));}for(let u of d.flows)n.push(wn(u,l));}catch(d){s.push({source:"portal",filePath:l,message:d.message});}}for(let c of t.nodes){let l=c.tags?.includes("idea");if(!c.content&&!l){let d=n.find(u=>u.symbol===c.symbol);if(d){d.position=c.position,d.tags=c.tags;continue}}n.push(G({id:c.id,symbol:c.symbol,type:c.type,source:"premise",filePath:".premise",data:c,description:c.content,position:c.position,tags:c.tags,created:c.created,modified:c.modified}));}Sn(n);let i=new Map;for(let c of n){let l=i.get(c.symbol)||[];l.includes(c.filePath)||l.push(c.filePath),i.set(c.symbol,l);}let a=[];for(let[c,l]of i)l.length>1&&a.push({symbol:c,files:l});return {symbols:n,purposeFiles:r,portalFiles:o,errors:s,timestamp:Date.now(),...a.length>0?{duplicateSymbols:a}:{}}}function G(t){return {...t,data:t.data??null,references:t.references??[],referencedBy:t.referencedBy??[]}}function yn(t,e){let n=t.id.startsWith("^")?t.id.slice(1):t.id;return G({id:`gate-${n}`,symbol:`^${n}`,type:"gate",source:"portal",filePath:e,data:t,description:t.description,position:t.position})}function wn(t,e){return G({id:`gate-flow-${t.id}`,symbol:`$${t.id}`,type:"flow",source:"portal",filePath:e,data:t,description:t.description})}function Xe(t){let e=t.lastIndexOf(":");if(e===-1||e===t.length-1)return {path:t,lines:0,raw:t};let n=t.slice(e+1),s=t.slice(0,e);if(!/^[\d,\- ]+$/.test(n))return {path:t,lines:0,raw:t};if(n.includes("-")){let[r,o]=n.split("-").map(Number);return {path:s,lines:[r,o],raw:t}}else if(n.includes(",")){let r=n.split(",").map(Number);return {path:s,lines:r,raw:t}}else return {path:s,lines:Number(n),raw:t}}var bn=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function Sn(t){let e=new Map(t.map(n=>[n.symbol,n]));for(let n of t){let s=JSON.stringify(n.data),r=/(?:\?[@#$%~^!]|[@#$%~^!?])[a-zA-Z][\w-]*/g,o=(s.match(r)||[]).filter(i=>!bn.has(i));for(let i of o)if(i!==n.symbol&&e.has(i)){n.references.includes(i)||n.references.push(i);let a=e.get(i);a&&!a.referencedBy.includes(n.symbol)&&a.referencedBy.push(n.symbol);}}}async function Bt(t){let e={metadata:{name:P.basename(t),created:new Date().toISOString(),modified:new Date().toISOString()},sources:{purpose:[{path:"./"}],portal:[{path:"./"}]},nodes:[]};return hn(e,t)}function xn(){return {entries:new Map,byType:new Map,bySource:new Map,timestamp:0}}function uo(t){let e=xn();e.timestamp=t.timestamp;for(let n of t.symbols)e.entries.set(n.id,n),e.byType.has(n.type)||e.byType.set(n.type,[]),e.byType.get(n.type).push(n),e.bySource.has(n.source)||e.bySource.set(n.source,[]),e.bySource.get(n.source).push(n);return e}function $e(t,e){for(let n of t.entries.values())if(n.symbol===e)return n}function po(t,e){return t.byType.get(e)||[]}function fo(t,e){let n=e.toLowerCase(),s=[];for(let r of t.entries.values()){if(r.symbol.toLowerCase().includes(n)){s.push(r);continue}if(r.description?.toLowerCase().includes(n)){s.push(r);continue}if(r.tags?.some(o=>o.toLowerCase().includes(n))){s.push(r);continue}if(r.componentType?.toLowerCase().includes(n)){s.push(r);continue}}return s}function mo(t,e){let n=$e(t,e);return n?n.referencedBy.map(s=>$e(t,s)).filter(s=>s!==void 0):[]}function go(t,e){let n=$e(t,e);return n?n.references.map(s=>$e(t,s)).filter(s=>s!==void 0):[]}function ho(t){let e={component:0,flow:0,gate:0,signal:0,aspect:0};for(let[n,s]of t.byType)n in e&&(e[n]=s.length);return e}function yo(t){return Array.from(t.entries.values())}var vn="0.1.0",En="1.0.0";function qe(t,e){let n={$meta:Tn(e.projectName,t),components:{},features:{},flows:{},state:{},gates:{},signals:{},aspects:{},screens:{},symbolMap:{}};for(let r of t.symbols)kn(r,n,e);if(e.screenDefinitions)for(let[r,o]of Object.entries(e.screenDefinitions))n.screens[r]||(n.screens[r]={id:r,name:re(r),route:o.route,path:"",components:o.components,features:o.features});let s={};for(let r of Object.values(n.components))r.componentType&&(s[r.componentType]=(s[r.componentType]||0)+1);for(let r of Object.values(n.features))r.componentType&&(s[r.componentType]=(s[r.componentType]||0)+1);return Object.keys(s).length>0&&(n.$meta.componentTypes=s),jn(n),n}function Tn(t,e){return {version:En,project:t,generatedAt:new Date().toISOString(),paradigmVersion:vn,sources:{purposeFiles:e.purposeFiles.length,portalFiles:e.portalFiles.length,premiseFiles:e.symbols.filter(n=>n.source==="premise").length>0?1:0}}}function kn(t,e,n){let{type:s}=t;switch(s){case "component":_n(t,e,n);break;case "feature":Pn(t,e,n);break;case "flow":Rn(t,e);break;case "state":In(t,e);break;case "gate":$n(t,e);break;case "signal":Cn(t,e);break;case "aspect":An(t,e);break;}}function _n(t,e,n){let s=le(t.symbol),r=Xt(s,t.data,n.visualTagMappings),o={id:s,name:re(s),symbol:t.symbol,category:"components",path:t.filePath,description:t.description,visualTags:r,related:t.references,componentType:t.componentType,parent:t.parentSymbol};e.components[s]=o,e.symbolMap[t.symbol]={category:"components",id:s};}function Pn(t,e,n){let s=le(t.symbol),r=Xt(s,t.data,n.visualTagMappings),o={id:s,name:re(s),symbol:t.symbol,category:"features",path:t.filePath,description:t.description,visualTags:r,related:t.references,componentType:t.componentType,parent:t.parentSymbol};e.features[s]=o,e.symbolMap[t.symbol]={category:"features",id:s};}function Rn(t,e){let n=le(t.symbol),s=t.data,r=[];if(s?.steps)for(let i=0;i<s.steps.length;i++){let a=s.steps[i];r.push({id:`${n}-step-${i}`,name:a.action||`Step ${i+1}`,target:a.component,description:a.description,order:i});}let o={id:n,name:re(n),symbol:t.symbol,path:t.filePath,description:t.description,steps:r};e.flows[n]=o,e.symbolMap[t.symbol]={category:"flows",id:n};}function In(t,e){let n=le(t.symbol),s={id:n,name:re(n),symbol:t.symbol,path:t.filePath,description:t.description,consumers:t.referencedBy};e.state[n]=s,e.symbolMap[t.symbol]={category:"state",id:n};}function $n(t,e){let n=le(t.symbol),s={id:n,name:re(n),symbol:t.symbol,category:"gates",path:t.filePath,description:t.description,related:t.references};e.gates[n]=s,e.symbolMap[t.symbol]={category:"gates",id:n};}function Cn(t,e){let n=le(t.symbol),s={id:n,name:re(n),symbol:t.symbol,category:"signals",path:t.filePath,description:t.description,related:t.references};e.signals[n]=s,e.symbolMap[t.symbol]={category:"signals",id:n};}function An(t,e){let n=le(t.symbol),s={id:n,name:re(n),symbol:t.symbol,category:"aspects",path:t.filePath,description:t.description,related:t.references};e.aspects[n]=s,e.symbolMap[t.symbol]={category:"aspects",id:n};}function jn(t){for(let e of Object.values(t.screens))if(e.components)for(let n of e.components){let s=t.components[n];s&&(s.screens=s.screens||[],s.screens.includes(e.id)||s.screens.push(e.id));}}function le(t){return t.slice(1)}function re(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Xt(t,e,n){let s=[];if(n?.[t])return n[t];let r=[[/button/i,"button"],[/btn/i,"button"],[/form/i,"form"],[/input/i,"input"],[/field/i,"input"],[/select/i,"input"],[/card/i,"card"],[/list/i,"list"],[/table/i,"list"],[/modal/i,"modal"],[/dialog/i,"modal"],[/drawer/i,"modal"],[/nav/i,"nav"],[/menu/i,"menu"],[/dropdown/i,"menu"],[/header/i,"header"],[/footer/i,"footer"],[/sidebar/i,"sidebar"],[/hero/i,"hero"],[/grid/i,"grid"],[/chart/i,"chart"],[/graph/i,"chart"],[/icon/i,"icon"],[/image/i,"image"],[/avatar/i,"avatar"],[/badge/i,"badge"],[/tag/i,"badge"],[/tab/i,"tab"],[/accordion/i,"accordion"],[/toast/i,"toast"],[/notification/i,"toast"],[/alert/i,"toast"],[/spinner/i,"spinner"],[/loader/i,"spinner"],[/loading/i,"spinner"],[/skeleton/i,"skeleton"]];for(let[o,i]of r)o.test(t)&&s.push(i);return s}function Ve(t){return JSON.stringify(t,null,2)}function Ye(t,e="unknown"){j$1().trackToolCall(e,t);}function Ro(t,e="paradigm://unknown"){j$1().trackResourceRead(e,t);}function Ln(){k();}function On(t,e){switch(t){case "paradigm_search":return {summary:`Searched for "${e.query}"${e.type?` (type: ${e.type})`:""}`,symbol:e.query};case "paradigm_ripple":return {summary:`Ripple analysis on ${e.symbol}${e.depth?` (depth: ${e.depth})`:""}`,symbol:e.symbol};case "paradigm_related":return {summary:`Checked relations for ${e.symbol}`,symbol:e.symbol};case "paradigm_status":return {summary:"Checked project status"};case "paradigm_navigate":{let n=e.intent,s=e.target,r=e.task;return n==="context"&&r?{summary:`Navigate context: "${r}"`}:s?{summary:`Navigate ${n||"find"}: ${s}`,symbol:s}:{summary:`Navigate (${n||"unknown"})`}}case "paradigm_gates_for_route":return {summary:`Gate suggestions for ${e.method||"GET"} ${e.route}`};case "paradigm_wisdom_context":return {summary:`Checked wisdom for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_context":return {summary:`Checked history for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_record":return {summary:`Recorded ${e.type}: ${(e.description||"").slice(0,60)}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_fragility":return {summary:`Checked fragility for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_flows_affected":return {summary:`Checked flows affected by ${e.symbol}`,symbol:e.symbol};case "paradigm_reindex":return {summary:"Rebuilt static index files"};case "paradigm_session_checkpoint":return {summary:`Checkpoint: phase=${e.phase}, ${(e.context||"").slice(0,60)}`};case "paradigm_task_create":return {summary:`Created task: "${(e.blurb||"").slice(0,60)}"`};case "paradigm_task_done":return {summary:`Completed task ${e.id}`};case "paradigm_task_shelve":return {summary:`Shelved task ${e.id}`};case "paradigm_task_list":return {summary:`Listed tasks (status: ${e.status||"open"})`};case "paradigm_task_update":return {summary:`Updated task ${e.id}`};case "paradigm_assessment_record":return {summary:`Assessment: ${(e.title||"").slice(0,60)} \u2192 ${e.arc_id}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_assessment_list":return {summary:e.arc_id?`Listed entries in ${e.arc_id}`:"Listed assessment arcs"};case "paradigm_assessment_search":return {summary:`Searched assessments${e.symbol?` for ${e.symbol}`:""}`,symbol:e.symbol};case "paradigm_assessment_arc_create":return {summary:`Created arc: ${e.id}`};case "paradigm_assessment_arc_close":return {summary:`Closed arc: ${e.arc_id}`};default:{let n=t.replace(/^paradigm_/,""),s=Object.values(e).find(r=>typeof r=="string"&&r.length>0);return {summary:s?`${n}: ${s.slice(0,60)}`:n,symbol:e.symbol||void 0}}}}function Io(t,e){let n=j$1(),{summary:s,symbol:r}=On(t,e);n.addBreadcrumb("tool-call",s,{tool:t,symbol:r});}function $o(){return [{name:"paradigm_session_health",description:"Check if context handoff is recommended based on session activity. Call this periodically during long sessions. Returns usage percentage and recommendation (continue, consider-handoff, handoff-recommended, handoff-urgent). ~100 tokens.",inputSchema:{type:"object",properties:{estimatedTotalTokens:{type:"number",description:"Optional: Your estimate of total conversation tokens (if available)"},contextWindowSize:{type:"number",description:"Context window size in tokens (default: 200000)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_context_check",description:"DEPRECATED: renamed to paradigm_session_health. This alias will be removed in a future version.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_handoff_prepare",description:"Prepare a handoff summary. Generates a structured handoff file with markdown summary and recovery instructions. Returns structured markdown with summary, modified files, and next steps. ~300 tokens.",inputSchema:{type:"object",properties:{summary:{type:"string",description:"Brief summary of work done in this session"},nextSteps:{type:"array",items:{type:"string"},description:"List of next steps for the continuing session"},agent:{type:"string",description:'Target agent role (e.g., "builder", "architect")'},modifiedFiles:{type:"array",items:{type:"string"},description:"List of files modified in this session"},symbolsTouched:{type:"array",items:{type:"string"},description:"List of symbols (@feature, #component, etc.) touched"},openQuestions:{type:"array",items:{type:"string"},description:"Unresolved questions or decisions needed"}},required:["summary"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_session_stats",description:"Get current session statistics (MCP interactions, estimated tokens). Returns tool call count, estimated tokens used, and cost breakdown. ~100 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_session_recover",description:"Load previous session breadcrumbs for continuity. Call this at the start of a new session to understand what was done before. Returns symbols modified, files explored, recent actions, and suggestions for continuity. ~200 tokens. NOTE: Recovery data is automatically surfaced as a preamble on the first tool call of each session \u2014 explicit calls are retained for direct inspection or forcing a second recovery pass.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["resume","pick up","continue","what was I doing","last session","recover"]},{name:"paradigm_session_checkpoint",description:"Save a cognitive-transition checkpoint for crash recovery. Call when transitioning between phases (planning \u2192 implementing \u2192 validating \u2192 complete). ~100 tokens.",inputSchema:{type:"object",properties:{phase:{type:"string",enum:["planning","implementing","validating","complete"],description:"Current workflow phase"},context:{type:"string",description:"What's top-of-mind right now (1-3 sentences)"},externalId:{type:"string",description:'Optional: deterministic ID from external source for automatic session recovery (e.g. "linear:PROJ-123", "github:owner/repo#42")'},plan:{type:"string",description:"Optional: the current plan or approach"},modifiedFiles:{type:"array",items:{type:"string"},description:"Optional: files modified so far"},symbolsTouched:{type:"array",items:{type:"string"},description:"Optional: symbols touched so far"},decisions:{type:"array",items:{type:"string"},description:"Optional: key decisions made so far"}},required:["phase","context"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function Co(t,e,n){let s=j$1();if(t==="paradigm_session_health"||t==="paradigm_context_check"){let r=e.contextWindowSize||2e5,o=e.estimatedTotalTokens,i=s.getStats(),{recommendation:a,message:c,usagePercent:l,signals:d}=s.getHandoffRecommendation(r,o),u=s.getDurationMinutes();return {handled:true,text:JSON.stringify({recommendation:a,message:c,stats:{sessionDurationMinutes:u,mcpToolCalls:i.totals.toolCallCount,mcpResourceReads:i.totals.resourceReadCount,estimatedMcpTokens:i.totals.totalTokens,estimatedTotalTokens:o||Math.round(i.totals.totalTokens*5),contextWindowSize:r,usagePercent:l},signals:d,action:a==="continue"?null:"Call paradigm_handoff_prepare to create handoff file"},null,2)}}if(t==="paradigm_handoff_prepare"){let r=e.summary,o=e.nextSteps||[],i=e.agent||"builder",a$1=e.modifiedFiles||[],c=e.symbolsTouched||[],l=e.openQuestions||[],d=s.getStats(),u=s.getCostBreakdown(),p=`h${Date.now().toString(36)}`,g=new Date().toISOString(),m={id:p,timestamp:g,from:"current-session",to:i,summary:r,nextSteps:o,modifiedFiles:a$1,symbolsTouched:c,openQuestions:l,sessionStats:{duration:s.getDurationMinutes(),mcpCalls:d.totals.toolCallCount+d.totals.resourceReadCount,estimatedTokens:d.totals.totalTokens,estimatedCostUsd:u.total.costUsd,model:u.model},status:"pending"},h=false;try{a(n.rootDir,m),h=!0;}catch{}let v=`# Handoff: ${g}
12
-
13
- ## Session Summary
14
- ${r}
15
-
16
- ## Next Steps
17
- ${o.map((T,C)=>`${C+1}. ${T}`).join(`
18
- `)||"(none specified)"}
19
-
20
- ## Key Context
21
- - Modified files: ${a$1.length>0?a$1.join(", "):"(not specified)"}
22
- - Symbols touched: ${c.length>0?c.join(", "):"(not specified)"}
23
- - Open questions: ${l.length>0?l.join(", "):"(none)"}
24
- `;return Ln(),{handled:true,text:JSON.stringify({handoff:m,markdownSummary:v,persisted:h,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(t==="paradigm_session_stats"){let r=s.getStats(),o=s.getCostBreakdown(),i=s.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(r.startTime).toISOString(),durationMinutes:i,lastActivity:new Date(r.lastActivity).toISOString()},model:{name:o.model,id:o.modelId,pricing:{inputPerMillion:`$${o.pricing.input.toFixed(2)}`,outputPerMillion:`$${o.pricing.output.toFixed(2)}`}},interactions:{toolCalls:r.totals.toolCallCount,resourceReads:r.totals.resourceReadCount,totalInteractions:r.totals.toolCallCount+r.totals.resourceReadCount},tokens:{total:r.totals.totalTokens,byCategory:{resources:o.resources.tokens,tools:o.tools.tokens}},cost:{totalUsd:`$${o.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${o.resources.costUsd.toFixed(4)}`,tools:`$${o.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:o.resources.byType,toolsByName:o.tools.byName}},null,2)}}if(t==="paradigm_session_recover"){let{checkpoint:r,pendingHandoffs:o,previousSession:i}=qt(n.rootDir);if(!i&&o.length===0&&!r)return {handled:true,text:JSON.stringify({found:false,message:"No previous session breadcrumbs, checkpoints, or pending handoffs found.",tip:"Breadcrumbs persist to ~/.paradigm/sessions/ and handoffs persist via paradigm_handoff_prepare. Checkpoints persist via paradigm_session_checkpoint."},null,2)};let a={found:true};if(r){let l=Date.now()-r.timestamp,d=Math.round(l/6e4),u=Math.round(l/36e5);a.checkpoint={phase:r.phase,context:r.context,age:u>1?`${u} hours ago`:`${d} minutes ago`,timestamp:new Date(r.timestamp).toISOString(),sessionId:r.sessionId,plan:r.plan,modifiedFiles:r.modifiedFiles,symbolsTouched:r.symbolsTouched,decisions:r.decisions,recentBreadcrumbs:r.recentBreadcrumbs?.map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}))};}if(i){let l=Date.now()-i.lastActivity,d=Math.round(l/6e4),u=Math.round(l/36e5),g=i.breadcrumbs.slice(-10).map(m=>({time:new Date(m.timestamp).toISOString(),action:m.action,tool:m.tool,symbol:m.symbol,summary:m.summary}));a.previousSession={sessionId:i.sessionId,startTime:new Date(i.startTime).toISOString(),lastActivity:new Date(i.lastActivity).toISOString(),age:u>1?`${u} hours ago`:`${d} minutes ago`},a.context={symbolsModified:i.symbolsModified,filesExplored:i.filesExplored},a.recentActions=g;}if(o.length>0){a.pendingHandoffs=o.map(l=>({id:l.id,timestamp:l.timestamp,from:l.from,to:l.to,summary:l.summary,nextSteps:l.nextSteps,modifiedFiles:l.modifiedFiles,symbolsTouched:l.symbolsTouched,openQuestions:l.openQuestions}));for(let l of o)try{c$1(n.rootDir,l.id);}catch{}}let c="Continue where the previous session left off.";if(r)c=`Previous session was in "${r.phase}" phase: ${r.context}`,r.decisions?.length&&(c+=` Key decisions: ${r.decisions.slice(0,2).join("; ")}`);else if(o.length>0){let l=o[o.length-1];c=`Handoff received: "${l.summary}". `,l.nextSteps.length>0&&(c+=`Start with: ${l.nextSteps[0]}`);}else if(i){let l=i.breadcrumbs.slice(-10);if(l.length>0){let d=l[l.length-1];d.symbol&&(c=`Last work involved ${d.symbol}. Consider checking its current state with paradigm_ripple.`);}}return a.suggestion=c,a.agentInstruction="Present a brief summary of the previous session, then ask the user what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking.",s.markRecovered(),{handled:true,text:JSON.stringify(a,null,2)}}if(t==="paradigm_session_checkpoint"){s.setRootDir(n.rootDir);let r=e.phase,o=e.context,i=e.externalId,a=e.plan,c=e.modifiedFiles,l=e.symbolsTouched,d=e.decisions,{checkpoint:u,persisted:p}=s.saveCheckpoint({phase:r,context:o,externalId:i,plan:a,modifiedFiles:c,symbolsTouched:l,decisions:d}),g=p.local||p.global;return {handled:true,text:JSON.stringify({saved:g,persisted:p,checkpoint:{phase:u.phase,context:u.context,sessionId:u.sessionId,...u.externalId?{externalId:u.externalId}:{},timestamp:new Date(u.timestamp).toISOString(),modifiedFiles:u.modifiedFiles?.length||0,symbolsTouched:u.symbolsTouched?.length||0,decisions:u.decisions?.length||0,recentBreadcrumbs:u.recentBreadcrumbs?.length||0},...g?{note:"Checkpoint saved. Recovery data will be auto-surfaced on the first tool call of the next session."}:{warning:"Checkpoint was NOT persisted to disk. Both local and global writes failed. Check MCP server stderr for details."}},null,2)}}return {handled:false,text:""}}function qt(t){let e=j$1();e.setRootDir(t);let n=e.loadCheckpoint(),s=e.loadPreviousSession(),r=[];try{r=b$2(t);}catch{}return {checkpoint:n,pendingHandoffs:r,previousSession:s}}async function Ao(t){let{checkpoint:e,pendingHandoffs:n}=qt(t);if(!e&&n.length===0)return null;let s=[];if(s.push("--- SESSION RECOVERY ---"),e){let r=Date.now()-e.timestamp,o=Math.round(r/6e4),i=Math.round(r/36e5),a=i>1?`${i}h ago`:`${o}m ago`;s.push(`Previous session was in "${e.phase}" phase (${a}): ${e.context}`),e.modifiedFiles?.length&&s.push(`Modified files: ${e.modifiedFiles.join(", ")}`),e.symbolsTouched?.length&&s.push(`Symbols: ${e.symbolsTouched.join(", ")}`),e.decisions?.length&&s.push(`Decisions: ${e.decisions.join("; ")}`),e.plan&&s.push(`Plan: ${e.plan.slice(0,200)}`);}if(n.length>0){let r=n[n.length-1];s.push(`Pending handoff: "${r.summary}"`),r.nextSteps.length>0&&s.push(`Next steps: ${r.nextSteps.slice(0,3).join(", ")}`);}try{let{loadTasks:r}=await import('./task-loader-NZFDTUQ5.js'),o=await r(t,{status:"open",limit:5});if(o.length>0){s.push(""),s.push("Open tasks:");for(let i of o){let a=i.tags.length>0?` [${i.tags.join(", ")}]`:"";s.push(` [${i.priority}] ${i.id}: ${i.blurb}${a}`);}}}catch{}try{let{loadLoreEntries:r}=await import('./lore-loader-PXFKMKAN.js'),i=(await r(t,{limit:10})).filter(a=>a.tags?.some(c=>c.startsWith("arc:")));if(i.length>0){let a=new Map;for(let d of i){let u=d.tags?.find(p=>p.startsWith("arc:"))||"";a.set(u,(a.get(u)||0)+1);}let c=e?.symbolsTouched||[];if((c.length>0?i.filter(d=>d.symbols_touched?.some(u=>c.includes(u))):i.slice(0,3)).length>0||a.size>0){s.push(""),s.push("Active lore arcs:");for(let[d,u]of a)s.push(` ${d} (${u} entries)`);}}}catch{}try{let{loadNominations:r}=await import('./nomination-engine-NCLTGMAK.js'),o=r(t,{pending_only:!0}).filter(i=>i.urgency==="critical"||i.urgency==="high");if(o.length>0){s.push(""),s.push("Ambient nominations (urgent):");for(let i of o.slice(0,5))s.push(` [${i.urgency}] ${i.brief}`);o.length>5&&s.push(` ... and ${o.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return s.push(""),s.push("IMPORTANT: Present a brief summary of this recovery data to the user, then ask what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking."),s.push("---"),s.join(`
25
- `)}var Ke=class{cache=new Map;ttlMs;constructor(e=3e4){this.ttlMs=e;}async getOrCompute(e,n){let s=this.cache.get(e);if(s&&Date.now()-s.createdAt<this.ttlMs)return s.data;let r=await n();return this.cache.set(e,{data:r,createdAt:Date.now()}),r}invalidate(e){this.cache.delete(e);}invalidatePrefix(e){for(let n of this.cache.keys())n.startsWith(e)&&this.cache.delete(n);}clear(){this.cache.clear();}stats(){return {size:this.cache.size,ttlMs:this.ttlMs}}},Vt=new Ke(3e4);var Fn=300*1e3,xe=null;function Kt(){xe=null;}function K(t,e){return w.existsSync(P.join(t,e))}function oe(t,e){return w.existsSync(P.join(t,e))}function Nn(t,e,n){let s=t;try{if(!w.existsSync(s))return !1;let r=w.readdirSync(s,{withFileTypes:!0});for(let o of r){if(o.isFile()&&o.name.endsWith(e))return !0;if(o.isDirectory())try{if(w.readdirSync(P.join(s,o.name)).some(a=>a.endsWith(e)))return !0}catch{}}}catch{}return false}var Mn={wisdom:t=>K(t,".paradigm/wisdom"),history:t=>K(t,".paradigm/history"),lore:t=>K(t,".paradigm/lore"),habits:t=>oe(t,".paradigm/habits.yaml"),sentinel:t=>{try{let e=P.join(t,".paradigm","config.yaml");return w.existsSync(e)?w.readFileSync(e,"utf-8").includes("sentinel"):!1}catch{return false}},flows:t=>oe(t,".paradigm/flow-index.json")||oe(t,".paradigm/flows.yaml"),fixtures:t=>oe(t,".paradigm/fixtures.yaml"),orchestration:t=>oe(t,".paradigm/agents.yaml"),tasks:t=>K(t,".paradigm/tasks"),assessment:t=>K(t,".paradigm/lore"),personas:t=>Nn(t,".persona"),protocols:t=>K(t,".paradigm/protocols"),symphony:()=>{let t=P.join(Ce.homedir(),".paradigm","score");return w.existsSync(t)},university:t=>K(t,".paradigm/university"),agents:t=>{let e=P.join(Ce.homedir(),".paradigm","agents");return K(t,".paradigm/agents")||w.existsSync(e)},"aspect-graph":t=>oe(t,".paradigm/aspect-graph.db"),pan:t=>oe(t,".pan")||oe(t,"nevr.yaml"),notebooks:t=>{let e=P.join(Ce.homedir(),".paradigm","notebooks");return K(t,".paradigm/notebooks")||w.existsSync(e)}},Yt=class{modules=new Map;activatedAdvanced=new Set;rootDir;constructor(e){this.rootDir=e;}register(e){this.modules.set(e.key,e);}registerAll(e){for(let n of e)this.register(n);}detectActiveFeatures(){if(xe&&Date.now()-xe.timestamp<Fn)return xe.features;let e=new Set;for(let[n,s]of this.modules){if(s.tier==="core"){e.add(n);continue}if(s.tier==="advanced"){this.activatedAdvanced.has(n)&&e.add(n);continue}let r=s.detect||Mn[n];if(r)try{r(this.rootDir)&&e.add(n);}catch{}else e.add(n);}return xe={features:e,timestamp:Date.now()},e}getActiveTools(){let e=this.detectActiveFeatures(),n=[];for(let[s,r]of this.modules)e.has(s)&&n.push(...r.getToolsList());return n}activateAdvanced(e){let n=this.modules.get(e);return !n||n.tier!=="advanced"?null:(this.activatedAdvanced.add(e),n.getToolsList())}getAvailableAdvanced(){let e=[];for(let[n,s]of this.modules)s.tier==="advanced"&&!this.activatedAdvanced.has(n)&&e.push({key:n,toolCount:s.getToolsList().length});return e}async dispatch(e,n,s,r){let o=this.detectActiveFeatures();for(let[i,a]of this.modules)if(o.has(i))try{let c=await a.handleTool(e,n,s,r);if(c.handled)return c}catch(c){return {handled:true,text:JSON.stringify({error:`Tool handler error in module "${i}"`,message:c.message},null,2)}}return null}get size(){return this.modules.size}getRegistryInfo(){let e=this.detectActiveFeatures(),n={core:0,feature:0,advanced:0};for(let s of this.modules.values())n[s.tier]++;return {total:this.modules.size,byTier:n,activeFeatures:[...e],availableAdvanced:[...this.modules.entries()].filter(([s,r])=>r.tier==="advanced"&&!this.activatedAdvanced.has(s)).map(([s])=>s)}}};function Je(t,e,n){if(P.isAbsolute(t))return {resolvedPath:t,baseUsed:"absolute",exists:w.existsSync(t)};let s=P.join(n,t);if(w.existsSync(s))return {resolvedPath:s,baseUsed:"project-root",exists:true};let r=P.resolve(e,t);return w.existsSync(r)?{resolvedPath:r,baseUsed:"purpose-dir",exists:true}:{resolvedPath:s,baseUsed:"project-root",exists:false}}function Fo(t,e,n){if(P.isAbsolute(t)){let o=w.existsSync(t);return {rootResolves:o,purposeResolves:o,mismatch:false}}let s=w.existsSync(P.join(n,t)),r=w.existsSync(P.resolve(e,t));return {rootResolves:s,purposeResolves:r,mismatch:s!==r}}var et=null;async function qn(){return et||(et=await Xn()),et}var Vn=[`CREATE TABLE IF NOT EXISTS aspects (
26
- id TEXT PRIMARY KEY,
27
- description TEXT NOT NULL,
28
- category TEXT DEFAULT 'rule',
29
- severity TEXT DEFAULT 'medium',
30
- value TEXT,
31
- enforcement TEXT,
32
- defined_in TEXT NOT NULL,
33
- tags TEXT,
34
- created_at TEXT NOT NULL,
35
- updated_at TEXT NOT NULL
36
- )`,`CREATE TABLE IF NOT EXISTS anchors (
37
- id INTEGER PRIMARY KEY AUTOINCREMENT,
38
- aspect_id TEXT NOT NULL REFERENCES aspects(id) ON DELETE CASCADE,
39
- file_path TEXT NOT NULL,
40
- start_line INTEGER NOT NULL,
41
- end_line INTEGER NOT NULL,
42
- content_hash TEXT,
43
- normalized_hash TEXT,
44
- materialized_at_commit TEXT,
45
- last_verified TEXT,
46
- drifted INTEGER DEFAULT 0
47
- )`,"CREATE INDEX IF NOT EXISTS idx_anchors_file ON anchors(file_path)","CREATE INDEX IF NOT EXISTS idx_anchors_aspect ON anchors(aspect_id)",`CREATE TABLE IF NOT EXISTS edges (
48
- id INTEGER PRIMARY KEY AUTOINCREMENT,
49
- source TEXT NOT NULL,
50
- target TEXT NOT NULL,
51
- relation TEXT NOT NULL,
52
- weight REAL DEFAULT 1.0,
53
- origin TEXT DEFAULT 'explicit',
54
- created_at TEXT NOT NULL
55
- )`,"CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)",`CREATE TABLE IF NOT EXISTS lore_links (
56
- aspect_id TEXT NOT NULL,
57
- lore_id TEXT NOT NULL,
58
- PRIMARY KEY (aspect_id, lore_id)
59
- )`,`CREATE TABLE IF NOT EXISTS search_log (
60
- id INTEGER PRIMARY KEY AUTOINCREMENT,
61
- query TEXT NOT NULL,
62
- results_returned TEXT NOT NULL,
63
- selected_result TEXT,
64
- timestamp TEXT NOT NULL
65
- )`,"CREATE INDEX IF NOT EXISTS idx_search_query ON search_log(query)",`CREATE TABLE IF NOT EXISTS search_weights (
66
- query_normalized TEXT NOT NULL,
67
- aspect_id TEXT NOT NULL,
68
- weight REAL DEFAULT 1.0,
69
- hit_count INTEGER DEFAULT 1,
70
- last_hit TEXT NOT NULL,
71
- PRIMARY KEY (query_normalized, aspect_id)
72
- )`,`CREATE TABLE IF NOT EXISTS heatmap (
73
- aspect_id TEXT NOT NULL,
74
- access_type TEXT NOT NULL,
75
- count INTEGER DEFAULT 0,
76
- last_accessed TEXT NOT NULL,
77
- PRIMARY KEY (aspect_id, access_type)
78
- )`],Yn=["ALTER TABLE anchors ADD COLUMN original_content TEXT",`CREATE TABLE IF NOT EXISTS anchor_history (
79
- id INTEGER PRIMARY KEY AUTOINCREMENT,
80
- anchor_id INTEGER NOT NULL,
81
- action TEXT NOT NULL,
82
- old_start INTEGER,
83
- old_end INTEGER,
84
- new_start INTEGER,
85
- new_end INTEGER,
86
- old_path TEXT,
87
- new_path TEXT,
88
- confidence REAL,
89
- commit_hash TEXT,
90
- healed_at TEXT NOT NULL
91
- )`],Kn="CREATE VIRTUAL TABLE IF NOT EXISTS aspects_fts USING fts5(id, description, enforcement, tags)";function X(t,e,n){let s=t.prepare(e);n&&n.length>0&&s.bind(n);let r=[];for(;s.step();)r.push(s.getAsObject());return s.free(),r}function Jn(t,e,n){let s=t.prepare(e);n&&n.length>0&&s.bind(n);let r=null;return s.step()&&(r=s.getAsObject()),s.free(),r}async function as(t){let e=await qn(),n=P.join(t,".paradigm"),s=P.join(n,"aspect-graph.db"),r;if(w.existsSync(s)){let o=w.readFileSync(s);r=new e.Database(o);}else w.existsSync(n)||w.mkdirSync(n,{recursive:true}),r=new e.Database;for(let o of Vn)r.run(o);try{r.run(Kn);}catch{}for(let o of Yn)try{r.run(o);}catch{}return r}function cs(t,e){if(e){let n=P.join(e,".paradigm");w.existsSync(n)||w.mkdirSync(n,{recursive:true});let s=P.join(n,"aspect-graph.db"),r=t.export();w.writeFileSync(s,Buffer.from(r));}t.close();}function ls(t,e,n){let s=e.filter(i=>i.type==="aspect"),r=new Date().toISOString(),o=null;try{o=execSync("git rev-parse HEAD",{cwd:n,encoding:"utf8"}).trim();}catch{}t.run("DELETE FROM anchors"),t.run("DELETE FROM edges"),t.run("DELETE FROM aspects");try{t.run("DELETE FROM aspects_fts");}catch{}for(let i of s){let a=i.data??{},c=tr(a,i),l=sr(a,i),d=a.value!=null?String(a.value):null,u=i.enforcement??(a.enforcement!=null?String(a.enforcement):null),p=i.tags?JSON.stringify(i.tags):null;if(t.run(`INSERT INTO aspects (id, description, category, severity, value, enforcement, defined_in, tags, created_at, updated_at)
92
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.symbol,i.description??"",c,l,d,u,i.filePath,p,i.created??r,i.modified??r]),i.anchors)for(let m of i.anchors){let{startLine:h,endLine:v}=ds(m),T=er();t.run(`INSERT INTO anchors (aspect_id, file_path, start_line, end_line, content_hash, normalized_hash, materialized_at_commit, last_verified, original_content)
93
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.symbol,m.path,h,v,T.exact,T.normalized,o,r,T.normalizedContent]);}let g=a.edges;if(Array.isArray(g))for(let m of g)t.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
94
- VALUES (?, ?, ?, ?, ?, ?)`,[m.source??i.symbol,m.target??"",m.relation??"related-to",m.weight??1,m.origin??"explicit",r]);if(i.appliesTo)for(let m of i.appliesTo)t.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
95
- VALUES (?, ?, ?, ?, ?, ?)`,[i.symbol,m,"related-to",.5,"inferred",r]);try{t.run(`INSERT INTO aspects_fts (id, description, enforcement, tags)
96
- VALUES (?, ?, ?, ?)`,[i.symbol,i.description??"",u??"",p??""]);}catch{}}}function Ho(t,e){return Jn(t,"SELECT * FROM aspects WHERE id = ?",[e])}function Wo(t,e){return X(t,"SELECT * FROM anchors WHERE aspect_id = ?",[e])}function Go(t,e){return X(t,"SELECT * FROM edges WHERE source = ?",[e])}function Bo(t,e){return X(t,"SELECT * FROM edges WHERE target = ?",[e])}function Xo(t,e){return X(t,"SELECT * FROM edges WHERE source = ? OR target = ?",[e,e])}function qo(t,e,n){let s=new Date().toISOString();t.run(`INSERT INTO heatmap (aspect_id, access_type, count, last_accessed)
97
- VALUES (?, ?, 1, ?)
98
- ON CONFLICT(aspect_id, access_type)
99
- DO UPDATE SET count = count + 1, last_accessed = ?`,[e,n,s,s]);}function Vo(t,e=20,n){return n?X(t,"SELECT * FROM heatmap WHERE access_type = ? ORDER BY count DESC LIMIT ?",[n,e]):X(t,"SELECT * FROM heatmap ORDER BY count DESC LIMIT ?",[e])}function Yo(t,e,n,s=true,r=.7,o=.85){let i=n?X(t,"SELECT * FROM anchors WHERE aspect_id = ?",[n]):X(t,"SELECT * FROM anchors"),a=[];for(let c of i){let d$1=X(t,"SELECT defined_in FROM aspects WHERE id = ?",[c.aspect_id])[0]?.defined_in,u=d$1?P.dirname(P.isAbsolute(d$1)?d$1:P.resolve(e,d$1)):e,p=Je(c.file_path,u,e),g=p.resolvedPath;if(!p.exists){a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"missing",resolvedBy:"none",exists:false,drifted:true});continue}try{let h=w.readFileSync(g,"utf8").split(`
100
- `),v=Math.max(0,c.start_line-1),T=Math.min(h.length,c.end_line),C=h.slice(v,T).join(`
101
- `),N=ie.createHash("sha256").update(C).digest("hex");if(c.content_hash!=null&&N===c.content_hash){a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1}),c.drifted===1&&t.run("UPDATE anchors SET drifted = 0 WHERE id = ?",[c.id]);continue}let b=ie.createHash("sha256").update(st(C)).digest("hex");if(c.normalized_hash!=null&&b===c.normalized_hash){t.run("UPDATE anchors SET content_hash = ?, drifted = 0 WHERE id = ?",[N,c.id]),a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"cosmetic",resolvedBy:"normalized-hash",exists:!0,drifted:!1});continue}if(c.content_hash==null&&c.normalized_hash==null){t.run("UPDATE anchors SET content_hash = ?, normalized_hash = ?, drifted = 0 WHERE id = ?",[N,b,c.id]),a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1});continue}let S=!1;if(c.materialized_at_commit){let x=Zn(e,c.file_path,c.materialized_at_commit,c.start_line,c.end_line);if(x){let k=Math.max(0,x.currentStart-1),E=Math.min(h.length,x.currentEnd),j=h.slice(k,E).join(`
102
- `),te=ie.createHash("sha256").update(j).digest("hex");if(c.content_hash!=null&&te===c.content_hash){let se=s;if(se){t.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[x.currentStart,x.currentEnd,c.id]);let pe=X(t,"SELECT defined_in FROM aspects WHERE id = ?",[c.aspect_id]);pe.length>0&&tt(e,pe[0].defined_in,c.file_path,c.start_line,c.end_line,x.currentStart,x.currentEnd);}a.push({aspectId:c.aspect_id,path:c.file_path,startLine:se?x.currentStart:c.start_line,endLine:se?x.currentEnd:c.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:x.currentStart,suggestedEnd:x.currentEnd,autoHealed:se}),S=!0;}else {let se=ie.createHash("sha256").update(st(j)).digest("hex");if(c.normalized_hash!=null&&se===c.normalized_hash){if(s){let pe=ie.createHash("sha256").update(j).digest("hex");t.run("UPDATE anchors SET start_line = ?, end_line = ?, content_hash = ?, drifted = 0 WHERE id = ?",[x.currentStart,x.currentEnd,pe,c.id]);let ke=X(t,"SELECT defined_in FROM aspects WHERE id = ?",[c.aspect_id]);ke.length>0&&tt(e,ke[0].defined_in,c.file_path,c.start_line,c.end_line,x.currentStart,x.currentEnd);}a.push({aspectId:c.aspect_id,path:c.file_path,startLine:s?x.currentStart:c.start_line,endLine:s?x.currentEnd:c.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:x.currentStart,suggestedEnd:x.currentEnd,autoHealed:s}),S=!0;}}}}if(S)continue;if(c.original_content){let{contentSearch:x}=(os(),d(rs)),k=x(e,c.file_path,c.original_content,s);if(k.found&&k.score>=r){if(s&&k.score>=o&&!k.suggestedPath&&k.suggestedStart&&k.suggestedEnd){t.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[k.suggestedStart,k.suggestedEnd,c.id]);try{t.run(`INSERT INTO anchor_history (anchor_id, action, old_start, old_end, new_start, new_end, confidence, healed_at)
103
- VALUES (?, 'relocated', ?, ?, ?, ?, ?, ?)`,[c.id,c.start_line,c.end_line,k.suggestedStart,k.suggestedEnd,k.score,new Date().toISOString()]);}catch{}let j=X(t,"SELECT defined_in FROM aspects WHERE id = ?",[c.aspect_id]);j.length>0&&tt(e,j[0].defined_in,c.file_path,c.start_line,c.end_line,k.suggestedStart,k.suggestedEnd),a.push({aspectId:c.aspect_id,path:c.file_path,startLine:k.suggestedStart,endLine:k.suggestedEnd,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:k.similarity,suggestedStart:k.suggestedStart,suggestedEnd:k.suggestedEnd,autoHealed:!0,drifted:!1});continue}a.push({aspectId:c.aspect_id,path:k.suggestedPath||c.file_path,startLine:c.start_line,endLine:c.end_line,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:k.similarity,suggestedStart:k.suggestedStart,suggestedEnd:k.suggestedEnd,autoHealed:!1,drifted:!0});continue}}t.run("UPDATE anchors SET drifted = 1 WHERE id = ?",[c.id]),a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"modified",resolvedBy:"none",exists:!0,currentContent:C,drifted:!0});}catch{a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"modified",resolvedBy:"none",exists:true,drifted:true});}}return a}function ds(t){let{lines:e}=t;return typeof e=="number"?{startLine:e,endLine:e}:Array.isArray(e)?e.length===2?{startLine:e[0],endLine:e[1]}:{startLine:Math.min(...e),endLine:Math.max(...e)}:{startLine:1,endLine:1}}function Qn(t){let e=[],n=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm,s;for(;(s=n.exec(t))!==null;)e.push({oldStart:parseInt(s[1],10),oldCount:s[2]!==void 0?parseInt(s[2],10):1,newStart:parseInt(s[3],10),newCount:s[4]!==void 0?parseInt(s[4],10):1});return e}function Zn(t,e,n,s,r){let o;try{o=execSync(`git diff ${n}..HEAD --unified=0 -- "${e}"`,{cwd:t,encoding:"utf8",timeout:5e3});}catch{return null}if(!o.trim())return {originalStart:s,originalEnd:r,currentStart:s,currentEnd:r};let i=Qn(o),a=0;for(let c of i){if(c.oldStart+c.oldCount<=s){a+=c.newCount-c.oldCount;continue}if(c.oldStart<r)return null;break}return a===0?null:{originalStart:s,originalEnd:r,currentStart:s+a,currentEnd:r+a}}function tt(t,e,n,s,r,o,i){let a=P.isAbsolute(e)?e:P.join(t,e);if(!w.existsSync(a))return false;try{let c=w.readFileSync(a,"utf8"),l=s===r?`${n}:${s}`:`${n}:${s}-${r}`,d=o===i?`${n}:${o}`:`${n}:${o}-${i}`;if(!c.includes(l))return !1;let u=c.replace(l,d);return w.writeFileSync(a,u,"utf8"),!0}catch{return false}}function st(t){return t.split(`
104
- `).map(e=>e.trimEnd()).filter(e=>e.trim()!=="").map(e=>e.replace(/\s+/g," ")).join(`
105
- `)}function er(t,e,n){return {exact:null,normalized:null,normalizedContent:null};}function tr(t,e){if(typeof t.category=="string")return t.category;let n=(e.description??"").toLowerCase();return /\b(must|require|always)\b/.test(n)?"rule":/\b(decided|chose)\b/.test(n)?"decision":/\b(limit|cannot)\b/.test(n)?"constraint":/\b(set to|configured|value)\b/.test(n)?"configuration":"rule"}function sr(t,e){if(typeof t.severity=="string")return t.severity;let n=e.tags??[];return n.includes("critical")?"critical":n.includes("security")||n.includes("compliance")?"high":"medium"}j();var nr=/L-\d{4}-\d{2}-\d{2}-\d{3}/g;async function us(t,e){t.run("DELETE FROM lore_links");let n=await a$3(e);if(n.length===0)return 0;let s=rr(n),r=new Map;for(let l of n)r.set(l.id,l);let o=new Set,i=t.exec("SELECT id, enforcement FROM aspects");if(i.length>0){let{columns:l,values:d}=i[0],u=l.indexOf("id"),p=l.indexOf("enforcement");for(let g of d){let m=String(g[u]),h=g[p];if(h&&typeof h=="string"){let v=h.match(nr);if(v)for(let T of v)r.has(T)&&o.add(`${m}\0${T}`);}}}let a=t.exec("SELECT source, target FROM edges");if(a.length>0&&i.length>0){let l=or(t,a);for(let[d,u]of l)for(let p of u){let g=s.get(p);if(g)for(let m of g)o.add(`${d}\0${m}`);}}if(o.size===0)return 0;let c=t.prepare("INSERT OR IGNORE INTO lore_links (aspect_id, lore_id) VALUES (?, ?)");try{for(let l of o){let[d,u]=l.split("\0");c.bind([d,u]),c.step(),c.reset();}}finally{c.free();}return o.size}async function Qo(t,e,n){let s=t.exec("SELECT lore_id FROM lore_links WHERE aspect_id = ?",[n]);if(s.length===0||s[0].values.length===0)return [];let r=s[0].values.map(o=>String(o[0]));return ir(e,r)}async function ps(t,e){let n=await a$3(e);if(n.length===0)return 0;let s=t.exec("SELECT id FROM aspects"),r=new Set;if(s.length>0)for(let c of s[0].values)r.add(String(c[0]));if(r.size<2)return 0;let o=new Date().toISOString(),i=0,a=t.prepare(`INSERT OR IGNORE INTO edges (source, target, relation, weight, origin, created_at)
106
- VALUES (?, ?, 'related-to', 0.3, 'learned', ?)`);try{for(let c of n){if(!c.symbols_touched||c.symbols_touched.length<2)continue;let l=[];for(let d of c.symbols_touched){let u=d.startsWith("~")?d.slice(1):d;r.has(u)&&l.push(u);}for(let d=0;d<l.length;d++)for(let u=d+1;u<l.length;u++){let[p,g]=l[d]<l[u]?[l[d],l[u]]:[l[u],l[d]];a.bind([p,g,o]),a.step(),a.reset(),i++;}}}finally{a.free();}return i}function rr(t){let e=new Map;for(let n of t)if(n.symbols_touched)for(let s of n.symbols_touched){let r=e.get(s);r||(r=new Set,e.set(s,r)),r.add(n.id);}return e}function or(t,e){let n=t.exec("SELECT id FROM aspects"),s=new Set;if(n.length>0)for(let l of n[0].values)s.add(String(l[0]));let r=new Map;if(e.length===0)return r;let{columns:o,values:i}=e[0],a=o.indexOf("source"),c=o.indexOf("target");for(let l of i){let d=String(l[a]),u=String(l[c]);if(s.has(d)){let p=r.get(d);p||(p=new Set,r.set(d,p)),p.add(u),p.add(`~${d}`);}if(s.has(u)){let p=r.get(u);p||(p=new Set,r.set(u,p)),p.add(d),p.add(`~${u}`);}}return r}async function ir(t,e){let n=new Set,s=[];for(let r of e){if(n.has(r))continue;n.add(r);let o=await b$3(t,r);o&&s.push(ar(o));}return s}function ar(t){return {id:t.id,title:t.title,summary:t.summary,timestamp:t.timestamp,symbolsTouched:t.symbols_touched}}var ge=".paradigm/personas",cr="index.yaml";async function ve(t,e){let n=P.join(t,ge);if(!w.existsSync(n))return [];let s=w.readdirSync(n).filter(o=>o.endsWith(".persona")),r=[];for(let o of s)try{let i=w.readFileSync(P.join(n,o),"utf8"),a=z.load(i);a&&a.id&&r.push(a);}catch{}return lr(r,e)}async function Ee(t,e){let n=P.join(t,ge,`${e}.persona`);if(!w.existsSync(n))return null;try{return z.load(w.readFileSync(n,"utf8"))}catch{return null}}function lr(t,e){if(!e)return t;let n=t;return e.tag&&(n=n.filter(s=>s.tags?.includes(e.tag))),e.trigger_type&&(n=n.filter(s=>s.trigger.type===e.trigger_type)),e.gate&&(n=n.filter(s=>s.journey.some(r=>r.gates.includes(e.gate)))),e.flow&&(n=n.filter(s=>s.journey.some(r=>r.flow===e.flow))),e.limit&&(n=n.slice(0,e.limit)),n}async function ei(t,e){let n=P.join(t,ge);w.mkdirSync(n,{recursive:true});let s=P.join(n,`${e.id}.persona`);if(w.existsSync(s))throw new Error(`Persona ${e.id} already exists`);let r=new Date().toISOString(),o={version:"1.0",id:e.id,name:e.name,description:e.description,traits:e.traits,trigger:e.trigger,fixtures:e.fixtures,tags:e.tags||[],journey:e.journey||[],created:r,updated:r};return w.writeFileSync(s,z.dump(o,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await Te(t),e.id}async function fs(t,e,n){let s=await Ee(t,e);if(!s)return false;let r=P.join(t,ge,`${e}.persona`),o={...s,...n,id:s.id,version:s.version,created:s.created,updated:new Date().toISOString()};return w.writeFileSync(r,z.dump(o,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await Te(t),true}async function ti(t,e){let n=P.join(t,ge,`${e}.persona`);if(!w.existsSync(n))return {deleted:false,warnings:[]};let s=[],r=await ve(t);for(let o of r)if(o.id!==e){o.trigger.spawned_by?.startsWith(e+".")&&s.push(`Persona ${o.id} is spawned by ${e} \u2014 it will become orphaned`);for(let i of o.journey)i.spawns?.some(a=>a.persona===e)&&s.push(`Persona ${o.id} step ${i.id} spawns ${e} \u2014 spawn will break`);}return w.unlinkSync(n),await Te(t),{deleted:true,warnings:s}}async function si(t,e,n,s){let r=await Ee(t,e);if(!r)return false;if(r.journey.some(o=>o.id===n.id))throw new Error(`Step ${n.id} already exists in persona ${e}`);if(s){let o=r.journey.findIndex(i=>i.id===s);if(o===-1)throw new Error(`Step ${s} not found in persona ${e}`);r.journey.splice(o+1,0,n);}else r.journey.push(n);return fs(t,e,{journey:r.journey})}async function ni(t,e,n){let s=await Ee(t,e);if(!s)return {removed:false,warnings:[]};let r=s.journey.findIndex(a=>a.id===n);if(r===-1)return {removed:false,warnings:[]};let o=s.journey[r],i=[];if(o.produces)for(let a of Object.keys(o.produces)){let c=`{{produces.${a}}}`;for(let l=r+1;l<s.journey.length;l++){let d=s.journey[l];JSON.stringify(d).includes(c)&&i.push(`Step ${d.id} consumes {{produces.${a}}} from this step`);}}if(o.spawns&&o.spawns.length>0)for(let a of o.spawns)i.push(`Step spawns persona ${a.persona} \u2014 spawn chain will break`);return s.journey.splice(r,1),await fs(t,e,{journey:s.journey}),{removed:true,warnings:i}}var dr=/^[a-z][a-z0-9-]*$/,ur=/^[a-z][a-z0-9-]*$/,pr=/^(GET|POST|PUT|PATCH|DELETE)\s+\//;async function ri(t,e,n=false){let s=[],r=[];dr.test(e.id)||s.push({type:"invalid-id",detail:`ID "${e.id}" must match /^[a-z][a-z0-9-]*$/`}),(!e.name||e.name.trim()==="")&&s.push({type:"missing-name",detail:"Name is required"}),(!e.trigger||!e.trigger.type)&&s.push({type:"missing-trigger",detail:"Trigger with type is required"}),e.trigger.type!=="root"&&!e.trigger.spawned_by&&s.push({type:"missing-spawned-by",detail:`Non-root trigger type "${e.trigger.type}" requires spawned_by`}),(!e.journey||e.journey.length===0)&&s.push({type:"empty-journey",detail:"Journey must have at least one step"});let o=new Set,i=new Set;for(let a of e.journey){ur.test(a.id)||s.push({type:"invalid-step-id",step:a.id,detail:"Step ID must match /^[a-z][a-z0-9-]*$/"}),o.has(a.id)&&s.push({type:"duplicate-step-id",step:a.id,detail:`Duplicate step ID "${a.id}"`}),o.add(a.id),pr.test(a.route)||s.push({type:"invalid-route",step:a.id,route:a.route,detail:'Route must match "METHOD /path" (e.g., "POST /api/auth/signup")'}),(!a.gates||a.gates.length===0)&&s.push({type:"missing-gates",step:a.id,detail:"Step must have at least one gate"}),(!a.expect||a.expect.status===void 0)&&s.push({type:"missing-expect",step:a.id,detail:"Step must have expect with status"});let l=JSON.stringify(a).match(/\{\{produces\.([^}]+)\}\}/g)||[];for(let d of l){let u=d.replace("{{produces.","").replace("}}","");i.has(u)||s.push({type:"unresolved-produces",step:a.id,key:u,detail:`{{produces.${u}}} used but not produced by a prior step`});}if(a.produces)for(let d of Object.keys(a.produces))i.add(d);}if(n){let a=P.join(t,"portal.yaml"),c=[],l=[];if(w.existsSync(a))try{let u=z.load(w.readFileSync(a,"utf8"));u.gates&&typeof u.gates=="object"&&(c=Object.keys(u.gates)),u.routes&&typeof u.routes=="object"&&(l=Object.keys(u.routes));}catch{}for(let u of e.journey)for(let p of u.gates)c.length>0&&!c.includes(p)&&s.push({type:"gate-not-found",step:u.id,gate:p,detail:`Gate ${p} not defined in portal.yaml`});for(let u of e.journey)if(l.length>0){let p=u.route;l.some(m=>nt(m,p))||r.push({type:"route-not-in-portal",detail:`Route "${p}" (step ${u.id}) not found in portal.yaml`});}for(let u of e.journey)if(u.spawns)for(let p of u.spawns)await Ee(t,p.persona)||s.push({type:"spawn-target-missing",step:u.id,detail:`Spawn target persona "${p.persona}" does not exist`});let d=await fr(t,e.id);if(d&&s.push({type:"spawn-cycle",detail:`Circular spawn dependency: ${d.join(" \u2192 ")}`}),l.length>0||c.length>0){let u=await ve(t),p=new Set,g=new Set;for(let T of u)for(let C of T.journey){for(let N of C.gates)p.add(N);g.add(C.route);}let m=[],h=P.join(t,".paradigm","flow-index.json");if(w.existsSync(h))try{let T=JSON.parse(w.readFileSync(h,"utf8"));m=Object.keys(T.flows||{});}catch{}let v=new Set;for(let T of u)for(let C of T.journey)C.flow&&v.add(C.flow);return {persona:e.id,valid:s.length===0,errors:s,warnings:r,coverage:{routes:{covered:g.size,total:l.length,uncovered:l.filter(T=>!g.has(T))},gates:{covered:p.size,total:c.length,uncovered:c.filter(T=>!p.has(T))},flows:{covered:v.size,total:m.length,uncovered:m.filter(T=>!v.has(T))}}}}}return {persona:e.id,valid:s.length===0,errors:s,warnings:r}}function nt(t,e){let n=s=>s.replace(/:[a-zA-Z_]+/g,":param").replace(/\{\{[^}]+\}\}/g,":param");return n(t)===n(e)}async function fr(t,e){let n=new Set,s=[];async function r(o){if(n.has(o)){let a=s.indexOf(o);return a!==-1?[...s.slice(a),o]:null}n.add(o),s.push(o);let i=await Ee(t,o);if(i){for(let a of i.journey)if(a.spawns)for(let c of a.spawns){let l=await r(c.persona);if(l)return l}}return s.pop(),null}return r(e)}async function Te(t){let e=P.join(t,ge);w.mkdirSync(e,{recursive:true});let n=await ve(t),s={},r={},o={};for(let u of n){let p=new Set,g=new Set,m=[],h=new Set;for(let v of u.journey){for(let T of v.gates)p.add(T);if(v.flow&&g.add(v.flow),m.push(v.route),v.spawns)for(let T of v.spawns)h.add(T.persona);}s[u.id]={name:u.name,trigger:u.trigger.type,spawned_by:u.trigger.spawned_by,steps:u.journey.length,gates:[...p],flows:[...g],routes:m,spawns:[...h],tags:u.tags||[]};for(let v of p)r[v]||(r[v]=[]),r[v].push(u.id);for(let v of m)o[v]||(o[v]=[]),o[v].push(u.id);}let i=[],a=P.join(t,"portal.yaml");if(w.existsSync(a))try{let u=z.load(w.readFileSync(a,"utf8"));u.routes&&typeof u.routes=="object"&&(i=Object.keys(u.routes).filter(g=>!Object.keys(o).some(m=>nt(g,m))));}catch{}let c={},l=P.join(e,"chains");if(w.existsSync(l)){let u=w.readdirSync(l).filter(p=>p.endsWith(".yaml"));for(let p of u)try{let g=w.readFileSync(P.join(l,p),"utf8"),m=z.load(g);if(m&&m.id){let h=m.order.map(C=>C.persona),v=0,T=new Set;for(let C of h){let N=s[C];if(N){v+=N.steps;for(let b of N.gates)T.add(b);}}c[m.id]={description:m.description||"",order:h,total_steps:v,total_gates:T.size};}}catch{}}let d={version:"1.0",generated:new Date().toISOString(),personas:s,chains:c,gate_coverage:r,route_coverage:o,uncovered_routes:i};return w.writeFileSync(P.join(e,cr),z.dump(d,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),d}async function oi(t){let e=await ve(t),n=new Set,s=new Set,r=new Set;for(let d of e)for(let u of d.journey){for(let p of u.gates)n.add(p);s.add(u.route),u.flow&&r.add(u.flow);}let o=[],i=[],a=P.join(t,"portal.yaml");if(w.existsSync(a))try{let d=z.load(w.readFileSync(a,"utf8"));d.gates&&typeof d.gates=="object"&&(o=Object.keys(d.gates)),d.routes&&typeof d.routes=="object"&&(i=Object.keys(d.routes));}catch{}let c=[],l=P.join(t,".paradigm","flow-index.json");if(w.existsSync(l))try{let d=JSON.parse(w.readFileSync(l,"utf8"));c=Object.keys(d.flows||{});}catch{}return {routes:{covered:s.size,total:i.length,uncovered:i.filter(d=>!Array.from(s).some(u=>nt(d,u)))},gates:{covered:n.size,total:o.length,uncovered:o.filter(d=>!n.has(d))},flows:{covered:r.size,total:c.length,uncovered:c.filter(d=>!r.has(d))},personas:e.length}}async function ii(t,e){let n=await ve(t),s=[];for(let r of n){let o=[],i=[];for(let a of r.journey)if((a.gates.includes(e)||a.flow===e||a.route===e||a.signals?.includes(e))&&(o.push(a.id),a.spawns))for(let l of a.spawns)i.push(l.persona);o.length>0&&s.push({persona:r.id,steps:o,spawns_blocked:i});}return s}function mr(t,e){let n=e.split(/[.\[\]]+/).filter(Boolean),s=t;for(let r of n){if(s==null||typeof s!="object")return;s=s[r];}return s}function gr(t,e){let n=[];if(e.status!==t.expect.status&&n.push({type:"status",field:"status",expected:t.expect.status,actual:e.status,message:`Step ${t.id}: status is ${e.status}, expected ${t.expect.status}`}),t.expect.body?.has){let s=e.body;for(let r of t.expect.body.has)(!s||typeof s!="object"||!(r in s))&&n.push({type:"body.has",field:r,expected:true,actual:false,message:`Step ${t.id}: body missing key '${r}'`});}if(t.expect.body?.match){let s=e.body;for(let[r,o]of Object.entries(t.expect.body.match)){let i=s?mr(s,r):void 0;JSON.stringify(i)!==JSON.stringify(o)&&n.push({type:"body.match",field:r,expected:o,actual:i??null,message:`Step ${t.id}: '${r}' is ${JSON.stringify(i??null)}, expected ${JSON.stringify(o)}`});}}if(t.signals&&t.signals.length>0){let s=e.signals_fired||[];for(let r of t.signals)s.includes(r)||n.push({type:"signal",field:"signals_fired",expected:r,actual:s,message:`Step ${t.id}: signal '${r}' was not fired`});}if(t.gates.length>0&&e.gates_traversed)for(let s of t.gates)e.gates_traversed.includes(s)||n.push({type:"gate",field:"gates_traversed",expected:s,actual:e.gates_traversed,message:`Step ${t.id}: gate '${s}' was not traversed`});return n}async function ai(t,e={}){let n=[];try{let{SentinelStorage:a}=await import('./dist-W3XCATBJ.js'),c=new a,d=(c.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.complete",scopeValue:t.id,limit:500})||[]).filter(m=>{let h=JSON.parse(m.data_json||"{}");return !(e.run_id&&h.run_id!==e.run_id||e.chain_id&&h.chain_id!==e.chain_id||e.environment&&h.environment!==e.environment)}),p=(c.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.fail",scopeValue:t.id,limit:500})||[]).filter(m=>{let h=JSON.parse(m.data_json||"{}");return !(e.run_id&&h.run_id!==e.run_id||e.chain_id&&h.chain_id!==e.chain_id||e.environment&&h.environment!==e.environment)}),g=new Map;for(let m of [...d,...p]){let h=JSON.parse(m.data_json||"{}");h.step_id&&g.set(h.step_id,h);}for(let m of t.journey){let h=g.get(m.id);if(!h){n.push({step_id:m.id,matched:!1,assertions:[],message:`No Sentinel event found for step '${m.id}' \u2014 step was never exercised`});continue}let v=gr(m,{status:h.status,body:h.body,gates_traversed:h.gates_traversed,signals_fired:h.signals_fired});n.push({step_id:m.id,matched:!0,passed:v.length===0,assertions:v});}}catch{for(let a of t.journey)n.push({step_id:a.id,matched:false,assertions:[],message:"Sentinel unavailable \u2014 cannot validate events"});}let s=n.filter(a=>a.matched).length,r=n.filter(a=>a.passed).length,o=n.filter(a=>a.matched&&!a.passed).length,i=n.reduce((a,c)=>a+c.assertions.length,0);return {run_id:e.run_id,environment:e.environment,steps:n,summary:{total_steps:t.journey.length,matched:s,unmatched:t.journey.length-s,passed:r,failed:o,assertion_failures:i}}}var ue=".paradigm/protocols",ms="index.yaml";async function rt(t){let e=P.join(t,ue);if(!w.existsSync(e))return [];let n=w.readdirSync(e).filter(r=>r.endsWith(".protocol")).sort(),s=[];for(let r of n)try{let o=w.readFileSync(P.join(e,r),"utf8"),i=z.load(o);i?.id&&i?.name&&s.push(i);}catch{}return s}async function hr(t,e){let n=e.replace(/^P-/,""),s=P.join(t,ue,`${n}.protocol`);if(w.existsSync(s))try{let o=w.readFileSync(s,"utf8");return z.load(o)}catch{return null}return (await rt(t)).find(o=>o.id===e)||null}async function li(t){let e=P.join(t,ue,ms);if(!w.existsSync(e))return null;try{let n=w.readFileSync(e,"utf8");return z.load(n)}catch{return null}}async function di(t,e,n=3){let s=await rt(t);if(s.length===0)return [];let r=wr(e);if(r.length===0)return [];let o=[];for(let i of s){let a=0;for(let d of i.trigger){let u=d.toLowerCase();for(let p of r)u.includes(p)&&(a+=3);}for(let d of i.tags){let u=d.toLowerCase();for(let p of r)(u.includes(p)||p.includes(u))&&(a+=2);}let c=i.name.toLowerCase(),l=i.description.toLowerCase();for(let d of r)c.includes(d)&&(a+=1),l.includes(d)&&(a+=1);for(let d of i.steps)if(d.notes){let u=d.notes.toLowerCase();for(let p of r)u.includes(p)&&(a+=.5);}a>0&&o.push({protocol:i,score:a});}return o.sort((i,a)=>a.score-i.score),o.slice(0,n)}async function ui(t,e){let n=P.join(t,ue);w.existsSync(n)||w.mkdirSync(n,{recursive:true});let s=Sr(e.name),r=`P-${s}`,o=new Date().toISOString(),i={id:r,name:e.name,description:e.description,trigger:e.trigger,tags:e.tags,symbols:e.symbols||[],exemplar:e.exemplar,steps:e.steps,recorded_from:e.recorded_from,recorded_at:o,last_verified:o,verified_by:e.verified_by||"claude-opus-4-6",status:"current"},a=P.join(n,`${s}.protocol`);return w.writeFileSync(a,z.dump(i,{lineWidth:-1,noRefs:true}),"utf8"),r}async function pi(t,e,n,s=false){let r=await hr(t,e);if(!r)return false;n.name!==void 0&&(r.name=n.name),n.description!==void 0&&(r.description=n.description),n.trigger!==void 0&&(r.trigger=n.trigger),n.tags!==void 0&&(r.tags=n.tags),n.symbols!==void 0&&(r.symbols=n.symbols),n.exemplar!==void 0&&(r.exemplar=n.exemplar),n.steps!==void 0&&(r.steps=n.steps),n.status!==void 0&&(r.status=n.status),n.verified_by!==void 0&&(r.verified_by=n.verified_by),s&&(r.last_verified=new Date().toISOString(),r.verified_by=n.verified_by||"claude-opus-4-6");let o=e.replace(/^P-/,""),i=P.join(t,ue,`${o}.protocol`);return w.writeFileSync(i,z.dump(r,{lineWidth:-1,noRefs:true}),"utf8"),true}function yr(t,e){let n=[],s="current";if(e.exemplar){let r=P.join(t,e.exemplar);w.existsSync(r)?w.statSync(r).mtime.toISOString()>e.last_verified&&(n.push(`Exemplar modified since last verified: ${e.exemplar}`),s!=="broken"&&(s="stale")):(n.push(`Exemplar missing: ${e.exemplar}`),s="broken");}for(let r of e.steps){if(r.template_from){let o=P.join(t,r.template_from);w.existsSync(o)||(n.push(`Template file missing: ${r.template_from}`),s="broken");}if(r.action==="modify"&&r.target){let o=P.join(t,r.target);!r.target.includes("{")&&!w.existsSync(o)&&(n.push(`Modify target missing: ${r.target}`),s="broken");}}return {status:s,issues:n}}async function gs(t){let e=await rt(t),n=[],s=0,r=0,o=0;for(let c of e){let l=yr(t,c);if(c.status!==l.status){c.status=l.status;let d=c.id.replace(/^P-/,""),u=P.join(t,ue,`${d}.protocol`);w.existsSync(u)&&w.writeFileSync(u,z.dump(c,{lineWidth:-1,noRefs:true}),"utf8");}switch(l.status){case "current":s++;break;case "stale":r++;break;case "broken":o++;break}n.push({id:c.id,name:c.name,status:l.status,last_verified:c.last_verified,trigger:c.trigger,tags:c.tags});}let i={version:"1.0",generated:new Date().toISOString(),protocols:n,health:{total:e.length,current:s,stale:r,broken:o}},a=P.join(t,ue);if(e.length>0){w.existsSync(a)||w.mkdirSync(a,{recursive:true});let c=P.join(a,ms);w.writeFileSync(c,z.dump(i,{lineWidth:-1,noRefs:true}),"utf8");}return i}function fi(t,e,n){if(!e||e.length<2)return null;let s={};for(let r of e){let o=P.dirname(r);s[o]||(s[o]=[]),s[o].push(r);}for(let[r,o]of Object.entries(s)){if(o.length<2)continue;let i=P.join(t,r);if(!w.existsSync(i))continue;let c=w.readdirSync(i).filter(l=>{let d=P.extname(l);return [".ts",".tsx",".js",".jsx",".rs",".py"].includes(d)}).filter(l=>!o.some(d=>P.basename(d)===l));if(c.length>0){let l=P.join(r,c[0]),d=[...o.map(u=>({action:"create",target:u})),...n.map(u=>({action:"modify",target:u}))];return {hint:`This session created ${o.length} new files in ${r}/ following existing patterns. Consider recording a protocol.`,draft:{name:`Add a ${P.basename(r).replace(/s$/,"")}`,exemplar:l,steps:d}}}}return null}function wr(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(e=>e.length>1).filter(e=>!br.has(e))}var br=new Set(["a","an","the","is","are","was","were","be","been","to","of","in","for","on","with","at","by","from","it","this","that","and","or","but","if","then","so","as","do","does","did","will","would","can","could","should","may","might","must","shall","i","me","my","we","our","you","your","he","she","how","what","when","where","which","who","whom"]);function Sr(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var ee="pack.yaml";var xr="PARADIGM_STRICT";function he(){let t=process.env[xr];if(t===void 0||t==="")return false;let e=t.toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}function vr(t){return Dt(t)}function ws(t,e){if(!w.existsSync(t))return {status:"missing"};let n;try{n=w.readFileSync(t,"utf-8");}catch{return ot({status:"unparseable",errorClass:"other",detail:"file read error"},e)}let s;try{s=z.load(n);}catch(r){let{errorClass:o,detail:i}=vr(r);return ot({status:"unparseable",errorClass:o,detail:i},e)}if(e?.schema){let r=e.schema.safeParse(s);if(!r.success){let o={status:"invalid",errorClass:"schema",detail:`schema validation failed (${r.error.issues.length} issue(s))`};return ot(o,e)}return {status:"ok",data:r.data}}return {status:"ok",data:s}}function ot(t,e){if(!(e?.strict??he())||t.status==="ok"||t.status==="missing")return t;throw new Error(`yaml load failed under PARADIGM_STRICT=1 (${t.errorClass}: ${t.detail})`)}b$1();var bs="@a-company/university",Ss=".paradigm/university",xs=".paradigm/cache/packs.json",U=class extends Error{constructor(n,s){super(`pack-load failed (${n}: ${s})`);this.errorClass=n;this.detail=s;this.name="PackLoadError";}},Er=["id","name","version","schema_version","tenant_kind"],Tr=new Set(["first-party","project","external"]);function ye(t){let e=P.join(t,ee),n=ws(e);switch(n.status){case "missing":throw new U("missing-manifest",`no ${ee} at pack root`);case "unparseable":throw new U("manifest-unparseable",n.detail);case "invalid":throw new U("manifest-invalid",n.detail);case "ok":{let s=n.data;if(!s||typeof s!="object")throw new U("manifest-invalid","manifest is not an object");for(let r of Er){let o=s[r];if(o==null||o==="")throw new U("missing-required-field",`required field ${String(r)} is missing or empty`)}if(!Tr.has(String(s.tenant_kind)))throw new U("missing-required-field","tenant_kind must be one of first-party|project|external");return s}}}function vs(t){let e=Pr(t);if(e)return e;let n=[],s=P.join(t,"node_modules",bs);if(w.existsSync(P.join(s,ee)))try{let o=ye(s);n.push({manifest:o,rootDir:s,source:"first-party"});}catch(o){a$1.component("#pack-loader").warn("first-party pack manifest invalid",{errorClass:o instanceof U?o.errorClass:"other"});}for(let o of kr(t))try{let i=ye(o);n.push({manifest:i,rootDir:o,source:"npm"});}catch(i){a$1.component("#pack-loader").warn("npm pack manifest invalid",{errorClass:i instanceof U?i.errorClass:"other"});}let r=P.join(t,Ss);if(w.existsSync(r)&&w.statSync(r).isDirectory()){let o=P.join(r,ee),i;if(w.existsSync(o))try{i=ye(r),n.push({manifest:i,rootDir:r,source:"local"});}catch(c){a$1.component("#pack-loader").warn("local pack manifest invalid",{errorClass:c instanceof U?c.errorClass:"other"});}let a=i?.id??"project";for(let c of _r(r))try{let l=ye(c);n.push({manifest:l,rootDir:c,source:"local",parentPackId:a});}catch(l){a$1.component("#pack-loader").warn("discipline sub-pack manifest invalid",{errorClass:l instanceof U?l.errorClass:"other"});}}return Rr(t,n),n}function kr(t){let e=P.join(t,"package.json");if(!w.existsSync(e))return [];let n;try{n=JSON.parse(w.readFileSync(e,"utf8"));}catch{return []}let s=new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.devDependencies||{}),...Object.keys(n.peerDependencies||{})]);if(s.size===0)return [];let r=P.join(t,"node_modules");if(!w.existsSync(r))return [];let o=[];for(let i of s){if(i===bs)continue;let a=P.join(r,i,"package.json");if(!w.existsSync(a))continue;let c;try{c=JSON.parse(w.readFileSync(a,"utf8"));}catch{continue}let l=c.paradigm?.universityPack;if(typeof l!="string"||l.length===0)continue;let d=P.resolve(P.dirname(a),l);w.existsSync(P.join(d,ee))&&o.push(d);}return o}function _r(t){let e=[],n;try{n=w.readdirSync(t,{withFileTypes:!0});}catch{return e}for(let s of n){if(!s.isDirectory()||s.name.startsWith("."))continue;let r=P.join(t,s.name);w.existsSync(P.join(r,ee))&&e.push(r);}return e}function Ei(t,e){if(typeof t!="string"||t.length===0)throw new Error("resolveEntryAddress: address must be a non-empty string");let n=t.indexOf(":");if(n!==-1){let r=t.slice(0,n),o=t.slice(n+1);if(!r||!o)throw new Error("resolveEntryAddress: malformed <pack-id>:<entry-id> address");return {packId:r,entryId:o}}let s=t;if(e.candidatePacks&&e.entryExistsIn){let r=e.candidatePacks.filter(o=>e.entryExistsIn(o,s));if(r.length>1){let o=r.map(i=>`${i}:${s}`).join(", ");throw new Error(`resolveEntryAddress: bare entry id "${s}" is ambiguous across packs. Candidates: ${o}`)}if(r.length===1)return {packId:r[0],entryId:s}}return {packId:e.activePack,entryId:s}}function Es(t){try{return w.statSync(P.join(t,"node_modules")).mtime.getTime()}catch{return}}function Ts(t){try{return w.statSync(P.join(t,Ss)).mtime.getTime()}catch{return}}function Pr(t){let e=P.join(t,xs);if(!w.existsSync(e))return null;let n;try{n=JSON.parse(w.readFileSync(e,"utf8"));}catch{return null}if(n.version!==1||!Array.isArray(n.packs))return null;let s=Es(t),r=Ts(t);return n.node_modules_mtime_ms!==s||n.local_university_mtime_ms!==r?null:n.packs.map(o=>({manifest:o.manifest,rootDir:o.rootDir,source:o.source,...o.parentPackId?{parentPackId:o.parentPackId}:{}}))}function Rr(t,e){let n=P.join(t,xs);try{w.mkdirSync(P.dirname(n),{recursive:!0});let s={version:1,node_modules_mtime_ms:Es(t),local_university_mtime_ms:Ts(t),packs:e.map(r=>({manifest:r.manifest,rootDir:r.rootDir,source:r.source,...r.parentPackId?{parentPackId:r.parentPackId}:{}}))};w.writeFileSync(n,JSON.stringify(s,null,2),"utf8");}catch{}}b$1();var we=".paradigm/university",ae="content",at="notes",Oe="policies",Fe="quizzes",Ne="paths",ks="diplomas",_s="index.yaml",Ir="config.yaml";function ct(t){let e=P.join(t,we);if(w.existsSync(e))return e;try{let s=vs(t).find(r=>r.manifest.tenant_kind==="first-party");if(s)return s.rootDir}catch{}return e}function Ps(t){if(!w.existsSync(t))return null;let e=P.join(t,ee);if(w.existsSync(e))try{return ye(t)}catch(s){a$1.component("#university-loader").warn("pack manifest invalid, using implicit manifest",{errorClass:s instanceof U?s.errorClass:"other"});}let n=P.basename(t)||"project";return {id:n,name:n,version:"0.0.0",schema_version:"1",tenant_kind:"project",description:"Implicit project pack (pack.yaml not present \u2014 v5 layout)",origin_hint:"authored"}}function $r(t,e,n){return e?{...t,...t.pack_id?{}:{pack_id:e.id},...t.discipline||!n?{}:{discipline:n}}:t}var Rs={name:"Project University",tagline:"Learn the codebase",institution:"Paradigm"},Is={primary:"#6366f1",secondary:"#8b5cf6",accent:"#f59e0b",background:"#0f172a",surface:"#1e293b",text:"#f8fafc",textMuted:"#94a3b8",success:"#22c55e",error:"#ef4444",font:"Inter, system-ui, sans-serif"},it={branding:Rs,theme:Is,content:{categories:[],defaultDifficulty:"beginner",requireApproval:false},diplomas:{includeGlobalPLSAT:true,customCertStyle:null}};function lt(t){let e=P.join(t,we,Ir);if(!w.existsSync(e))return {...it};try{let n=w.readFileSync(e,"utf8"),s=z.load(n);return s?{branding:{...Rs,...s.branding||{}},theme:{...Is,...s.theme||{}},content:{categories:s.content?.categories||[],defaultDifficulty:s.content?.defaultDifficulty||"beginner",requireApproval:s.content?.requireApproval??!1,defaultCategory:s.content?.defaultCategory},diplomas:{includeGlobalPLSAT:s.diplomas?.includeGlobalPLSAT??!0,customCertStyle:s.diplomas?.customCertStyle??null}}:{...it}}catch{return {...it}}}function Me(t){let e=P.join(t,we,_s);if(!w.existsSync(e))return null;try{let n=w.readFileSync(e,"utf8");return z.load(n)}catch{return null}}function $s(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:z.load(e[1]),body:e[2].trim()}}catch{return null}}function Cr(t,e){return `---
107
- ${z.dump(t,{lineWidth:-1,noRefs:true,sortKeys:false})}---
108
-
109
- ${e}
110
- `}function Ri(t,e,n){let s=ut(t,e,".md",n);if(!s)return null;try{let r=w.readFileSync(s,"utf8"),o=$s(r);if(!o)return null;let i=o.frontmatter;return {frontmatter:Or(i),body:o.body}}catch{return null}}function Ii(t,e,n,s){let r=e.type==="policy"?Oe:at,o=s??ct(t),i=P.join(o,ae,r);w.mkdirSync(i,{recursive:true});let a=Ps(o),c=$r(e,a),l=P.join(i,`${c.id}.md`),d=Cr(c,n);return w.writeFileSync(l,d,"utf8"),l}function Ar(t,e,n){let s=ut(t,e,".yaml",n);if(!s)return null;try{let r=w.readFileSync(s,"utf8"),o=z.load(r);return !o||!o.id?null:Fr(o)}catch{return null}}function $i(t,e,n){let s=n??ct(t),r=P.join(s,ae,Fe);w.mkdirSync(r,{recursive:true});let o=Ps(s),i={...e,...e.pack_id||!o?{}:{pack_id:o.id}},a=P.join(r,`${i.id}.yaml`);return w.writeFileSync(a,z.dump(i,{lineWidth:-1,noRefs:true}),"utf8"),a}function Cs(t,e,n){let s=ut(t,e,".yaml",n);if(!s)return null;try{let r=w.readFileSync(s,"utf8"),o=z.load(r);return !o||!o.id?null:o}catch{return null}}function Ci(t,e,n){let s=n??ct(t),r=P.join(s,ae,Ne);w.mkdirSync(r,{recursive:true});let o=P.join(r,`${e.id}.yaml`);return w.writeFileSync(o,z.dump(e,{lineWidth:-1,noRefs:true}),"utf8"),o}function As(t,e){let n=P.join(t,we,ks);if(!w.existsSync(n))return [];let s=[];try{let r=w.readdirSync(n).filter(o=>o.endsWith(".yaml"));for(let o of r)try{let i=w.readFileSync(P.join(n,o),"utf8"),a=z.load(i);if(!a||!a.id||e?.student&&a.student!==e.student||e?.type&&a.type!==e.type)continue;s.push(a);}catch{}}catch{}return s.sort((r,o)=>o.earnedAt.localeCompare(r.earnedAt))}function Ai(t,e){let n=Me(t);if(!n)return [];let s=[...n.entries];if(e.type&&(s=s.filter(o=>o.type===e.type)),e.tag&&(s=s.filter(o=>o.tags.some(i=>i.startsWith(e.tag)))),e.difficulty&&(s=s.filter(o=>o.difficulty===e.difficulty)),e.symbol&&(s=s.filter(o=>o.symbols.some(i=>i===e.symbol))),e.author&&(s=s.filter(o=>o.author===e.author)),e.query){let o=e.query.toLowerCase();s=s.filter(i=>i.title.toLowerCase().includes(o)||i.id.toLowerCase().includes(o)||i.tags.some(a=>a.toLowerCase().includes(o)));}if(e.category&&(s=s.filter(o=>o.category===e.category)),e.track){let o=lt(t),i=new Map;for(let a of o.content.categories)i.set(a.id,a.track||"core");s=s.filter(a=>(a.category&&i.get(a.category)||"core")===e.track);}let r=e.limit||20;return s.slice(0,r)}function dt(t){let e=P.join(t,we),n=P.join(e,ae),s=[];for(let d of [at,Oe]){let u=P.join(n,d);if(w.existsSync(u))try{for(let p of w.readdirSync(u).filter(g=>g.endsWith(".md")))try{let g=w.readFileSync(P.join(u,p),"utf8"),m=$s(g);if(!m)continue;let h=m.frontmatter;s.push({id:h.id||p.replace(".md",""),title:h.title||p,type:h.type||(d===Oe?"policy":"note"),author:h.author||"unknown",created:h.created||"",updated:h.updated||"",tags:Array.isArray(h.tags)?h.tags:[],symbols:Array.isArray(h.symbols)?h.symbols:[],difficulty:h.difficulty||"beginner",file:`${ae}/${d}/${p}`,...h.category?{category:h.category}:{}});}catch{}}catch{}}let r=P.join(n,Fe);if(w.existsSync(r))try{for(let d of w.readdirSync(r).filter(u=>u.endsWith(".yaml")))try{let u=w.readFileSync(P.join(r,d),"utf8"),p=z.load(u);if(!p||!p.id)continue;s.push({id:p.id,title:p.title||d,type:"quiz",author:p.author||"unknown",created:p.created||"",updated:p.updated||"",tags:p.tags||[],symbols:p.symbols||[],difficulty:p.difficulty||"beginner",file:`${ae}/${Fe}/${d}`,...p.category?{category:p.category}:{}});}catch{}}catch{}let o=P.join(n,Ne);if(w.existsSync(o))try{for(let d of w.readdirSync(o).filter(u=>u.endsWith(".yaml")))try{let u=w.readFileSync(P.join(o,d),"utf8"),p=z.load(u);if(!p||!p.id)continue;s.push({id:p.id,title:p.title||d,type:"path",author:p.author||"unknown",created:p.created||"",updated:p.updated||"",tags:p.tags||[],symbols:[],file:`${ae}/${Ne}/${d}`,...p.category?{category:p.category}:{}});}catch{}}catch{}let i=0,a=P.join(e,ks);if(w.existsSync(a))try{i=w.readdirSync(a).filter(d=>d.endsWith(".yaml")).length;}catch{}let c={version:"1.0",generatedAt:new Date().toISOString(),totalContent:s.length,entries:s,diplomaCount:i};w.mkdirSync(e,{recursive:true});let l=P.join(e,_s);return w.writeFileSync(l,z.dump(c,{lineWidth:-1,noRefs:true}),"utf8"),c}function ji(t,e){let n=Me(t)||dt(t),s=[],r=n.entries;e?.id&&(r=r.filter(l=>l.id===e.id));let o=null;e?.deep&&(o=js(t));let i=new Set(n.entries.map(l=>l.id));for(let l of r){if(l.title||s.push({contentId:l.id,severity:"error",check:"missing-title",message:"Content is missing a title",fix:"Add a title field to the content frontmatter"}),l.type==="quiz"&&jr(t,l.id,s),l.type==="path"&&Lr(t,l.id,i,s),o&&l.symbols.length>0){lt(t).content.categories.find(g=>g.id===l.category)?.validationStrictness==="relaxed";for(let g of l.symbols)o.has(g)||s.push({contentId:l.id,severity:"warning",check:"broken-symbol-ref",message:`Symbol "${g}" not found in scan-index`,fix:`Remove or update the symbol reference in ${l.id}`});}e?.deep&&l.symbols.length>0&&l.updated&&Mr(t,l,s);}let a=As(t);for(let l of a)if(l.total>0&&l.percentage!==Math.round(l.score/l.total*1e4)/100){let d=Math.round(l.score/l.total*1e4)/100;Math.abs(l.percentage-d)>.1&&s.push({contentId:l.id,severity:"warning",check:"diploma-score-mismatch",message:`Diploma percentage ${l.percentage} doesn't match score ${l.score}/${l.total} (expected ${d})`});}let c=Nr(t,n);return {status:s.some(l=>l.severity==="error")?"errors":s.length>0?"warnings":"healthy",totalContent:n.totalContent,checked:r.length,issues:s,symbolCoverage:c}}function jr(t,e,n){let s=Ar(t,e);if(!s){n.push({contentId:e,severity:"error",check:"unreadable-quiz",message:"Quiz file could not be parsed"});return}(!s.passThreshold||s.passThreshold<0||s.passThreshold>1)&&n.push({contentId:e,severity:"warning",check:"invalid-pass-threshold",message:`passThreshold should be between 0 and 1, got ${s.passThreshold}`,fix:"Set passThreshold to a value between 0.0 and 1.0"});for(let r of s.questions){if(!r.choices||typeof r.choices!="object"){n.push({contentId:e,severity:"error",check:"invalid-quiz-choices",message:`Question ${r.id} has no choices defined`});continue}(!r.correct||!(r.correct in r.choices))&&n.push({contentId:e,severity:"error",check:"invalid-quiz-answer",message:`Question ${r.id}: correct answer "${r.correct}" not found in choices [${Object.keys(r.choices).join(", ")}]`,fix:`Set correct to one of: ${Object.keys(r.choices).join(", ")}`});}}function Lr(t,e,n,s){let r=Cs(t,e);if(!r){s.push({contentId:e,severity:"error",check:"unreadable-path",message:"Learning path file could not be parsed"});return}for(let o of r.steps)o.content.startsWith("plsat:")||n.has(o.content)||s.push({contentId:e,severity:"error",check:"broken-path-step",message:`Learning path step references "${o.content}" which doesn't exist`,fix:`Create content with id "${o.content}" or remove this step`});}function Li(t,e){let n=Me(t);if(!n)return [];let s=[];for(let r of n.entries)if(r.symbols.includes(e)){let o=Ls(t,r,e);s.push({id:r.id,title:r.title,type:r.type,stale:o});}return s}function Oi(t,e){let n=Me(t);if(!n)return {paths:[],suggestedContent:[],extracurricular:[],diplomaCount:0,totalContent:0};let s=lt(t),r=new Set;for(let p of s.content.categories)p.excludeFromOnboarding&&r.add(p.id);let o=n.entries.filter(p=>!p.category||!r.has(p.category)),i=n.entries.filter(p=>p.category&&r.has(p.category)),a=o.filter(p=>p.type==="path"),c=e?As(t,{student:e}):[],l=new Set(c.map(p=>p.source)),d=a.map(p=>{let g=Cs(t,p.id);return {id:p.id,title:p.title,steps:g?.steps.length||0,completed:l.has(p.id)}}),u=o.filter(p=>p.type!=="path"&&(p.difficulty==="beginner"||p.tags.includes("onboarding"))).slice(0,10);return {paths:d,suggestedContent:u,extracurricular:i,diplomaCount:c.length,totalContent:n.totalContent}}function ut(t,e,n,s){let r=s??P.join(t,we),o=P.join(r,ae);for(let i of [at,Oe,Fe,Ne]){let a=P.join(o,i,`${e}${n}`);if(w.existsSync(a))return a}return null}function Or(t){return {id:t.id||"",title:t.title||"",type:t.type||"note",author:t.author||"unknown",created:t.created||"",updated:t.updated||"",tags:Array.isArray(t.tags)?t.tags:[],symbols:Array.isArray(t.symbols)?t.symbols:[],difficulty:t.difficulty||"beginner",estimatedMinutes:t.estimatedMinutes,prerequisites:Array.isArray(t.prerequisites)?t.prerequisites:[],...t.category?{category:t.category}:{},...t.origin?{origin:t.origin}:{},...t.source?{source:t.source}:{},...t.pack_id?{pack_id:t.pack_id}:{},...t.discipline?{discipline:t.discipline}:{}}}function Fr(t){return {...t,tags:t.tags||[],symbols:t.symbols||[],difficulty:t.difficulty||"beginner",passThreshold:t.passThreshold??.7,questions:t.questions||[]}}function js(t){let e=new Set,n=P.join(t,".paradigm","scan-index.json");if(!w.existsSync(n))return e;try{let s=w.readFileSync(n,"utf8"),r=JSON.parse(s);if(r.symbols&&Array.isArray(r.symbols))for(let o of r.symbols)o.symbol&&e.add(o.symbol);}catch{}return e}function Nr(t,e){let n=js(t),s=new Set;for(let o of e.entries)for(let i of o.symbols)n.has(i)&&s.add(i);let r=n.size;return {totalSymbols:r,coveredByContent:s.size,percentage:r>0?Math.round(s.size/r*100):0}}function Ls(t,e,n){if(!e.updated)return false;let s=new Date(e.updated).getTime();if(isNaN(s))return false;let r=P.join(t,".paradigm","scan-index.json");if(!w.existsSync(r))return false;try{let o=w.readFileSync(r,"utf8"),i=JSON.parse(o);if(i.symbols&&Array.isArray(i.symbols)){for(let a of i.symbols)if(a.symbol===n&&a.filePath){let c=P.join(t,a.filePath);if(w.existsSync(c)&&w.statSync(c).mtime.getTime()>s)return !0}}}catch{}return false}function Mr(t,e,n){for(let s of e.symbols)if(Ls(t,e,s)){n.push({contentId:e.id,severity:"warning",check:"stale-content",message:`Content may be stale: symbol "${s}" was updated after content was last modified`,fix:`Review and update ${e.id} to reflect changes to ${s}`});break}}var Os=new Set(["duplicate-key-detected"]);function Dr(t){let e=t.trim();if(e.includes("/")||e.includes("\\")){let n=e.split(/[/\\]/);e=n[n.length-1]||"unknown";}return e.length>40&&(e=e.slice(0,40)),e||"unknown"}var De=class{transforms=new Map;record(e,n,s=1){let r=Dr(n),o=`${e}::${r}`,i=this.transforms.get(o);i?i.count+=s:this.transforms.set(o,{kind:e,surface:r,count:s});}report(){let e=Array.from(this.transforms.values()).sort((s,r)=>s.kind!==r.kind?s.kind.localeCompare(r.kind):s.surface.localeCompare(r.surface)),n=e.filter(s=>Os.has(s.kind)).reduce((s,r)=>s+r.count,0);return {reindex_ts:new Date().toISOString(),transformations:e,lossy_count:n,strict_mode:he()}}hasLossy(){for(let e of this.transforms.values())if(Os.has(e.kind))return true;return false}totalCount(){let e=0;for(let n of this.transforms.values())e+=n.count;return e}};b$1();var Ur={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},zr={features:["src/features/","features/","app/","src/app/","src/modules/","modules/"],components:["src/components/","components/","src/lib/","lib/","src/ui/","ui/"],gates:["middleware/","src/middleware/","auth/","src/auth/","guards/","src/guards/"],flows:["flows/","src/flows/","workflows/","src/workflows/","sagas/","src/sagas/"],integrations:["integrations/","src/integrations/","external/","src/external/","vendors/"],signals:["events/","src/events/","handlers/","src/handlers/"],state:["stores/","src/stores/","state/","src/state/","reducers/","src/reducers/"]},Hr={config:[".paradigm/config.yaml","package.json","tsconfig.json",".env.example"],entry:["src/index.ts","src/index.tsx","src/main.ts","src/main.tsx","index.ts","main.ts","src/app.ts","src/app.tsx"],types:["src/types/","types/","src/types.ts","types.ts"]},pt={always:["node_modules/","dist/","build/",".git/",".next/",".nuxt/",".cache/","*.lock","*.log"],unless_testing:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","__tests__/","test/","tests/"],unless_docs:["docs/","*.md","README*","CHANGELOG*"]};function ea(){return [{name:"paradigm_reindex",description:"Rebuild scan-index.json, navigator.yaml, and flow-index.json from .purpose files. Call after modifying paradigm files or at the end of a work session to ensure static index files are fresh. Returns counts of indexed symbols, files processed, and any errors. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:false,destructiveHint:true},aliases:["rebuild","refresh","rescan","regenerate index","update index"]}]}async function ta(t,e,n,s){if(t!=="paradigm_reindex")return {handled:false,text:""};try{let r=await Wr(n.rootDir,n);await s(),Vt.clear(),Kt();let o=(r.integrityReport?.brokenReferences?.length||0)+(r.integrityReport?.duplicateSymbols?.length||0)+(r.componentAnchorIssues||0)+(r.crossFileIssues||0),i={success:!0,symbolCount:r.symbolCount,breakdown:r.breakdown,flowCount:r.flowCount,filesWritten:r.filesWritten.length,...r.aspectGraphStats?{aspects:r.aspectGraphStats.aspects,loreLinks:r.aspectGraphStats.loreLinks}:{},...r.protocolHealth?{protocols:r.protocolHealth.total,staleProtocols:r.protocolHealth.stale}:{},...o>0?{issues:o}:{}};r.consistency&&(i.consistency=r.consistency);let a=JSON.stringify(i,null,2);return Ye(a.length,t),{handled:!0,text:a}}catch(r){let o=JSON.stringify({error:r.message},null,2);return Ye(o.length,t),{handled:true,text:o}}}async function Wr(t,e){let n=[],s=new De,r;e?r=e.aggregation:r=await Bt(t);let o=e?.projectName||P.basename(t),i=P.join(t,".paradigm");w.existsSync(i)||w.mkdirSync(i,{recursive:true}),Gr(t,s),Br(r.purposeFiles,s);let a=qe({symbols:r.symbols,purposeFiles:r.purposeFiles,portalFiles:r.portalFiles},{projectName:o}),c=P.join(i,"scan-index.json");w.writeFileSync(c,Ve(a),"utf8"),n.push(".paradigm/scan-index.json");let l=Xr(t,r),d=P.join(i,"navigator.yaml");w.writeFileSync(d,z.dump(l,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),n.push(".paradigm/navigator.yaml");let u=Qr(t,r.purposeFiles),p=0;if(u&&Object.keys(u.flows).length>0){let E=P.join(i,"flow-index.json");w.writeFileSync(E,JSON.stringify(u,null,2),"utf8"),n.push(".paradigm/flow-index.json"),p=Object.keys(u.flows).length;}let g;try{let E=await as(t);ls(E,r.symbols,t);let j=await us(E,t),te=await ps(E,t),se=E.exec("SELECT COUNT(*) FROM aspects")[0]?.values[0]?.[0]??0,pe=E.exec("SELECT COUNT(*) FROM anchors")[0]?.values[0]?.[0]??0,ke=E.exec("SELECT COUNT(*) FROM edges")[0]?.values[0]?.[0]??0;cs(E,t),n.push(".paradigm/aspect-graph.db"),g={aspects:se,anchors:pe,edges:ke,loreLinks:j};}catch{}let m=0;try{let E=await Te(t);m=Object.keys(E.personas).length,m>0&&n.push(".paradigm/personas/index.yaml");}catch{}let h;try{let E=await gs(t);E.health.total>0&&(h=E.health,n.push(".paradigm/protocols/index.yaml"));}catch{}let v;try{let E=P.join(t,".paradigm","university");if(w.existsSync(E)){let j=dt(t);(j.totalContent>0||j.diplomaCount>0)&&(v={totalContent:j.totalContent,diplomaCount:j.diplomaCount},n.push(".paradigm/university/index.yaml"));}}catch{}let T;try{T=a$2(r,t);}catch{}let C;try{let E=b$4(r.symbols,t),j=E.missing+E.outOfBounds;j>0&&(C=j);}catch{}let N;try{N=c$2(r.purposeFiles,t);}catch{}let b;try{let E=[];for(let j of r.purposeFiles){let te=Ge(j);te.data&&E.push({filePath:j,data:te.data});}if(E.length>0){let te=Ot(E).issues.length;te>0&&(b=te);}}catch{}let S={};for(let E of r.symbols)S[E.type]=(S[E.type]||0)+1;let x={};for(let E of r.symbols)E.type==="component"&&E.componentType&&(x[E.componentType]=(x[E.componentType]||0)+1);let k=s.report();try{let E=P.join(i,"manifest.consistency.json");w.writeFileSync(E,JSON.stringify(k,null,2),"utf-8"),n.push(".paradigm/manifest.consistency.json");}catch{a$1.component("#reindex").warn("failed to write consistency manifest",{stage:"manifest-write"});}if(he()&&s.hasLossy())throw new Error(`reindex aborted: ${k.lossy_count} lossy transformation(s) detected under PARADIGM_STRICT=1. See .paradigm/manifest.consistency.json.`);return {action:"reindex",filesWritten:n,symbolCount:r.symbols.length,breakdown:S,flowCount:p,aspectGraphStats:g,personaCount:m,protocolHealth:h,consistency:k,...Object.keys(x).length>0?{componentTypeBreakdown:x}:{},...v?{universityStats:v}:{},...T?{integrityReport:T}:{},...C!==void 0?{componentAnchorIssues:C}:{},...N?{purposeHealth:N}:{},...b!==void 0?{crossFileIssues:b}:{}}}function Gr(t,e){let n=P.join(t,"portal.yaml");if(!w.existsSync(n))return;let s;try{s=w.readFileSync(n,"utf-8");}catch{return}try{z.load(s);}catch(c){(c?.reason?.toLowerCase()||"").includes("duplicate")&&e.record("duplicate-key-detected","portal.yaml");return}let r;try{r=z.load(s,{schema:z.FAILSAFE_SCHEMA});}catch{return}if(!r||typeof r!="object")return;let o=r,i=o.gates;if(i&&typeof i=="object"&&!Array.isArray(i)){let c=0;for(let l of Object.keys(i))l.startsWith("^")&&c++;c>0&&e.record("prefix-stripped","portal.yaml",c);}else Array.isArray(i)&&i.length>0&&e.record("array-coerced","portal.yaml");let a=o.routes;Array.isArray(a)&&a.length>0&&e.record("array-coerced","portal.yaml"),o.version||e.record("default-applied","portal.yaml");}function Br(t,e){for(let n of t){let s;try{s=w.readFileSync(n,"utf-8");}catch{continue}try{z.load(s);}catch(d){(d?.reason?.toLowerCase()||"").includes("duplicate")&&e.record("duplicate-key-detected","purpose.yaml");continue}let r;try{r=z.load(s,{schema:z.FAILSAFE_SCHEMA});}catch{continue}if(!r||typeof r!="object")continue;let o=r,i=["components","features","gates","signals","aspects","states"],a=0;for(let d of i)Array.isArray(o[d])&&a++;a>0&&e.record("array-coerced","purpose.yaml",a);let c=(d,u)=>{if(!d||typeof d!="object"||Array.isArray(d))return 0;let p=0;for(let g of Object.keys(d))g.startsWith(u)&&p++;return p},l=c(o.gates,"^")+c(o.signals,"!")+c(o.aspects,"~")+c(o.components,"#")+c(o.features,"#");l>0&&e.record("prefix-stripped","purpose.yaml",l);}}function Xr(t,e){let n={};for(let s of e.symbols)if(s.type==="component"&&s.componentType){let r=s.componentType;n[r]||(n[r]=[]),n[r].push(s.symbol);}return {version:"1.0",generated:new Date().toISOString(),structure:qr(t),key_files:Vr(t),skip_patterns:Yr(t),symbols:Jr(e.symbols,e.purposeFiles),...Object.keys(n).length>0?{symbolsByComponentType:n}:{}}}function qr(t){let e={};for(let[n,s]of Object.entries(zr)){let r=s.filter(o=>w.existsSync(P.join(t,o)));if(r.length>0){let o=Object.values(Ur).find(i=>i.category===n);e[n]={paths:r,symbol:o?.prefix||"@"};}}return e}function Vr(t){let e={};for(let[n,s]of Object.entries(Hr)){let r=s.filter(o=>w.existsSync(P.join(t,o)));r.length>0&&(e[n]=r);}return e.config||(e.config=[]),e.entry||(e.entry=[]),e.types||(e.types=[]),e}function Yr(t){let e={always:[...pt.always],unless_testing:[...pt.unless_testing],unless_docs:[...pt.unless_docs]},n=P.join(t,".gitignore");if(w.existsSync(n))try{let r=w.readFileSync(n,"utf8").split(`
111
- `).map(o=>o.trim()).filter(o=>o&&!o.startsWith("#")).filter(o=>o.endsWith("/")||o.includes("*")||["node_modules","dist","build",".cache"].some(i=>o.includes(i))).slice(0,20);for(let o of r)e.always.includes(o)||e.always.push(o);}catch{}return e}function Kr(t){switch(t){case "feature":return "@";case "component":return "#";case "gate":return "^";case "flow":return "$";case "integration":return "&";case "signal":return "!";case "state":return "%";case "idea":return "?";case "deprecated":return "~";case "aspect":return "~";default:return "@"}}function Jr(t,e,n){let s={};for(let r of t){let i=`${Kr(r.type)}${r.id}`;if(r.filePath)s[i]=r.filePath;else {let a=e.find(c=>P.dirname(c).toLowerCase().includes(r.id.toLowerCase()));a&&(s[i]=P.dirname(a)+"/");}}return s}function Qr(t,e){let n={},s={};for(let r of e)try{let o=w.readFileSync(r,"utf8"),i=z.load(o);if(!i?.flows)continue;if(Array.isArray(i.flows))for(let a of i.flows){let c=a;if(!c.name)continue;let l=`$${c.name}`,d=Fs(c.steps);d.length>0&&(n[l]={id:l,description:c.description||"",steps:d,definedIn:P.relative(t,r)},Ns(l,d,s));}else for(let[a,c]of Object.entries(i.flows)){let l=a.startsWith("$")?a:`$${a}`,d=Fs(c.steps);d.length>0&&(n[l]={id:l,description:c.description||"",trigger:c.trigger,steps:d,validation:c.validation,definedIn:P.relative(t,r)},Ns(l,d,s));}}catch{}return Object.keys(n).length===0?null:{version:"1.0",generatedAt:new Date().toISOString(),flows:n,symbolToFlows:s}}function Fs(t){if(!t||!Array.isArray(t))return [];let e=[];for(let n=0;n<t.length;n++){let s=t[n];if(typeof s=="object"&&s!==null){let r=s,o=r.action||r.description||r.component||"";o&&e.push({id:r.id||`step-${n+1}`,action:o,symbol:r.symbol||r.component,expect:r.expect});}}return e}function Ns(t,e,n){for(let s of e)s.symbol&&(n[s.symbol]||(n[s.symbol]=[]),n[s.symbol].includes(t)||n[s.symbol].push(t));}export{li as $,ti as A,si as B,ni as C,ri as D,oi as E,ii as F,ai as G,he as H,ws as I,vs as J,Ei as K,ct as L,Ps as M,lt as N,Ri as O,Ii as P,Ar as Q,$i as R,Cs as S,Ci as T,Ai as U,dt as V,ji as W,Li as X,Oi as Y,rt as Z,hr as _,en as a,di as aa,eo as b,ui as ba,sn as c,pi as ca,so as d,yr as da,Ie as e,fi as ea,Bt as f,Je as fa,uo as g,Fo as ga,$e as h,as as ha,po as i,cs as ia,fo as j,Ho as ja,mo as k,Wo as ka,go as l,Go as la,ho as m,Bo as ma,yo as n,Xo as na,Ye as o,qo as oa,Ro as p,Vo as pa,Io as q,Yo as qa,$o as r,Qo as ra,Co as s,ea as sa,Ao as t,ta,Yt as u,Wr as ua,Vt as v,ve as w,Ee as x,ei as y,fs as z};