@a-company/paradigm 5.23.0 → 5.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-loader-EPXURMO7.js → agent-loader-MQMXCI3D.js} +1 -1
- package/dist/{agent-loader-PYGPX6D2.js → agent-loader-RGPE3LRD.js} +1 -1
- package/dist/{ambient-WEPHBAJD.js → ambient-2RAKMUC7.js} +2 -2
- package/dist/{chunk-V7K6CQVX.js → chunk-4YIKDQRB.js} +9 -9
- package/dist/chunk-73R63P7K.js +2 -0
- package/dist/{chunk-Z34K6GY2.js → chunk-CUOEZAVL.js} +4 -4
- package/dist/{chunk-HXKWL3VK.js → chunk-DJERXYEL.js} +1 -1
- package/dist/{chunk-4ZGGWZ32.js → chunk-HBGRP73K.js} +1 -1
- package/dist/{chunk-PUBB7LIT.js → chunk-PBVBTHGE.js} +1 -1
- package/dist/{chunk-AD5TAD2A.js → chunk-UELDOSWH.js} +1 -1
- package/dist/{chunk-6EX37L4Q.js → chunk-VZLGBGU3.js} +5 -5
- package/dist/{chunk-2QO33NYK.js → chunk-XGAOYG77.js} +2 -2
- package/dist/{chunk-XUFYOXOU.js → chunk-ZMQXXFG2.js} +2 -2
- package/dist/{compliance-TSXLXADI.js → compliance-LM2NN2S6.js} +2 -2
- package/dist/{docs-RXPN6CK7.js → docs-5BX2YWYK.js} +1 -1
- package/dist/{habits-LX5IWCZM.js → habits-GICVMTJL.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/mcp.js +24 -24
- package/dist/{nomination-engine-XF7TWPAP.js → nomination-engine-K7MQD53E.js} +1 -1
- package/dist/platform-server-G6MJIAJS.js +25 -0
- package/dist/reindex-HA3CJG7S.js +2 -0
- package/dist/{serve-JE6UF5P2.js → serve-ZJ3EXVA5.js} +1 -1
- package/dist/session-tracker-G7VOLRMR.js +2 -0
- package/dist/{session-work-log-3MNUDEZ6.js → session-work-log-HFOD7LEG.js} +1 -1
- package/dist/{session-work-log-J2H5OZBR.js → session-work-log-IEYBPFUC.js} +1 -1
- package/dist/{symphony-3QMBGCZY.js → symphony-43N4R6C2.js} +1 -1
- package/dist/{symphony-QI63XL62.js → symphony-ZQ5OHJTP.js} +3 -3
- package/dist/{symphony-loader-XACVV2E3.js → symphony-loader-XJT43FOS.js} +1 -1
- package/dist/{symphony-relay-5GY5JIPT.js → symphony-relay-KBHN3ZMR.js} +1 -1
- package/dist/university-FJ7OCOA3.js +2 -0
- package/package.json +1 -1
- package/platform-ui/dist/assets/AmbientSection-BYjt75R1.js +1 -0
- package/platform-ui/dist/assets/{CanvasSection-DLW0s-Bu.js → CanvasSection-rKvA_vZj.js} +2 -2
- package/platform-ui/dist/assets/{DocsSection-BQ9Hi51g.js → DocsSection-CI9K73M-.js} +1 -1
- package/platform-ui/dist/assets/GitSection-DSGj_c6S.js +4 -0
- package/platform-ui/dist/assets/{GraphSection-0c9C-w7K.js → GraphSection-CawN7pC5.js} +2 -2
- package/platform-ui/dist/assets/LoreSection-oO5dCe6O.js +1 -0
- package/platform-ui/dist/assets/{SentinelSection-C4OoME9U.js → SentinelSection-DNgoYMH0.js} +1 -1
- package/platform-ui/dist/assets/SymphonySection-C0zfcqv3.js +1 -0
- package/platform-ui/dist/assets/TeamSection-Bzd3Dt9Q.js +1 -0
- package/platform-ui/dist/assets/UniversitySection-B3ltVfpt.css +1 -0
- package/platform-ui/dist/assets/UniversitySection-tBr62R0S.js +1 -0
- package/platform-ui/dist/assets/{index-DPpOdAtC.js → index-BaOmyn11.js} +12 -12
- package/platform-ui/dist/index.html +1 -1
- package/dist/chunk-RMOALQJN.js +0 -2
- package/dist/platform-server-2KXHGHFV.js +0 -25
- package/dist/reindex-PGDQSM42.js +0 -2
- package/dist/session-tracker-SKOMBDOW.js +0 -2
- package/platform-ui/dist/assets/AmbientSection-DqQ2mfCO.js +0 -1
- package/platform-ui/dist/assets/GitSection-QQeUX6o3.js +0 -4
- package/platform-ui/dist/assets/LoreSection--t56kCj2.js +0 -1
- package/platform-ui/dist/assets/SymphonySection-B-rvsLxq.js +0 -1
- package/platform-ui/dist/assets/TeamSection-CBFmNEEo.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a as a$1,b as b$3,c as c$2}from'./chunk-M4UMM6DC.js';import {j,b as b$2,a as a$2}from'./chunk-ODVKPZZ4.js';import {j as j$1,a,b as b$1,c as c$1,k}from'./chunk-
|
|
3
|
-
`).filter(n=>n.trim()!=="");return {firstLine:ye(e[0]||""),lastLine:ye(e[e.length-1]||""),lineCount:e.length,structuralHash:At(e)}}function At(t){let e=t.map(n=>n.trim()).filter(n=>kt.test(n)).map(n=>{let s=n.match(kt);return s?s[1].trim():""}).join("|");return
|
|
2
|
+
import {a as a$1,b as b$3,c as c$2}from'./chunk-M4UMM6DC.js';import {j,b as b$2,a as a$2}from'./chunk-ODVKPZZ4.js';import {j as j$1,a,b as b$1,c as c$1,k}from'./chunk-HBGRP73K.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as v from'fs';import*as $ from'path';import*as K from'crypto';import {execSync}from'child_process';import*as O from'js-yaml';import {z as z$1}from'zod';import {glob}from'glob';import*as he from'os';import ms from'sql.js';var Ft={};c(Ft,{contentSearch:()=>gs,detectFileRename:()=>Ot,generateFingerprint:()=>Ct,levenshteinDistance:()=>jt,levenshteinSimilarity:()=>Fe,searchSiblingFiles:()=>Lt,slidingWindowSearch:()=>we});function Ct(t){let e=t.split(`
|
|
3
|
+
`).filter(n=>n.trim()!=="");return {firstLine:ye(e[0]||""),lastLine:ye(e[e.length-1]||""),lineCount:e.length,structuralHash:At(e)}}function At(t){let e=t.map(n=>n.trim()).filter(n=>kt.test(n)).map(n=>{let s=n.match(kt);return s?s[1].trim():""}).join("|");return K.createHash("sha256").update(e).digest("hex").slice(0,16)}function ye(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function jt(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 o=new Array(n+1),r=new Array(n+1);for(let i=0;i<=n;i++)o[i]=i;for(let i=1;i<=s;i++){r[0]=i;for(let a=1;a<=n;a++){let l=t[a-1]===e[i-1]?0:1;r[a]=Math.min(o[a]+1,r[a-1]+1,o[a-1]+l);}[o,r]=[r,o];}return o[n]}function Fe(t,e){if(t.length===0&&e.length===0)return 1;let n=Math.max(t.length,e.length);return 1-jt(t,e)/n}function we(t,e,n,s=3){let{lineCount:o}=e,r=Math.max(1,Math.floor(o*.8)),i=Math.ceil(o*1.2),a=[],l=Le(n);for(let d of [o,r,i])if(!(d>t.length))for(let u=0;u<=t.length-d;u++){let p=t.slice(u,u+d),g=fs(p,e,l);if(g>=.5){let m=p.join(`
|
|
4
4
|
`);a.push({windowStart:u+1,windowEnd:u+d,similarity:Fe(Le(m),l),score:g});}}let c=new Map;for(let d of a){let u=c.get(d.windowStart);(!u||d.score>u.score)&&c.set(d.windowStart,d);}return Array.from(c.values()).sort((d,u)=>u.score-d.score).slice(0,s)}function fs(t,e,n){let s=t.filter(p=>p.trim()!=="");if(s.length===0)return 0;let o=0,r=ye(s[0]),i=ye(s[s.length-1]),a=0;r===e.firstLine&&(a+=.5),i===e.lastLine&&(a+=.5),o+=a*ls,At(s)===e.structuralHash&&(o+=ds);let c=s.join(`
|
|
5
5
|
`),d=Fe(Le(c),n);d>=.8&&(o+=(d-.8)/.2*us);let u=s.length/e.lineCount;if(u>=.8&&u<=1.2){let p=1-Math.abs(1-u)/.2;o+=p*ps;}return o}function Le(t){return t.split(`
|
|
6
6
|
`).map(e=>e.trim()).filter(e=>e!=="").join(`
|
|
@@ -8,7 +8,7 @@ import {a as a$1,b as b$3,c as c$2}from'./chunk-M4UMM6DC.js';import {j,b as b$2,
|
|
|
8
8
|
`);for(let o of s){let r=o.split(" ");if(r.length>=3&&r[0].startsWith("R"))return r[2]}return null}catch{return null}}function Lt(t,e,n,s,o=10){let r=$.isAbsolute(e)?e:$.join(t,e);if(!v.existsSync(r))return [];let i=[];try{let a=v.readdirSync(r).filter(l=>!l.startsWith(".")&&v.statSync($.join(r,l)).isFile()).slice(0,o);for(let l of a)try{let d=v.readFileSync($.join(r,l),"utf8").split(`
|
|
9
9
|
`),u=we(d,n,s,1);if(u.length>0&&u[0].score>=.7){let p=$.relative(t,$.join(r,l));i.push({file:p,score:u[0].score,start:u[0].windowStart,end:u[0].windowEnd});}}catch{}}catch{return []}return i.sort((a,l)=>l.score-a.score)}function gs(t,e,n,s=true){let o=Ct(n),r=$.isAbsolute(e)?e:$.join(t,e);if(v.existsSync(r)){let d=v.readFileSync(r,"utf8").split(`
|
|
10
10
|
`),u=we(d,o,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=Ot(t,e);if(i){let c=$.join(t,i);if(v.existsSync(c)){let u=v.readFileSync(c,"utf8").split(`
|
|
11
|
-
`),p=we(u,o,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=$.dirname(e),l=Lt(t,a,o,n);if(l.length>0&&l[0].score>=.7){let c=l[0];return {found:true,score:c.score,suggestedStart:c.start,suggestedEnd:c.end,suggestedPath:c.file!==e?c.file:void 0,similarity:c.score}}return {found:false,score:0}}var kt,ls,ds,us,ps,Nt=b(()=>{kt=/^\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 )/;ls=.4,ds=.3,us=.2,ps=.1;});var Re=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(),nt=Re.extend({id:z$1.string()}),pn=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()}),fn=z$1.union([pn,z$1.string().transform(t=>({description:t}))]),gn=z$1.object({from:z$1.string(),to:z$1.string(),type:z$1.string(),description:z$1.string().optional()}),mn=z$1.union([gn,z$1.string()]),hn=z$1.object({component:z$1.string(),action:z$1.string(),description:z$1.string().optional()}),it=z$1.union([hn,z$1.string()]),yn=z$1.object({name:z$1.string(),description:z$1.string().optional(),steps:z$1.array(it)}),wn=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(it).optional()}),bn=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()}),Sn=z$1.object({description:z$1.string().optional(),default:z$1.unknown().optional(),type:z$1.string().optional()}),xn=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()}),vn=z$1.object({target:z$1.string(),type:z$1.string(),path:z$1.string()}),En=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(nt),z$1.record(Re)]).optional(),components:z$1.union([z$1.array(nt),z$1.record(Re)]).optional(),gates:z$1.record(bn).optional(),states:z$1.record(Sn).optional(),signals:z$1.record(fn).optional(),aspects:z$1.record(xn).optional(),relationships:z$1.array(mn).optional(),flows:z$1.union([z$1.array(yn),z$1.record(wn)]).optional(),references:z$1.array(vn).optional()});function Ie(t){let e=Tn(t);return {data:e.data,errors:e.errors}}function Tn(t){let e=[],n=[],s;try{s=v.readFileSync(t,"utf8");}catch(a){let l=`Cannot read file: ${a.message}`;return e.push(l),n.push({message:l,type:"file"}),{data:null,errors:e,detailedErrors:n,rawContent:void 0,isYamlValid:false}}let o=s.replace(/^([#~!$^][\w-]+):/gm,'"$1":').replace(/^(\s*-\s+)([!#][\w-]+)$/gm,'$1"$2"'),r=null;try{r=O.load(o);}catch(a){let l=a,c=l.mark?.line?l.mark.line+1:void 0,d=`YAML syntax error: ${l.reason||a.message}`;return e.push(`${d}${c?` (line ${c})`:""}`),n.push({message:d,line:c,type:"yaml"}),{data:null,errors:e,detailedErrors:n,rawContent:s,isYamlValid:false}}if(r==null)return {data:{},errors:[],detailedErrors:[],rawContent:s,isYamlValid:true};if(typeof r=="object"&&r!==null){let a=r,l={"#":"components",$:"flows","^":"gates","!":"signals","~":"aspects"};for(let c of Object.keys(a)){let d=c[0],u=l[d];if(!u||c.length<2)continue;let p=c.slice(1),g=a[c];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[c];}}let i=En.safeParse(r);if(!i.success){for(let a of i.error.issues){let l=a.path.join("."),c=a.message;e.push(`Schema error at ${l||"/"}: ${c}`),n.push({message:c,path:l||"/",type:"schema"});}return {data:r,errors:e,detailedErrors:n,rawContent:s,isYamlValid:true}}return {data:i.data,errors:[],detailedErrors:[],rawContent:s,isYamlValid:true}}function po(t){return O.dump(t,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function ue(t){return t?Array.isArray(t)?t.map(e=>[e.id,e]):Object.entries(t):[]}async function $n(t){let e=$.resolve(t);return (await glob("**/.purpose",{cwd:e,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})).sort((s,o)=>{let r=s.split($.sep).length,i=o.split($.sep).length;return r-i})}async function at(t){let e=await $n(t),n=[];for(let s of e){let{data:o,errors:r}=Ie(s);o&&(n.push({filePath:s,data:o}),r.length>0&&console.warn(`Warnings parsing ${s}:`,r));}return n}function ct(t){let e=new Map;for(let{filePath:n,data:s}of t){let o=ue(s.features);for(let[r,i]of o)e.set(r,{item:i,filePath:n});}return e}function lt(t){let e=new Map;for(let{filePath:n,data:s}of t){let o=ue(s.components);for(let[r,i]of o)e.set(r,{item:i,filePath:n});}return e}function dt(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.gates)for(let[o,r]of Object.entries(s.gates))e.set(o,{item:r,filePath:n});return e}function ut(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.states)for(let[o,r]of Object.entries(s.states))e.set(o,{item:r,filePath:n});return e}function pt(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.flows)if(Array.isArray(s.flows))for(let o of s.flows)e.set(o.name,{item:{id:o.name,description:o.description,steps:o.steps},filePath:n});else for(let[o,r]of Object.entries(s.flows))e.set(o,{item:{id:o,description:r.description,gates:r.gates,signals:r.signals,components:r.components,steps:r.steps},filePath:n});return e}function ft(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.signals)for(let[o,r]of Object.entries(s.signals))e.set(o,{item:r,filePath:n});return e}function gt(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.aspects)for(let[o,r]of Object.entries(s.aspects))e.set(o,{item:r,filePath:n});return e}function mt(t){let e=[],n=new Set;for(let{filePath:s,data:o}of t){let r=ue(o.features);for(let[a,l]of r)st(`#${a}`,l,s,e,n);let i=ue(o.components);for(let[a,l]of i)st(`#${a}`,l,s,e,n);}return e}function st(t,e,n,s,o){if(e.flows)for(let r of e.flows){let i=r.startsWith("$")?r:`$${r}`;o.has(i)||(o.add(i),s.push({symbol:i,type:"flow",sourceSymbol:t,filePath:n}));}if(e.gates)for(let r of e.gates){let i=r.startsWith("^")?r:`^${r}`;o.has(i)||(o.add(i),s.push({symbol:i,type:"gate",sourceSymbol:t,filePath:n}));}if(e.signals)for(let r of e.signals){let i=r.startsWith("!")?r:`!${r}`;o.has(i)||(o.add(i),s.push({symbol:i,type:"signal",sourceSymbol:t,filePath:n}));}if(e.states)for(let r of e.states){let i=r.startsWith("#")?r:r.startsWith("%")?`#${r.slice(1)}`:`#${r}`;o.has(i)||(o.add(i),s.push({symbol:i,type:"component",sourceSymbol:t,filePath:n}));}if(e.components)for(let r of e.components){let i=r.startsWith("#")?r:`#${r}`;o.has(i)||(o.add(i),s.push({symbol:i,type:"component",sourceSymbol:t,filePath:n}));}if(e.aspects)for(let r of e.aspects){let i=r.startsWith("~")?r:`~${r}`;o.has(i)||(o.add(i),s.push({symbol:i,type:"aspect",sourceSymbol:t,filePath:n}));}if(e.description){let r=In(e.description);for(let{symbol:i,type:a}of r)o.has(i)||(o.add(i),s.push({symbol:i,type:a,sourceSymbol:t,filePath:n}));}}var Rn=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function In(t){let e=[],n=/([$^!#~%])([a-zA-Z][a-zA-Z0-9._-]*)/g,s;for(;(s=n.exec(t))!==null;){let o=s[1],r=s[2],i,a;switch(o){case "#":a="component",i=`#${r}`;break;case "$":a="flow",i=`$${r}`;break;case "^":a="gate",i=`^${r}`;break;case "!":a="signal",i=`!${r}`;break;case "~":a="aspect",i=`~${r}`;break;case "%":a="component",i=`#${r}`;break;default:continue}Rn.has(i)||e.push({symbol:i,type:a});}return e}function ne(t){return t?Array.isArray(t)?t.map(e=>[e.id,e]):Object.entries(t):[]}function $e(t){return t?Array.isArray(t)?t.map(e=>e.id):Object.keys(t):[]}function go(t,e){let n=[],s=e?`${e}: `:"",o=ne(t.features);for(let[i,a]of o)ot(i,a,"feature",s,n);let r=ne(t.components);for(let[i,a]of r)ot(i,a,"component",s,n);if(t.relationships){let i=new Set([...$e(t.features),...$e(t.components)]);for(let a of t.relationships){if(typeof a=="string"||!a||!a.from||!a.to)continue;let l=a.from.replace(/^[@#$%~^!?]/,"");!i.has(l)&&!a.from.includes(".")&&n.push({type:"warning",message:`${s}Relationship references unknown source: "${a.from}"`,path:"relationships"});let c=a.to.replace(/^[@#$%~^!?]/,"");!i.has(c)&&!a.to.includes(".")&&n.push({type:"warning",message:`${s}Relationship references unknown target: "${a.to}"`,path:"relationships"});}}if(t.flows){let i=new Set($e(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 l of a.steps){if(typeof l=="string"||!l||!l.component)continue;let c=l.component.replace(/^#/,"");i.has(c)||n.push({type:"warning",message:`${s}Flow "${a.name}" references unknown component: "${l.component}"`,path:`flows.${a.name}`});}}else for(let[a,l]of Object.entries(t.flows))if(!(!l||typeof l!="object")&&l.steps&&Array.isArray(l.steps))for(let c of l.steps){if(typeof c=="string"||!c||!c.component)continue;let d=c.component.replace(/^#/,"");i.has(d)||n.push({type:"warning",message:`${s}Flow "${a}" references unknown component: "${c.component}"`,path:`flows.${a}`});}}return {valid:n.filter(i=>i.type==="error").length===0,issues:n}}function ot(t,e,n,s,o){let r=`${n}s.${t}`;if(/^[a-zA-Z][a-zA-Z0-9-]*$/.test(t)||o.push({type:"warning",message:`${s}${n} ID "${t}" should use alphanumeric characters and hyphens`,path:r}),(!e.description||e.description.trim()==="")&&o.push({type:"warning",message:`${s}${n} "${t}" has no description`,path:r}),e.endpoints)for(let i of e.endpoints)/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+\//.test(i)||o.push({type:"warning",message:`${s}Endpoint "${i}" in ${n} "${t}" may not be in standard format (e.g., "GET /api/users")`,path:`${r}.endpoints`});}function ht(t){let e=[],n=new Set;for(let{data:s}of t){let o=ne(s.components);for(let[i]of o)n.add(`#${i}`),n.add(i);let r=ne(s.features);for(let[i]of r)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:o}of t){let r=s?`${s}: `:"",i=[...ne(o.components),...ne(o.features)];for(let[a,l]of i){if(l.parent){let d=l.parent.replace(/^["']|["']$/g,""),u=d.replace(/^[#$^!~@%?&]/,"");!n.has(d)&&!n.has(u)&&e.push({type:"warning",message:`${r}Component "${a}" references parent "${d}" which is not defined in any .purpose file`,path:`components.${a}.parent`});}let c=[{field:"gates",refs:l.gates},{field:"signals",refs:l.signals},{field:"flows",refs:l.flows},{field:"components",refs:l.components},{field:"aspects",refs:l.aspects}];for(let{field:d,refs:u}of c)if(u)for(let p of u){let g=p.replace(/^[#$^!~@%?&]/,"");!n.has(p)&&!n.has(g)&&e.push({type:"warning",message:`${r}Symbol "${a}" references ${d} "${p}" which is not defined`,path:`components.${a}.${d}`});}}if(o.flows){if(Array.isArray(o.flows)){for(let a of o.flows)if(a?.steps)for(let l of a.steps){if(typeof l=="string"||!l?.component)continue;let c=l.component.replace(/^#/,"");!n.has(l.component)&&!n.has(c)&&e.push({type:"warning",message:`${r}Flow "${a.name}" step references "${l.component}" which is not defined`,path:`flows.${a.name}.steps`});}}else for(let[a,l]of Object.entries(o.flows))if(l?.steps)for(let c of l.steps){if(typeof c=="string"||!c?.component)continue;let d=c.component.replace(/^#/,"");!n.has(c.component)&&!n.has(d)&&e.push({type:"warning",message:`${r}Flow "${a}" step references "${c.component}" which is not defined`,path:`flows.${a}.steps`});}}}return {valid:e.filter(s=>s.type==="error").length===0,issues:e}}var kn={visualizerPort:42195,watcherPort:42196,autoConnect:true};async function ge(t){let e=$.resolve(t),n=$.dirname(e);if(!v.existsSync(e))throw new Error(`Gate config not found: ${e}`);let s=v.readFileSync(e,"utf8"),o=O.load(s);if(!o.version)throw new Error('Gate config missing required "version" field');let r=[],i=o,a=o.gates||i.portals;if(a)for(let[c,d]of Object.entries(a))r.push(ke(c,d));if(o.include)for(let c of o.include){let d=$.join(n,c),u=await glob(d.replace(/\\/g,"/"));for(let p of u){let g=await Pn(p);r.push(...g);}}let l=[];if(o.flows)for(let[c,d]of Object.entries(o.flows))l.push(jn(c,d));return {version:o.version,gates:r,flows:l,settings:{dev:{...kn,...o.settings?.dev}}}}async function Pn(t){let e=v.readFileSync(t,"utf8"),n=O.load(e);if(n.id)return [ke(n.id,n)];if(n.gates){let s=[];for(let[o,r]of Object.entries(n.gates))s.push(ke(o,r));return s}return []}function ke(t,e){let n=[];if(e.locks)for(let o of e.locks)n.push(Cn(o));let s=[];if(e.prizes)for(let o of e.prizes)s.push(An(o));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 o=s;n.push({expression:o.expression,description:o.description});}}return {id:e.id,description:e.description,keys:n,mode:e.mode||"all"}}function An(t){let e=t;return {id:e.id,oneTime:e.oneTime??false,metadata:e.metadata}}function jn(t,e){return {id:t,description:e.description,gates:e.gates||[],forkable:e.forkable}}async function wt(t){let e=$.resolve(t);return await glob("**/portal.yaml",{cwd:e,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})}var On=z$1.object({x:z$1.number(),y:z$1.number()}),Ln=z$1.object({x:z$1.number(),y:z$1.number(),zoom:z$1.number()}),bt=z$1.object({path:z$1.string(),include:z$1.array(z$1.string()).optional(),exclude:z$1.array(z$1.string()).optional()}),xt=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:On,tags:z$1.array(z$1.string()).optional(),created:z$1.string(),modified:z$1.string().optional()}),vt=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()}),Et=z$1.object({viewport:Ln,groups:z$1.array(Fn).optional()}),Nn=z$1.object({nodes:z$1.array(xt),connections:z$1.array(vt),layout:Et}),Dn=z$1.object({id:z$1.string(),name:z$1.string(),timestamp:z$1.string(),description:z$1.string().optional(),state:Nn});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(bt).optional(),portal:z$1.array(bt).optional()}),nodes:z$1.array(xt),connections:z$1.array(vt),layout:Et,snapshots:z$1.array(Dn).optional()});async function Mn(t,e){let n=[],s=[],o=[],r=[];if(t.sources.purpose)for(let l of t.sources.purpose){let c=$.resolve(e,l.path);try{let d=await at(c);o.push(...d.map(E=>E.filePath));let u=ct(d);for(let[E,{item:x,filePath:S}]of u){let I=["feature",...x.tags||[]];n.push(D({id:`purpose-feature-${E}`,symbol:`#${E}`,type:"component",source:"purpose",filePath:S,data:x,description:x.description,tags:I,componentType:x.type,parentSymbol:x.parent,anchors:x.anchors?.map(q=>Pe(q))}));}let p=lt(d);for(let[E,{item:x,filePath:S}]of p)n.push(D({id:`purpose-component-${E}`,symbol:`#${E}`,type:"component",source:"purpose",filePath:S,data:x,description:x.description,tags:x.tags,componentType:x.type,parentSymbol:x.parent,anchors:x.anchors?.map(I=>Pe(I))}));let g=dt(d);for(let[E,{item:x,filePath:S}]of g)n.push(D({id:`purpose-gate-${E}`,symbol:`^${E}`,type:"gate",source:"purpose",filePath:S,data:x,description:x.description}));let m=ut(d);for(let[E,{item:x,filePath:S}]of m)n.push(D({id:`purpose-state-${E}`,symbol:`#${E}`,type:"component",source:"purpose",filePath:S,data:x,description:x.description,tags:["state"]}));let y=pt(d);for(let[E,{item:x,filePath:S}]of y)n.push(D({id:`purpose-flow-${E}`,symbol:`$${E}`,type:"flow",source:"purpose",filePath:S,data:x,description:x.description}));let h=ft(d);for(let[E,{item:x,filePath:S}]of h)n.push(D({id:`purpose-signal-${E}`,symbol:`!${E}`,type:"signal",source:"purpose",filePath:S,data:x,description:x.description}));let w=gt(d);for(let[E,{item:x,filePath:S}]of w)n.push(D({id:`purpose-aspect-${E}`,symbol:`~${E}`,type:"aspect",source:"purpose",filePath:S,data:x,description:x.description,anchors:x.anchors?.map(I=>Pe(I)),appliesTo:x["applies-to"],tags:x.tags,enforcement:x.enforcement}));let P=mt(d),k=new Set(n.map(E=>E.symbol));for(let E of P)k.has(E.symbol)||(k.add(E.symbol),n.push(D({id:`purpose-ref-${E.type}-${E.symbol.slice(1)}`,symbol:E.symbol,type:E.type,source:"purpose",filePath:E.filePath,data:{referencedFrom:E.sourceSymbol},description:`Referenced from ${E.sourceSymbol}`})));}catch(d){s.push({source:"purpose",filePath:c,message:d.message});}}if(t.sources.portal)for(let l of t.sources.portal){let c=$.resolve(e,l.path);try{let d;if(c.endsWith(".yaml")||c.endsWith(".yml"))d=await ge(c),r.push(c);else {let u=await wt(c);if(r.push(...u),u.length>0){d=await ge(u[0]);for(let p=1;p<u.length;p++){let g=await ge(u[p]);d.gates.push(...g.gates),d.flows.push(...g.flows);}}else continue}for(let u of d.gates){n.push(Un(u,c));for(let p of u.prizes)n.push(D({id:`gate-signal-${u.id}-${p.id}`,symbol:`!${p.id}`,type:"signal",source:"portal",filePath:c,data:p,description:`Signal from gate ${u.id}`}));}for(let u of d.flows)n.push(zn(u,c));}catch(d){s.push({source:"portal",filePath:c,message:d.message});}}for(let l of t.nodes){let c=l.tags?.includes("idea");if(!l.content&&!c){let d=n.find(u=>u.symbol===l.symbol);if(d){d.position=l.position,d.tags=l.tags;continue}}n.push(D({id:l.id,symbol:l.symbol,type:l.type,source:"premise",filePath:".premise",data:l,description:l.content,position:l.position,tags:l.tags,created:l.created,modified:l.modified}));}Wn(n);let i=new Map;for(let l of n){let c=i.get(l.symbol)||[];c.includes(l.filePath)||c.push(l.filePath),i.set(l.symbol,c);}let a=[];for(let[l,c]of i)c.length>1&&a.push({symbol:l,files:c});return {symbols:n,purposeFiles:o,portalFiles:r,errors:s,timestamp:Date.now(),...a.length>0?{duplicateSymbols:a}:{}}}function D(t){return {...t,data:t.data??null,references:t.references??[],referencedBy:t.referencedBy??[]}}function Un(t,e){return D({id:`gate-${t.id}`,symbol:`^${t.id}`,type:"gate",source:"portal",filePath:e,data:t,description:t.description,position:t.position})}function zn(t,e){return D({id:`gate-flow-${t.id}`,symbol:`$${t.id}`,type:"flow",source:"portal",filePath:e,data:t,description:t.description})}function Pe(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[o,r]=n.split("-").map(Number);return {path:s,lines:[o,r],raw:t}}else if(n.includes(",")){let o=n.split(",").map(Number);return {path:s,lines:o,raw:t}}else return {path:s,lines:Number(n),raw:t}}var Hn=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function Wn(t){let e=new Map(t.map(n=>[n.symbol,n]));for(let n of t){let s=JSON.stringify(n.data),o=/(?:\?[@#$%~^!]|[@#$%~^!?])[a-zA-Z][\w-]*/g,r=(s.match(o)||[]).filter(i=>!Hn.has(i));for(let i of r)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 Tt(t){let e={metadata:{name:$.basename(t),created:new Date().toISOString(),modified:new Date().toISOString()},sources:{purpose:[{path:"./"}],portal:[{path:"./"}]},nodes:[]};return Mn(e,t)}function Gn(){return {entries:new Map,byType:new Map,bySource:new Map,timestamp:0}}function vo(t){let e=Gn();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 me(t,e){for(let n of t.entries.values())if(n.symbol===e)return n}function Eo(t,e){return t.byType.get(e)||[]}function To(t,e){let n=e.toLowerCase(),s=[];for(let o of t.entries.values()){if(o.symbol.toLowerCase().includes(n)){s.push(o);continue}if(o.description?.toLowerCase().includes(n)){s.push(o);continue}if(o.tags?.some(r=>r.toLowerCase().includes(n))){s.push(o);continue}if(o.componentType?.toLowerCase().includes(n)){s.push(o);continue}}return s}function _o(t,e){let n=me(t,e);return n?n.referencedBy.map(s=>me(t,s)).filter(s=>s!==void 0):[]}function $o(t,e){let n=me(t,e);return n?n.references.map(s=>me(t,s)).filter(s=>s!==void 0):[]}function Ro(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 Io(t){return Array.from(t.entries.values())}var Bn="0.1.0",Xn="1.0.0";function Ce(t,e){let n={$meta:qn(e.projectName,t),components:{},features:{},flows:{},state:{},gates:{},signals:{},aspects:{},screens:{},symbolMap:{}};for(let o of t.symbols)Vn(o,n,e);if(e.screenDefinitions)for(let[o,r]of Object.entries(e.screenDefinitions))n.screens[o]||(n.screens[o]={id:o,name:Y(o),route:r.route,path:"",components:r.components,features:r.features});let s={};for(let o of Object.values(n.components))o.componentType&&(s[o.componentType]=(s[o.componentType]||0)+1);for(let o of Object.values(n.features))o.componentType&&(s[o.componentType]=(s[o.componentType]||0)+1);return Object.keys(s).length>0&&(n.$meta.componentTypes=s),ns(n),n}function qn(t,e){return {version:Xn,project:t,generatedAt:new Date().toISOString(),paradigmVersion:Bn,sources:{purposeFiles:e.purposeFiles.length,portalFiles:e.portalFiles.length,premiseFiles:e.symbols.filter(n=>n.source==="premise").length>0?1:0}}}function Vn(t,e,n){let{type:s}=t;switch(s){case "component":Yn(t,e,n);break;case "feature":Jn(t,e,n);break;case "flow":Kn(t,e);break;case "state":Qn(t,e);break;case "gate":Zn(t,e);break;case "signal":es(t,e);break;case "aspect":ts(t,e);break;}}function Yn(t,e,n){let s=Z(t.symbol),o=_t(s,t.data,n.visualTagMappings),r={id:s,name:Y(s),symbol:t.symbol,category:"components",path:t.filePath,description:t.description,visualTags:o,related:t.references,componentType:t.componentType,parent:t.parentSymbol};e.components[s]=r,e.symbolMap[t.symbol]={category:"components",id:s};}function Jn(t,e,n){let s=Z(t.symbol),o=_t(s,t.data,n.visualTagMappings),r={id:s,name:Y(s),symbol:t.symbol,category:"features",path:t.filePath,description:t.description,visualTags:o,related:t.references,componentType:t.componentType,parent:t.parentSymbol};e.features[s]=r,e.symbolMap[t.symbol]={category:"features",id:s};}function Kn(t,e){let n=Z(t.symbol),s=t.data,o=[];if(s?.steps)for(let i=0;i<s.steps.length;i++){let a=s.steps[i];o.push({id:`${n}-step-${i}`,name:a.action||`Step ${i+1}`,target:a.component,description:a.description,order:i});}let r={id:n,name:Y(n),symbol:t.symbol,path:t.filePath,description:t.description,steps:o};e.flows[n]=r,e.symbolMap[t.symbol]={category:"flows",id:n};}function Qn(t,e){let n=Z(t.symbol),s={id:n,name:Y(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 Zn(t,e){let n=Z(t.symbol),s={id:n,name:Y(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 es(t,e){let n=Z(t.symbol),s={id:n,name:Y(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 ts(t,e){let n=Z(t.symbol),s={id:n,name:Y(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 ns(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 Z(t){return t.slice(1)}function Y(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function _t(t,e,n){let s=[];if(n?.[t])return n[t];let o=[[/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[r,i]of o)r.test(t)&&s.push(i);return s}function Ae(t){return JSON.stringify(t,null,2)}function je(t,e="unknown"){j$1().trackToolCall(e,t);}function Mo(t,e="paradigm://unknown"){j$1().trackResourceRead(e,t);}function ss(){k();}function os(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,o=e.task;return n==="context"&&o?{summary:`Navigate context: "${o}"`}: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(o=>typeof o=="string"&&o.length>0);return {summary:s?`${n}: ${s.slice(0,60)}`:n,symbol:e.symbol||void 0}}}}function Uo(t,e){let n=j$1(),{summary:s,symbol:o}=os(t,e);n.addBreadcrumb("tool-call",s,{tool:t,symbol:o});}function zo(){return [{name:"paradigm_context_check",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_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.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{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}},{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"]}}]}async function Ho(t,e,n){let s=j$1();if(t==="paradigm_context_check"){let o=e.contextWindowSize||2e5,r=e.estimatedTotalTokens,i=s.getStats(),{recommendation:a,message:l,usagePercent:c,signals:d}=s.getHandoffRecommendation(o,r),u=s.getDurationMinutes();return {handled:true,text:JSON.stringify({recommendation:a,message:l,stats:{sessionDurationMinutes:u,mcpToolCalls:i.totals.toolCallCount,mcpResourceReads:i.totals.resourceReadCount,estimatedMcpTokens:i.totals.totalTokens,estimatedTotalTokens:r||Math.round(i.totals.totalTokens*5),contextWindowSize:o,usagePercent:c},signals:d,action:a==="continue"?null:"Call paradigm_handoff_prepare to create handoff file"},null,2)}}if(t==="paradigm_handoff_prepare"){let o=e.summary,r=e.nextSteps||[],i=e.agent||"builder",a$1=e.modifiedFiles||[],l=e.symbolsTouched||[],c=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:o,nextSteps:r,modifiedFiles:a$1,symbolsTouched:l,openQuestions:c,sessionStats:{duration:s.getDurationMinutes(),mcpCalls:d.totals.toolCallCount+d.totals.resourceReadCount,estimatedTokens:d.totals.totalTokens,estimatedCostUsd:u.total.costUsd,model:u.model},status:"pending"};try{a(n.rootDir,m);}catch{}let y=`# Handoff: ${g}
|
|
11
|
+
`),p=we(u,o,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=$.dirname(e),l=Lt(t,a,o,n);if(l.length>0&&l[0].score>=.7){let c=l[0];return {found:true,score:c.score,suggestedStart:c.start,suggestedEnd:c.end,suggestedPath:c.file!==e?c.file:void 0,similarity:c.score}}return {found:false,score:0}}var kt,ls,ds,us,ps,Nt=b(()=>{kt=/^\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 )/;ls=.4,ds=.3,us=.2,ps=.1;});var Re=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(),nt=Re.extend({id:z$1.string()}),pn=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()}),fn=z$1.union([pn,z$1.string().transform(t=>({description:t}))]),gn=z$1.object({from:z$1.string(),to:z$1.string(),type:z$1.string(),description:z$1.string().optional()}),mn=z$1.union([gn,z$1.string()]),hn=z$1.object({component:z$1.string(),action:z$1.string(),description:z$1.string().optional()}),it=z$1.union([hn,z$1.string()]),yn=z$1.object({name:z$1.string(),description:z$1.string().optional(),steps:z$1.array(it)}),wn=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(it).optional()}),bn=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()}),Sn=z$1.object({description:z$1.string().optional(),default:z$1.unknown().optional(),type:z$1.string().optional()}),xn=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()}),vn=z$1.object({target:z$1.string(),type:z$1.string(),path:z$1.string()}),En=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(nt),z$1.record(Re)]).optional(),components:z$1.union([z$1.array(nt),z$1.record(Re)]).optional(),gates:z$1.record(bn).optional(),states:z$1.record(Sn).optional(),signals:z$1.record(fn).optional(),aspects:z$1.record(xn).optional(),relationships:z$1.array(mn).optional(),flows:z$1.union([z$1.array(yn),z$1.record(wn)]).optional(),references:z$1.array(vn).optional()});function Ie(t){let e=Tn(t);return {data:e.data,errors:e.errors}}function Tn(t){let e=[],n=[],s;try{s=v.readFileSync(t,"utf8");}catch(a){let l=`Cannot read file: ${a.message}`;return e.push(l),n.push({message:l,type:"file"}),{data:null,errors:e,detailedErrors:n,rawContent:void 0,isYamlValid:false}}let o=s.replace(/^([#~!$^][\w-]+):/gm,'"$1":').replace(/^(\s*-\s+)([!#][\w-]+)$/gm,'$1"$2"'),r=null;try{r=O.load(o);}catch(a){let l=a,c=l.mark?.line?l.mark.line+1:void 0,d=`YAML syntax error: ${l.reason||a.message}`;return e.push(`${d}${c?` (line ${c})`:""}`),n.push({message:d,line:c,type:"yaml"}),{data:null,errors:e,detailedErrors:n,rawContent:s,isYamlValid:false}}if(r==null)return {data:{},errors:[],detailedErrors:[],rawContent:s,isYamlValid:true};if(typeof r=="object"&&r!==null){let a=r,l={"#":"components",$:"flows","^":"gates","!":"signals","~":"aspects"};for(let c of Object.keys(a)){let d=c[0],u=l[d];if(!u||c.length<2)continue;let p=c.slice(1),g=a[c];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[c];}}let i=En.safeParse(r);if(!i.success){for(let a of i.error.issues){let l=a.path.join("."),c=a.message;e.push(`Schema error at ${l||"/"}: ${c}`),n.push({message:c,path:l||"/",type:"schema"});}return {data:r,errors:e,detailedErrors:n,rawContent:s,isYamlValid:true}}return {data:i.data,errors:[],detailedErrors:[],rawContent:s,isYamlValid:true}}function po(t){return O.dump(t,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function ue(t){return t?Array.isArray(t)?t.map(e=>[e.id,e]):Object.entries(t):[]}async function $n(t){let e=$.resolve(t);return (await glob("**/.purpose",{cwd:e,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})).sort((s,o)=>{let r=s.split($.sep).length,i=o.split($.sep).length;return r-i})}async function at(t){let e=await $n(t),n=[];for(let s of e){let{data:o,errors:r}=Ie(s);o&&(n.push({filePath:s,data:o}),r.length>0&&console.warn(`Warnings parsing ${s}:`,r));}return n}function ct(t){let e=new Map;for(let{filePath:n,data:s}of t){let o=ue(s.features);for(let[r,i]of o)e.set(r,{item:i,filePath:n});}return e}function lt(t){let e=new Map;for(let{filePath:n,data:s}of t){let o=ue(s.components);for(let[r,i]of o)e.set(r,{item:i,filePath:n});}return e}function dt(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.gates)for(let[o,r]of Object.entries(s.gates))e.set(o,{item:r,filePath:n});return e}function ut(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.states)for(let[o,r]of Object.entries(s.states))e.set(o,{item:r,filePath:n});return e}function pt(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.flows)if(Array.isArray(s.flows))for(let o of s.flows)e.set(o.name,{item:{id:o.name,description:o.description,steps:o.steps},filePath:n});else for(let[o,r]of Object.entries(s.flows))e.set(o,{item:{id:o,description:r.description,gates:r.gates,signals:r.signals,components:r.components,steps:r.steps},filePath:n});return e}function ft(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.signals)for(let[o,r]of Object.entries(s.signals))e.set(o,{item:r,filePath:n});return e}function gt(t){let e=new Map;for(let{filePath:n,data:s}of t)if(s.aspects)for(let[o,r]of Object.entries(s.aspects))e.set(o,{item:r,filePath:n});return e}function mt(t){let e=[],n=new Set;for(let{filePath:s,data:o}of t){let r=ue(o.features);for(let[a,l]of r)st(`#${a}`,l,s,e,n);let i=ue(o.components);for(let[a,l]of i)st(`#${a}`,l,s,e,n);}return e}function st(t,e,n,s,o){if(e.flows)for(let r of e.flows){let i=r.startsWith("$")?r:`$${r}`;o.has(i)||(o.add(i),s.push({symbol:i,type:"flow",sourceSymbol:t,filePath:n}));}if(e.gates)for(let r of e.gates){let i=r.startsWith("^")?r:`^${r}`;o.has(i)||(o.add(i),s.push({symbol:i,type:"gate",sourceSymbol:t,filePath:n}));}if(e.signals)for(let r of e.signals){let i=r.startsWith("!")?r:`!${r}`;o.has(i)||(o.add(i),s.push({symbol:i,type:"signal",sourceSymbol:t,filePath:n}));}if(e.states)for(let r of e.states){let i=r.startsWith("#")?r:r.startsWith("%")?`#${r.slice(1)}`:`#${r}`;o.has(i)||(o.add(i),s.push({symbol:i,type:"component",sourceSymbol:t,filePath:n}));}if(e.components)for(let r of e.components){let i=r.startsWith("#")?r:`#${r}`;o.has(i)||(o.add(i),s.push({symbol:i,type:"component",sourceSymbol:t,filePath:n}));}if(e.aspects)for(let r of e.aspects){let i=r.startsWith("~")?r:`~${r}`;o.has(i)||(o.add(i),s.push({symbol:i,type:"aspect",sourceSymbol:t,filePath:n}));}if(e.description){let r=In(e.description);for(let{symbol:i,type:a}of r)o.has(i)||(o.add(i),s.push({symbol:i,type:a,sourceSymbol:t,filePath:n}));}}var Rn=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function In(t){let e=[],n=/([$^!#~%])([a-zA-Z][a-zA-Z0-9._-]*)/g,s;for(;(s=n.exec(t))!==null;){let o=s[1],r=s[2],i,a;switch(o){case "#":a="component",i=`#${r}`;break;case "$":a="flow",i=`$${r}`;break;case "^":a="gate",i=`^${r}`;break;case "!":a="signal",i=`!${r}`;break;case "~":a="aspect",i=`~${r}`;break;case "%":a="component",i=`#${r}`;break;default:continue}Rn.has(i)||e.push({symbol:i,type:a});}return e}function se(t){return t?Array.isArray(t)?t.map(e=>[e.id,e]):Object.entries(t):[]}function $e(t){return t?Array.isArray(t)?t.map(e=>e.id):Object.keys(t):[]}function go(t,e){let n=[],s=e?`${e}: `:"",o=se(t.features);for(let[i,a]of o)ot(i,a,"feature",s,n);let r=se(t.components);for(let[i,a]of r)ot(i,a,"component",s,n);if(t.relationships){let i=new Set([...$e(t.features),...$e(t.components)]);for(let a of t.relationships){if(typeof a=="string"||!a||!a.from||!a.to)continue;let l=a.from.replace(/^[@#$%~^!?]/,"");!i.has(l)&&!a.from.includes(".")&&n.push({type:"warning",message:`${s}Relationship references unknown source: "${a.from}"`,path:"relationships"});let c=a.to.replace(/^[@#$%~^!?]/,"");!i.has(c)&&!a.to.includes(".")&&n.push({type:"warning",message:`${s}Relationship references unknown target: "${a.to}"`,path:"relationships"});}}if(t.flows){let i=new Set($e(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 l of a.steps){if(typeof l=="string"||!l||!l.component)continue;let c=l.component.replace(/^#/,"");i.has(c)||n.push({type:"warning",message:`${s}Flow "${a.name}" references unknown component: "${l.component}"`,path:`flows.${a.name}`});}}else for(let[a,l]of Object.entries(t.flows))if(!(!l||typeof l!="object")&&l.steps&&Array.isArray(l.steps))for(let c of l.steps){if(typeof c=="string"||!c||!c.component)continue;let d=c.component.replace(/^#/,"");i.has(d)||n.push({type:"warning",message:`${s}Flow "${a}" references unknown component: "${c.component}"`,path:`flows.${a}`});}}return {valid:n.filter(i=>i.type==="error").length===0,issues:n}}function ot(t,e,n,s,o){let r=`${n}s.${t}`;if(/^[a-zA-Z][a-zA-Z0-9-]*$/.test(t)||o.push({type:"warning",message:`${s}${n} ID "${t}" should use alphanumeric characters and hyphens`,path:r}),(!e.description||e.description.trim()==="")&&o.push({type:"warning",message:`${s}${n} "${t}" has no description`,path:r}),e.endpoints)for(let i of e.endpoints)/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+\//.test(i)||o.push({type:"warning",message:`${s}Endpoint "${i}" in ${n} "${t}" may not be in standard format (e.g., "GET /api/users")`,path:`${r}.endpoints`});}function ht(t){let e=[],n=new Set;for(let{data:s}of t){let o=se(s.components);for(let[i]of o)n.add(`#${i}`),n.add(i);let r=se(s.features);for(let[i]of r)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:o}of t){let r=s?`${s}: `:"",i=[...se(o.components),...se(o.features)];for(let[a,l]of i){if(l.parent){let d=l.parent.replace(/^["']|["']$/g,""),u=d.replace(/^[#$^!~@%?&]/,"");!n.has(d)&&!n.has(u)&&e.push({type:"warning",message:`${r}Component "${a}" references parent "${d}" which is not defined in any .purpose file`,path:`components.${a}.parent`});}let c=[{field:"gates",refs:l.gates},{field:"signals",refs:l.signals},{field:"flows",refs:l.flows},{field:"components",refs:l.components},{field:"aspects",refs:l.aspects}];for(let{field:d,refs:u}of c)if(u)for(let p of u){let g=p.replace(/^[#$^!~@%?&]/,"");!n.has(p)&&!n.has(g)&&e.push({type:"warning",message:`${r}Symbol "${a}" references ${d} "${p}" which is not defined`,path:`components.${a}.${d}`});}}if(o.flows){if(Array.isArray(o.flows)){for(let a of o.flows)if(a?.steps)for(let l of a.steps){if(typeof l=="string"||!l?.component)continue;let c=l.component.replace(/^#/,"");!n.has(l.component)&&!n.has(c)&&e.push({type:"warning",message:`${r}Flow "${a.name}" step references "${l.component}" which is not defined`,path:`flows.${a.name}.steps`});}}else for(let[a,l]of Object.entries(o.flows))if(l?.steps)for(let c of l.steps){if(typeof c=="string"||!c?.component)continue;let d=c.component.replace(/^#/,"");!n.has(c.component)&&!n.has(d)&&e.push({type:"warning",message:`${r}Flow "${a}" step references "${c.component}" which is not defined`,path:`flows.${a}.steps`});}}}return {valid:e.filter(s=>s.type==="error").length===0,issues:e}}var kn={visualizerPort:42195,watcherPort:42196,autoConnect:true};async function ge(t){let e=$.resolve(t),n=$.dirname(e);if(!v.existsSync(e))throw new Error(`Gate config not found: ${e}`);let s=v.readFileSync(e,"utf8"),o=O.load(s);if(!o.version)throw new Error('Gate config missing required "version" field');let r=[],i=o,a=o.gates||i.portals;if(a)for(let[c,d]of Object.entries(a))r.push(ke(c,d));if(o.include)for(let c of o.include){let d=$.join(n,c),u=await glob(d.replace(/\\/g,"/"));for(let p of u){let g=await Pn(p);r.push(...g);}}let l=[];if(o.flows)for(let[c,d]of Object.entries(o.flows))l.push(jn(c,d));return {version:o.version,gates:r,flows:l,settings:{dev:{...kn,...o.settings?.dev}}}}async function Pn(t){let e=v.readFileSync(t,"utf8"),n=O.load(e);if(n.id)return [ke(n.id,n)];if(n.gates){let s=[];for(let[o,r]of Object.entries(n.gates))s.push(ke(o,r));return s}return []}function ke(t,e){let n=[];if(e.locks)for(let o of e.locks)n.push(Cn(o));let s=[];if(e.prizes)for(let o of e.prizes)s.push(An(o));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 o=s;n.push({expression:o.expression,description:o.description});}}return {id:e.id,description:e.description,keys:n,mode:e.mode||"all"}}function An(t){let e=t;return {id:e.id,oneTime:e.oneTime??false,metadata:e.metadata}}function jn(t,e){return {id:t,description:e.description,gates:e.gates||[],forkable:e.forkable}}async function wt(t){let e=$.resolve(t);return await glob("**/portal.yaml",{cwd:e,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})}var On=z$1.object({x:z$1.number(),y:z$1.number()}),Ln=z$1.object({x:z$1.number(),y:z$1.number(),zoom:z$1.number()}),bt=z$1.object({path:z$1.string(),include:z$1.array(z$1.string()).optional(),exclude:z$1.array(z$1.string()).optional()}),xt=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:On,tags:z$1.array(z$1.string()).optional(),created:z$1.string(),modified:z$1.string().optional()}),vt=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()}),Et=z$1.object({viewport:Ln,groups:z$1.array(Fn).optional()}),Nn=z$1.object({nodes:z$1.array(xt),connections:z$1.array(vt),layout:Et}),Dn=z$1.object({id:z$1.string(),name:z$1.string(),timestamp:z$1.string(),description:z$1.string().optional(),state:Nn});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(bt).optional(),portal:z$1.array(bt).optional()}),nodes:z$1.array(xt),connections:z$1.array(vt),layout:Et,snapshots:z$1.array(Dn).optional()});async function Mn(t,e){let n=[],s=[],o=[],r=[];if(t.sources.purpose)for(let l of t.sources.purpose){let c=$.resolve(e,l.path);try{let d=await at(c);o.push(...d.map(E=>E.filePath));let u=ct(d);for(let[E,{item:x,filePath:S}]of u){let I=["feature",...x.tags||[]];n.push(D({id:`purpose-feature-${E}`,symbol:`#${E}`,type:"component",source:"purpose",filePath:S,data:x,description:x.description,tags:I,componentType:x.type,parentSymbol:x.parent,anchors:x.anchors?.map(q=>Pe(q))}));}let p=lt(d);for(let[E,{item:x,filePath:S}]of p)n.push(D({id:`purpose-component-${E}`,symbol:`#${E}`,type:"component",source:"purpose",filePath:S,data:x,description:x.description,tags:x.tags,componentType:x.type,parentSymbol:x.parent,anchors:x.anchors?.map(I=>Pe(I))}));let g=dt(d);for(let[E,{item:x,filePath:S}]of g)n.push(D({id:`purpose-gate-${E}`,symbol:`^${E}`,type:"gate",source:"purpose",filePath:S,data:x,description:x.description}));let m=ut(d);for(let[E,{item:x,filePath:S}]of m)n.push(D({id:`purpose-state-${E}`,symbol:`#${E}`,type:"component",source:"purpose",filePath:S,data:x,description:x.description,tags:["state"]}));let y=pt(d);for(let[E,{item:x,filePath:S}]of y)n.push(D({id:`purpose-flow-${E}`,symbol:`$${E}`,type:"flow",source:"purpose",filePath:S,data:x,description:x.description}));let h=ft(d);for(let[E,{item:x,filePath:S}]of h)n.push(D({id:`purpose-signal-${E}`,symbol:`!${E}`,type:"signal",source:"purpose",filePath:S,data:x,description:x.description}));let w=gt(d);for(let[E,{item:x,filePath:S}]of w)n.push(D({id:`purpose-aspect-${E}`,symbol:`~${E}`,type:"aspect",source:"purpose",filePath:S,data:x,description:x.description,anchors:x.anchors?.map(I=>Pe(I)),appliesTo:x["applies-to"],tags:x.tags,enforcement:x.enforcement}));let P=mt(d),k=new Set(n.map(E=>E.symbol));for(let E of P)k.has(E.symbol)||(k.add(E.symbol),n.push(D({id:`purpose-ref-${E.type}-${E.symbol.slice(1)}`,symbol:E.symbol,type:E.type,source:"purpose",filePath:E.filePath,data:{referencedFrom:E.sourceSymbol},description:`Referenced from ${E.sourceSymbol}`})));}catch(d){s.push({source:"purpose",filePath:c,message:d.message});}}if(t.sources.portal)for(let l of t.sources.portal){let c=$.resolve(e,l.path);try{let d;if(c.endsWith(".yaml")||c.endsWith(".yml"))d=await ge(c),r.push(c);else {let u=await wt(c);if(r.push(...u),u.length>0){d=await ge(u[0]);for(let p=1;p<u.length;p++){let g=await ge(u[p]);d.gates.push(...g.gates),d.flows.push(...g.flows);}}else continue}for(let u of d.gates){n.push(Un(u,c));for(let p of u.prizes)n.push(D({id:`gate-signal-${u.id}-${p.id}`,symbol:`!${p.id}`,type:"signal",source:"portal",filePath:c,data:p,description:`Signal from gate ${u.id}`}));}for(let u of d.flows)n.push(zn(u,c));}catch(d){s.push({source:"portal",filePath:c,message:d.message});}}for(let l of t.nodes){let c=l.tags?.includes("idea");if(!l.content&&!c){let d=n.find(u=>u.symbol===l.symbol);if(d){d.position=l.position,d.tags=l.tags;continue}}n.push(D({id:l.id,symbol:l.symbol,type:l.type,source:"premise",filePath:".premise",data:l,description:l.content,position:l.position,tags:l.tags,created:l.created,modified:l.modified}));}Wn(n);let i=new Map;for(let l of n){let c=i.get(l.symbol)||[];c.includes(l.filePath)||c.push(l.filePath),i.set(l.symbol,c);}let a=[];for(let[l,c]of i)c.length>1&&a.push({symbol:l,files:c});return {symbols:n,purposeFiles:o,portalFiles:r,errors:s,timestamp:Date.now(),...a.length>0?{duplicateSymbols:a}:{}}}function D(t){return {...t,data:t.data??null,references:t.references??[],referencedBy:t.referencedBy??[]}}function Un(t,e){return D({id:`gate-${t.id}`,symbol:`^${t.id}`,type:"gate",source:"portal",filePath:e,data:t,description:t.description,position:t.position})}function zn(t,e){return D({id:`gate-flow-${t.id}`,symbol:`$${t.id}`,type:"flow",source:"portal",filePath:e,data:t,description:t.description})}function Pe(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[o,r]=n.split("-").map(Number);return {path:s,lines:[o,r],raw:t}}else if(n.includes(",")){let o=n.split(",").map(Number);return {path:s,lines:o,raw:t}}else return {path:s,lines:Number(n),raw:t}}var Hn=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function Wn(t){let e=new Map(t.map(n=>[n.symbol,n]));for(let n of t){let s=JSON.stringify(n.data),o=/(?:\?[@#$%~^!]|[@#$%~^!?])[a-zA-Z][\w-]*/g,r=(s.match(o)||[]).filter(i=>!Hn.has(i));for(let i of r)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 Tt(t){let e={metadata:{name:$.basename(t),created:new Date().toISOString(),modified:new Date().toISOString()},sources:{purpose:[{path:"./"}],portal:[{path:"./"}]},nodes:[]};return Mn(e,t)}function Gn(){return {entries:new Map,byType:new Map,bySource:new Map,timestamp:0}}function vo(t){let e=Gn();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 me(t,e){for(let n of t.entries.values())if(n.symbol===e)return n}function Eo(t,e){return t.byType.get(e)||[]}function To(t,e){let n=e.toLowerCase(),s=[];for(let o of t.entries.values()){if(o.symbol.toLowerCase().includes(n)){s.push(o);continue}if(o.description?.toLowerCase().includes(n)){s.push(o);continue}if(o.tags?.some(r=>r.toLowerCase().includes(n))){s.push(o);continue}if(o.componentType?.toLowerCase().includes(n)){s.push(o);continue}}return s}function _o(t,e){let n=me(t,e);return n?n.referencedBy.map(s=>me(t,s)).filter(s=>s!==void 0):[]}function $o(t,e){let n=me(t,e);return n?n.references.map(s=>me(t,s)).filter(s=>s!==void 0):[]}function Ro(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 Io(t){return Array.from(t.entries.values())}var Bn="0.1.0",Xn="1.0.0";function Ce(t,e){let n={$meta:qn(e.projectName,t),components:{},features:{},flows:{},state:{},gates:{},signals:{},aspects:{},screens:{},symbolMap:{}};for(let o of t.symbols)Vn(o,n,e);if(e.screenDefinitions)for(let[o,r]of Object.entries(e.screenDefinitions))n.screens[o]||(n.screens[o]={id:o,name:Y(o),route:r.route,path:"",components:r.components,features:r.features});let s={};for(let o of Object.values(n.components))o.componentType&&(s[o.componentType]=(s[o.componentType]||0)+1);for(let o of Object.values(n.features))o.componentType&&(s[o.componentType]=(s[o.componentType]||0)+1);return Object.keys(s).length>0&&(n.$meta.componentTypes=s),ns(n),n}function qn(t,e){return {version:Xn,project:t,generatedAt:new Date().toISOString(),paradigmVersion:Bn,sources:{purposeFiles:e.purposeFiles.length,portalFiles:e.portalFiles.length,premiseFiles:e.symbols.filter(n=>n.source==="premise").length>0?1:0}}}function Vn(t,e,n){let{type:s}=t;switch(s){case "component":Yn(t,e,n);break;case "feature":Jn(t,e,n);break;case "flow":Kn(t,e);break;case "state":Qn(t,e);break;case "gate":Zn(t,e);break;case "signal":es(t,e);break;case "aspect":ts(t,e);break;}}function Yn(t,e,n){let s=ee(t.symbol),o=_t(s,t.data,n.visualTagMappings),r={id:s,name:Y(s),symbol:t.symbol,category:"components",path:t.filePath,description:t.description,visualTags:o,related:t.references,componentType:t.componentType,parent:t.parentSymbol};e.components[s]=r,e.symbolMap[t.symbol]={category:"components",id:s};}function Jn(t,e,n){let s=ee(t.symbol),o=_t(s,t.data,n.visualTagMappings),r={id:s,name:Y(s),symbol:t.symbol,category:"features",path:t.filePath,description:t.description,visualTags:o,related:t.references,componentType:t.componentType,parent:t.parentSymbol};e.features[s]=r,e.symbolMap[t.symbol]={category:"features",id:s};}function Kn(t,e){let n=ee(t.symbol),s=t.data,o=[];if(s?.steps)for(let i=0;i<s.steps.length;i++){let a=s.steps[i];o.push({id:`${n}-step-${i}`,name:a.action||`Step ${i+1}`,target:a.component,description:a.description,order:i});}let r={id:n,name:Y(n),symbol:t.symbol,path:t.filePath,description:t.description,steps:o};e.flows[n]=r,e.symbolMap[t.symbol]={category:"flows",id:n};}function Qn(t,e){let n=ee(t.symbol),s={id:n,name:Y(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 Zn(t,e){let n=ee(t.symbol),s={id:n,name:Y(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 es(t,e){let n=ee(t.symbol),s={id:n,name:Y(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 ts(t,e){let n=ee(t.symbol),s={id:n,name:Y(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 ns(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 ee(t){return t.slice(1)}function Y(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function _t(t,e,n){let s=[];if(n?.[t])return n[t];let o=[[/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[r,i]of o)r.test(t)&&s.push(i);return s}function Ae(t){return JSON.stringify(t,null,2)}function je(t,e="unknown"){j$1().trackToolCall(e,t);}function Mo(t,e="paradigm://unknown"){j$1().trackResourceRead(e,t);}function ss(){k();}function os(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,o=e.task;return n==="context"&&o?{summary:`Navigate context: "${o}"`}: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(o=>typeof o=="string"&&o.length>0);return {summary:s?`${n}: ${s.slice(0,60)}`:n,symbol:e.symbol||void 0}}}}function Uo(t,e){let n=j$1(),{summary:s,symbol:o}=os(t,e);n.addBreadcrumb("tool-call",s,{tool:t,symbol:o});}function zo(){return [{name:"paradigm_context_check",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_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.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{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}},{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"]}}]}async function Ho(t,e,n){let s=j$1();if(t==="paradigm_context_check"){let o=e.contextWindowSize||2e5,r=e.estimatedTotalTokens,i=s.getStats(),{recommendation:a,message:l,usagePercent:c,signals:d}=s.getHandoffRecommendation(o,r),u=s.getDurationMinutes();return {handled:true,text:JSON.stringify({recommendation:a,message:l,stats:{sessionDurationMinutes:u,mcpToolCalls:i.totals.toolCallCount,mcpResourceReads:i.totals.resourceReadCount,estimatedMcpTokens:i.totals.totalTokens,estimatedTotalTokens:r||Math.round(i.totals.totalTokens*5),contextWindowSize:o,usagePercent:c},signals:d,action:a==="continue"?null:"Call paradigm_handoff_prepare to create handoff file"},null,2)}}if(t==="paradigm_handoff_prepare"){let o=e.summary,r=e.nextSteps||[],i=e.agent||"builder",a$1=e.modifiedFiles||[],l=e.symbolsTouched||[],c=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:o,nextSteps:r,modifiedFiles:a$1,symbolsTouched:l,openQuestions:c,sessionStats:{duration:s.getDurationMinutes(),mcpCalls:d.totals.toolCallCount+d.totals.resourceReadCount,estimatedTokens:d.totals.totalTokens,estimatedCostUsd:u.total.costUsd,model:u.model},status:"pending"};try{a(n.rootDir,m);}catch{}let y=`# Handoff: ${g}
|
|
12
12
|
|
|
13
13
|
## Session Summary
|
|
14
14
|
${o}
|
|
@@ -21,8 +21,8 @@ ${r.map((h,w)=>`${w+1}. ${h}`).join(`
|
|
|
21
21
|
- Modified files: ${a$1.length>0?a$1.join(", "):"(not specified)"}
|
|
22
22
|
- Symbols touched: ${l.length>0?l.join(", "):"(not specified)"}
|
|
23
23
|
- Open questions: ${c.length>0?c.join(", "):"(none)"}
|
|
24
|
-
`;return ss(),{handled:true,text:JSON.stringify({handoff:m,markdownSummary:y,persisted:true,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(t==="paradigm_session_stats"){let o=s.getStats(),r=s.getCostBreakdown(),i=s.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(o.startTime).toISOString(),durationMinutes:i,lastActivity:new Date(o.lastActivity).toISOString()},model:{name:r.model,id:r.modelId,pricing:{inputPerMillion:`$${r.pricing.input.toFixed(2)}`,outputPerMillion:`$${r.pricing.output.toFixed(2)}`}},interactions:{toolCalls:o.totals.toolCallCount,resourceReads:o.totals.resourceReadCount,totalInteractions:o.totals.toolCallCount+o.totals.resourceReadCount},tokens:{total:o.totals.totalTokens,byCategory:{resources:r.resources.tokens,tools:r.tools.tokens}},cost:{totalUsd:`$${r.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${r.resources.costUsd.toFixed(4)}`,tools:`$${r.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:r.resources.byType,toolsByName:r.tools.byName}},null,2)}}if(t==="paradigm_session_recover"){s.setRootDir(n.rootDir);let o=s.loadPreviousSession(),r=s.loadCheckpoint(),i=[];try{i=b$1(n.rootDir);}catch{}if(!o&&i.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 c=Date.now()-r.timestamp,d=Math.round(c/6e4),u=Math.round(c/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(o){let c=Date.now()-o.lastActivity,d=Math.round(c/6e4),u=Math.round(c/36e5),g=o.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:o.sessionId,startTime:new Date(o.startTime).toISOString(),lastActivity:new Date(o.lastActivity).toISOString(),age:u>1?`${u} hours ago`:`${d} minutes ago`},a.context={symbolsModified:o.symbolsModified,filesExplored:o.filesExplored},a.recentActions=g;}if(i.length>0){a.pendingHandoffs=i.map(c=>({id:c.id,timestamp:c.timestamp,from:c.from,to:c.to,summary:c.summary,nextSteps:c.nextSteps,modifiedFiles:c.modifiedFiles,symbolsTouched:c.symbolsTouched,openQuestions:c.openQuestions}));for(let c of i)try{c$1(n.rootDir,c.id);}catch{}}let l="Continue where the previous session left off.";if(r)l=`Previous session was in "${r.phase}" phase: ${r.context}`,r.decisions?.length&&(l+=` Key decisions: ${r.decisions.slice(0,2).join("; ")}`);else if(i.length>0){let c=i[i.length-1];l=`Handoff received: "${c.summary}". `,c.nextSteps.length>0&&(l+=`Start with: ${c.nextSteps[0]}`);}else if(o){let c=o.breadcrumbs.slice(-10);if(c.length>0){let d=c[c.length-1];d.symbol&&(l=`Last work involved ${d.symbol}. Consider checking its current state with paradigm_ripple.`);}}return a.suggestion=l,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 o=e.phase,r=e.context,i=e.externalId,a=e.plan,l=e.modifiedFiles,c=e.symbolsTouched,d=e.decisions,{checkpoint:u,persisted:p}=s.saveCheckpoint({phase:o,context:r,externalId:i,plan:a,modifiedFiles:l,symbolsTouched:c,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:""}}async function Wo(t){let e=j$1();e.setRootDir(t);let n=e.loadCheckpoint(),s=[];try{s=b$1(t);}catch{}if(!n&&s.length===0)return null;let o=[];if(o.push("--- SESSION RECOVERY ---"),n){let r=Date.now()-n.timestamp,i=Math.round(r/6e4),a=Math.round(r/36e5),l=a>1?`${a}h ago`:`${i}m ago`;o.push(`Previous session was in "${n.phase}" phase (${l}): ${n.context}`),n.modifiedFiles?.length&&o.push(`Modified files: ${n.modifiedFiles.join(", ")}`),n.symbolsTouched?.length&&o.push(`Symbols: ${n.symbolsTouched.join(", ")}`),n.decisions?.length&&o.push(`Decisions: ${n.decisions.join("; ")}`),n.plan&&o.push(`Plan: ${n.plan.slice(0,200)}`);}if(s.length>0){let r=s[s.length-1];o.push(`Pending handoff: "${r.summary}"`),r.nextSteps.length>0&&o.push(`Next steps: ${r.nextSteps.slice(0,3).join(", ")}`);}try{let{loadTasks:r}=await import('./task-loader-NZFDTUQ5.js'),i=await r(t,{status:"open",limit:5});if(i.length>0){o.push(""),o.push("Open tasks:");for(let a of i){let l=a.tags.length>0?` [${a.tags.join(", ")}]`:"";o.push(` [${a.priority}] ${a.id}: ${a.blurb}${l}`);}}}catch{}try{let{loadLoreEntries:r}=await import('./lore-loader-RVQI5GXL.js'),a=(await r(t,{limit:10})).filter(l=>l.tags?.some(c=>c.startsWith("arc:")));if(a.length>0){let l=new Map;for(let u of a){let p=u.tags?.find(g=>g.startsWith("arc:"))||"";l.set(p,(l.get(p)||0)+1);}let c=n?.symbolsTouched||[];if((c.length>0?a.filter(u=>u.symbols_touched?.some(p=>c.includes(p))):a.slice(0,3)).length>0||l.size>0){o.push(""),o.push("Active lore arcs:");for(let[u,p]of l)o.push(` ${u} (${p} entries)`);}}}catch{}try{let{loadNominations:r}=await import('./nomination-engine-
|
|
25
|
-
`)}var Oe=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 o=await n();return this.cache.set(e,{data:o,createdAt:Date.now()}),o}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}}},$t=new Oe(3e4);var rs=300*1e3,ae=null;function It(){ae=null;}function W(t,e){return v.existsSync($.join(t,e))}function
|
|
24
|
+
`;return ss(),{handled:true,text:JSON.stringify({handoff:m,markdownSummary:y,persisted:true,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(t==="paradigm_session_stats"){let o=s.getStats(),r=s.getCostBreakdown(),i=s.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(o.startTime).toISOString(),durationMinutes:i,lastActivity:new Date(o.lastActivity).toISOString()},model:{name:r.model,id:r.modelId,pricing:{inputPerMillion:`$${r.pricing.input.toFixed(2)}`,outputPerMillion:`$${r.pricing.output.toFixed(2)}`}},interactions:{toolCalls:o.totals.toolCallCount,resourceReads:o.totals.resourceReadCount,totalInteractions:o.totals.toolCallCount+o.totals.resourceReadCount},tokens:{total:o.totals.totalTokens,byCategory:{resources:r.resources.tokens,tools:r.tools.tokens}},cost:{totalUsd:`$${r.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${r.resources.costUsd.toFixed(4)}`,tools:`$${r.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:r.resources.byType,toolsByName:r.tools.byName}},null,2)}}if(t==="paradigm_session_recover"){s.setRootDir(n.rootDir);let o=s.loadPreviousSession(),r=s.loadCheckpoint(),i=[];try{i=b$1(n.rootDir);}catch{}if(!o&&i.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 c=Date.now()-r.timestamp,d=Math.round(c/6e4),u=Math.round(c/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(o){let c=Date.now()-o.lastActivity,d=Math.round(c/6e4),u=Math.round(c/36e5),g=o.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:o.sessionId,startTime:new Date(o.startTime).toISOString(),lastActivity:new Date(o.lastActivity).toISOString(),age:u>1?`${u} hours ago`:`${d} minutes ago`},a.context={symbolsModified:o.symbolsModified,filesExplored:o.filesExplored},a.recentActions=g;}if(i.length>0){a.pendingHandoffs=i.map(c=>({id:c.id,timestamp:c.timestamp,from:c.from,to:c.to,summary:c.summary,nextSteps:c.nextSteps,modifiedFiles:c.modifiedFiles,symbolsTouched:c.symbolsTouched,openQuestions:c.openQuestions}));for(let c of i)try{c$1(n.rootDir,c.id);}catch{}}let l="Continue where the previous session left off.";if(r)l=`Previous session was in "${r.phase}" phase: ${r.context}`,r.decisions?.length&&(l+=` Key decisions: ${r.decisions.slice(0,2).join("; ")}`);else if(i.length>0){let c=i[i.length-1];l=`Handoff received: "${c.summary}". `,c.nextSteps.length>0&&(l+=`Start with: ${c.nextSteps[0]}`);}else if(o){let c=o.breadcrumbs.slice(-10);if(c.length>0){let d=c[c.length-1];d.symbol&&(l=`Last work involved ${d.symbol}. Consider checking its current state with paradigm_ripple.`);}}return a.suggestion=l,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 o=e.phase,r=e.context,i=e.externalId,a=e.plan,l=e.modifiedFiles,c=e.symbolsTouched,d=e.decisions,{checkpoint:u,persisted:p}=s.saveCheckpoint({phase:o,context:r,externalId:i,plan:a,modifiedFiles:l,symbolsTouched:c,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:""}}async function Wo(t){let e=j$1();e.setRootDir(t);let n=e.loadCheckpoint(),s=[];try{s=b$1(t);}catch{}if(!n&&s.length===0)return null;let o=[];if(o.push("--- SESSION RECOVERY ---"),n){let r=Date.now()-n.timestamp,i=Math.round(r/6e4),a=Math.round(r/36e5),l=a>1?`${a}h ago`:`${i}m ago`;o.push(`Previous session was in "${n.phase}" phase (${l}): ${n.context}`),n.modifiedFiles?.length&&o.push(`Modified files: ${n.modifiedFiles.join(", ")}`),n.symbolsTouched?.length&&o.push(`Symbols: ${n.symbolsTouched.join(", ")}`),n.decisions?.length&&o.push(`Decisions: ${n.decisions.join("; ")}`),n.plan&&o.push(`Plan: ${n.plan.slice(0,200)}`);}if(s.length>0){let r=s[s.length-1];o.push(`Pending handoff: "${r.summary}"`),r.nextSteps.length>0&&o.push(`Next steps: ${r.nextSteps.slice(0,3).join(", ")}`);}try{let{loadTasks:r}=await import('./task-loader-NZFDTUQ5.js'),i=await r(t,{status:"open",limit:5});if(i.length>0){o.push(""),o.push("Open tasks:");for(let a of i){let l=a.tags.length>0?` [${a.tags.join(", ")}]`:"";o.push(` [${a.priority}] ${a.id}: ${a.blurb}${l}`);}}}catch{}try{let{loadLoreEntries:r}=await import('./lore-loader-RVQI5GXL.js'),a=(await r(t,{limit:10})).filter(l=>l.tags?.some(c=>c.startsWith("arc:")));if(a.length>0){let l=new Map;for(let u of a){let p=u.tags?.find(g=>g.startsWith("arc:"))||"";l.set(p,(l.get(p)||0)+1);}let c=n?.symbolsTouched||[];if((c.length>0?a.filter(u=>u.symbols_touched?.some(p=>c.includes(p))):a.slice(0,3)).length>0||l.size>0){o.push(""),o.push("Active lore arcs:");for(let[u,p]of l)o.push(` ${u} (${p} entries)`);}}}catch{}try{let{loadNominations:r}=await import('./nomination-engine-K7MQD53E.js'),i=r(t,{pending_only:!0}).filter(a=>a.urgency==="critical"||a.urgency==="high");if(i.length>0){o.push(""),o.push("Ambient nominations (urgent):");for(let a of i.slice(0,5))o.push(` [${a.urgency}] ${a.brief}`);i.length>5&&o.push(` ... and ${i.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return o.push(""),o.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."),o.push("---"),o.join(`
|
|
25
|
+
`)}var Oe=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 o=await n();return this.cache.set(e,{data:o,createdAt:Date.now()}),o}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}}},$t=new Oe(3e4);var rs=300*1e3,ae=null;function It(){ae=null;}function W(t,e){return v.existsSync($.join(t,e))}function J(t,e){return v.existsSync($.join(t,e))}function is(t,e,n){let s=t;try{if(!v.existsSync(s))return !1;let o=v.readdirSync(s,{withFileTypes:!0});for(let r of o){if(r.isFile()&&r.name.endsWith(e))return !0;if(r.isDirectory())try{if(v.readdirSync($.join(s,r.name)).some(a=>a.endsWith(e)))return !0}catch{}}}catch{}return false}var as={wisdom:t=>W(t,".paradigm/wisdom"),history:t=>W(t,".paradigm/history"),lore:t=>W(t,".paradigm/lore"),habits:t=>J(t,".paradigm/habits.yaml"),sentinel:t=>{try{let e=$.join(t,".paradigm","config.yaml");return v.existsSync(e)?v.readFileSync(e,"utf-8").includes("sentinel"):!1}catch{return false}},flows:t=>J(t,".paradigm/flow-index.json")||J(t,".paradigm/flows.yaml"),fixtures:t=>J(t,".paradigm/fixtures.yaml"),orchestration:t=>J(t,".paradigm/agents.yaml"),tasks:t=>W(t,".paradigm/tasks"),assessment:t=>W(t,".paradigm/lore"),personas:t=>is(t,".persona"),protocols:t=>W(t,".paradigm/protocols"),symphony:()=>{let t=$.join(he.homedir(),".paradigm","score");return v.existsSync(t)},university:t=>W(t,".paradigm/university"),agents:t=>{let e=$.join(he.homedir(),".paradigm","agents");return W(t,".paradigm/agents")||v.existsSync(e)},"aspect-graph":t=>J(t,".paradigm/aspect-graph.db"),pan:t=>J(t,".pan")||J(t,"nevr.yaml"),notebooks:t=>{let e=$.join(he.homedir(),".paradigm","notebooks");return W(t,".paradigm/notebooks")||v.existsSync(e)}},Rt=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(ae&&Date.now()-ae.timestamp<rs)return ae.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 o=s.detect||as[n];if(o)try{o(this.rootDir)&&e.add(n);}catch{}else e.add(n);}return ae={features:e,timestamp:Date.now()},e}getActiveTools(){let e=this.detectActiveFeatures(),n=[];for(let[s,o]of this.modules)e.has(s)&&n.push(...o.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,o){let r=this.detectActiveFeatures();for(let[i,a]of this.modules)if(r.has(i))try{let l=await a.handleTool(e,n,s,o);if(l.handled)return l}catch(l){return {handled:true,text:JSON.stringify({error:`Tool handler error in module "${i}"`,message:l.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,o])=>o.tier==="advanced"&&!this.activatedAdvanced.has(s)).map(([s])=>s)}}};var Ne=null;async function hs(){return Ne||(Ne=await ms()),Ne}var ys=[`CREATE TABLE IF NOT EXISTS aspects (
|
|
26
26
|
id TEXT PRIMARY KEY,
|
|
27
27
|
description TEXT NOT NULL,
|
|
28
28
|
category TEXT DEFAULT 'rule',
|
|
@@ -98,14 +98,14 @@ ${r.map((h,w)=>`${w+1}. ${h}`).join(`
|
|
|
98
98
|
ON CONFLICT(aspect_id, access_type)
|
|
99
99
|
DO UPDATE SET count = count + 1, last_accessed = ?`,[e,n,s,s]);}function nr(t,e=20,n){return n?z(t,"SELECT * FROM heatmap WHERE access_type = ? ORDER BY count DESC LIMIT ?",[n,e]):z(t,"SELECT * FROM heatmap ORDER BY count DESC LIMIT ?",[e])}function sr(t,e,n,s=true){let o=n?z(t,"SELECT * FROM anchors WHERE aspect_id = ?",[n]):z(t,"SELECT * FROM anchors"),r=[];for(let i of o){let a=$.isAbsolute(i.file_path)?i.file_path:$.join(e,i.file_path);if(!v.existsSync(a)){r.push({aspectId:i.aspect_id,path:i.file_path,startLine:i.start_line,endLine:i.end_line,status:"missing",resolvedBy:"none",exists:false,drifted:true});continue}try{let c=v.readFileSync(a,"utf8").split(`
|
|
100
100
|
`),d$1=Math.max(0,i.start_line-1),u=Math.min(c.length,i.end_line),p=c.slice(d$1,u).join(`
|
|
101
|
-
`),g=
|
|
102
|
-
`),E=
|
|
101
|
+
`),g=K.createHash("sha256").update(p).digest("hex");if(i.content_hash!=null&&g===i.content_hash){r.push({aspectId:i.aspect_id,path:i.file_path,startLine:i.start_line,endLine:i.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1}),i.drifted===1&&t.run("UPDATE anchors SET drifted = 0 WHERE id = ?",[i.id]);continue}let m=K.createHash("sha256").update(Me(p)).digest("hex");if(i.normalized_hash!=null&&m===i.normalized_hash){t.run("UPDATE anchors SET content_hash = ?, drifted = 0 WHERE id = ?",[g,i.id]),r.push({aspectId:i.aspect_id,path:i.file_path,startLine:i.start_line,endLine:i.end_line,status:"cosmetic",resolvedBy:"normalized-hash",exists:!0,drifted:!1});continue}if(i.content_hash==null&&i.normalized_hash==null){t.run("UPDATE anchors SET content_hash = ?, normalized_hash = ?, drifted = 0 WHERE id = ?",[g,m,i.id]),r.push({aspectId:i.aspect_id,path:i.file_path,startLine:i.start_line,endLine:i.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1});continue}let y=!1;if(i.materialized_at_commit){let h=vs(e,i.file_path,i.materialized_at_commit,i.start_line,i.end_line);if(h){let w=Math.max(0,h.currentStart-1),P=Math.min(c.length,h.currentEnd),k=c.slice(w,P).join(`
|
|
102
|
+
`),E=K.createHash("sha256").update(k).digest("hex");if(i.content_hash!=null&&E===i.content_hash){let x=s;if(x){t.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[h.currentStart,h.currentEnd,i.id]);let S=z(t,"SELECT defined_in FROM aspects WHERE id = ?",[i.aspect_id]);S.length>0&&De(e,S[0].defined_in,i.file_path,i.start_line,i.end_line,h.currentStart,h.currentEnd);}r.push({aspectId:i.aspect_id,path:i.file_path,startLine:x?h.currentStart:i.start_line,endLine:x?h.currentEnd:i.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:h.currentStart,suggestedEnd:h.currentEnd,autoHealed:x}),y=!0;}else {let x=K.createHash("sha256").update(Me(k)).digest("hex");if(i.normalized_hash!=null&&x===i.normalized_hash){if(s){let S=K.createHash("sha256").update(k).digest("hex");t.run("UPDATE anchors SET start_line = ?, end_line = ?, content_hash = ?, drifted = 0 WHERE id = ?",[h.currentStart,h.currentEnd,S,i.id]);let I=z(t,"SELECT defined_in FROM aspects WHERE id = ?",[i.aspect_id]);I.length>0&&De(e,I[0].defined_in,i.file_path,i.start_line,i.end_line,h.currentStart,h.currentEnd);}r.push({aspectId:i.aspect_id,path:i.file_path,startLine:s?h.currentStart:i.start_line,endLine:s?h.currentEnd:i.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:h.currentStart,suggestedEnd:h.currentEnd,autoHealed:s}),y=!0;}}}}if(y)continue;if(i.original_content){let{contentSearch:h}=(Nt(),d(Ft)),w=h(e,i.file_path,i.original_content,s);if(w.found&&w.score>=.7){if(s&&w.score>=.85&&!w.suggestedPath&&w.suggestedStart&&w.suggestedEnd){t.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[w.suggestedStart,w.suggestedEnd,i.id]);try{t.run(`INSERT INTO anchor_history (anchor_id, action, old_start, old_end, new_start, new_end, confidence, healed_at)
|
|
103
103
|
VALUES (?, 'relocated', ?, ?, ?, ?, ?, ?)`,[i.id,i.start_line,i.end_line,w.suggestedStart,w.suggestedEnd,w.score,new Date().toISOString()]);}catch{}let k=z(t,"SELECT defined_in FROM aspects WHERE id = ?",[i.aspect_id]);k.length>0&&De(e,k[0].defined_in,i.file_path,i.start_line,i.end_line,w.suggestedStart,w.suggestedEnd),r.push({aspectId:i.aspect_id,path:i.file_path,startLine:w.suggestedStart,endLine:w.suggestedEnd,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:w.similarity,suggestedStart:w.suggestedStart,suggestedEnd:w.suggestedEnd,autoHealed:!0,drifted:!1});continue}r.push({aspectId:i.aspect_id,path:w.suggestedPath||i.file_path,startLine:i.start_line,endLine:i.end_line,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:w.similarity,suggestedStart:w.suggestedStart,suggestedEnd:w.suggestedEnd,autoHealed:!1,drifted:!0});continue}}t.run("UPDATE anchors SET drifted = 1 WHERE id = ?",[i.id]),r.push({aspectId:i.aspect_id,path:i.file_path,startLine:i.start_line,endLine:i.end_line,status:"modified",resolvedBy:"none",exists:!0,currentContent:p,drifted:!0});}catch{r.push({aspectId:i.aspect_id,path:i.file_path,startLine:i.start_line,endLine:i.end_line,status:"modified",resolvedBy:"none",exists:true,drifted:true});}}return r}function Ht(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 xs(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 vs(t,e,n,s,o){let r;try{r=execSync(`git diff ${n}..HEAD --unified=0 -- "${e}"`,{cwd:t,encoding:"utf8",timeout:5e3});}catch{return null}if(!r.trim())return {originalStart:s,originalEnd:o,currentStart:s,currentEnd:o};let i=xs(r),a=0;for(let l of i){if(l.oldStart+l.oldCount<=s){a+=l.newCount-l.oldCount;continue}if(l.oldStart<o)return null;break}return a===0?null:{originalStart:s,originalEnd:o,currentStart:s+a,currentEnd:o+a}}function De(t,e,n,s,o,r,i){let a=$.isAbsolute(e)?e:$.join(t,e);if(!v.existsSync(a))return false;try{let l=v.readFileSync(a,"utf8"),c=s===o?`${n}:${s}`:`${n}:${s}-${o}`,d=r===i?`${n}:${r}`:`${n}:${r}-${i}`;if(!l.includes(c))return !1;let u=l.replace(c,d);return v.writeFileSync(a,u,"utf8"),!0}catch{return false}}function Me(t){return t.split(`
|
|
104
104
|
`).map(e=>e.trimEnd()).filter(e=>e.trim()!=="").map(e=>e.replace(/\s+/g," ")).join(`
|
|
105
105
|
`)}function Es(t,e){return {exact:null,normalized:null,normalizedContent:null};}function Ts(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 _s(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 $s=/L-\d{4}-\d{2}-\d{2}-\d{3}/g;async function Wt(t,e){t.run("DELETE FROM lore_links");let n=await a$2(e);if(n.length===0)return 0;let s=Rs(n),o=new Map;for(let c of n)o.set(c.id,c);let r=new Set,i=t.exec("SELECT id, enforcement FROM aspects");if(i.length>0){let{columns:c,values:d}=i[0],u=c.indexOf("id"),p=c.indexOf("enforcement");for(let g of d){let m=String(g[u]),y=g[p];if(y&&typeof y=="string"){let h=y.match($s);if(h)for(let w of h)o.has(w)&&r.add(`${m}\0${w}`);}}}let a=t.exec("SELECT source, target FROM edges");if(a.length>0&&i.length>0){let c=Is(t,a);for(let[d,u]of c)for(let p of u){let g=s.get(p);if(g)for(let m of g)r.add(`${d}\0${m}`);}}if(r.size===0)return 0;let l=t.prepare("INSERT OR IGNORE INTO lore_links (aspect_id, lore_id) VALUES (?, ?)");try{for(let c of r){let[d,u]=c.split("\0");l.bind([d,u]),l.step(),l.reset();}}finally{l.free();}return r.size}async function ir(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 o=s[0].values.map(r=>String(r[0]));return ks(e,o)}async function Gt(t,e){let n=await a$2(e);if(n.length===0)return 0;let s=t.exec("SELECT id FROM aspects"),o=new Set;if(s.length>0)for(let l of s[0].values)o.add(String(l[0]));if(o.size<2)return 0;let r=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 l of n){if(!l.symbols_touched||l.symbols_touched.length<2)continue;let c=[];for(let d of l.symbols_touched){let u=d.startsWith("~")?d.slice(1):d;o.has(u)&&c.push(u);}for(let d=0;d<c.length;d++)for(let u=d+1;u<c.length;u++){let[p,g]=c[d]<c[u]?[c[d],c[u]]:[c[u],c[d]];a.bind([p,g,r]),a.step(),a.reset(),i++;}}}finally{a.free();}return i}function Rs(t){let e=new Map;for(let n of t)if(n.symbols_touched)for(let s of n.symbols_touched){let o=e.get(s);o||(o=new Set,e.set(s,o)),o.add(n.id);}return e}function Is(t,e){let n=t.exec("SELECT id FROM aspects"),s=new Set;if(n.length>0)for(let c of n[0].values)s.add(String(c[0]));let o=new Map;if(e.length===0)return o;let{columns:r,values:i}=e[0],a=r.indexOf("source"),l=r.indexOf("target");for(let c of i){let d=String(c[a]),u=String(c[l]);if(s.has(d)){let p=o.get(d);p||(p=new Set,o.set(d,p)),p.add(u),p.add(`~${d}`);}if(s.has(u)){let p=o.get(u);p||(p=new Set,o.set(u,p)),p.add(d),p.add(`~${u}`);}}return o}async function ks(t,e){let n=new Set,s=[];for(let o of e){if(n.has(o))continue;n.add(o);let r=await b$2(t,o);r&&s.push(Ps(r));}return s}function Ps(t){return {id:t.id,title:t.title,summary:t.summary,timestamp:t.timestamp,symbolsTouched:t.symbols_touched}}var oe=".paradigm/personas",Cs="index.yaml";async function ce(t,e){let n=$.join(t,oe);if(!v.existsSync(n))return [];let s=v.readdirSync(n).filter(r=>r.endsWith(".persona")),o=[];for(let r of s)try{let i=v.readFileSync($.join(n,r),"utf8"),a=O.load(i);a&&a.id&&o.push(a);}catch{}return As(o,e)}async function le(t,e){let n=$.join(t,oe,`${e}.persona`);if(!v.existsSync(n))return null;try{return O.load(v.readFileSync(n,"utf8"))}catch{return null}}function As(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(o=>o.gates.includes(e.gate)))),e.flow&&(n=n.filter(s=>s.journey.some(o=>o.flow===e.flow))),e.limit&&(n=n.slice(0,e.limit)),n}async function cr(t,e){let n=$.join(t,oe);v.mkdirSync(n,{recursive:true});let s=$.join(n,`${e.id}.persona`);if(v.existsSync(s))throw new Error(`Persona ${e.id} already exists`);let o=new Date().toISOString(),r={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:o,updated:o};return v.writeFileSync(s,O.dump(r,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await de(t),e.id}async function Bt(t,e,n){let s=await le(t,e);if(!s)return false;let o=$.join(t,oe,`${e}.persona`),r={...s,...n,id:s.id,version:s.version,created:s.created,updated:new Date().toISOString()};return v.writeFileSync(o,O.dump(r,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await de(t),true}async function lr(t,e){let n=$.join(t,oe,`${e}.persona`);if(!v.existsSync(n))return {deleted:false,warnings:[]};let s=[],o=await ce(t);for(let r of o)if(r.id!==e){r.trigger.spawned_by?.startsWith(e+".")&&s.push(`Persona ${r.id} is spawned by ${e} \u2014 it will become orphaned`);for(let i of r.journey)i.spawns?.some(a=>a.persona===e)&&s.push(`Persona ${r.id} step ${i.id} spawns ${e} \u2014 spawn will break`);}return v.unlinkSync(n),await de(t),{deleted:true,warnings:s}}async function dr(t,e,n,s){let o=await le(t,e);if(!o)return false;if(o.journey.some(r=>r.id===n.id))throw new Error(`Step ${n.id} already exists in persona ${e}`);if(s){let r=o.journey.findIndex(i=>i.id===s);if(r===-1)throw new Error(`Step ${s} not found in persona ${e}`);o.journey.splice(r+1,0,n);}else o.journey.push(n);return Bt(t,e,{journey:o.journey})}async function ur(t,e,n){let s=await le(t,e);if(!s)return {removed:false,warnings:[]};let o=s.journey.findIndex(a=>a.id===n);if(o===-1)return {removed:false,warnings:[]};let r=s.journey[o],i=[];if(r.produces)for(let a of Object.keys(r.produces)){let l=`{{produces.${a}}}`;for(let c=o+1;c<s.journey.length;c++){let d=s.journey[c];JSON.stringify(d).includes(l)&&i.push(`Step ${d.id} consumes {{produces.${a}}} from this step`);}}if(r.spawns&&r.spawns.length>0)for(let a of r.spawns)i.push(`Step spawns persona ${a.persona} \u2014 spawn chain will break`);return s.journey.splice(o,1),await Bt(t,e,{journey:s.journey}),{removed:true,warnings:i}}var js=/^[a-z][a-z0-9-]*$/,Os=/^[a-z][a-z0-9-]*$/,Ls=/^(GET|POST|PUT|PATCH|DELETE)\s+\//;async function pr(t,e,n=false){let s=[],o=[];js.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 r=new Set,i=new Set;for(let a of e.journey){Os.test(a.id)||s.push({type:"invalid-step-id",step:a.id,detail:"Step ID must match /^[a-z][a-z0-9-]*$/"}),r.has(a.id)&&s.push({type:"duplicate-step-id",step:a.id,detail:`Duplicate step ID "${a.id}"`}),r.add(a.id),Ls.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 c=JSON.stringify(a).match(/\{\{produces\.([^}]+)\}\}/g)||[];for(let d of c){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=$.join(t,"portal.yaml"),l=[],c=[];if(v.existsSync(a))try{let u=O.load(v.readFileSync(a,"utf8"));u.gates&&typeof u.gates=="object"&&(l=Object.keys(u.gates)),u.routes&&typeof u.routes=="object"&&(c=Object.keys(u.routes));}catch{}for(let u of e.journey)for(let p of u.gates)l.length>0&&!l.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(c.length>0){let p=u.route;c.some(m=>Ue(m,p))||o.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 le(t,p.persona)||s.push({type:"spawn-target-missing",step:u.id,detail:`Spawn target persona "${p.persona}" does not exist`});let d=await Fs(t,e.id);if(d&&s.push({type:"spawn-cycle",detail:`Circular spawn dependency: ${d.join(" \u2192 ")}`}),c.length>0||l.length>0){let u=await ce(t),p=new Set,g=new Set;for(let w of u)for(let P of w.journey){for(let k of P.gates)p.add(k);g.add(P.route);}let m=[],y=$.join(t,".paradigm","flow-index.json");if(v.existsSync(y))try{let w=JSON.parse(v.readFileSync(y,"utf8"));m=Object.keys(w.flows||{});}catch{}let h=new Set;for(let w of u)for(let P of w.journey)P.flow&&h.add(P.flow);return {persona:e.id,valid:s.length===0,errors:s,warnings:o,coverage:{routes:{covered:g.size,total:c.length,uncovered:c.filter(w=>!g.has(w))},gates:{covered:p.size,total:l.length,uncovered:l.filter(w=>!p.has(w))},flows:{covered:h.size,total:m.length,uncovered:m.filter(w=>!h.has(w))}}}}}return {persona:e.id,valid:s.length===0,errors:s,warnings:o}}function Ue(t,e){let n=s=>s.replace(/:[a-zA-Z_]+/g,":param").replace(/\{\{[^}]+\}\}/g,":param");return n(t)===n(e)}async function Fs(t,e){let n=new Set,s=[];async function o(r){if(n.has(r)){let a=s.indexOf(r);return a!==-1?[...s.slice(a),r]:null}n.add(r),s.push(r);let i=await le(t,r);if(i){for(let a of i.journey)if(a.spawns)for(let l of a.spawns){let c=await o(l.persona);if(c)return c}}return s.pop(),null}return o(e)}async function de(t){let e=$.join(t,oe);v.mkdirSync(e,{recursive:true});let n=await ce(t),s={},o={},r={};for(let u of n){let p=new Set,g=new Set,m=[],y=new Set;for(let h of u.journey){for(let w of h.gates)p.add(w);if(h.flow&&g.add(h.flow),m.push(h.route),h.spawns)for(let w of h.spawns)y.add(w.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:[...y],tags:u.tags||[]};for(let h of p)o[h]||(o[h]=[]),o[h].push(u.id);for(let h of m)r[h]||(r[h]=[]),r[h].push(u.id);}let i=[],a=$.join(t,"portal.yaml");if(v.existsSync(a))try{let u=O.load(v.readFileSync(a,"utf8"));u.routes&&typeof u.routes=="object"&&(i=Object.keys(u.routes).filter(g=>!Object.keys(r).some(m=>Ue(g,m))));}catch{}let l={},c=$.join(e,"chains");if(v.existsSync(c)){let u=v.readdirSync(c).filter(p=>p.endsWith(".yaml"));for(let p of u)try{let g=v.readFileSync($.join(c,p),"utf8"),m=O.load(g);if(m&&m.id){let y=m.order.map(P=>P.persona),h=0,w=new Set;for(let P of y){let k=s[P];if(k){h+=k.steps;for(let E of k.gates)w.add(E);}}l[m.id]={description:m.description||"",order:y,total_steps:h,total_gates:w.size};}}catch{}}let d={version:"1.0",generated:new Date().toISOString(),personas:s,chains:l,gate_coverage:o,route_coverage:r,uncovered_routes:i};return v.writeFileSync($.join(e,Cs),O.dump(d,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),d}async function fr(t){let e=await ce(t),n=new Set,s=new Set,o=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&&o.add(u.flow);}let r=[],i=[],a=$.join(t,"portal.yaml");if(v.existsSync(a))try{let d=O.load(v.readFileSync(a,"utf8"));d.gates&&typeof d.gates=="object"&&(r=Object.keys(d.gates)),d.routes&&typeof d.routes=="object"&&(i=Object.keys(d.routes));}catch{}let l=[],c=$.join(t,".paradigm","flow-index.json");if(v.existsSync(c))try{let d=JSON.parse(v.readFileSync(c,"utf8"));l=Object.keys(d.flows||{});}catch{}return {routes:{covered:s.size,total:i.length,uncovered:i.filter(d=>!Array.from(s).some(u=>Ue(d,u)))},gates:{covered:n.size,total:r.length,uncovered:r.filter(d=>!n.has(d))},flows:{covered:o.size,total:l.length,uncovered:l.filter(d=>!o.has(d))},personas:e.length}}async function gr(t,e){let n=await ce(t),s=[];for(let o of n){let r=[],i=[];for(let a of o.journey)if((a.gates.includes(e)||a.flow===e||a.route===e||a.signals?.includes(e))&&(r.push(a.id),a.spawns))for(let c of a.spawns)i.push(c.persona);r.length>0&&s.push({persona:o.id,steps:r,spawns_blocked:i});}return s}function Ns(t,e){let n=e.split(/[.\[\]]+/).filter(Boolean),s=t;for(let o of n){if(s==null||typeof s!="object")return;s=s[o];}return s}function Ds(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 o of t.expect.body.has)(!s||typeof s!="object"||!(o in s))&&n.push({type:"body.has",field:o,expected:true,actual:false,message:`Step ${t.id}: body missing key '${o}'`});}if(t.expect.body?.match){let s=e.body;for(let[o,r]of Object.entries(t.expect.body.match)){let i=s?Ns(s,o):void 0;JSON.stringify(i)!==JSON.stringify(r)&&n.push({type:"body.match",field:o,expected:r,actual:i??null,message:`Step ${t.id}: '${o}' is ${JSON.stringify(i??null)}, expected ${JSON.stringify(r)}`});}}if(t.signals&&t.signals.length>0){let s=e.signals_fired||[];for(let o of t.signals)s.includes(o)||n.push({type:"signal",field:"signals_fired",expected:o,actual:s,message:`Step ${t.id}: signal '${o}' 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 mr(t,e={}){let n=[];try{let{SentinelStorage:a}=await import('./dist-W3XCATBJ.js'),l=new a,d=(l.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.complete",scopeValue:t.id,limit:500})||[]).filter(m=>{let y=JSON.parse(m.data_json||"{}");return !(e.run_id&&y.run_id!==e.run_id||e.chain_id&&y.chain_id!==e.chain_id||e.environment&&y.environment!==e.environment)}),p=(l.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.fail",scopeValue:t.id,limit:500})||[]).filter(m=>{let y=JSON.parse(m.data_json||"{}");return !(e.run_id&&y.run_id!==e.run_id||e.chain_id&&y.chain_id!==e.chain_id||e.environment&&y.environment!==e.environment)}),g=new Map;for(let m of [...d,...p]){let y=JSON.parse(m.data_json||"{}");y.step_id&&g.set(y.step_id,y);}for(let m of t.journey){let y=g.get(m.id);if(!y){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 h=Ds(m,{status:y.status,body:y.body,gates_traversed:y.gates_traversed,signals_fired:y.signals_fired});n.push({step_id:m.id,matched:!0,passed:h.length===0,assertions:h});}}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,o=n.filter(a=>a.passed).length,r=n.filter(a=>a.matched&&!a.passed).length,i=n.reduce((a,l)=>a+l.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:o,failed:r,assertion_failures:i}}}var ee=".paradigm/protocols",Xt="index.yaml";async function ze(t){let e=$.join(t,ee);if(!v.existsSync(e))return [];let n=v.readdirSync(e).filter(o=>o.endsWith(".protocol")).sort(),s=[];for(let o of n)try{let r=v.readFileSync($.join(e,o),"utf8"),i=O.load(r);i?.id&&i?.name&&s.push(i);}catch{}return s}async function Ms(t,e){let n=e.replace(/^P-/,""),s=$.join(t,ee,`${n}.protocol`);if(v.existsSync(s))try{let r=v.readFileSync(s,"utf8");return O.load(r)}catch{return null}return (await ze(t)).find(r=>r.id===e)||null}async function yr(t){let e=$.join(t,ee,Xt);if(!v.existsSync(e))return null;try{let n=v.readFileSync(e,"utf8");return O.load(n)}catch{return null}}async function wr(t,e,n=3){let s=await ze(t);if(s.length===0)return [];let o=zs(e);if(o.length===0)return [];let r=[];for(let i of s){let a=0;for(let d of i.trigger){let u=d.toLowerCase();for(let p of o)u.includes(p)&&(a+=3);}for(let d of i.tags){let u=d.toLowerCase();for(let p of o)(u.includes(p)||p.includes(u))&&(a+=2);}let l=i.name.toLowerCase(),c=i.description.toLowerCase();for(let d of o)l.includes(d)&&(a+=1),c.includes(d)&&(a+=1);for(let d of i.steps)if(d.notes){let u=d.notes.toLowerCase();for(let p of o)u.includes(p)&&(a+=.5);}a>0&&r.push({protocol:i,score:a});}return r.sort((i,a)=>a.score-i.score),r.slice(0,n)}async function br(t,e){let n=$.join(t,ee);v.existsSync(n)||v.mkdirSync(n,{recursive:true});let s=Ws(e.name),o=`P-${s}`,r=new Date().toISOString(),i={id:o,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:r,last_verified:r,verified_by:e.verified_by||"claude-opus-4-6",status:"current"},a=$.join(n,`${s}.protocol`);return v.writeFileSync(a,O.dump(i,{lineWidth:-1,noRefs:true}),"utf8"),o}async function Sr(t,e,n,s=false){let o=await Ms(t,e);if(!o)return false;n.name!==void 0&&(o.name=n.name),n.description!==void 0&&(o.description=n.description),n.trigger!==void 0&&(o.trigger=n.trigger),n.tags!==void 0&&(o.tags=n.tags),n.symbols!==void 0&&(o.symbols=n.symbols),n.exemplar!==void 0&&(o.exemplar=n.exemplar),n.steps!==void 0&&(o.steps=n.steps),n.status!==void 0&&(o.status=n.status),n.verified_by!==void 0&&(o.verified_by=n.verified_by),s&&(o.last_verified=new Date().toISOString(),o.verified_by=n.verified_by||"claude-opus-4-6");let r=e.replace(/^P-/,""),i=$.join(t,ee,`${r}.protocol`);return v.writeFileSync(i,O.dump(o,{lineWidth:-1,noRefs:true}),"utf8"),true}function Us(t,e){let n=[],s="current";if(e.exemplar){let o=$.join(t,e.exemplar);v.existsSync(o)?v.statSync(o).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 o of e.steps){if(o.template_from){let r=$.join(t,o.template_from);v.existsSync(r)||(n.push(`Template file missing: ${o.template_from}`),s="broken");}if(o.action==="modify"&&o.target){let r=$.join(t,o.target);!o.target.includes("{")&&!v.existsSync(r)&&(n.push(`Modify target missing: ${o.target}`),s="broken");}}return {status:s,issues:n}}async function qt(t){let e=await ze(t),n=[],s=0,o=0,r=0;for(let l of e){let c=Us(t,l);if(l.status!==c.status){l.status=c.status;let d=l.id.replace(/^P-/,""),u=$.join(t,ee,`${d}.protocol`);v.existsSync(u)&&v.writeFileSync(u,O.dump(l,{lineWidth:-1,noRefs:true}),"utf8");}switch(c.status){case "current":s++;break;case "stale":o++;break;case "broken":r++;break}n.push({id:l.id,name:l.name,status:c.status,last_verified:l.last_verified,trigger:l.trigger,tags:l.tags});}let i={version:"1.0",generated:new Date().toISOString(),protocols:n,health:{total:e.length,current:s,stale:o,broken:r}},a=$.join(t,ee);if(e.length>0){v.existsSync(a)||v.mkdirSync(a,{recursive:true});let l=$.join(a,Xt);v.writeFileSync(l,O.dump(i,{lineWidth:-1,noRefs:true}),"utf8");}return i}function xr(t,e,n){if(!e||e.length<2)return null;let s={};for(let o of e){let r=$.dirname(o);s[r]||(s[r]=[]),s[r].push(o);}for(let[o,r]of Object.entries(s)){if(r.length<2)continue;let i=$.join(t,o);if(!v.existsSync(i))continue;let l=v.readdirSync(i).filter(c=>{let d=$.extname(c);return [".ts",".tsx",".js",".jsx",".rs",".py"].includes(d)}).filter(c=>!r.some(d=>$.basename(d)===c));if(l.length>0){let c=$.join(o,l[0]),d=[...r.map(u=>({action:"create",target:u})),...n.map(u=>({action:"modify",target:u}))];return {hint:`This session created ${r.length} new files in ${o}/ following existing patterns. Consider recording a protocol.`,draft:{name:`Add a ${$.basename(o).replace(/s$/,"")}`,exemplar:c,steps:d}}}}return null}function zs(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(e=>e.length>1).filter(e=>!Hs.has(e))}var Hs=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 Ws(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var X=".paradigm/university",K="content",We="notes",be="policies",Se="quizzes",xe="paths",Ge="diplomas",Vt="index.yaml",Gs="config.yaml",Yt={name:"Project University",tagline:"Learn the codebase",institution:"Paradigm"},Jt={primary:"#6366f1",secondary:"#8b5cf6",accent:"#f59e0b",background:"#0f172a",surface:"#1e293b",text:"#f8fafc",textMuted:"#94a3b8",success:"#22c55e",error:"#ef4444",font:"Inter, system-ui, sans-serif"},He={branding:Yt,theme:Jt,content:{categories:[],defaultDifficulty:"beginner",requireApproval:false},diplomas:{includeGlobalPLSAT:true,customCertStyle:null}};function Be(t){let e=$.join(t,X,Gs);if(!v.existsSync(e))return {...He};try{let n=v.readFileSync(e,"utf8"),s=O.load(n);return s?{branding:{...Yt,...s.branding||{}},theme:{...Jt,...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}}:{...He}}catch{return {...He}}}function ve(t){let e=$.join(t,X,Vt);if(!v.existsSync(e))return null;try{let n=v.readFileSync(e,"utf8");return O.load(n)}catch{return null}}function Kt(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:O.load(e[1]),body:e[2].trim()}}catch{return null}}function Bs(t,e){return `---
|
|
106
|
+
VALUES (?, ?, 'related-to', 0.3, 'learned', ?)`);try{for(let l of n){if(!l.symbols_touched||l.symbols_touched.length<2)continue;let c=[];for(let d of l.symbols_touched){let u=d.startsWith("~")?d.slice(1):d;o.has(u)&&c.push(u);}for(let d=0;d<c.length;d++)for(let u=d+1;u<c.length;u++){let[p,g]=c[d]<c[u]?[c[d],c[u]]:[c[u],c[d]];a.bind([p,g,r]),a.step(),a.reset(),i++;}}}finally{a.free();}return i}function Rs(t){let e=new Map;for(let n of t)if(n.symbols_touched)for(let s of n.symbols_touched){let o=e.get(s);o||(o=new Set,e.set(s,o)),o.add(n.id);}return e}function Is(t,e){let n=t.exec("SELECT id FROM aspects"),s=new Set;if(n.length>0)for(let c of n[0].values)s.add(String(c[0]));let o=new Map;if(e.length===0)return o;let{columns:r,values:i}=e[0],a=r.indexOf("source"),l=r.indexOf("target");for(let c of i){let d=String(c[a]),u=String(c[l]);if(s.has(d)){let p=o.get(d);p||(p=new Set,o.set(d,p)),p.add(u),p.add(`~${d}`);}if(s.has(u)){let p=o.get(u);p||(p=new Set,o.set(u,p)),p.add(d),p.add(`~${u}`);}}return o}async function ks(t,e){let n=new Set,s=[];for(let o of e){if(n.has(o))continue;n.add(o);let r=await b$2(t,o);r&&s.push(Ps(r));}return s}function Ps(t){return {id:t.id,title:t.title,summary:t.summary,timestamp:t.timestamp,symbolsTouched:t.symbols_touched}}var oe=".paradigm/personas",Cs="index.yaml";async function ce(t,e){let n=$.join(t,oe);if(!v.existsSync(n))return [];let s=v.readdirSync(n).filter(r=>r.endsWith(".persona")),o=[];for(let r of s)try{let i=v.readFileSync($.join(n,r),"utf8"),a=O.load(i);a&&a.id&&o.push(a);}catch{}return As(o,e)}async function le(t,e){let n=$.join(t,oe,`${e}.persona`);if(!v.existsSync(n))return null;try{return O.load(v.readFileSync(n,"utf8"))}catch{return null}}function As(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(o=>o.gates.includes(e.gate)))),e.flow&&(n=n.filter(s=>s.journey.some(o=>o.flow===e.flow))),e.limit&&(n=n.slice(0,e.limit)),n}async function cr(t,e){let n=$.join(t,oe);v.mkdirSync(n,{recursive:true});let s=$.join(n,`${e.id}.persona`);if(v.existsSync(s))throw new Error(`Persona ${e.id} already exists`);let o=new Date().toISOString(),r={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:o,updated:o};return v.writeFileSync(s,O.dump(r,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await de(t),e.id}async function Bt(t,e,n){let s=await le(t,e);if(!s)return false;let o=$.join(t,oe,`${e}.persona`),r={...s,...n,id:s.id,version:s.version,created:s.created,updated:new Date().toISOString()};return v.writeFileSync(o,O.dump(r,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await de(t),true}async function lr(t,e){let n=$.join(t,oe,`${e}.persona`);if(!v.existsSync(n))return {deleted:false,warnings:[]};let s=[],o=await ce(t);for(let r of o)if(r.id!==e){r.trigger.spawned_by?.startsWith(e+".")&&s.push(`Persona ${r.id} is spawned by ${e} \u2014 it will become orphaned`);for(let i of r.journey)i.spawns?.some(a=>a.persona===e)&&s.push(`Persona ${r.id} step ${i.id} spawns ${e} \u2014 spawn will break`);}return v.unlinkSync(n),await de(t),{deleted:true,warnings:s}}async function dr(t,e,n,s){let o=await le(t,e);if(!o)return false;if(o.journey.some(r=>r.id===n.id))throw new Error(`Step ${n.id} already exists in persona ${e}`);if(s){let r=o.journey.findIndex(i=>i.id===s);if(r===-1)throw new Error(`Step ${s} not found in persona ${e}`);o.journey.splice(r+1,0,n);}else o.journey.push(n);return Bt(t,e,{journey:o.journey})}async function ur(t,e,n){let s=await le(t,e);if(!s)return {removed:false,warnings:[]};let o=s.journey.findIndex(a=>a.id===n);if(o===-1)return {removed:false,warnings:[]};let r=s.journey[o],i=[];if(r.produces)for(let a of Object.keys(r.produces)){let l=`{{produces.${a}}}`;for(let c=o+1;c<s.journey.length;c++){let d=s.journey[c];JSON.stringify(d).includes(l)&&i.push(`Step ${d.id} consumes {{produces.${a}}} from this step`);}}if(r.spawns&&r.spawns.length>0)for(let a of r.spawns)i.push(`Step spawns persona ${a.persona} \u2014 spawn chain will break`);return s.journey.splice(o,1),await Bt(t,e,{journey:s.journey}),{removed:true,warnings:i}}var js=/^[a-z][a-z0-9-]*$/,Os=/^[a-z][a-z0-9-]*$/,Ls=/^(GET|POST|PUT|PATCH|DELETE)\s+\//;async function pr(t,e,n=false){let s=[],o=[];js.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 r=new Set,i=new Set;for(let a of e.journey){Os.test(a.id)||s.push({type:"invalid-step-id",step:a.id,detail:"Step ID must match /^[a-z][a-z0-9-]*$/"}),r.has(a.id)&&s.push({type:"duplicate-step-id",step:a.id,detail:`Duplicate step ID "${a.id}"`}),r.add(a.id),Ls.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 c=JSON.stringify(a).match(/\{\{produces\.([^}]+)\}\}/g)||[];for(let d of c){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=$.join(t,"portal.yaml"),l=[],c=[];if(v.existsSync(a))try{let u=O.load(v.readFileSync(a,"utf8"));u.gates&&typeof u.gates=="object"&&(l=Object.keys(u.gates)),u.routes&&typeof u.routes=="object"&&(c=Object.keys(u.routes));}catch{}for(let u of e.journey)for(let p of u.gates)l.length>0&&!l.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(c.length>0){let p=u.route;c.some(m=>Ue(m,p))||o.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 le(t,p.persona)||s.push({type:"spawn-target-missing",step:u.id,detail:`Spawn target persona "${p.persona}" does not exist`});let d=await Fs(t,e.id);if(d&&s.push({type:"spawn-cycle",detail:`Circular spawn dependency: ${d.join(" \u2192 ")}`}),c.length>0||l.length>0){let u=await ce(t),p=new Set,g=new Set;for(let w of u)for(let P of w.journey){for(let k of P.gates)p.add(k);g.add(P.route);}let m=[],y=$.join(t,".paradigm","flow-index.json");if(v.existsSync(y))try{let w=JSON.parse(v.readFileSync(y,"utf8"));m=Object.keys(w.flows||{});}catch{}let h=new Set;for(let w of u)for(let P of w.journey)P.flow&&h.add(P.flow);return {persona:e.id,valid:s.length===0,errors:s,warnings:o,coverage:{routes:{covered:g.size,total:c.length,uncovered:c.filter(w=>!g.has(w))},gates:{covered:p.size,total:l.length,uncovered:l.filter(w=>!p.has(w))},flows:{covered:h.size,total:m.length,uncovered:m.filter(w=>!h.has(w))}}}}}return {persona:e.id,valid:s.length===0,errors:s,warnings:o}}function Ue(t,e){let n=s=>s.replace(/:[a-zA-Z_]+/g,":param").replace(/\{\{[^}]+\}\}/g,":param");return n(t)===n(e)}async function Fs(t,e){let n=new Set,s=[];async function o(r){if(n.has(r)){let a=s.indexOf(r);return a!==-1?[...s.slice(a),r]:null}n.add(r),s.push(r);let i=await le(t,r);if(i){for(let a of i.journey)if(a.spawns)for(let l of a.spawns){let c=await o(l.persona);if(c)return c}}return s.pop(),null}return o(e)}async function de(t){let e=$.join(t,oe);v.mkdirSync(e,{recursive:true});let n=await ce(t),s={},o={},r={};for(let u of n){let p=new Set,g=new Set,m=[],y=new Set;for(let h of u.journey){for(let w of h.gates)p.add(w);if(h.flow&&g.add(h.flow),m.push(h.route),h.spawns)for(let w of h.spawns)y.add(w.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:[...y],tags:u.tags||[]};for(let h of p)o[h]||(o[h]=[]),o[h].push(u.id);for(let h of m)r[h]||(r[h]=[]),r[h].push(u.id);}let i=[],a=$.join(t,"portal.yaml");if(v.existsSync(a))try{let u=O.load(v.readFileSync(a,"utf8"));u.routes&&typeof u.routes=="object"&&(i=Object.keys(u.routes).filter(g=>!Object.keys(r).some(m=>Ue(g,m))));}catch{}let l={},c=$.join(e,"chains");if(v.existsSync(c)){let u=v.readdirSync(c).filter(p=>p.endsWith(".yaml"));for(let p of u)try{let g=v.readFileSync($.join(c,p),"utf8"),m=O.load(g);if(m&&m.id){let y=m.order.map(P=>P.persona),h=0,w=new Set;for(let P of y){let k=s[P];if(k){h+=k.steps;for(let E of k.gates)w.add(E);}}l[m.id]={description:m.description||"",order:y,total_steps:h,total_gates:w.size};}}catch{}}let d={version:"1.0",generated:new Date().toISOString(),personas:s,chains:l,gate_coverage:o,route_coverage:r,uncovered_routes:i};return v.writeFileSync($.join(e,Cs),O.dump(d,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),d}async function fr(t){let e=await ce(t),n=new Set,s=new Set,o=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&&o.add(u.flow);}let r=[],i=[],a=$.join(t,"portal.yaml");if(v.existsSync(a))try{let d=O.load(v.readFileSync(a,"utf8"));d.gates&&typeof d.gates=="object"&&(r=Object.keys(d.gates)),d.routes&&typeof d.routes=="object"&&(i=Object.keys(d.routes));}catch{}let l=[],c=$.join(t,".paradigm","flow-index.json");if(v.existsSync(c))try{let d=JSON.parse(v.readFileSync(c,"utf8"));l=Object.keys(d.flows||{});}catch{}return {routes:{covered:s.size,total:i.length,uncovered:i.filter(d=>!Array.from(s).some(u=>Ue(d,u)))},gates:{covered:n.size,total:r.length,uncovered:r.filter(d=>!n.has(d))},flows:{covered:o.size,total:l.length,uncovered:l.filter(d=>!o.has(d))},personas:e.length}}async function gr(t,e){let n=await ce(t),s=[];for(let o of n){let r=[],i=[];for(let a of o.journey)if((a.gates.includes(e)||a.flow===e||a.route===e||a.signals?.includes(e))&&(r.push(a.id),a.spawns))for(let c of a.spawns)i.push(c.persona);r.length>0&&s.push({persona:o.id,steps:r,spawns_blocked:i});}return s}function Ns(t,e){let n=e.split(/[.\[\]]+/).filter(Boolean),s=t;for(let o of n){if(s==null||typeof s!="object")return;s=s[o];}return s}function Ds(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 o of t.expect.body.has)(!s||typeof s!="object"||!(o in s))&&n.push({type:"body.has",field:o,expected:true,actual:false,message:`Step ${t.id}: body missing key '${o}'`});}if(t.expect.body?.match){let s=e.body;for(let[o,r]of Object.entries(t.expect.body.match)){let i=s?Ns(s,o):void 0;JSON.stringify(i)!==JSON.stringify(r)&&n.push({type:"body.match",field:o,expected:r,actual:i??null,message:`Step ${t.id}: '${o}' is ${JSON.stringify(i??null)}, expected ${JSON.stringify(r)}`});}}if(t.signals&&t.signals.length>0){let s=e.signals_fired||[];for(let o of t.signals)s.includes(o)||n.push({type:"signal",field:"signals_fired",expected:o,actual:s,message:`Step ${t.id}: signal '${o}' 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 mr(t,e={}){let n=[];try{let{SentinelStorage:a}=await import('./dist-W3XCATBJ.js'),l=new a,d=(l.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.complete",scopeValue:t.id,limit:500})||[]).filter(m=>{let y=JSON.parse(m.data_json||"{}");return !(e.run_id&&y.run_id!==e.run_id||e.chain_id&&y.chain_id!==e.chain_id||e.environment&&y.environment!==e.environment)}),p=(l.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.fail",scopeValue:t.id,limit:500})||[]).filter(m=>{let y=JSON.parse(m.data_json||"{}");return !(e.run_id&&y.run_id!==e.run_id||e.chain_id&&y.chain_id!==e.chain_id||e.environment&&y.environment!==e.environment)}),g=new Map;for(let m of [...d,...p]){let y=JSON.parse(m.data_json||"{}");y.step_id&&g.set(y.step_id,y);}for(let m of t.journey){let y=g.get(m.id);if(!y){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 h=Ds(m,{status:y.status,body:y.body,gates_traversed:y.gates_traversed,signals_fired:y.signals_fired});n.push({step_id:m.id,matched:!0,passed:h.length===0,assertions:h});}}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,o=n.filter(a=>a.passed).length,r=n.filter(a=>a.matched&&!a.passed).length,i=n.reduce((a,l)=>a+l.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:o,failed:r,assertion_failures:i}}}var te=".paradigm/protocols",Xt="index.yaml";async function ze(t){let e=$.join(t,te);if(!v.existsSync(e))return [];let n=v.readdirSync(e).filter(o=>o.endsWith(".protocol")).sort(),s=[];for(let o of n)try{let r=v.readFileSync($.join(e,o),"utf8"),i=O.load(r);i?.id&&i?.name&&s.push(i);}catch{}return s}async function Ms(t,e){let n=e.replace(/^P-/,""),s=$.join(t,te,`${n}.protocol`);if(v.existsSync(s))try{let r=v.readFileSync(s,"utf8");return O.load(r)}catch{return null}return (await ze(t)).find(r=>r.id===e)||null}async function yr(t){let e=$.join(t,te,Xt);if(!v.existsSync(e))return null;try{let n=v.readFileSync(e,"utf8");return O.load(n)}catch{return null}}async function wr(t,e,n=3){let s=await ze(t);if(s.length===0)return [];let o=zs(e);if(o.length===0)return [];let r=[];for(let i of s){let a=0;for(let d of i.trigger){let u=d.toLowerCase();for(let p of o)u.includes(p)&&(a+=3);}for(let d of i.tags){let u=d.toLowerCase();for(let p of o)(u.includes(p)||p.includes(u))&&(a+=2);}let l=i.name.toLowerCase(),c=i.description.toLowerCase();for(let d of o)l.includes(d)&&(a+=1),c.includes(d)&&(a+=1);for(let d of i.steps)if(d.notes){let u=d.notes.toLowerCase();for(let p of o)u.includes(p)&&(a+=.5);}a>0&&r.push({protocol:i,score:a});}return r.sort((i,a)=>a.score-i.score),r.slice(0,n)}async function br(t,e){let n=$.join(t,te);v.existsSync(n)||v.mkdirSync(n,{recursive:true});let s=Ws(e.name),o=`P-${s}`,r=new Date().toISOString(),i={id:o,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:r,last_verified:r,verified_by:e.verified_by||"claude-opus-4-6",status:"current"},a=$.join(n,`${s}.protocol`);return v.writeFileSync(a,O.dump(i,{lineWidth:-1,noRefs:true}),"utf8"),o}async function Sr(t,e,n,s=false){let o=await Ms(t,e);if(!o)return false;n.name!==void 0&&(o.name=n.name),n.description!==void 0&&(o.description=n.description),n.trigger!==void 0&&(o.trigger=n.trigger),n.tags!==void 0&&(o.tags=n.tags),n.symbols!==void 0&&(o.symbols=n.symbols),n.exemplar!==void 0&&(o.exemplar=n.exemplar),n.steps!==void 0&&(o.steps=n.steps),n.status!==void 0&&(o.status=n.status),n.verified_by!==void 0&&(o.verified_by=n.verified_by),s&&(o.last_verified=new Date().toISOString(),o.verified_by=n.verified_by||"claude-opus-4-6");let r=e.replace(/^P-/,""),i=$.join(t,te,`${r}.protocol`);return v.writeFileSync(i,O.dump(o,{lineWidth:-1,noRefs:true}),"utf8"),true}function Us(t,e){let n=[],s="current";if(e.exemplar){let o=$.join(t,e.exemplar);v.existsSync(o)?v.statSync(o).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 o of e.steps){if(o.template_from){let r=$.join(t,o.template_from);v.existsSync(r)||(n.push(`Template file missing: ${o.template_from}`),s="broken");}if(o.action==="modify"&&o.target){let r=$.join(t,o.target);!o.target.includes("{")&&!v.existsSync(r)&&(n.push(`Modify target missing: ${o.target}`),s="broken");}}return {status:s,issues:n}}async function qt(t){let e=await ze(t),n=[],s=0,o=0,r=0;for(let l of e){let c=Us(t,l);if(l.status!==c.status){l.status=c.status;let d=l.id.replace(/^P-/,""),u=$.join(t,te,`${d}.protocol`);v.existsSync(u)&&v.writeFileSync(u,O.dump(l,{lineWidth:-1,noRefs:true}),"utf8");}switch(c.status){case "current":s++;break;case "stale":o++;break;case "broken":r++;break}n.push({id:l.id,name:l.name,status:c.status,last_verified:l.last_verified,trigger:l.trigger,tags:l.tags});}let i={version:"1.0",generated:new Date().toISOString(),protocols:n,health:{total:e.length,current:s,stale:o,broken:r}},a=$.join(t,te);if(e.length>0){v.existsSync(a)||v.mkdirSync(a,{recursive:true});let l=$.join(a,Xt);v.writeFileSync(l,O.dump(i,{lineWidth:-1,noRefs:true}),"utf8");}return i}function xr(t,e,n){if(!e||e.length<2)return null;let s={};for(let o of e){let r=$.dirname(o);s[r]||(s[r]=[]),s[r].push(o);}for(let[o,r]of Object.entries(s)){if(r.length<2)continue;let i=$.join(t,o);if(!v.existsSync(i))continue;let l=v.readdirSync(i).filter(c=>{let d=$.extname(c);return [".ts",".tsx",".js",".jsx",".rs",".py"].includes(d)}).filter(c=>!r.some(d=>$.basename(d)===c));if(l.length>0){let c=$.join(o,l[0]),d=[...r.map(u=>({action:"create",target:u})),...n.map(u=>({action:"modify",target:u}))];return {hint:`This session created ${r.length} new files in ${o}/ following existing patterns. Consider recording a protocol.`,draft:{name:`Add a ${$.basename(o).replace(/s$/,"")}`,exemplar:c,steps:d}}}}return null}function zs(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(e=>e.length>1).filter(e=>!Hs.has(e))}var Hs=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 Ws(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var X=".paradigm/university",Q="content",We="notes",be="policies",Se="quizzes",xe="paths",Ge="diplomas",Vt="index.yaml",Gs="config.yaml",Yt={name:"Project University",tagline:"Learn the codebase",institution:"Paradigm"},Jt={primary:"#6366f1",secondary:"#8b5cf6",accent:"#f59e0b",background:"#0f172a",surface:"#1e293b",text:"#f8fafc",textMuted:"#94a3b8",success:"#22c55e",error:"#ef4444",font:"Inter, system-ui, sans-serif"},He={branding:Yt,theme:Jt,content:{categories:[],defaultDifficulty:"beginner",requireApproval:false},diplomas:{includeGlobalPLSAT:true,customCertStyle:null}};function Be(t){let e=$.join(t,X,Gs);if(!v.existsSync(e))return {...He};try{let n=v.readFileSync(e,"utf8"),s=O.load(n);return s?{branding:{...Yt,...s.branding||{}},theme:{...Jt,...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}}:{...He}}catch{return {...He}}}function ve(t){let e=$.join(t,X,Vt);if(!v.existsSync(e))return null;try{let n=v.readFileSync(e,"utf8");return O.load(n)}catch{return null}}function Kt(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:O.load(e[1]),body:e[2].trim()}}catch{return null}}function Bs(t,e){return `---
|
|
107
107
|
${O.dump(t,{lineWidth:-1,noRefs:true,sortKeys:false})}---
|
|
108
108
|
|
|
109
109
|
${e}
|
|
110
|
-
`}function Er(t,e){let n=qe(t,e,".md");if(!n)return null;try{let s=v.readFileSync(n,"utf8"),o=Kt(s);if(!o)return null;let r=o.frontmatter;return {frontmatter:Ys(r),body:o.body}}catch{return null}}function Tr(t,e,n){let s=e.type==="policy"?be:We,o=$.join(t,X,K,s);v.mkdirSync(o,{recursive:true});let r=$.join(o,`${e.id}.md`),i=Bs(e,n);return v.writeFileSync(r,i,"utf8"),r}function Xs(t,e){let n=qe(t,e,".yaml");if(!n)return null;try{let s=v.readFileSync(n,"utf8"),o=O.load(s);return !o||!o.id?null:Js(o)}catch{return null}}function _r(t,e){let n=$.join(t,X,K,Se);v.mkdirSync(n,{recursive:true});let s=$.join(n,`${e.id}.yaml`);return v.writeFileSync(s,O.dump(e,{lineWidth:-1,noRefs:true}),"utf8"),s}function Qt(t,e){let n=qe(t,e,".yaml");if(!n)return null;try{let s=v.readFileSync(n,"utf8"),o=O.load(s);return !o||!o.id?null:o}catch{return null}}function $r(t,e){let n=$.join(t,X,K,xe);v.mkdirSync(n,{recursive:true});let s=$.join(n,`${e.id}.yaml`);return v.writeFileSync(s,O.dump(e,{lineWidth:-1,noRefs:true}),"utf8"),s}function Zt(t,e){let n=$.join(t,X,Ge);if(!v.existsSync(n))return [];let s=[];try{let o=v.readdirSync(n).filter(r=>r.endsWith(".yaml"));for(let r of o)try{let i=v.readFileSync($.join(n,r),"utf8"),a=O.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((o,r)=>r.earnedAt.localeCompare(o.earnedAt))}function Rr(t,e){let n=$.join(t,X,Ge);v.mkdirSync(n,{recursive:true});let s=$.join(n,`${e.id}.yaml`);return v.writeFileSync(s,O.dump(e,{lineWidth:-1,noRefs:true}),"utf8"),s}function Ir(t,e){let n=ve(t);if(!n)return [];let s=[...n.entries];if(e.type&&(s=s.filter(r=>r.type===e.type)),e.tag&&(s=s.filter(r=>r.tags.some(i=>i.startsWith(e.tag)))),e.difficulty&&(s=s.filter(r=>r.difficulty===e.difficulty)),e.symbol&&(s=s.filter(r=>r.symbols.some(i=>i===e.symbol))),e.author&&(s=s.filter(r=>r.author===e.author)),e.query){let r=e.query.toLowerCase();s=s.filter(i=>i.title.toLowerCase().includes(r)||i.id.toLowerCase().includes(r)||i.tags.some(a=>a.toLowerCase().includes(r)));}if(e.category&&(s=s.filter(r=>r.category===e.category)),e.track){let r=Be(t),i=new Map;for(let a of r.content.categories)i.set(a.id,a.track||"core");s=s.filter(a=>(a.category&&i.get(a.category)||"core")===e.track);}let o=e.limit||20;return s.slice(0,o)}function Xe(t){let e=$.join(t,X),n=$.join(e,K),s=[];for(let d of [We,be]){let u=$.join(n,d);if(v.existsSync(u))try{for(let p of v.readdirSync(u).filter(g=>g.endsWith(".md")))try{let g=v.readFileSync($.join(u,p),"utf8"),m=Kt(g);if(!m)continue;let y=m.frontmatter;s.push({id:y.id||p.replace(".md",""),title:y.title||p,type:y.type||(d===be?"policy":"note"),author:y.author||"unknown",created:y.created||"",updated:y.updated||"",tags:Array.isArray(y.tags)?y.tags:[],symbols:Array.isArray(y.symbols)?y.symbols:[],difficulty:y.difficulty||"beginner",file:`${K}/${d}/${p}`,...y.category?{category:y.category}:{}});}catch{}}catch{}}let o=$.join(n,Se);if(v.existsSync(o))try{for(let d of v.readdirSync(o).filter(u=>u.endsWith(".yaml")))try{let u=v.readFileSync($.join(o,d),"utf8"),p=O.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:`${K}/${Se}/${d}`,...p.category?{category:p.category}:{}});}catch{}}catch{}let r=$.join(n,xe);if(v.existsSync(r))try{for(let d of v.readdirSync(r).filter(u=>u.endsWith(".yaml")))try{let u=v.readFileSync($.join(r,d),"utf8"),p=O.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:`${K}/${xe}/${d}`,...p.category?{category:p.category}:{}});}catch{}}catch{}let i=0,a=$.join(e,Ge);if(v.existsSync(a))try{i=v.readdirSync(a).filter(d=>d.endsWith(".yaml")).length;}catch{}let l={version:"1.0",generatedAt:new Date().toISOString(),totalContent:s.length,entries:s,diplomaCount:i};v.mkdirSync(e,{recursive:true});let c=$.join(e,Vt);return v.writeFileSync(c,O.dump(l,{lineWidth:-1,noRefs:true}),"utf8"),l}function kr(t,e){let n=ve(t)||Xe(t),s=[],o=n.entries;e?.id&&(o=o.filter(c=>c.id===e.id));let r=null;e?.deep&&(r=en(t));let i=new Set(n.entries.map(c=>c.id));for(let c of o){if(c.title||s.push({contentId:c.id,severity:"error",check:"missing-title",message:"Content is missing a title",fix:"Add a title field to the content frontmatter"}),c.type==="quiz"&&qs(t,c.id,s),c.type==="path"&&Vs(t,c.id,i,s),r&&c.symbols.length>0){Be(t).content.categories.find(g=>g.id===c.category)?.validationStrictness==="relaxed";for(let g of c.symbols)r.has(g)||s.push({contentId:c.id,severity:"warning",check:"broken-symbol-ref",message:`Symbol "${g}" not found in scan-index`,fix:`Remove or update the symbol reference in ${c.id}`});}e?.deep&&c.symbols.length>0&&c.updated&&Qs(t,c,s);}let a=Zt(t);for(let c of a)if(c.total>0&&c.percentage!==Math.round(c.score/c.total*1e4)/100){let d=Math.round(c.score/c.total*1e4)/100;Math.abs(c.percentage-d)>.1&&s.push({contentId:c.id,severity:"warning",check:"diploma-score-mismatch",message:`Diploma percentage ${c.percentage} doesn't match score ${c.score}/${c.total} (expected ${d})`});}let l=Ks(t,n);return {status:s.some(c=>c.severity==="error")?"errors":s.length>0?"warnings":"healthy",totalContent:n.totalContent,checked:o.length,issues:s,symbolCoverage:l}}function qs(t,e,n){let s=Xs(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 o of s.questions){if(!o.choices||typeof o.choices!="object"){n.push({contentId:e,severity:"error",check:"invalid-quiz-choices",message:`Question ${o.id} has no choices defined`});continue}(!o.correct||!(o.correct in o.choices))&&n.push({contentId:e,severity:"error",check:"invalid-quiz-answer",message:`Question ${o.id}: correct answer "${o.correct}" not found in choices [${Object.keys(o.choices).join(", ")}]`,fix:`Set correct to one of: ${Object.keys(o.choices).join(", ")}`});}}function Vs(t,e,n,s){let o=Qt(t,e);if(!o){s.push({contentId:e,severity:"error",check:"unreadable-path",message:"Learning path file could not be parsed"});return}for(let r of o.steps)r.content.startsWith("plsat:")||n.has(r.content)||s.push({contentId:e,severity:"error",check:"broken-path-step",message:`Learning path step references "${r.content}" which doesn't exist`,fix:`Create content with id "${r.content}" or remove this step`});}function Pr(t,e){let n=ve(t);if(!n)return [];let s=[];for(let o of n.entries)if(o.symbols.includes(e)){let r=tn(t,o,e);s.push({id:o.id,title:o.title,type:o.type,stale:r});}return s}function Cr(t,e){let n=ve(t);if(!n)return {paths:[],suggestedContent:[],extracurricular:[],diplomaCount:0,totalContent:0};let s=Be(t),o=new Set;for(let p of s.content.categories)p.excludeFromOnboarding&&o.add(p.id);let r=n.entries.filter(p=>!p.category||!o.has(p.category)),i=n.entries.filter(p=>p.category&&o.has(p.category)),a=r.filter(p=>p.type==="path"),l=e?Zt(t,{student:e}):[],c=new Set(l.map(p=>p.source)),d=a.map(p=>{let g=Qt(t,p.id);return {id:p.id,title:p.title,steps:g?.steps.length||0,completed:c.has(p.id)}}),u=r.filter(p=>p.type!=="path"&&(p.difficulty==="beginner"||p.tags.includes("onboarding"))).slice(0,10);return {paths:d,suggestedContent:u,extracurricular:i,diplomaCount:l.length,totalContent:n.totalContent}}function qe(t,e,n){let s=$.join(t,X,K);for(let o of [We,be,Se,xe]){let r=$.join(s,o,`${e}${n}`);if(v.existsSync(r))return r}return null}function Ys(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}:{}}}function Js(t){return {...t,tags:t.tags||[],symbols:t.symbols||[],difficulty:t.difficulty||"beginner",passThreshold:t.passThreshold??.7,questions:t.questions||[]}}function en(t){let e=new Set,n=$.join(t,".paradigm","scan-index.json");if(!v.existsSync(n))return e;try{let s=v.readFileSync(n,"utf8"),o=JSON.parse(s);if(o.symbols&&Array.isArray(o.symbols))for(let r of o.symbols)r.symbol&&e.add(r.symbol);}catch{}return e}function Ks(t,e){let n=en(t),s=new Set;for(let r of e.entries)for(let i of r.symbols)n.has(i)&&s.add(i);let o=n.size;return {totalSymbols:o,coveredByContent:s.size,percentage:o>0?Math.round(s.size/o*100):0}}function tn(t,e,n){if(!e.updated)return false;let s=new Date(e.updated).getTime();if(isNaN(s))return false;let o=$.join(t,".paradigm","scan-index.json");if(!v.existsSync(o))return false;try{let r=v.readFileSync(o,"utf8"),i=JSON.parse(r);if(i.symbols&&Array.isArray(i.symbols)){for(let a of i.symbols)if(a.symbol===n&&a.filePath){let l=$.join(t,a.filePath);if(v.existsSync(l)&&v.statSync(l).mtime.getTime()>s)return !0}}}catch{}return false}function Qs(t,e,n){for(let s of e.symbols)if(tn(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 Zs={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},eo={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/"]},to={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"]},Ve={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 Br(){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}}]}async function Xr(t,e,n,s){if(t!=="paradigm_reindex")return {handled:false,text:""};try{let o=await no(n.rootDir,n);await s(),$t.clear(),It();let r=JSON.stringify(o,null,2);return je(r.length,t),{handled:!0,text:r}}catch(o){let r=JSON.stringify({error:o.message},null,2);return je(r.length,t),{handled:true,text:r}}}async function no(t,e){let n=[],s;e?s=e.aggregation:s=await Tt(t);let o=e?.projectName||$.basename(t),r=$.join(t,".paradigm");v.existsSync(r)||v.mkdirSync(r,{recursive:true});let i=Ce({symbols:s.symbols,purposeFiles:s.purposeFiles,portalFiles:s.portalFiles},{projectName:o}),a=$.join(r,"scan-index.json");v.writeFileSync(a,Ae(i),"utf8"),n.push(".paradigm/scan-index.json");let l=so(t,s),c=$.join(r,"navigator.yaml");v.writeFileSync(c,O.dump(l,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),n.push(".paradigm/navigator.yaml");let d=lo(t,s.purposeFiles),u=0;if(d&&Object.keys(d.flows).length>0){let S=$.join(r,"flow-index.json");v.writeFileSync(S,JSON.stringify(d,null,2),"utf8"),n.push(".paradigm/flow-index.json"),u=Object.keys(d.flows).length;}let p;try{let S=await Mt(t);zt(S,s.symbols,t);let I=await Wt(S,t),q=await Gt(S,t),on=S.exec("SELECT COUNT(*) FROM aspects")[0]?.values[0]?.[0]??0,rn=S.exec("SELECT COUNT(*) FROM anchors")[0]?.values[0]?.[0]??0,an=S.exec("SELECT COUNT(*) FROM edges")[0]?.values[0]?.[0]??0;Ut(S,t),n.push(".paradigm/aspect-graph.db"),p={aspects:on,anchors:rn,edges:an,loreLinks:I};}catch{}let g=0;try{let S=await de(t);g=Object.keys(S.personas).length,g>0&&n.push(".paradigm/personas/index.yaml");}catch{}let m;try{let S=await qt(t);S.health.total>0&&(m=S.health,n.push(".paradigm/protocols/index.yaml"));}catch{}let y;try{let S=$.join(t,".paradigm","university");if(v.existsSync(S)){let I=Xe(t);(I.totalContent>0||I.diplomaCount>0)&&(y={totalContent:I.totalContent,diplomaCount:I.diplomaCount},n.push(".paradigm/university/index.yaml"));}}catch{}let h;try{h=a$1(s,t);}catch{}let w;try{let S=b$3(s.symbols,t),I=S.missing+S.outOfBounds;I>0&&(w=I);}catch{}let P;try{P=c$2(s.purposeFiles,t);}catch{}let k;try{let S=[];for(let I of s.purposeFiles){let q=Ie(I);q.data&&S.push({filePath:I,data:q.data});}if(S.length>0){let q=ht(S).issues.length;q>0&&(k=q);}}catch{}let E={};for(let S of s.symbols)E[S.type]=(E[S.type]||0)+1;let x={};for(let S of s.symbols)S.type==="component"&&S.componentType&&(x[S.componentType]=(x[S.componentType]||0)+1);return {action:"reindex",filesWritten:n,symbolCount:s.symbols.length,breakdown:E,flowCount:u,aspectGraphStats:p,personaCount:g,protocolHealth:m,...Object.keys(x).length>0?{componentTypeBreakdown:x}:{},...y?{universityStats:y}:{},...h?{integrityReport:h}:{},...w!==void 0?{componentAnchorIssues:w}:{},...P?{purposeHealth:P}:{},...k!==void 0?{crossFileIssues:k}:{}}}function so(t,e){let n={};for(let s of e.symbols)if(s.type==="component"&&s.componentType){let o=s.componentType;n[o]||(n[o]=[]),n[o].push(s.symbol);}return {version:"1.0",generated:new Date().toISOString(),structure:oo(t),key_files:ro(t),skip_patterns:io(t),symbols:co(e.symbols,e.purposeFiles),...Object.keys(n).length>0?{symbolsByComponentType:n}:{}}}function oo(t){let e={};for(let[n,s]of Object.entries(eo)){let o=s.filter(r=>v.existsSync($.join(t,r)));if(o.length>0){let r=Object.values(Zs).find(i=>i.category===n);e[n]={paths:o,symbol:r?.prefix||"@"};}}return e}function ro(t){let e={};for(let[n,s]of Object.entries(to)){let o=s.filter(r=>v.existsSync($.join(t,r)));o.length>0&&(e[n]=o);}return e.config||(e.config=[]),e.entry||(e.entry=[]),e.types||(e.types=[]),e}function io(t){let e={always:[...Ve.always],unless_testing:[...Ve.unless_testing],unless_docs:[...Ve.unless_docs]},n=$.join(t,".gitignore");if(v.existsSync(n))try{let o=v.readFileSync(n,"utf8").split(`
|
|
110
|
+
`}function Er(t,e){let n=qe(t,e,".md");if(!n)return null;try{let s=v.readFileSync(n,"utf8"),o=Kt(s);if(!o)return null;let r=o.frontmatter;return {frontmatter:Ys(r),body:o.body}}catch{return null}}function Tr(t,e,n){let s=e.type==="policy"?be:We,o=$.join(t,X,Q,s);v.mkdirSync(o,{recursive:true});let r=$.join(o,`${e.id}.md`),i=Bs(e,n);return v.writeFileSync(r,i,"utf8"),r}function Xs(t,e){let n=qe(t,e,".yaml");if(!n)return null;try{let s=v.readFileSync(n,"utf8"),o=O.load(s);return !o||!o.id?null:Js(o)}catch{return null}}function _r(t,e){let n=$.join(t,X,Q,Se);v.mkdirSync(n,{recursive:true});let s=$.join(n,`${e.id}.yaml`);return v.writeFileSync(s,O.dump(e,{lineWidth:-1,noRefs:true}),"utf8"),s}function Qt(t,e){let n=qe(t,e,".yaml");if(!n)return null;try{let s=v.readFileSync(n,"utf8"),o=O.load(s);return !o||!o.id?null:o}catch{return null}}function $r(t,e){let n=$.join(t,X,Q,xe);v.mkdirSync(n,{recursive:true});let s=$.join(n,`${e.id}.yaml`);return v.writeFileSync(s,O.dump(e,{lineWidth:-1,noRefs:true}),"utf8"),s}function Zt(t,e){let n=$.join(t,X,Ge);if(!v.existsSync(n))return [];let s=[];try{let o=v.readdirSync(n).filter(r=>r.endsWith(".yaml"));for(let r of o)try{let i=v.readFileSync($.join(n,r),"utf8"),a=O.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((o,r)=>r.earnedAt.localeCompare(o.earnedAt))}function Rr(t,e){let n=$.join(t,X,Ge);v.mkdirSync(n,{recursive:true});let s=$.join(n,`${e.id}.yaml`);return v.writeFileSync(s,O.dump(e,{lineWidth:-1,noRefs:true}),"utf8"),s}function Ir(t,e){let n=ve(t);if(!n)return [];let s=[...n.entries];if(e.type&&(s=s.filter(r=>r.type===e.type)),e.tag&&(s=s.filter(r=>r.tags.some(i=>i.startsWith(e.tag)))),e.difficulty&&(s=s.filter(r=>r.difficulty===e.difficulty)),e.symbol&&(s=s.filter(r=>r.symbols.some(i=>i===e.symbol))),e.author&&(s=s.filter(r=>r.author===e.author)),e.query){let r=e.query.toLowerCase();s=s.filter(i=>i.title.toLowerCase().includes(r)||i.id.toLowerCase().includes(r)||i.tags.some(a=>a.toLowerCase().includes(r)));}if(e.category&&(s=s.filter(r=>r.category===e.category)),e.track){let r=Be(t),i=new Map;for(let a of r.content.categories)i.set(a.id,a.track||"core");s=s.filter(a=>(a.category&&i.get(a.category)||"core")===e.track);}let o=e.limit||20;return s.slice(0,o)}function Xe(t){let e=$.join(t,X),n=$.join(e,Q),s=[];for(let d of [We,be]){let u=$.join(n,d);if(v.existsSync(u))try{for(let p of v.readdirSync(u).filter(g=>g.endsWith(".md")))try{let g=v.readFileSync($.join(u,p),"utf8"),m=Kt(g);if(!m)continue;let y=m.frontmatter;s.push({id:y.id||p.replace(".md",""),title:y.title||p,type:y.type||(d===be?"policy":"note"),author:y.author||"unknown",created:y.created||"",updated:y.updated||"",tags:Array.isArray(y.tags)?y.tags:[],symbols:Array.isArray(y.symbols)?y.symbols:[],difficulty:y.difficulty||"beginner",file:`${Q}/${d}/${p}`,...y.category?{category:y.category}:{}});}catch{}}catch{}}let o=$.join(n,Se);if(v.existsSync(o))try{for(let d of v.readdirSync(o).filter(u=>u.endsWith(".yaml")))try{let u=v.readFileSync($.join(o,d),"utf8"),p=O.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:`${Q}/${Se}/${d}`,...p.category?{category:p.category}:{}});}catch{}}catch{}let r=$.join(n,xe);if(v.existsSync(r))try{for(let d of v.readdirSync(r).filter(u=>u.endsWith(".yaml")))try{let u=v.readFileSync($.join(r,d),"utf8"),p=O.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:`${Q}/${xe}/${d}`,...p.category?{category:p.category}:{}});}catch{}}catch{}let i=0,a=$.join(e,Ge);if(v.existsSync(a))try{i=v.readdirSync(a).filter(d=>d.endsWith(".yaml")).length;}catch{}let l={version:"1.0",generatedAt:new Date().toISOString(),totalContent:s.length,entries:s,diplomaCount:i};v.mkdirSync(e,{recursive:true});let c=$.join(e,Vt);return v.writeFileSync(c,O.dump(l,{lineWidth:-1,noRefs:true}),"utf8"),l}function kr(t,e){let n=ve(t)||Xe(t),s=[],o=n.entries;e?.id&&(o=o.filter(c=>c.id===e.id));let r=null;e?.deep&&(r=en(t));let i=new Set(n.entries.map(c=>c.id));for(let c of o){if(c.title||s.push({contentId:c.id,severity:"error",check:"missing-title",message:"Content is missing a title",fix:"Add a title field to the content frontmatter"}),c.type==="quiz"&&qs(t,c.id,s),c.type==="path"&&Vs(t,c.id,i,s),r&&c.symbols.length>0){Be(t).content.categories.find(g=>g.id===c.category)?.validationStrictness==="relaxed";for(let g of c.symbols)r.has(g)||s.push({contentId:c.id,severity:"warning",check:"broken-symbol-ref",message:`Symbol "${g}" not found in scan-index`,fix:`Remove or update the symbol reference in ${c.id}`});}e?.deep&&c.symbols.length>0&&c.updated&&Qs(t,c,s);}let a=Zt(t);for(let c of a)if(c.total>0&&c.percentage!==Math.round(c.score/c.total*1e4)/100){let d=Math.round(c.score/c.total*1e4)/100;Math.abs(c.percentage-d)>.1&&s.push({contentId:c.id,severity:"warning",check:"diploma-score-mismatch",message:`Diploma percentage ${c.percentage} doesn't match score ${c.score}/${c.total} (expected ${d})`});}let l=Ks(t,n);return {status:s.some(c=>c.severity==="error")?"errors":s.length>0?"warnings":"healthy",totalContent:n.totalContent,checked:o.length,issues:s,symbolCoverage:l}}function qs(t,e,n){let s=Xs(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 o of s.questions){if(!o.choices||typeof o.choices!="object"){n.push({contentId:e,severity:"error",check:"invalid-quiz-choices",message:`Question ${o.id} has no choices defined`});continue}(!o.correct||!(o.correct in o.choices))&&n.push({contentId:e,severity:"error",check:"invalid-quiz-answer",message:`Question ${o.id}: correct answer "${o.correct}" not found in choices [${Object.keys(o.choices).join(", ")}]`,fix:`Set correct to one of: ${Object.keys(o.choices).join(", ")}`});}}function Vs(t,e,n,s){let o=Qt(t,e);if(!o){s.push({contentId:e,severity:"error",check:"unreadable-path",message:"Learning path file could not be parsed"});return}for(let r of o.steps)r.content.startsWith("plsat:")||n.has(r.content)||s.push({contentId:e,severity:"error",check:"broken-path-step",message:`Learning path step references "${r.content}" which doesn't exist`,fix:`Create content with id "${r.content}" or remove this step`});}function Pr(t,e){let n=ve(t);if(!n)return [];let s=[];for(let o of n.entries)if(o.symbols.includes(e)){let r=tn(t,o,e);s.push({id:o.id,title:o.title,type:o.type,stale:r});}return s}function Cr(t,e){let n=ve(t);if(!n)return {paths:[],suggestedContent:[],extracurricular:[],diplomaCount:0,totalContent:0};let s=Be(t),o=new Set;for(let p of s.content.categories)p.excludeFromOnboarding&&o.add(p.id);let r=n.entries.filter(p=>!p.category||!o.has(p.category)),i=n.entries.filter(p=>p.category&&o.has(p.category)),a=r.filter(p=>p.type==="path"),l=e?Zt(t,{student:e}):[],c=new Set(l.map(p=>p.source)),d=a.map(p=>{let g=Qt(t,p.id);return {id:p.id,title:p.title,steps:g?.steps.length||0,completed:c.has(p.id)}}),u=r.filter(p=>p.type!=="path"&&(p.difficulty==="beginner"||p.tags.includes("onboarding"))).slice(0,10);return {paths:d,suggestedContent:u,extracurricular:i,diplomaCount:l.length,totalContent:n.totalContent}}function qe(t,e,n){let s=$.join(t,X,Q);for(let o of [We,be,Se,xe]){let r=$.join(s,o,`${e}${n}`);if(v.existsSync(r))return r}return null}function Ys(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}:{}}}function Js(t){return {...t,tags:t.tags||[],symbols:t.symbols||[],difficulty:t.difficulty||"beginner",passThreshold:t.passThreshold??.7,questions:t.questions||[]}}function en(t){let e=new Set,n=$.join(t,".paradigm","scan-index.json");if(!v.existsSync(n))return e;try{let s=v.readFileSync(n,"utf8"),o=JSON.parse(s);if(o.symbols&&Array.isArray(o.symbols))for(let r of o.symbols)r.symbol&&e.add(r.symbol);}catch{}return e}function Ks(t,e){let n=en(t),s=new Set;for(let r of e.entries)for(let i of r.symbols)n.has(i)&&s.add(i);let o=n.size;return {totalSymbols:o,coveredByContent:s.size,percentage:o>0?Math.round(s.size/o*100):0}}function tn(t,e,n){if(!e.updated)return false;let s=new Date(e.updated).getTime();if(isNaN(s))return false;let o=$.join(t,".paradigm","scan-index.json");if(!v.existsSync(o))return false;try{let r=v.readFileSync(o,"utf8"),i=JSON.parse(r);if(i.symbols&&Array.isArray(i.symbols)){for(let a of i.symbols)if(a.symbol===n&&a.filePath){let l=$.join(t,a.filePath);if(v.existsSync(l)&&v.statSync(l).mtime.getTime()>s)return !0}}}catch{}return false}function Qs(t,e,n){for(let s of e.symbols)if(tn(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 Zs={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},eo={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/"]},to={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"]},Ve={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 Br(){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}}]}async function Xr(t,e,n,s){if(t!=="paradigm_reindex")return {handled:false,text:""};try{let o=await no(n.rootDir,n);await s(),$t.clear(),It();let r=(o.integrityReport?.brokenReferences?.length||0)+(o.integrityReport?.duplicateSymbols?.length||0)+(o.componentAnchorIssues||0)+(o.crossFileIssues||0),i={success:!0,symbolCount:o.symbolCount,breakdown:o.breakdown,flowCount:o.flowCount,filesWritten:o.filesWritten.length,...o.aspectGraphStats?{aspects:o.aspectGraphStats.aspects,loreLinks:o.aspectGraphStats.loreLinks}:{},...o.protocolHealth?{protocols:o.protocolHealth.total,staleProtocols:o.protocolHealth.stale}:{},...r>0?{issues:r}:{}},a=JSON.stringify(i,null,2);return je(a.length,t),{handled:!0,text:a}}catch(o){let r=JSON.stringify({error:o.message},null,2);return je(r.length,t),{handled:true,text:r}}}async function no(t,e){let n=[],s;e?s=e.aggregation:s=await Tt(t);let o=e?.projectName||$.basename(t),r=$.join(t,".paradigm");v.existsSync(r)||v.mkdirSync(r,{recursive:true});let i=Ce({symbols:s.symbols,purposeFiles:s.purposeFiles,portalFiles:s.portalFiles},{projectName:o}),a=$.join(r,"scan-index.json");v.writeFileSync(a,Ae(i),"utf8"),n.push(".paradigm/scan-index.json");let l=so(t,s),c=$.join(r,"navigator.yaml");v.writeFileSync(c,O.dump(l,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),n.push(".paradigm/navigator.yaml");let d=lo(t,s.purposeFiles),u=0;if(d&&Object.keys(d.flows).length>0){let S=$.join(r,"flow-index.json");v.writeFileSync(S,JSON.stringify(d,null,2),"utf8"),n.push(".paradigm/flow-index.json"),u=Object.keys(d.flows).length;}let p;try{let S=await Mt(t);zt(S,s.symbols,t);let I=await Wt(S,t),q=await Gt(S,t),on=S.exec("SELECT COUNT(*) FROM aspects")[0]?.values[0]?.[0]??0,rn=S.exec("SELECT COUNT(*) FROM anchors")[0]?.values[0]?.[0]??0,an=S.exec("SELECT COUNT(*) FROM edges")[0]?.values[0]?.[0]??0;Ut(S,t),n.push(".paradigm/aspect-graph.db"),p={aspects:on,anchors:rn,edges:an,loreLinks:I};}catch{}let g=0;try{let S=await de(t);g=Object.keys(S.personas).length,g>0&&n.push(".paradigm/personas/index.yaml");}catch{}let m;try{let S=await qt(t);S.health.total>0&&(m=S.health,n.push(".paradigm/protocols/index.yaml"));}catch{}let y;try{let S=$.join(t,".paradigm","university");if(v.existsSync(S)){let I=Xe(t);(I.totalContent>0||I.diplomaCount>0)&&(y={totalContent:I.totalContent,diplomaCount:I.diplomaCount},n.push(".paradigm/university/index.yaml"));}}catch{}let h;try{h=a$1(s,t);}catch{}let w;try{let S=b$3(s.symbols,t),I=S.missing+S.outOfBounds;I>0&&(w=I);}catch{}let P;try{P=c$2(s.purposeFiles,t);}catch{}let k;try{let S=[];for(let I of s.purposeFiles){let q=Ie(I);q.data&&S.push({filePath:I,data:q.data});}if(S.length>0){let q=ht(S).issues.length;q>0&&(k=q);}}catch{}let E={};for(let S of s.symbols)E[S.type]=(E[S.type]||0)+1;let x={};for(let S of s.symbols)S.type==="component"&&S.componentType&&(x[S.componentType]=(x[S.componentType]||0)+1);return {action:"reindex",filesWritten:n,symbolCount:s.symbols.length,breakdown:E,flowCount:u,aspectGraphStats:p,personaCount:g,protocolHealth:m,...Object.keys(x).length>0?{componentTypeBreakdown:x}:{},...y?{universityStats:y}:{},...h?{integrityReport:h}:{},...w!==void 0?{componentAnchorIssues:w}:{},...P?{purposeHealth:P}:{},...k!==void 0?{crossFileIssues:k}:{}}}function so(t,e){let n={};for(let s of e.symbols)if(s.type==="component"&&s.componentType){let o=s.componentType;n[o]||(n[o]=[]),n[o].push(s.symbol);}return {version:"1.0",generated:new Date().toISOString(),structure:oo(t),key_files:ro(t),skip_patterns:io(t),symbols:co(e.symbols,e.purposeFiles),...Object.keys(n).length>0?{symbolsByComponentType:n}:{}}}function oo(t){let e={};for(let[n,s]of Object.entries(eo)){let o=s.filter(r=>v.existsSync($.join(t,r)));if(o.length>0){let r=Object.values(Zs).find(i=>i.category===n);e[n]={paths:o,symbol:r?.prefix||"@"};}}return e}function ro(t){let e={};for(let[n,s]of Object.entries(to)){let o=s.filter(r=>v.existsSync($.join(t,r)));o.length>0&&(e[n]=o);}return e.config||(e.config=[]),e.entry||(e.entry=[]),e.types||(e.types=[]),e}function io(t){let e={always:[...Ve.always],unless_testing:[...Ve.unless_testing],unless_docs:[...Ve.unless_docs]},n=$.join(t,".gitignore");if(v.existsSync(n))try{let o=v.readFileSync(n,"utf8").split(`
|
|
111
111
|
`).map(r=>r.trim()).filter(r=>r&&!r.startsWith("#")).filter(r=>r.endsWith("/")||r.includes("*")||["node_modules","dist","build",".cache"].some(i=>r.includes(i))).slice(0,20);for(let r of o)e.always.includes(r)||e.always.push(r);}catch{}return e}function ao(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 co(t,e,n){let s={};for(let o of t){let i=`${ao(o.type)}${o.id}`;if(o.filePath)s[i]=o.filePath;else {let a=e.find(l=>$.dirname(l).toLowerCase().includes(o.id.toLowerCase()));a&&(s[i]=$.dirname(a)+"/");}}return s}function lo(t,e){let n={},s={};for(let o of e)try{let r=v.readFileSync(o,"utf8"),i=O.load(r);if(!i?.flows)continue;if(Array.isArray(i.flows))for(let a of i.flows){let l=a;if(!l.name)continue;let c=`$${l.name}`,d=nn(l.steps);d.length>0&&(n[c]={id:c,description:l.description||"",steps:d,definedIn:$.relative(t,o)},sn(c,d,s));}else for(let[a,l]of Object.entries(i.flows)){let c=a.startsWith("$")?a:`$${a}`,d=nn(l.steps);d.length>0&&(n[c]={id:c,description:l.description||"",trigger:l.trigger,steps:d,validation:l.validation,definedIn:$.relative(t,o)},sn(c,d,s));}}catch{}return Object.keys(n).length===0?null:{version:"1.0",generatedAt:new Date().toISOString(),flows:n,symbolToFlows:s}}function nn(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 o=s,r=o.action||o.description||o.component||"";r&&e.push({id:o.id||`step-${n+1}`,action:r,symbol:o.symbol||o.component,expect:o.expect});}}return e}function sn(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{Er as $,Qo as A,Zo as B,er as C,tr as D,nr as E,sr as F,ir as G,ce as H,le as I,cr as J,Bt as K,lr as L,dr as M,ur as N,pr as O,fr as P,gr as Q,mr as R,ze as S,Ms as T,yr as U,wr as V,br as W,Sr as X,Us as Y,xr as Z,Be as _,Tn as a,Tr as aa,po as b,Xs as ba,$n as c,_r as ca,go as d,Qt as da,ge as e,$r as ea,Tt as f,Zt as fa,vo as g,Rr as ga,me as h,Ir as ha,Eo as i,Xe as ia,To as j,kr as ja,_o as k,Pr as ka,$o as l,Cr as la,Ro as m,Br as ma,Io as n,Xr as na,je as o,no as oa,Mo as p,Uo as q,zo as r,Ho as s,Wo as t,Rt as u,$t as v,Mt as w,Ut as x,Jo as y,Ko as z};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {b as b$1,c as c$1,d}from'./chunk-5TAVYPOV.js';import*as c from'fs';import*as l from'path';import*as y from'js-yaml';var g,R=b$1(()=>{g={enabled:true,thresholds:{minComplianceRate:90,minEvents:20,timeWindowDays:30,minConsecutiveSessions:5,recencyDays:7},demotion:{failureThreshold:3,failureWindowDays:7,cooldownDays:14},neverGraduate:["explore-before-implement","ripple-before-modify","check-fragility","wisdom-before-implement","confidence-on-decisions","university-onboarded","university-content-valid"]};});var M={};c$1(M,{getAllStates:()=>ie,getConfig:()=>te,getState:()=>G,incrementFailure:()=>se,invalidateGraduationCache:()=>ae,isGraduated:()=>oe,loadGraduation:()=>p,markNeverGraduate:()=>ne,saveGraduation:()=>H,setTier:()=>re});function A(e){return l.join(e,".paradigm","graduation.yaml")}function p(e){let t=l.resolve(e);if(m&&b===t&&Date.now()-v<ee)return m;let o=A(t),i;if(c.existsSync(o))try{let r=c.readFileSync(o,"utf8");i=y.load(r);}catch{i={version:"1.0",config:{},states:{}};}else i={version:"1.0",config:{},states:{}};return i.version||(i.version="1.0"),i.config||(i.config={}),i.states||(i.states={}),m=i,b=t,v=Date.now(),i}function H(e,t){let o=l.resolve(e),i=A(o),r=l.dirname(i);c.existsSync(r)||c.mkdirSync(r,{recursive:true});let n=y.dump(t,{lineWidth:120,noRefs:true,sortKeys:true});c.writeFileSync(i,n,"utf8"),m=t,b=o,v=Date.now();}function te(e){let t=p(e);return {...g,...t.config,thresholds:{...g.thresholds,...t.config?.thresholds},demotion:{...g.demotion,...t.config?.demotion},neverGraduate:t.config?.neverGraduate??g.neverGraduate}}function w(e){return {habitId:e,tier:"habit",previousTier:null,graduatedAt:null,demotedAt:null,complianceAtGraduation:0,hookScript:null,failureCount:0,cooldownUntil:null,neverGraduate:false}}function G(e,t){let i=p(e).states[t];return i?{...w(t),...i,habitId:t}:w(t)}function ie(e){let t=p(e),o={};for(let[i,r]of Object.entries(t.states))o[i]={...w(i),...r,habitId:i};return o}function oe(e,t){return G(e,t).tier==="hook"}function re(e,t,o,i){let r=p(e),n=r.states[t]||{};r.states[t]={...n,tier:o,previousTier:n.tier||"habit",...o==="hook"?{graduatedAt:new Date().toISOString(),failureCount:0}:{},...o==="habit"&&n.tier==="hook"?{demotedAt:new Date().toISOString()}:{},...i},H(e,r);}function ne(e,t){let o=p(e);o.states[t]||(o.states[t]={}),o.states[t].neverGraduate=true,o.states[t].tier="habit",H(e,o);}function se(e,t){let o=p(e);o.states[t]||(o.states[t]={});let i=(o.states[t].failureCount||0)+1;return o.states[t].failureCount=i,H(e,o),i}function ae(){m=null,b=null,v=0;}var m,b,v,ee,j=b$1(()=>{R();m=null,b=null,v=0,ee=3e4;});var E=[{id:"explore-before-implement",name:"Explore Before Implementing",description:"Call ripple/navigate/search before modifying existing symbols to understand impact",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple","paradigm_navigate","paradigm_search","paradigm_related"]}},enabled:true},{id:"ripple-before-modify",name:"Ripple Before Modifying",description:"Run ripple analysis before modifying symbols with dependents",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple"]}},enabled:true},{id:"check-fragility",name:"Check Fragility",description:"Check history fragility for symbols before modifying frequently-broken code",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_history_fragility"]}},enabled:true},{id:"wisdom-before-implement",name:"Check Team Wisdom",description:"Check team wisdom (preferences, antipatterns, decisions) before implementing",category:"collaboration",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_wisdom_context","paradigm_wisdom_expert"]}},enabled:true},{id:"verify-before-done",name:"Verify Before Done",description:"Run postflight compliance checks before finishing a session",category:"verification",trigger:"on-stop",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight"]}},enabled:true},{id:"postflight-compliance",name:"Postflight Compliance",description:"Ensure postflight checks pass without errors before finishing",category:"verification",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight","paradigm_reindex"]}},enabled:true},{id:"test-new-components",name:"Test New Components",description:"New components should have associated tests or test plan documented",category:"testing",trigger:"postflight",severity:"advisory",check:{type:"tests-exist",params:{patterns:["**/*.test.*","**/*.spec.*","**/tests/**"]}},enabled:true},{id:"purpose-coverage",name:"Purpose File Coverage",description:"All modified source directories should have .purpose file coverage",category:"documentation",trigger:"postflight",severity:"warn",check:{type:"file-exists",params:{patterns:["**/.purpose"]}},enabled:true},{id:"record-lore-for-significant",name:"Record Lore for Significant Changes",description:"Sessions modifying 3+ files should record a lore entry",category:"documentation",trigger:"on-stop",severity:"warn",check:{type:"lore-recorded",params:{}},enabled:true},{id:"gates-for-routes",name:"Gates for Routes",description:"API routes should have corresponding gate declarations in portal.yaml",category:"security",trigger:"postflight",severity:"warn",check:{type:"gates-declared",params:{requireRoutes:true}},enabled:true},{id:"commit-message-symbols",name:"Commit Message Format",description:"Commit messages should follow type(#symbol): format and include a Symbols: trailer",category:"documentation",trigger:"on-commit",severity:"advisory",check:{type:"commit-message-format",params:{messagePatterns:["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"]}},enabled:true},{id:"flow-coverage-for-multi-component",name:"Flow Coverage",description:"Changes spanning 3+ components should have a documented $flow",category:"documentation",trigger:"postflight",severity:"advisory",check:{type:"flow-coverage",params:{minSteps:3}},enabled:true},{id:"context-session-awareness",name:"Context Awareness",description:"Use session recovery or context check tools for session continuity",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"context-checked",params:{contextTools:["paradigm_context_check","paradigm_session_recover","paradigm_session_checkpoint"]}},enabled:true},{id:"aspect-anchors-valid",name:"Aspect Anchors Valid",description:"Aspects touched during the session should have their code anchors validated",category:"verification",trigger:"postflight",severity:"advisory",check:{type:"aspect-anchored",params:{checkAnchors:true}},enabled:true}];var V=E,Y=30*1e3;function K(e){try{let t=l.join(e,".paradigm","config.yaml");if(c.existsSync(t)){let o=c.readFileSync(t,"utf8"),r=y.load(o)?.limits;if(r?.habitsCacheTtlMs&&typeof r.habitsCacheTtlMs=="number")return r.habitsCacheTtlMs}}catch{}return Y}var k=new Map;function z(e){let t=l.resolve(e),o=k.get(t),i=K(t);if(o&&Date.now()-o.loadedAt<i)return o.habits;let r=Q(t);return k.set(t,{habits:r,loadedAt:Date.now()}),r}function Q(e){let t=new Map;for(let s of V)t.set(s.id,{...s});let o=process.env.HOME||process.env.USERPROFILE||"~",i=S(l.join(o,".paradigm","habits.yaml"));i&&D(t,i);let r=T(l.join(o,".paradigm","habits"));for(let s of r)t.set(s.id,s);let n=S(l.join(e,".paradigm","habits.yaml"));n&&D(t,n);let u=T(l.join(e,".paradigm","habits"));for(let s of u)t.set(s.id,s);return Array.from(t.values())}function T(e){if(!c.existsSync(e))return [];try{let t=c.readdirSync(e).filter(i=>i.endsWith(".habit")).sort(),o=[];for(let i of t)try{let r=c.readFileSync(l.join(e,i),"utf8"),n=y.load(r);n?.id&&n?.name&&o.push(n);}catch{}return o}catch{return []}}function S(e){if(!c.existsSync(e))return null;try{let t=c.readFileSync(e,"utf8");return y.load(t)}catch{return null}}function D(e,t){if(t.habits)for(let o of t.habits)e.set(o.id,{...o});if(t.overrides)for(let[o,i]of Object.entries(t.overrides)){let r=e.get(o);r&&J(r,i);}}function J(e,t){t.severity!==void 0&&(e.severity=t.severity),t.enabled!==void 0&&(e.enabled=t.enabled);}function X(e){return e.filter(t=>t.enabled)}function Z(e){let t=l.resolve(e);k.delete(t);}var le=[{id:"explore-before-implement",name:"Explore Before Implementing",description:"Call ripple/navigate/search before modifying existing symbols to understand impact",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple","paradigm_navigate","paradigm_search","paradigm_related"]}},enabled:true},{id:"ripple-before-modify",name:"Ripple Before Modifying",description:"Run ripple analysis before modifying symbols with dependents",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ripple"]}},enabled:true},{id:"check-fragility",name:"Check Fragility",description:"Check history fragility for symbols before modifying frequently-broken code",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_history_fragility"]}},enabled:true},{id:"wisdom-before-implement",name:"Check Team Wisdom",description:"Check team wisdom (preferences, antipatterns, decisions) before implementing",category:"collaboration",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_wisdom_context","paradigm_wisdom_expert"]}},enabled:true},{id:"verify-before-done",name:"Verify Before Done",description:"Run postflight compliance checks before finishing a session",category:"verification",trigger:"on-stop",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight"]}},enabled:true},{id:"postflight-compliance",name:"Postflight Compliance",description:"Ensure postflight checks pass without errors before finishing",category:"verification",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_pm_postflight","paradigm_reindex"]}},enabled:true},{id:"test-new-components",name:"Test New Components",description:"New components should have associated tests or test plan documented",category:"testing",trigger:"postflight",severity:"advisory",check:{type:"tests-exist",params:{patterns:["**/*.test.*","**/*.spec.*","**/tests/**"]}},enabled:true},{id:"purpose-coverage",name:"Purpose File Coverage",description:"All modified source directories should have .purpose file coverage",category:"documentation",trigger:"postflight",severity:"warn",check:{type:"file-exists",params:{patterns:["**/.purpose"]}},enabled:true},{id:"record-lore-for-significant",name:"Record Lore for Significant Changes",description:"Sessions modifying 3+ files should record a lore entry",category:"documentation",trigger:"on-stop",severity:"warn",check:{type:"lore-recorded",params:{}},enabled:true},{id:"confidence-on-decisions",name:"Confidence on Decisions",description:"When recording lore, include a confidence score (0.0-1.0) to enable calibration tracking over time",category:"documentation",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_lore_record"]}},enabled:true},{id:"gates-for-routes",name:"Gates for Routes",description:"API routes should have corresponding gate declarations in portal.yaml",category:"security",trigger:"postflight",severity:"warn",check:{type:"gates-declared",params:{requireRoutes:true}},enabled:true},{id:"university-content-valid",name:"University Content Valid",description:"Validate university content integrity when files in symbol-covered areas change",category:"quality",trigger:"on-stop",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_validate"]}},enabled:true},{id:"university-onboarded",name:"University Onboarding",description:"Call paradigm_university_onboard at session start for project-specific learning content",category:"discovery",trigger:"preflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_university_onboard"]}},enabled:false},{id:"orchestration-required",name:"Orchestrate Complex Tasks",description:"Tasks affecting 3+ files or touching security symbols should use paradigm_orchestrate_inline to determine which agents are needed. Ensures security review, test coverage, and documentation.",category:"collaboration",trigger:"preflight",severity:"warn",check:{type:"tool-called",params:{tools:["paradigm_orchestrate_inline"]}},enabled:true},{id:"agent-coverage-validated",name:"Validate Agent Involvement",description:"After completing work, verify that agents with relevant expertise were consulted. Check nominations that were surfaced but not acted on.",category:"collaboration",trigger:"postflight",severity:"advisory",check:{type:"tool-called",params:{tools:["paradigm_ambient_nominations","paradigm_agent_list"]}},enabled:true},{id:"hot-mode-incident",name:"Incident Response Acknowledgment",description:"During incident response, orchestration enforcement is waived. But a post-incident lore entry is required and a postflight review should be scheduled.",category:"collaboration",trigger:"on-stop",severity:"advisory",check:{type:"lore-recorded"},enabled:true}];function ce(e,t){return e.filter(o=>o.enabled&&o.trigger===t)}new Set(le.map(e=>e.id));function F(e,t,o,i,r){let n=ce(e,t);i&&(n=n.filter(a=>!a.platforms||a.platforms.includes(i)));let u=0;if(r)try{let{isGraduated:a}=(j(),d(M)),O=n.length;n=n.filter(q=>!a(r,q.id)),u=O-n.length;}catch{}let s=n.map(a=>ue(a,o)),W=s.filter(a=>a.result==="followed").length,I=s.filter(a=>a.result==="skipped").length,N=s.filter(a=>a.result==="partial").length,_=s.filter(a=>a.result==="skipped"&&a.habit.severity==="block").length;return {trigger:t,evaluations:s,summary:{total:s.length,followed:W,skipped:I,partial:N,blockingViolations:_},blocksCompletion:_>0}}function $(e){return {toolsCalled:e.toolsCalled||[],filesModified:e.filesModified||[],symbolsTouched:e.symbolsTouched||[],loreRecorded:e.loreRecorded||false,hasPortalRoutes:e.hasPortalRoutes||false,taskAddsRoutes:e.taskAddsRoutes||false,taskDescription:e.taskDescription,gitClean:e.gitClean}}function ue(e,t){switch(e.check.type){case "tool-called":return fe(e,t);case "file-exists":return pe(e,t);case "file-modified":return be(e,t);case "lore-recorded":return ge(e,t);case "symbols-registered":return me(e,t);case "gates-declared":return he(e,t);case "tests-exist":return ye(e,t);case "git-clean":return ve(e,t);case "commit-message-format":return Ce(e,t);case "flow-coverage":return He(e,t);case "context-checked":return ke(e,t);case "aspect-anchored":return we(e,t);default:return {habit:e,result:"partial",reason:`Unknown check: ${e.check.type}`}}}function fe(e,t){let o=e.check.params.tools||[];if(o.length===0)return {habit:e,result:"followed",reason:"No tools required"};let i=o.filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Called: ${i.join(", ")}`,evidence:i}:t.filesModified.length===0&&t.symbolsTouched.length===0?{habit:e,result:"followed",reason:"No modifications, habit not applicable"}:{habit:e,result:"skipped",reason:`None of [${o.join(", ")}] were called before modifying code`}}function pe(e,t){if(t.filesModified.length===0)return {habit:e,result:"followed",reason:"No files modified"};if(t.filesModified.some(r=>r.endsWith(".purpose")||r.includes(".paradigm/")))return {habit:e,result:"followed",reason:"Purpose files updated"};let i=t.filesModified.filter(r=>!r.endsWith(".md")&&!r.endsWith(".json")&&!r.endsWith(".yaml")&&!r.endsWith(".yml")&&!r.endsWith(".lock")&&!r.endsWith(".purpose")&&!r.includes(".paradigm/"));return i.length===0?{habit:e,result:"followed",reason:"Only non-source files modified"}:{habit:e,result:"skipped",reason:`${i.length} source file(s) without .purpose updates`,evidence:i.slice(0,5)}}function ge(e,t){let o=t.filesModified.filter(i=>!i.endsWith(".md")&&!i.endsWith(".json")&&!i.endsWith(".yaml")&&!i.endsWith(".yml")&&!i.endsWith(".lock")&&!i.endsWith(".purpose")&&!i.includes(".paradigm/"));return o.length<3?{habit:e,result:"followed",reason:"Session not significant (< 3 source files)"}:t.loreRecorded||t.toolsCalled.includes("paradigm_lore_record")?{habit:e,result:"followed",reason:"Lore recorded"}:{habit:e,result:"skipped",reason:`${o.length} source files modified, no lore entry`,evidence:o.slice(0,5)}}function me(e,t){if(t.symbolsTouched.length===0)return {habit:e,result:"followed",reason:"No symbols touched"};let i=["paradigm_purpose_add_component","paradigm_purpose_add_signal","paradigm_purpose_add_flow","paradigm_purpose_add_gate","paradigm_purpose_add_aspect","paradigm_purpose_init"].filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Purpose tools called: ${i.join(", ")}`,evidence:i}:{habit:e,result:"partial",reason:`${t.symbolsTouched.length} symbol(s) touched, no purpose registration`}}function he(e,t){if(!t.taskAddsRoutes)return {habit:e,result:"followed",reason:"No routes added"};if(t.hasPortalRoutes)return {habit:e,result:"followed",reason:"Portal.yaml has routes"};let i=["paradigm_gates_for_route","paradigm_portal_add_route","paradigm_portal_add_gate"].filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Gate tools called: ${i.join(", ")}`,evidence:i}:{habit:e,result:"skipped",reason:"Routes added without gate declarations"}}function ye(e,t){if(t.filesModified.length===0)return {habit:e,result:"followed",reason:"No files modified"};let o=t.filesModified.filter(r=>r.includes(".test.")||r.includes(".spec.")||r.includes("/tests/")||r.includes("/test/")||r.includes("__tests__"));if(o.length>0)return {habit:e,result:"followed",reason:`Test files: ${o.length}`,evidence:o.slice(0,5)};let i=t.filesModified.filter(r=>!r.endsWith(".md")&&!r.endsWith(".json")&&!r.endsWith(".yaml")&&!r.endsWith(".lock")&&!r.endsWith(".purpose")&&!r.includes(".paradigm/")&&!r.includes("node_modules/"));return i.length===0?{habit:e,result:"followed",reason:"No source files to test"}:{habit:e,result:"partial",reason:`${i.length} source file(s), no test files updated`,evidence:i.slice(0,5)}}function be(e,t){if(t.filesModified.length===0)return {habit:e,result:"followed",reason:"No files modified"};let o=e.check.params.patterns||[];if(o.length===0)return {habit:e,result:"followed",reason:"No patterns specified"};if(e.trigger==="on-stop"&&e.severity==="block"){let r=t.filesModified.filter(n=>o.some(u=>n.includes(u)||l.basename(n)===u));return r.length>0?{habit:e,result:"followed",reason:`Matching files: ${r.join(", ")}`,evidence:r}:{habit:e,result:"partial",reason:`None of [${o.join(", ")}] in git diff yet (may not be committed). Use on-commit trigger for reliable check.`}}let i=t.filesModified.filter(r=>o.some(n=>r.includes(n)||l.basename(r)===n));return i.length>0?{habit:e,result:"followed",reason:`Matching files: ${i.join(", ")}`,evidence:i}:{habit:e,result:"skipped",reason:`None of [${o.join(", ")}] found in modified files`}}function ve(e,t){return t.filesModified.length===0?{habit:e,result:"followed",reason:"No files modified"}:e.trigger==="on-stop"?{habit:e,result:"followed",reason:"git-clean skipped on-stop (uncommitted changes expected before commit)"}:t.gitClean===void 0?{habit:e,result:"partial",reason:"Git status not available"}:t.gitClean?{habit:e,result:"followed",reason:"Working tree is clean \u2014 changes committed"}:{habit:e,result:"skipped",reason:"Uncommitted changes in working tree"}}function Ce(e,t){if(!t.commitMessage)return {habit:e,result:"followed",reason:"No commit message to check (not a commit trigger)"};let o=e.check.params.messagePatterns||["^(feat|fix|refactor|chore|docs|test|style|perf|ci|build)\\(","Symbols:"],i=o.filter(r=>new RegExp(r,"m").test(t.commitMessage));if(i.length===o.length)return {habit:e,result:"followed",reason:"Commit message matches all required patterns",evidence:i};if(i.length>0){let r=o.filter(n=>!new RegExp(n,"m").test(t.commitMessage));return {habit:e,result:"partial",reason:`Matches ${i.length}/${o.length} patterns. Missing: ${r.join(", ")}`}}return {habit:e,result:"skipped",reason:"Commit message does not match required format patterns"}}function He(e,t){let o=t.symbolsTouched.filter(n=>n.startsWith("#"));if(o.length<3)return {habit:e,result:"followed",reason:"Fewer than 3 components touched \u2014 flow not required"};if(t.hasFlowCoverage)return {habit:e,result:"followed",reason:"Flow coverage exists for multi-component changes"};let r=["paradigm_flow_validate","paradigm_flows_affected","paradigm_purpose_add_flow"].filter(n=>t.toolsCalled.includes(n));return r.length>0?{habit:e,result:"followed",reason:`Flow tools called: ${r.join(", ")}`,evidence:r}:{habit:e,result:"skipped",reason:`${o.length} components touched without flow coverage`,evidence:o.slice(0,5)}}function ke(e,t){let i=(e.check.params.contextTools||["paradigm_context_check","paradigm_session_recover","paradigm_session_checkpoint"]).filter(r=>t.toolsCalled.includes(r));return i.length>0?{habit:e,result:"followed",reason:`Context tools called: ${i.join(", ")}`,evidence:i}:t.filesModified.length===0&&t.symbolsTouched.length===0?{habit:e,result:"followed",reason:"No modifications, context check not applicable"}:{habit:e,result:"skipped",reason:"No context/session tools called during session"}}function we(e,t){let o=t.symbolsTouched.filter(i=>i.startsWith("~"));return o.length===0?{habit:e,result:"followed",reason:"No aspects touched"}:t.aspectAnchorsValid===true?{habit:e,result:"followed",reason:"Aspect anchors validated and valid"}:t.toolsCalled.includes("paradigm_aspect_check")?{habit:e,result:"followed",reason:"paradigm_aspect_check was called to validate anchors"}:{habit:e,result:"skipped",reason:`${o.length} aspect(s) touched without anchor validation`,evidence:o.slice(0,5)}}export{z as a,X as b,Z as c,F as d,$ as e};
|