@a-company/paradigm 6.6.3 → 6.6.6

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.
@@ -8,7 +8,7 @@
8
8
  <link rel="preconnect" href="https://fonts.googleapis.com">
9
9
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
10
10
  <link href="https://fonts.googleapis.com/css2?family=Crimson+Pro:ital,wght@0,400;0,500;0,600;0,700;1,400&family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
11
- <script type="module" crossorigin src="/assets/index-BIQeax_b.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-DrtbBC21.js"></script>
12
12
  <link rel="stylesheet" crossorigin href="/assets/index-C9zUgT5x.css">
13
13
  </head>
14
14
  <body>
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import {k,l,n,a,c,d}from'./chunk-EKNLG73M.js';import'./chunk-5TAVYPOV.js';import u from'chalk';import*as h from'fs';import*as p from'path';import*as C from'js-yaml';var P=/^[a-z0-9][a-z0-9-]{0,63}$/,v=new Set(["track","index","chronological","featured"]);function j(n){let d=p.join(n,"pack.yaml");if(!h.existsSync(d))return null;try{let s=h.readFileSync(d,"utf8"),i=C.load(s);return Array.isArray(i?.sections)?i.sections:null}catch{return null}}function z(n,d,s){let i=new Set,r=false;if(!n||n.length===0)return i.add("main"),{knownIds:i,hadValidationError:r};let t=new Set,f=0;for(let c=0;c<n.length;c++){let l=n[c],y=`sections[${c}]`;if(typeof l.id!="string"||!P.test(l.id)){s.push({contentId:"pack.yaml",severity:"error",check:"section-bad-id",message:`${y}.id must be kebab-case matching /^[a-z0-9][a-z0-9-]{0,63}$/`,fix:"Use lowercase letters, digits, and hyphens; start with a letter or digit"}),r=true;continue}if(t.has(l.id)){s.push({contentId:"pack.yaml",severity:"error",check:"section-duplicate-id",message:`duplicate section id "${l.id}"`,fix:"Each section id must be unique within the pack"}),r=true;continue}t.add(l.id),i.add(l.id),(typeof l.style!="string"||!v.has(l.style))&&(s.push({contentId:"pack.yaml",severity:"error",check:"section-bad-style",message:`${y}.style must be one of: ${Array.from(v).join(", ")}`}),r=true),l.default===true&&f++;}f>1&&(s.push({contentId:"pack.yaml",severity:"error",check:"section-multiple-defaults",message:`at most one section may set default: true (found ${f})`,fix:"Set default: true on exactly one section"}),r=true);for(let c of d)i.has(c)||s.push({contentId:"pack.yaml",severity:"warning",check:"section-unknown-ref",message:`entries reference unknown section "${c}"`,fix:`Declare section "${c}" in pack.yaml, or remove the section: field from those entries`});return {knownIds:i,hadValidationError:r}}async function E(n$1){let d$1=process.cwd(),s=k(d$1,n$1),i=l(n$1)?s.subPackRoot??s.packRoot:void 0,r=i?n(i):a(d$1);if(!r||r.totalContent===0){console.log(u.yellow(`
3
+ No university content to validate.
4
+ `));return}let t=[],f=r.entries;n$1.id&&(f=f.filter(e=>e.id===n$1.id),f.length===0&&(console.error(u.red(`
5
+ Content "${n$1.id}" not found
6
+ `)),process.exit(1)));let c$1=null;if(n$1.deep){c$1=new Set;let e=p.join(d$1,".paradigm","scan-index.json");if(h.existsSync(e))try{let a=JSON.parse(h.readFileSync(e,"utf8"));if(a.symbols&&Array.isArray(a.symbols))for(let o of a.symbols)o.symbol&&c$1.add(o.symbol);}catch{}}let l$1=new Set(r.entries.map(e=>e.id)),y=s.subPackRoot??s.packRoot,R=j(y),k$1=new Set;for(let e of r.entries)e.section&&typeof e.section=="string"&&e.section.length>0&&k$1.add(e.section);z(R,k$1,t);for(let e of f){if(e.title||t.push({contentId:e.id,severity:"error",check:"missing-title",message:"Content is missing a title"}),e.type==="quiz"){let a=c(d$1,e.id,i);if(!a)t.push({contentId:e.id,severity:"error",check:"unreadable-quiz",message:"Quiz file could not be parsed"});else for(let o of a.questions)(!o.choices||!(o.correct in o.choices))&&t.push({contentId:e.id,severity:"error",check:"invalid-quiz-answer",message:`Question ${o.id}: correct "${o.correct}" not in choices [${Object.keys(o.choices||{}).join(", ")}]`,fix:`Set correct to one of: ${Object.keys(o.choices||{}).join(", ")}`});}if(e.type==="path"){let a=d(d$1,e.id,i);if(!a)t.push({contentId:e.id,severity:"error",check:"unreadable-path",message:"Learning path file could not be parsed"});else for(let o of a.steps)!o.content.startsWith("plsat:")&&!l$1.has(o.content)&&t.push({contentId:e.id,severity:"error",check:"broken-path-step",message:`Step references "${o.content}" which doesn't exist`,fix:`Create content with id "${o.content}"`});}if(c$1&&e.symbols.length>0)for(let a of e.symbols)c$1.has(a)||t.push({contentId:e.id,severity:"warning",check:"broken-symbol-ref",message:`Symbol "${a}" not found in scan-index`});}if(n$1.json){console.log(JSON.stringify({status:t.some(e=>e.severity==="error")?"errors":t.length>0?"warnings":"healthy",totalContent:r.totalContent,checked:f.length,issues:t},null,2));return}if(console.log(u.blue(`
7
+ University Validation \u2014 pack: ${s.subPackId??s.packId} (${f.length} items${n$1.deep?", deep mode":""})
8
+ `)),t.length===0){console.log(u.green(` All checks passed.
9
+ `));return}let g=t.filter(e=>e.severity==="error"),m=t.filter(e=>e.severity==="warning");for(let e of g)console.log(u.red(` x ${e.contentId}: ${e.message}`)),e.fix&&console.log(u.gray(` Fix: ${e.fix}`));for(let e of m)console.log(u.yellow(` ! ${e.contentId}: ${e.message}`)),e.fix&&console.log(u.gray(` Fix: ${e.fix}`));console.log(),g.length>0&&console.log(u.red(` ${g.length} error${g.length>1?"s":""}`)),m.length>0&&console.log(u.yellow(` ${m.length} warning${m.length>1?"s":""}`)),console.log();}export{E as universityValidateCommand};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a-company/paradigm",
3
- "version": "6.6.3",
3
+ "version": "6.6.6",
4
4
  "description": "Unified CLI for Paradigm developer tools",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -36,6 +36,7 @@
36
36
  "dependencies": {
37
37
  "@a-company/portal-core": "*",
38
38
  "@a-company/registry-client": "^0.1.0",
39
+ "@a-company/university-core": "*",
39
40
  "@modelcontextprotocol/sdk": "^1.0.0",
40
41
  "chalk": "^5.3.0",
41
42
  "commander": "^11.1.0",
@@ -1,12 +0,0 @@
1
- #!/usr/bin/env node
2
- import {g,i,f}from'./chunk-ERO4MJSH.js';import {c,a}from'./chunk-P344HV6Z.js';import'./chunk-5TAVYPOV.js';import r from'chalk';import {execSync}from'child_process';import*as $ from'os';function S(){try{return execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").slice(0,20)||"unknown"}catch{try{return $.userInfo().username}catch{return "unknown"}}}async function P(n,e){let s=process.cwd(),x=e.pack||e.project||e.discipline?e:{...e,project:true},c$1=c(s,x);if(e.title||(console.error(r.red(`
3
- Error: --title is required
4
- `)),process.exit(1)),e.section){let t=a(c$1.subPackRoot??c$1.packRoot);if(t.length>0&&!new Set(t.map(a=>a.id)).has(e.section)){let a=t.map(z=>z.id).join(", "),w=c$1.subPackId??c$1.packId;console.error(r.red(`
5
- Error: section "${e.section}" not declared in pack "${w}". Available: ${a}
6
- `)),process.exit(1);}}let i$1=e.order!==void 0?parseInt(e.order,10):void 0;e.order!==void 0&&(i$1===void 0||Number.isNaN(i$1))&&(console.error(r.red(`
7
- Error: --order must be an integer (got "${e.order}")
8
- `)),process.exit(1));let u=S(),o=new Date().toISOString().slice(0,10),f$1=e.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40),m=e.tags?e.tags.split(",").map(t=>t.trim()):[],g$1=e.symbols?e.symbols.split(",").map(t=>t.trim()):[];if(n==="quiz"){let t=`Q-${f$1}`,y={id:t,title:e.title,description:e.body||"",author:u,created:o,updated:o,tags:m,symbols:g$1,difficulty:e.difficulty||"beginner",passThreshold:.7,questions:[],...e.section?{section:e.section}:{},...i$1!==void 0?{order:i$1}:{}};g(s,y),i(s),console.log(r.green(`
9
- Created quiz: ${t}`)),console.log(r.gray(` Add questions by editing the YAML file
10
- `));return}let d=`${n==="policy"?"P":"N"}-${f$1}`,h={id:d,title:e.title,type:n,author:u,created:o,updated:o,tags:m,symbols:g$1,difficulty:e.difficulty||"beginner",estimatedMinutes:e.minutes?parseInt(e.minutes,10):void 0,prerequisites:[],...e.section?{section:e.section}:{},...i$1!==void 0?{order:i$1}:{}};f(s,h,e.body||""),i(s),console.log(r.green(`
11
- Created ${n}: ${d}`)),console.log(r.gray(` Edit at .paradigm/university/content/${n==="policy"?"policies":"notes"}/${d}.md
12
- `));}export{P as universityAddCommand};
@@ -1,6 +0,0 @@
1
- #!/usr/bin/env node
2
- import*as i from'fs';import*as l from'path';import*as c from'js-yaml';var f=".paradigm/university",y="content";function U(s){let t=s.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!t)return null;try{return {frontmatter:c.load(t[1]),body:t[2].trim()}}catch{return null}}function j(s,t){return `---
3
- ${c.dump(s,{lineWidth:-1,noRefs:true,sortKeys:false})}---
4
-
5
- ${t}
6
- `}function b(s){let t=l.join(s,f,"index.yaml");if(!i.existsSync(t))return null;try{return c.load(i.readFileSync(t,"utf8"))}catch{return null}}function h(s,t,e){let n=l.join(s,f,y);for(let r of ["notes","policies","quizzes","paths"]){let a=l.join(n,r,`${t}${e}`);if(i.existsSync(a))return a}return null}function F(s,t){let e=h(s,t,".md");if(!e)return null;try{let n=U(i.readFileSync(e,"utf8"));if(!n)return null;let r=n.frontmatter;return {frontmatter:{...r,tags:r.tags||[],symbols:r.symbols||[],prerequisites:r.prerequisites||[]},body:n.body}}catch{return null}}function z(s,t){let e=h(s,t,".yaml");if(!e)return null;try{let n=c.load(i.readFileSync(e,"utf8"));return n?.id?{...n,tags:n.tags||[],symbols:n.symbols||[],questions:n.questions||[]}:null}catch{return null}}function D(s,t){let e=h(s,t,".yaml");if(!e)return null;try{let n=c.load(i.readFileSync(e,"utf8"));return n?.id?n:null}catch{return null}}function w(s,t){let e=l.join(s,f,"diplomas");if(!i.existsSync(e))return [];let n=[];try{for(let r of i.readdirSync(e).filter(a=>a.endsWith(".yaml")))try{let a=c.load(i.readFileSync(l.join(e,r),"utf8"));if(!a?.id||t?.student&&a.student!==t.student||t?.type&&a.type!==t.type)continue;n.push(a);}catch{}}catch{}return n.sort((r,a)=>a.earnedAt.localeCompare(r.earnedAt))}function I(s,t,e){let n=t.type==="policy"?"policies":"notes",r=l.join(s,f,y,n);i.mkdirSync(r,{recursive:true});let a=l.join(r,`${t.id}.md`);return i.writeFileSync(a,j(t,e),"utf8"),a}function $(s,t){let e=l.join(s,f,y,"quizzes");i.mkdirSync(e,{recursive:true});let n=l.join(e,`${t.id}.yaml`);return i.writeFileSync(n,c.dump(t,{lineWidth:-1,noRefs:true}),"utf8"),n}function k(s,t){let e=l.join(s,f,"diplomas");i.mkdirSync(e,{recursive:true});let n=l.join(e,`${t.id}.yaml`);return i.writeFileSync(n,c.dump(t,{lineWidth:-1,noRefs:true}),"utf8"),n}function q(s){let t=l.join(s,f),e=l.join(t,y),n=[];for(let u of ["notes","policies"]){let o=l.join(e,u);if(i.existsSync(o))try{for(let p of i.readdirSync(o).filter(m=>m.endsWith(".md")))try{let m=i.readFileSync(l.join(o,p),"utf8"),S=U(m);if(!S)continue;let d=S.frontmatter;n.push({id:d.id||p.replace(".md",""),title:d.title||p,type:d.type||(u==="policies"?"policy":"note"),author:d.author||"unknown",created:d.created||"",updated:d.updated||"",tags:Array.isArray(d.tags)?d.tags:[],symbols:Array.isArray(d.symbols)?d.symbols:[],difficulty:d.difficulty||"beginner",file:`${y}/${u}/${p}`});}catch{}}catch{}}let r=l.join(e,"quizzes");if(i.existsSync(r))try{for(let u of i.readdirSync(r).filter(o=>o.endsWith(".yaml")))try{let o=c.load(i.readFileSync(l.join(r,u),"utf8"));if(!o?.id)continue;n.push({id:o.id,title:o.title||u,type:"quiz",author:o.author||"unknown",created:o.created||"",updated:o.updated||"",tags:o.tags||[],symbols:o.symbols||[],difficulty:o.difficulty||"beginner",file:`${y}/quizzes/${u}`});}catch{}}catch{}let a=l.join(e,"paths");if(i.existsSync(a))try{for(let u of i.readdirSync(a).filter(o=>o.endsWith(".yaml")))try{let o=c.load(i.readFileSync(l.join(a,u),"utf8"));if(!o?.id)continue;n.push({id:o.id,title:o.title||u,type:"path",author:o.author||"unknown",created:o.created||"",updated:o.updated||"",tags:o.tags||[],symbols:[],file:`${y}/paths/${u}`});}catch{}}catch{}let g=0,v=l.join(t,"diplomas");if(i.existsSync(v))try{g=i.readdirSync(v).filter(u=>u.endsWith(".yaml")).length;}catch{}let x={version:"1.0",generatedAt:new Date().toISOString(),totalContent:n.length,entries:n,diplomaCount:g};return i.mkdirSync(t,{recursive:true}),i.writeFileSync(l.join(t,"index.yaml"),c.dump(x,{lineWidth:-1,noRefs:true}),"utf8"),x}function Q(s,t){let e=b(s);if(!e)return [];let n=[...e.entries];if(t.type&&(n=n.filter(r=>r.type===t.type)),t.tag&&(n=n.filter(r=>r.tags.some(a=>a.startsWith(t.tag)))),t.difficulty&&(n=n.filter(r=>r.difficulty===t.difficulty)),t.symbol&&(n=n.filter(r=>r.symbols.includes(t.symbol))),t.section&&(n=n.filter(r=>r.section===t.section)),t.query){let r=t.query.toLowerCase();n=n.filter(a=>a.title.toLowerCase().includes(r)||a.id.toLowerCase().includes(r));}return n.slice(0,t.limit||20)}export{b as a,F as b,z as c,D as d,w as e,I as f,$ as g,k as h,q as i,Q as j};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import*as r from'fs';import*as o from'path';import*as m from'js-yaml';var f=".paradigm/university",g="pack.yaml";function j(s){let e=p(s);if(!e||!Array.isArray(e.sections))return [];let a=[];for(let t of e.sections)t&&typeof t.id=="string"&&t.id.length>0&&a.push({id:t.id,name:typeof t.name=="string"?t.name:void 0});return a}function p(s){let e=o.join(s,g);if(!r.existsSync(e))return null;try{let a=r.readFileSync(e,"utf8");return m.load(a)??null}catch{return null}}function R(s){let e=[],a=o.join(s,"node_modules","@a-company","university"),t=p(a);t&&t.id&&t.tenant_kind&&e.push({id:t.id,name:t.name,tenantKind:t.tenant_kind,packRoot:a,disciplines:t.disciplines,entryCount:k(a)});let n=o.join(s,f);if(r.existsSync(n)){let i=p(n),c=i?.id??o.basename(s),y=i?.tenant_kind??"project";e.push({id:c,name:i?.name,tenantKind:y,packRoot:n,disciplines:i?.disciplines,entryCount:k(n)});try{let h=r.readdirSync(n,{withFileTypes:!0});for(let l of h){if(!l.isDirectory()||l.name.startsWith("."))continue;let u=o.join(n,l.name),d=p(u);!d||!d.id||e.push({id:d.id,name:d.name,tenantKind:d.tenant_kind??"project",packRoot:u,disciplines:d.disciplines,entryCount:k(u)});}}catch{}}return e}function k(s){for(let e of ["content","src/content"]){let a=o.join(s,e);if(!r.existsSync(a))continue;let t=0;for(let n of ["notes","policies","quizzes","paths"]){let i=o.join(a,n);if(r.existsSync(i))try{t+=r.readdirSync(i).filter(c=>c.endsWith(".md")||c.endsWith(".yaml")).length;}catch{}}if(t>0)return t}return 0}function b(s,e){let a=R(s),t;if(e.pack){let n=a.find(i=>i.id===e.pack);if(n)t={packId:n.id,packRoot:n.packRoot,tenantKind:n.tenantKind,hasManifest:true};else {let i=o.join(s,f);t={packId:e.pack,packRoot:i,hasManifest:false};}}else if(e.project){let n=a.find(c=>c.tenantKind==="project"&&!c.disciplines),i=o.join(s,f);n?t={packId:n.id,packRoot:n.packRoot,tenantKind:n.tenantKind,hasManifest:true}:t={packId:o.basename(s),packRoot:i,hasManifest:false};}else {let n=a.find(i=>i.tenantKind==="project");if(n)t={packId:n.id,packRoot:n.packRoot,tenantKind:n.tenantKind,hasManifest:true};else {let i=a.find(c=>c.tenantKind==="first-party");if(i)t={packId:i.id,packRoot:i.packRoot,tenantKind:i.tenantKind,hasManifest:true};else {let c=o.join(s,f);t={packId:o.basename(s),packRoot:c,hasManifest:false};}}}if(e.discipline){let n=o.join(t.packRoot,e.discipline),i=p(n);i&&i.id?(t.subPackRoot=n,t.subPackId=i.id):r.existsSync(n)&&(t.subPackRoot=n,t.subPackId=`${t.packId}-${e.discipline}`);}return t}function x(s){return !!(s.pack||s.project||s.discipline)}export{j as a,R as b,b as c,x as d};
@@ -1,111 +0,0 @@
1
- #!/usr/bin/env node
2
- import {r,i,a as a$3,f,h as h$1}from'./chunk-TMDPDIWA.js';import {a as a$2,b as b$4,c as c$2}from'./chunk-M4UMM6DC.js';import {j as j$1,b as b$3,a as a$4}from'./chunk-GRZQIKST.js';import {j as j$2,a,c as c$1,b as b$2,k}from'./chunk-6QXBXZF6.js';import {b as b$1,a as a$1}from'./chunk-EK4ZRIFJ.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as h from'fs';import*as x from'path';import*as te from'crypto';import {execSync}from'child_process';import*as N from'js-yaml';import*as Se from'os';import jn from'sql.js';import {z}from'zod';var Tt={};c(Tt,{contentSearch:()=>Ln,detectFileRename:()=>xt,generateFingerprint:()=>St,levenshteinDistance:()=>bt,levenshteinSimilarity:()=>Oe,searchSiblingFiles:()=>Et,slidingWindowSearch:()=>be});function St(t){let e=t.split(`
3
- `).filter(r=>r.trim()!=="");return {firstLine:we(e[0]||""),lastLine:we(e[e.length-1]||""),lineCount:e.length,structuralHash:wt(e)}}function wt(t){let e=t.map(r=>r.trim()).filter(r=>ht.test(r)).map(r=>{let n=r.match(ht);return n?n[1].trim():""}).join("|");return te.createHash("sha256").update(e).digest("hex").slice(0,16)}function we(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function bt(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 r=t.length,n=e.length;if(r>5e3||n>5e3)return Math.abs(r-n);let s=new Array(r+1),o=new Array(r+1);for(let i=0;i<=r;i++)s[i]=i;for(let i=1;i<=n;i++){o[0]=i;for(let c=1;c<=r;c++){let a=t[c-1]===e[i-1]?0:1;o[c]=Math.min(s[c]+1,o[c-1]+1,s[c-1]+a);}[s,o]=[o,s];}return s[r]}function Oe(t,e){if(t.length===0&&e.length===0)return 1;let r=Math.max(t.length,e.length);return 1-bt(t,e)/r}function be(t,e,r,n=3){let{lineCount:s}=e,o=Math.max(1,Math.floor(s*.8)),i=Math.ceil(s*1.2),c=[],a=je(r);for(let u of [s,o,i])if(!(u>t.length))for(let d=0;d<=t.length-u;d++){let f=t.slice(d,d+u),g=An(f,e,a);if(g>=.5){let p=f.join(`
4
- `);c.push({windowStart:d+1,windowEnd:d+u,similarity:Oe(je(p),a),score:g});}}let l=new Map;for(let u of c){let d=l.get(u.windowStart);(!d||u.score>d.score)&&l.set(u.windowStart,u);}return Array.from(l.values()).sort((u,d)=>d.score-u.score).slice(0,n)}function An(t,e,r){let n=t.filter(f=>f.trim()!=="");if(n.length===0)return 0;let s=0,o=we(n[0]),i=we(n[n.length-1]),c=0;o===e.firstLine&&(c+=.5),i===e.lastLine&&(c+=.5),s+=c*Rn,wt(n)===e.structuralHash&&(s+=In);let l=n.join(`
5
- `),u=Oe(je(l),r);u>=.8&&(s+=(u-.8)/.2*Pn);let d=n.length/e.lineCount;if(d>=.8&&d<=1.2){let f=1-Math.abs(1-d)/.2;s+=f*Cn;}return s}function je(t){return t.split(`
6
- `).map(e=>e.trim()).filter(e=>e!=="").join(`
7
- `)}function xt(t,e){try{let r=execSync(`git log --follow --diff-filter=R --name-status --format="" -- "${e}"`,{cwd:t,encoding:"utf8",timeout:5e3}).trim();if(!r)return null;let n=r.split(`
8
- `);for(let s of n){let o=s.split(" ");if(o.length>=3&&o[0].startsWith("R"))return o[2]}return null}catch{return null}}function Et(t,e,r,n,s=10){let o=x.isAbsolute(e)?e:x.join(t,e);if(!h.existsSync(o))return [];let i=[];try{let c=h.readdirSync(o).filter(a=>!a.startsWith(".")&&h.statSync(x.join(o,a)).isFile()).slice(0,s);for(let a of c)try{let u=h.readFileSync(x.join(o,a),"utf8").split(`
9
- `),d=be(u,r,n,1);if(d.length>0&&d[0].score>=.7){let f=x.relative(t,x.join(o,a));i.push({file:f,score:d[0].score,start:d[0].windowStart,end:d[0].windowEnd});}}catch{}}catch{return []}return i.sort((c,a)=>a.score-c.score)}function Ln(t,e,r,n=true){let s=St(r),o=x.isAbsolute(e)?e:x.join(t,e);if(h.existsSync(o)){let u=h.readFileSync(o,"utf8").split(`
10
- `),d=be(u,s,r);if(d.length>0){let f=d[0];return {found:f.score>=.7,score:f.score,suggestedStart:f.windowStart,suggestedEnd:f.windowEnd,similarity:f.similarity}}}let i=xt(t,e);if(i){let l=x.join(t,i);if(h.existsSync(l)){let d=h.readFileSync(l,"utf8").split(`
11
- `),f=be(d,s,r);if(f.length>0&&f[0].score>=.7)return {found:true,score:f[0].score,suggestedStart:f[0].windowStart,suggestedEnd:f[0].windowEnd,suggestedPath:i,similarity:f[0].similarity}}}let c=x.dirname(e),a=Et(t,c,s,r);if(a.length>0&&a[0].score>=.7){let l=a[0];return {found:true,score:l.score,suggestedStart:l.start,suggestedEnd:l.end,suggestedPath:l.file!==e?l.file:void 0,similarity:l.score}}return {found:false,score:0}}var ht,Rn,In,Pn,Cn,_t=b(()=>{ht=/^\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 )/;Rn=.4,In=.3,Pn=.2,Cn=.1;});var ln="0.1.0",dn="1.0.0";function Pe(t,e){let r={$meta:un(e.projectName,t),components:{},features:{},flows:{},state:{},gates:{},signals:{},aspects:{},screens:{},symbolMap:{}};for(let s of t.symbols)fn(s,r,e);if(e.screenDefinitions)for(let[s,o]of Object.entries(e.screenDefinitions))r.screens[s]||(r.screens[s]={id:s,name:Z(s),route:o.route,path:"",components:o.components,features:o.features});let n={};for(let s of Object.values(r.components))s.componentType&&(n[s.componentType]=(n[s.componentType]||0)+1);for(let s of Object.values(r.features))s.componentType&&(n[s.componentType]=(n[s.componentType]||0)+1);return Object.keys(n).length>0&&(r.$meta.componentTypes=n),bn(r),r}function un(t,e){return {version:dn,project:t,generatedAt:new Date().toISOString(),paradigmVersion:ln,sources:{purposeFiles:e.purposeFiles.length,portalFiles:e.portalFiles.length,premiseFiles:e.symbols.filter(r=>r.source==="premise").length>0?1:0}}}function fn(t,e,r){let{type:n}=t;switch(n){case "component":pn(t,e,r);break;case "feature":mn(t,e,r);break;case "flow":gn(t,e);break;case "state":hn(t,e);break;case "gate":yn(t,e);break;case "signal":Sn(t,e);break;case "aspect":wn(t,e);break;}}function pn(t,e,r){let n=re(t.symbol),s=ut(n,t.data,r.visualTagMappings),o={id:n,name:Z(n),symbol:t.symbol,category:"components",path:t.filePath,description:t.description,visualTags:s,related:t.references,componentType:t.componentType,parent:t.parentSymbol};e.components[n]=o,e.symbolMap[t.symbol]={category:"components",id:n};}function mn(t,e,r){let n=re(t.symbol),s=ut(n,t.data,r.visualTagMappings),o={id:n,name:Z(n),symbol:t.symbol,category:"features",path:t.filePath,description:t.description,visualTags:s,related:t.references,componentType:t.componentType,parent:t.parentSymbol};e.features[n]=o,e.symbolMap[t.symbol]={category:"features",id:n};}function gn(t,e){let r=re(t.symbol),n=t.data,s=[];if(n?.steps)for(let i=0;i<n.steps.length;i++){let c=n.steps[i];s.push({id:`${r}-step-${i}`,name:c.action||`Step ${i+1}`,target:c.component,description:c.description,order:i});}let o={id:r,name:Z(r),symbol:t.symbol,path:t.filePath,description:t.description,steps:s};e.flows[r]=o,e.symbolMap[t.symbol]={category:"flows",id:r};}function hn(t,e){let r=re(t.symbol),n={id:r,name:Z(r),symbol:t.symbol,path:t.filePath,description:t.description,consumers:t.referencedBy};e.state[r]=n,e.symbolMap[t.symbol]={category:"state",id:r};}function yn(t,e){let r=re(t.symbol),n={id:r,name:Z(r),symbol:t.symbol,category:"gates",path:t.filePath,description:t.description,related:t.references};e.gates[r]=n,e.symbolMap[t.symbol]={category:"gates",id:r};}function Sn(t,e){let r=re(t.symbol),n={id:r,name:Z(r),symbol:t.symbol,category:"signals",path:t.filePath,description:t.description,related:t.references};e.signals[r]=n,e.symbolMap[t.symbol]={category:"signals",id:r};}function wn(t,e){let r=re(t.symbol),n={id:r,name:Z(r),symbol:t.symbol,category:"aspects",path:t.filePath,description:t.description,related:t.references};e.aspects[r]=n,e.symbolMap[t.symbol]={category:"aspects",id:r};}function bn(t){for(let e of Object.values(t.screens))if(e.components)for(let r of e.components){let n=t.components[r];n&&(n.screens=n.screens||[],n.screens.includes(e.id)||n.screens.push(e.id));}}function re(t){return t.slice(1)}function Z(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function ut(t,e,r){let n=[];if(r?.[t])return r[t];let s=[[/button/i,"button"],[/btn/i,"button"],[/form/i,"form"],[/input/i,"input"],[/field/i,"input"],[/select/i,"input"],[/card/i,"card"],[/list/i,"list"],[/table/i,"list"],[/modal/i,"modal"],[/dialog/i,"modal"],[/drawer/i,"modal"],[/nav/i,"nav"],[/menu/i,"menu"],[/dropdown/i,"menu"],[/header/i,"header"],[/footer/i,"footer"],[/sidebar/i,"sidebar"],[/hero/i,"hero"],[/grid/i,"grid"],[/chart/i,"chart"],[/graph/i,"chart"],[/icon/i,"icon"],[/image/i,"image"],[/avatar/i,"avatar"],[/badge/i,"badge"],[/tag/i,"badge"],[/tab/i,"tab"],[/accordion/i,"accordion"],[/toast/i,"toast"],[/notification/i,"toast"],[/alert/i,"toast"],[/spinner/i,"spinner"],[/loader/i,"spinner"],[/loading/i,"spinner"],[/skeleton/i,"skeleton"]];for(let[o,i]of s)o.test(t)&&n.push(i);return n}function Ce(t){return JSON.stringify(t,null,2)}function Ae(t,e="unknown"){j$2().trackToolCall(e,t);}function Ks(t,e="paradigm://unknown"){j$2().trackResourceRead(e,t);}function xn(){k();}function En(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 r=e.intent,n=e.target,s=e.task;return r==="context"&&s?{summary:`Navigate context: "${s}"`}:n?{summary:`Navigate ${r||"find"}: ${n}`,symbol:n}:{summary:`Navigate (${r||"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 r=t.replace(/^paradigm_/,""),n=Object.values(e).find(s=>typeof s=="string"&&s.length>0);return {summary:n?`${r}: ${n.slice(0,60)}`:r,symbol:e.symbol||void 0}}}}function Qs(t,e){let r=j$2(),{summary:n,symbol:s}=En(t,e);r.addBreadcrumb("tool-call",n,{tool:t,symbol:s});}function Zs(){return [{name:"paradigm_session_health",description:"Check if context handoff is recommended based on session activity. Call this periodically during long sessions. Returns usage percentage and recommendation (continue, consider-handoff, handoff-recommended, handoff-urgent). ~100 tokens.",inputSchema:{type:"object",properties:{estimatedTotalTokens:{type:"number",description:"Optional: Your estimate of total conversation tokens (if available)"},contextWindowSize:{type:"number",description:"Context window size in tokens (default: 200000)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_context_check",description:"DEPRECATED: renamed to paradigm_session_health. This alias will be removed in a future version.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_handoff_prepare",description:"Prepare a handoff summary. Generates a structured handoff file with markdown summary and recovery instructions. Returns structured markdown with summary, modified files, and next steps. ~300 tokens.",inputSchema:{type:"object",properties:{summary:{type:"string",description:"Brief summary of work done in this session"},nextSteps:{type:"array",items:{type:"string"},description:"List of next steps for the continuing session"},agent:{type:"string",description:'Target agent role (e.g., "builder", "architect")'},modifiedFiles:{type:"array",items:{type:"string"},description:"List of files modified in this session"},symbolsTouched:{type:"array",items:{type:"string"},description:"List of symbols (@feature, #component, etc.) touched"},openQuestions:{type:"array",items:{type:"string"},description:"Unresolved questions or decisions needed"}},required:["summary"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_session_stats",description:"Get current session statistics (MCP interactions, estimated tokens). Returns tool call count, estimated tokens used, and cost breakdown. ~100 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_session_recover",description:"Load previous session breadcrumbs for continuity. Call this at the start of a new session to understand what was done before. Returns symbols modified, files explored, recent actions, and suggestions for continuity. ~200 tokens. NOTE: Recovery data is automatically surfaced as a preamble on the first tool call of each session \u2014 explicit calls are retained for direct inspection or forcing a second recovery pass.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["resume","pick up","continue","what was I doing","last session","recover"]},{name:"paradigm_session_checkpoint",description:"Save a cognitive-transition checkpoint for crash recovery. Call when transitioning between phases (planning \u2192 implementing \u2192 validating \u2192 complete). ~100 tokens.",inputSchema:{type:"object",properties:{phase:{type:"string",enum:["planning","implementing","validating","complete"],description:"Current workflow phase"},context:{type:"string",description:"What's top-of-mind right now (1-3 sentences)"},externalId:{type:"string",description:'Optional: deterministic ID from external source for automatic session recovery (e.g. "linear:PROJ-123", "github:owner/repo#42")'},plan:{type:"string",description:"Optional: the current plan or approach"},modifiedFiles:{type:"array",items:{type:"string"},description:"Optional: files modified so far"},symbolsTouched:{type:"array",items:{type:"string"},description:"Optional: symbols touched so far"},decisions:{type:"array",items:{type:"string"},description:"Optional: key decisions made so far"}},required:["phase","context"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function er(t,e,r){let n=j$2();if(t==="paradigm_session_health"||t==="paradigm_context_check"){let s=e.contextWindowSize||2e5,o=e.estimatedTotalTokens,i=n.getStats(),{recommendation:c,message:a,usagePercent:l,signals:u}=n.getHandoffRecommendation(s,o),d=n.getDurationMinutes();return {handled:true,text:JSON.stringify({recommendation:c,message:a,stats:{sessionDurationMinutes:d,mcpToolCalls:i.totals.toolCallCount,mcpResourceReads:i.totals.resourceReadCount,estimatedMcpTokens:i.totals.totalTokens,estimatedTotalTokens:o||Math.round(i.totals.totalTokens*5),contextWindowSize:s,usagePercent:l},signals:u,action:c==="continue"?null:"Call paradigm_handoff_prepare to create handoff file"},null,2)}}if(t==="paradigm_handoff_prepare"){let s=e.summary,o=e.nextSteps||[],i=e.agent||"builder",c=e.modifiedFiles||[],a$1=e.symbolsTouched||[],l=e.openQuestions||[],u=n.getStats(),d=n.getCostBreakdown(),f=`h${Date.now().toString(36)}`,g=new Date().toISOString(),p={id:f,timestamp:g,from:"current-session",to:i,summary:s,nextSteps:o,modifiedFiles:c,symbolsTouched:a$1,openQuestions:l,sessionStats:{duration:n.getDurationMinutes(),mcpCalls:u.totals.toolCallCount+u.totals.resourceReadCount,estimatedTokens:u.totals.totalTokens,estimatedCostUsd:d.total.costUsd,model:d.model},status:"pending"},m=false;try{a(r.rootDir,p),m=!0;}catch{}let y=`# Handoff: ${g}
12
-
13
- ## Session Summary
14
- ${s}
15
-
16
- ## Next Steps
17
- ${o.map((w,P)=>`${P+1}. ${w}`).join(`
18
- `)||"(none specified)"}
19
-
20
- ## Key Context
21
- - Modified files: ${c.length>0?c.join(", "):"(not specified)"}
22
- - Symbols touched: ${a$1.length>0?a$1.join(", "):"(not specified)"}
23
- - Open questions: ${l.length>0?l.join(", "):"(none)"}
24
- `;return xn(),{handled:true,text:JSON.stringify({handoff:p,markdownSummary:y,persisted:m,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(t==="paradigm_session_stats"){let s=n.getStats(),o=n.getCostBreakdown(),i=n.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(s.startTime).toISOString(),durationMinutes:i,lastActivity:new Date(s.lastActivity).toISOString()},model:{name:o.model,id:o.modelId,pricing:{inputPerMillion:`$${o.pricing.input.toFixed(2)}`,outputPerMillion:`$${o.pricing.output.toFixed(2)}`}},interactions:{toolCalls:s.totals.toolCallCount,resourceReads:s.totals.resourceReadCount,totalInteractions:s.totals.toolCallCount+s.totals.resourceReadCount},tokens:{total:s.totals.totalTokens,byCategory:{resources:o.resources.tokens,tools:o.tools.tokens}},cost:{totalUsd:`$${o.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${o.resources.costUsd.toFixed(4)}`,tools:`$${o.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:o.resources.byType,toolsByName:o.tools.byName}},null,2)}}if(t==="paradigm_session_recover"){let{checkpoint:s,pendingHandoffs:o,previousSession:i}=ft(r.rootDir);if(!i&&o.length===0&&!s)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 c={found:true};if(s){let l=Date.now()-s.timestamp,u=Math.round(l/6e4),d=Math.round(l/36e5);c.checkpoint={phase:s.phase,context:s.context,age:d>1?`${d} hours ago`:`${u} minutes ago`,timestamp:new Date(s.timestamp).toISOString(),sessionId:s.sessionId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:s.recentBreadcrumbs?.map(f=>({time:new Date(f.timestamp).toISOString(),action:f.action,tool:f.tool,symbol:f.symbol,summary:f.summary}))};}if(i){let l=Date.now()-i.lastActivity,u=Math.round(l/6e4),d=Math.round(l/36e5),g=i.breadcrumbs.slice(-10).map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}));c.previousSession={sessionId:i.sessionId,startTime:new Date(i.startTime).toISOString(),lastActivity:new Date(i.lastActivity).toISOString(),age:d>1?`${d} hours ago`:`${u} minutes ago`},c.context={symbolsModified:i.symbolsModified,filesExplored:i.filesExplored},c.recentActions=g;}if(o.length>0){c.pendingHandoffs=o.map(l=>({id:l.id,timestamp:l.timestamp,from:l.from,to:l.to,summary:l.summary,nextSteps:l.nextSteps,modifiedFiles:l.modifiedFiles,symbolsTouched:l.symbolsTouched,openQuestions:l.openQuestions}));for(let l of o)try{c$1(r.rootDir,l.id);}catch{}}let a="Continue where the previous session left off.";if(s)a=`Previous session was in "${s.phase}" phase: ${s.context}`,s.decisions?.length&&(a+=` Key decisions: ${s.decisions.slice(0,2).join("; ")}`);else if(o.length>0){let l=o[o.length-1];a=`Handoff received: "${l.summary}". `,l.nextSteps.length>0&&(a+=`Start with: ${l.nextSteps[0]}`);}else if(i){let l=i.breadcrumbs.slice(-10);if(l.length>0){let u=l[l.length-1];u.symbol&&(a=`Last work involved ${u.symbol}. Consider checking its current state with paradigm_ripple.`);}}return c.suggestion=a,c.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.",n.markRecovered(),{handled:true,text:JSON.stringify(c,null,2)}}if(t==="paradigm_session_checkpoint"){n.setRootDir(r.rootDir);let s=e.phase,o=e.context,i=e.externalId,c=e.plan,a=e.modifiedFiles,l=e.symbolsTouched,u=e.decisions,{checkpoint:d,persisted:f}=n.saveCheckpoint({phase:s,context:o,externalId:i,plan:c,modifiedFiles:a,symbolsTouched:l,decisions:u}),g=f.local||f.global;return {handled:true,text:JSON.stringify({saved:g,persisted:f,checkpoint:{phase:d.phase,context:d.context,sessionId:d.sessionId,...d.externalId?{externalId:d.externalId}:{},timestamp:new Date(d.timestamp).toISOString(),modifiedFiles:d.modifiedFiles?.length||0,symbolsTouched:d.symbolsTouched?.length||0,decisions:d.decisions?.length||0,recentBreadcrumbs:d.recentBreadcrumbs?.length||0},...g?{note:"Checkpoint saved. Recovery data will be auto-surfaced on the first tool call of the next session."}:{warning:"Checkpoint was NOT persisted to disk. Both local and global writes failed. Check MCP server stderr for details."}},null,2)}}return {handled:false,text:""}}function ft(t){let e=j$2();e.setRootDir(t);let r=e.loadCheckpoint(),n=e.loadPreviousSession(),s=[];try{s=b$2(t);}catch{}return {checkpoint:r,pendingHandoffs:s,previousSession:n}}async function tr(t){let{checkpoint:e,pendingHandoffs:r}=ft(t);if(!e&&r.length===0)return null;let n=[];if(n.push("--- SESSION RECOVERY ---"),e){let s=Date.now()-e.timestamp,o=Math.round(s/6e4),i=Math.round(s/36e5),c=i>1?`${i}h ago`:`${o}m ago`;n.push(`Previous session was in "${e.phase}" phase (${c}): ${e.context}`),e.modifiedFiles?.length&&n.push(`Modified files: ${e.modifiedFiles.join(", ")}`),e.symbolsTouched?.length&&n.push(`Symbols: ${e.symbolsTouched.join(", ")}`),e.decisions?.length&&n.push(`Decisions: ${e.decisions.join("; ")}`),e.plan&&n.push(`Plan: ${e.plan.slice(0,200)}`);}if(r.length>0){let s=r[r.length-1];n.push(`Pending handoff: "${s.summary}"`),s.nextSteps.length>0&&n.push(`Next steps: ${s.nextSteps.slice(0,3).join(", ")}`);}try{let{loadTasks:s}=await import('./task-loader-NZFDTUQ5.js'),o=await s(t,{status:"open",limit:5});if(o.length>0){n.push(""),n.push("Open tasks:");for(let i of o){let c=i.tags.length>0?` [${i.tags.join(", ")}]`:"";n.push(` [${i.priority}] ${i.id}: ${i.blurb}${c}`);}}}catch{}try{let{loadLoreEntries:s}=await import('./lore-loader-PXFKMKAN.js'),i=(await s(t,{limit:10})).filter(c=>c.tags?.some(a=>a.startsWith("arc:")));if(i.length>0){let c=new Map;for(let u of i){let d=u.tags?.find(f=>f.startsWith("arc:"))||"";c.set(d,(c.get(d)||0)+1);}let a=e?.symbolsTouched||[];if((a.length>0?i.filter(u=>u.symbols_touched?.some(d=>a.includes(d))):i.slice(0,3)).length>0||c.size>0){n.push(""),n.push("Active lore arcs:");for(let[u,d]of c)n.push(` ${u} (${d} entries)`);}}}catch{}try{let{loadNominations:s}=await import('./nomination-engine-NCLTGMAK.js'),o=s(t,{pending_only:!0}).filter(i=>i.urgency==="critical"||i.urgency==="high");if(o.length>0){n.push(""),n.push("Ambient nominations (urgent):");for(let i of o.slice(0,5))n.push(` [${i.urgency}] ${i.brief}`);o.length>5&&n.push(` ... and ${o.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return n.push(""),n.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."),n.push("---"),n.join(`
25
- `)}var Le=class{cache=new Map;ttlMs;constructor(e=3e4){this.ttlMs=e;}async getOrCompute(e,r){let n=this.cache.get(e);if(n&&Date.now()-n.createdAt<this.ttlMs)return n.data;let s=await r();return this.cache.set(e,{data:s,createdAt:Date.now()}),s}invalidate(e){this.cache.delete(e);}invalidatePrefix(e){for(let r of this.cache.keys())r.startsWith(e)&&this.cache.delete(r);}clear(){this.cache.clear();}stats(){return {size:this.cache.size,ttlMs:this.ttlMs}}},pt=new Le(3e4);var Tn=300*1e3,fe=null;function gt(){fe=null;}function B(t,e){return h.existsSync(x.join(t,e))}function ee(t,e){return h.existsSync(x.join(t,e))}function _n(t,e,r){let n=t;try{if(!h.existsSync(n))return !1;let s=h.readdirSync(n,{withFileTypes:!0});for(let o of s){if(o.isFile()&&o.name.endsWith(e))return !0;if(o.isDirectory())try{if(h.readdirSync(x.join(n,o.name)).some(c=>c.endsWith(e)))return !0}catch{}}}catch{}return false}var vn={wisdom:t=>B(t,".paradigm/wisdom"),history:t=>B(t,".paradigm/history"),lore:t=>B(t,".paradigm/lore"),habits:t=>ee(t,".paradigm/habits.yaml"),sentinel:t=>{try{let e=x.join(t,".paradigm","config.yaml");return h.existsSync(e)?h.readFileSync(e,"utf-8").includes("sentinel"):!1}catch{return false}},flows:t=>ee(t,".paradigm/flow-index.json")||ee(t,".paradigm/flows.yaml"),fixtures:t=>ee(t,".paradigm/fixtures.yaml"),orchestration:t=>ee(t,".paradigm/agents.yaml"),tasks:t=>B(t,".paradigm/tasks"),assessment:t=>B(t,".paradigm/lore"),personas:t=>_n(t,".persona"),protocols:t=>B(t,".paradigm/protocols"),symphony:()=>{let t=x.join(Se.homedir(),".paradigm","score");return h.existsSync(t)},university:t=>B(t,".paradigm/university"),agents:t=>{let e=x.join(Se.homedir(),".paradigm","agents");return B(t,".paradigm/agents")||h.existsSync(e)},"aspect-graph":t=>ee(t,".paradigm/aspect-graph.db"),pan:t=>ee(t,".pan")||ee(t,"nevr.yaml"),notebooks:t=>{let e=x.join(Se.homedir(),".paradigm","notebooks");return B(t,".paradigm/notebooks")||h.existsSync(e)}},mt=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 r of e)this.register(r);}detectActiveFeatures(){if(fe&&Date.now()-fe.timestamp<Tn)return fe.features;let e=new Set;for(let[r,n]of this.modules){if(n.tier==="core"){e.add(r);continue}if(n.tier==="advanced"){this.activatedAdvanced.has(r)&&e.add(r);continue}let s=n.detect||vn[r];if(s)try{s(this.rootDir)&&e.add(r);}catch{}else e.add(r);}return fe={features:e,timestamp:Date.now()},e}getActiveTools(){let e=this.detectActiveFeatures(),r=[];for(let[n,s]of this.modules)e.has(n)&&r.push(...s.getToolsList());return r}activateAdvanced(e){let r=this.modules.get(e);return !r||r.tier!=="advanced"?null:(this.activatedAdvanced.add(e),r.getToolsList())}getAvailableAdvanced(){let e=[];for(let[r,n]of this.modules)n.tier==="advanced"&&!this.activatedAdvanced.has(r)&&e.push({key:r,toolCount:n.getToolsList().length});return e}async dispatch(e,r,n,s){let o=this.detectActiveFeatures();for(let[i,c]of this.modules)if(o.has(i))try{let a=await c.handleTool(e,r,n,s);if(a.handled)return a}catch(a){return {handled:true,text:JSON.stringify({error:`Tool handler error in module "${i}"`,message:a.message},null,2)}}return null}get size(){return this.modules.size}getRegistryInfo(){let e=this.detectActiveFeatures(),r={core:0,feature:0,advanced:0};for(let n of this.modules.values())r[n.tier]++;return {total:this.modules.size,byTier:r,activeFeatures:[...e],availableAdvanced:[...this.modules.entries()].filter(([n,s])=>s.tier==="advanced"&&!this.activatedAdvanced.has(n)).map(([n])=>n)}}};var Fe=null;async function On(){return Fe||(Fe=await jn()),Fe}var Fn=[`CREATE TABLE IF NOT EXISTS aspects (
26
- id TEXT PRIMARY KEY,
27
- description TEXT NOT NULL,
28
- category TEXT DEFAULT 'rule',
29
- severity TEXT DEFAULT 'medium',
30
- value TEXT,
31
- enforcement TEXT,
32
- defined_in TEXT NOT NULL,
33
- tags TEXT,
34
- created_at TEXT NOT NULL,
35
- updated_at TEXT NOT NULL
36
- )`,`CREATE TABLE IF NOT EXISTS anchors (
37
- id INTEGER PRIMARY KEY AUTOINCREMENT,
38
- aspect_id TEXT NOT NULL REFERENCES aspects(id) ON DELETE CASCADE,
39
- file_path TEXT NOT NULL,
40
- start_line INTEGER NOT NULL,
41
- end_line INTEGER NOT NULL,
42
- content_hash TEXT,
43
- normalized_hash TEXT,
44
- materialized_at_commit TEXT,
45
- last_verified TEXT,
46
- drifted INTEGER DEFAULT 0
47
- )`,"CREATE INDEX IF NOT EXISTS idx_anchors_file ON anchors(file_path)","CREATE INDEX IF NOT EXISTS idx_anchors_aspect ON anchors(aspect_id)",`CREATE TABLE IF NOT EXISTS edges (
48
- id INTEGER PRIMARY KEY AUTOINCREMENT,
49
- source TEXT NOT NULL,
50
- target TEXT NOT NULL,
51
- relation TEXT NOT NULL,
52
- weight REAL DEFAULT 1.0,
53
- origin TEXT DEFAULT 'explicit',
54
- created_at TEXT NOT NULL
55
- )`,"CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)",`CREATE TABLE IF NOT EXISTS lore_links (
56
- aspect_id TEXT NOT NULL,
57
- lore_id TEXT NOT NULL,
58
- PRIMARY KEY (aspect_id, lore_id)
59
- )`,`CREATE TABLE IF NOT EXISTS search_log (
60
- id INTEGER PRIMARY KEY AUTOINCREMENT,
61
- query TEXT NOT NULL,
62
- results_returned TEXT NOT NULL,
63
- selected_result TEXT,
64
- timestamp TEXT NOT NULL
65
- )`,"CREATE INDEX IF NOT EXISTS idx_search_query ON search_log(query)",`CREATE TABLE IF NOT EXISTS search_weights (
66
- query_normalized TEXT NOT NULL,
67
- aspect_id TEXT NOT NULL,
68
- weight REAL DEFAULT 1.0,
69
- hit_count INTEGER DEFAULT 1,
70
- last_hit TEXT NOT NULL,
71
- PRIMARY KEY (query_normalized, aspect_id)
72
- )`,`CREATE TABLE IF NOT EXISTS heatmap (
73
- aspect_id TEXT NOT NULL,
74
- access_type TEXT NOT NULL,
75
- count INTEGER DEFAULT 0,
76
- last_accessed TEXT NOT NULL,
77
- PRIMARY KEY (aspect_id, access_type)
78
- )`],Nn=["ALTER TABLE anchors ADD COLUMN original_content TEXT",`CREATE TABLE IF NOT EXISTS anchor_history (
79
- id INTEGER PRIMARY KEY AUTOINCREMENT,
80
- anchor_id INTEGER NOT NULL,
81
- action TEXT NOT NULL,
82
- old_start INTEGER,
83
- old_end INTEGER,
84
- new_start INTEGER,
85
- new_end INTEGER,
86
- old_path TEXT,
87
- new_path TEXT,
88
- confidence REAL,
89
- commit_hash TEXT,
90
- healed_at TEXT NOT NULL
91
- )`],$n="CREATE VIRTUAL TABLE IF NOT EXISTS aspects_fts USING fts5(id, description, enforcement, tags)";function H(t,e,r){let n=t.prepare(e);r&&r.length>0&&n.bind(r);let s=[];for(;n.step();)s.push(n.getAsObject());return n.free(),s}function Mn(t,e,r){let n=t.prepare(e);r&&r.length>0&&n.bind(r);let s=null;return n.step()&&(s=n.getAsObject()),n.free(),s}async function kt(t){let e=await On(),r=x.join(t,".paradigm"),n=x.join(r,"aspect-graph.db"),s;if(h.existsSync(n)){let o=h.readFileSync(n);s=new e.Database(o);}else h.existsSync(r)||h.mkdirSync(r,{recursive:true}),s=new e.Database;for(let o of Fn)s.run(o);try{s.run($n);}catch{}for(let o of Nn)try{s.run(o);}catch{}return s}function Rt(t,e){if(e){let r=x.join(e,".paradigm");h.existsSync(r)||h.mkdirSync(r,{recursive:true});let n=x.join(r,"aspect-graph.db"),s=t.export();h.writeFileSync(n,Buffer.from(s));}t.close();}function It(t,e,r){let n=e.filter(i=>i.type==="aspect"),s=new Date().toISOString(),o=null;try{o=execSync("git rev-parse HEAD",{cwd:r,encoding:"utf8"}).trim();}catch{}t.run("DELETE FROM anchors"),t.run("DELETE FROM edges"),t.run("DELETE FROM aspects");try{t.run("DELETE FROM aspects_fts");}catch{}for(let i of n){let c=i.data??{},a=zn(c,i),l=Wn(c,i),u=c.value!=null?String(c.value):null,d=i.enforcement??(c.enforcement!=null?String(c.enforcement):null),f=i.tags?JSON.stringify(i.tags):null;if(t.run(`INSERT INTO aspects (id, description, category, severity, value, enforcement, defined_in, tags, created_at, updated_at)
92
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.symbol,i.description??"",a,l,u,d,i.filePath,f,i.created??s,i.modified??s]),i.anchors)for(let p of i.anchors){let{startLine:m,endLine:y}=Pt(p),w=Hn();t.run(`INSERT INTO anchors (aspect_id, file_path, start_line, end_line, content_hash, normalized_hash, materialized_at_commit, last_verified, original_content)
93
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.symbol,p.path,m,y,w.exact,w.normalized,o,s,w.normalizedContent]);}let g=c.edges;if(Array.isArray(g))for(let p of g)t.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
94
- VALUES (?, ?, ?, ?, ?, ?)`,[p.source??i.symbol,p.target??"",p.relation??"related-to",p.weight??1,p.origin??"explicit",s]);if(i.appliesTo)for(let p of i.appliesTo)t.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
95
- VALUES (?, ?, ?, ?, ?, ?)`,[i.symbol,p,"related-to",.5,"inferred",s]);try{t.run(`INSERT INTO aspects_fts (id, description, enforcement, tags)
96
- VALUES (?, ?, ?, ?)`,[i.symbol,i.description??"",d??"",f??""]);}catch{}}}function fr(t,e){return Mn(t,"SELECT * FROM aspects WHERE id = ?",[e])}function pr(t,e){return H(t,"SELECT * FROM anchors WHERE aspect_id = ?",[e])}function mr(t,e){return H(t,"SELECT * FROM edges WHERE source = ?",[e])}function gr(t,e){return H(t,"SELECT * FROM edges WHERE target = ?",[e])}function hr(t,e){return H(t,"SELECT * FROM edges WHERE source = ? OR target = ?",[e,e])}function yr(t,e,r){let n=new Date().toISOString();t.run(`INSERT INTO heatmap (aspect_id, access_type, count, last_accessed)
97
- VALUES (?, ?, 1, ?)
98
- ON CONFLICT(aspect_id, access_type)
99
- DO UPDATE SET count = count + 1, last_accessed = ?`,[e,r,n,n]);}function Sr(t,e=20,r){return r?H(t,"SELECT * FROM heatmap WHERE access_type = ? ORDER BY count DESC LIMIT ?",[r,e]):H(t,"SELECT * FROM heatmap ORDER BY count DESC LIMIT ?",[e])}function wr(t,e,r$1,n=true,s=.7,o=.85){let i=r$1?H(t,"SELECT * FROM anchors WHERE aspect_id = ?",[r$1]):H(t,"SELECT * FROM anchors"),c=[];for(let a of i){let u=H(t,"SELECT defined_in FROM aspects WHERE id = ?",[a.aspect_id])[0]?.defined_in,d$1=u?x.dirname(x.isAbsolute(u)?u:x.resolve(e,u)):e,f=r(a.file_path,d$1,e),g=f.resolvedPath;if(!f.exists){c.push({aspectId:a.aspect_id,path:a.file_path,startLine:a.start_line,endLine:a.end_line,status:"missing",resolvedBy:"none",exists:false,drifted:true});continue}try{let m=h.readFileSync(g,"utf8").split(`
100
- `),y=Math.max(0,a.start_line-1),w=Math.min(m.length,a.end_line),P=m.slice(y,w).join(`
101
- `),$=te.createHash("sha256").update(P).digest("hex");if(a.content_hash!=null&&$===a.content_hash){c.push({aspectId:a.aspect_id,path:a.file_path,startLine:a.start_line,endLine:a.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1}),a.drifted===1&&t.run("UPDATE anchors SET drifted = 0 WHERE id = ?",[a.id]);continue}let J=te.createHash("sha256").update($e(P)).digest("hex");if(a.normalized_hash!=null&&J===a.normalized_hash){t.run("UPDATE anchors SET content_hash = ?, drifted = 0 WHERE id = ?",[$,a.id]),c.push({aspectId:a.aspect_id,path:a.file_path,startLine:a.start_line,endLine:a.end_line,status:"cosmetic",resolvedBy:"normalized-hash",exists:!0,drifted:!1});continue}if(a.content_hash==null&&a.normalized_hash==null){t.run("UPDATE anchors SET content_hash = ?, normalized_hash = ?, drifted = 0 WHERE id = ?",[$,J,a.id]),c.push({aspectId:a.aspect_id,path:a.file_path,startLine:a.start_line,endLine:a.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1});continue}let se=!1;if(a.materialized_at_commit){let _=Un(e,a.file_path,a.materialized_at_commit,a.start_line,a.end_line);if(_){let E=Math.max(0,_.currentStart-1),S=Math.min(m.length,_.currentEnd),I=m.slice(E,S).join(`
102
- `),K=te.createHash("sha256").update(I).digest("hex");if(a.content_hash!=null&&K===a.content_hash){let Q=n;if(Q){t.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[_.currentStart,_.currentEnd,a.id]);let ae=H(t,"SELECT defined_in FROM aspects WHERE id = ?",[a.aspect_id]);ae.length>0&&Ne(e,ae[0].defined_in,a.file_path,a.start_line,a.end_line,_.currentStart,_.currentEnd);}c.push({aspectId:a.aspect_id,path:a.file_path,startLine:Q?_.currentStart:a.start_line,endLine:Q?_.currentEnd:a.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:_.currentStart,suggestedEnd:_.currentEnd,autoHealed:Q}),se=!0;}else {let Q=te.createHash("sha256").update($e(I)).digest("hex");if(a.normalized_hash!=null&&Q===a.normalized_hash){if(n){let ae=te.createHash("sha256").update(I).digest("hex");t.run("UPDATE anchors SET start_line = ?, end_line = ?, content_hash = ?, drifted = 0 WHERE id = ?",[_.currentStart,_.currentEnd,ae,a.id]);let he=H(t,"SELECT defined_in FROM aspects WHERE id = ?",[a.aspect_id]);he.length>0&&Ne(e,he[0].defined_in,a.file_path,a.start_line,a.end_line,_.currentStart,_.currentEnd);}c.push({aspectId:a.aspect_id,path:a.file_path,startLine:n?_.currentStart:a.start_line,endLine:n?_.currentEnd:a.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:_.currentStart,suggestedEnd:_.currentEnd,autoHealed:n}),se=!0;}}}}if(se)continue;if(a.original_content){let{contentSearch:_}=(_t(),d(Tt)),E=_(e,a.file_path,a.original_content,n);if(E.found&&E.score>=s){if(n&&E.score>=o&&!E.suggestedPath&&E.suggestedStart&&E.suggestedEnd){t.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[E.suggestedStart,E.suggestedEnd,a.id]);try{t.run(`INSERT INTO anchor_history (anchor_id, action, old_start, old_end, new_start, new_end, confidence, healed_at)
103
- VALUES (?, 'relocated', ?, ?, ?, ?, ?, ?)`,[a.id,a.start_line,a.end_line,E.suggestedStart,E.suggestedEnd,E.score,new Date().toISOString()]);}catch{}let I=H(t,"SELECT defined_in FROM aspects WHERE id = ?",[a.aspect_id]);I.length>0&&Ne(e,I[0].defined_in,a.file_path,a.start_line,a.end_line,E.suggestedStart,E.suggestedEnd),c.push({aspectId:a.aspect_id,path:a.file_path,startLine:E.suggestedStart,endLine:E.suggestedEnd,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:E.similarity,suggestedStart:E.suggestedStart,suggestedEnd:E.suggestedEnd,autoHealed:!0,drifted:!1});continue}c.push({aspectId:a.aspect_id,path:E.suggestedPath||a.file_path,startLine:a.start_line,endLine:a.end_line,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:E.similarity,suggestedStart:E.suggestedStart,suggestedEnd:E.suggestedEnd,autoHealed:!1,drifted:!0});continue}}t.run("UPDATE anchors SET drifted = 1 WHERE id = ?",[a.id]),c.push({aspectId:a.aspect_id,path:a.file_path,startLine:a.start_line,endLine:a.end_line,status:"modified",resolvedBy:"none",exists:!0,currentContent:P,drifted:!0});}catch{c.push({aspectId:a.aspect_id,path:a.file_path,startLine:a.start_line,endLine:a.end_line,status:"modified",resolvedBy:"none",exists:true,drifted:true});}}return c}function Pt(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 Dn(t){let e=[],r=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm,n;for(;(n=r.exec(t))!==null;)e.push({oldStart:parseInt(n[1],10),oldCount:n[2]!==void 0?parseInt(n[2],10):1,newStart:parseInt(n[3],10),newCount:n[4]!==void 0?parseInt(n[4],10):1});return e}function Un(t,e,r,n,s){let o;try{o=execSync(`git diff ${r}..HEAD --unified=0 -- "${e}"`,{cwd:t,encoding:"utf8",timeout:5e3});}catch{return null}if(!o.trim())return {originalStart:n,originalEnd:s,currentStart:n,currentEnd:s};let i=Dn(o),c=0;for(let a of i){if(a.oldStart+a.oldCount<=n){c+=a.newCount-a.oldCount;continue}if(a.oldStart<s)return null;break}return c===0?null:{originalStart:n,originalEnd:s,currentStart:n+c,currentEnd:s+c}}function Ne(t,e,r,n,s,o,i){let c=x.isAbsolute(e)?e:x.join(t,e);if(!h.existsSync(c))return false;try{let a=h.readFileSync(c,"utf8"),l=n===s?`${r}:${n}`:`${r}:${n}-${s}`,u=o===i?`${r}:${o}`:`${r}:${o}-${i}`;if(!a.includes(l))return !1;let d=a.replace(l,u);return h.writeFileSync(c,d,"utf8"),!0}catch{return false}}function $e(t){return t.split(`
104
- `).map(e=>e.trimEnd()).filter(e=>e.trim()!=="").map(e=>e.replace(/\s+/g," ")).join(`
105
- `)}function Hn(t,e,r$1){return {exact:null,normalized:null,normalizedContent:null};}function zn(t,e){if(typeof t.category=="string")return t.category;let r=(e.description??"").toLowerCase();return /\b(must|require|always)\b/.test(r)?"rule":/\b(decided|chose)\b/.test(r)?"decision":/\b(limit|cannot)\b/.test(r)?"constraint":/\b(set to|configured|value)\b/.test(r)?"configuration":"rule"}function Wn(t,e){if(typeof t.severity=="string")return t.severity;let r=e.tags??[];return r.includes("critical")?"critical":r.includes("security")||r.includes("compliance")?"high":"medium"}j$1();var Gn=/L-\d{4}-\d{2}-\d{2}-\d{3}/g;async function Ct(t,e){t.run("DELETE FROM lore_links");let r=await a$4(e);if(r.length===0)return 0;let n=Xn(r),s=new Map;for(let l of r)s.set(l.id,l);let o=new Set,i=t.exec("SELECT id, enforcement FROM aspects");if(i.length>0){let{columns:l,values:u}=i[0],d=l.indexOf("id"),f=l.indexOf("enforcement");for(let g of u){let p=String(g[d]),m=g[f];if(m&&typeof m=="string"){let y=m.match(Gn);if(y)for(let w of y)s.has(w)&&o.add(`${p}\0${w}`);}}}let c=t.exec("SELECT source, target FROM edges");if(c.length>0&&i.length>0){let l=Bn(t,c);for(let[u,d]of l)for(let f of d){let g=n.get(f);if(g)for(let p of g)o.add(`${u}\0${p}`);}}if(o.size===0)return 0;let a=t.prepare("INSERT OR IGNORE INTO lore_links (aspect_id, lore_id) VALUES (?, ?)");try{for(let l of o){let[u,d]=l.split("\0");a.bind([u,d]),a.step(),a.reset();}}finally{a.free();}return o.size}async function Er(t,e,r){let n=t.exec("SELECT lore_id FROM lore_links WHERE aspect_id = ?",[r]);if(n.length===0||n[0].values.length===0)return [];let s=n[0].values.map(o=>String(o[0]));return qn(e,s)}async function At(t,e){let r=await a$4(e);if(r.length===0)return 0;let n=t.exec("SELECT id FROM aspects"),s=new Set;if(n.length>0)for(let a of n[0].values)s.add(String(a[0]));if(s.size<2)return 0;let o=new Date().toISOString(),i=0,c=t.prepare(`INSERT OR IGNORE INTO edges (source, target, relation, weight, origin, created_at)
106
- VALUES (?, ?, 'related-to', 0.3, 'learned', ?)`);try{for(let a of r){if(!a.symbols_touched||a.symbols_touched.length<2)continue;let l=[];for(let u of a.symbols_touched){let d=u.startsWith("~")?u.slice(1):u;s.has(d)&&l.push(d);}for(let u=0;u<l.length;u++)for(let d=u+1;d<l.length;d++){let[f,g]=l[u]<l[d]?[l[u],l[d]]:[l[d],l[u]];c.bind([f,g,o]),c.step(),c.reset(),i++;}}}finally{c.free();}return i}function Xn(t){let e=new Map;for(let r of t)if(r.symbols_touched)for(let n of r.symbols_touched){let s=e.get(n);s||(s=new Set,e.set(n,s)),s.add(r.id);}return e}function Bn(t,e){let r=t.exec("SELECT id FROM aspects"),n=new Set;if(r.length>0)for(let l of r[0].values)n.add(String(l[0]));let s=new Map;if(e.length===0)return s;let{columns:o,values:i}=e[0],c=o.indexOf("source"),a=o.indexOf("target");for(let l of i){let u=String(l[c]),d=String(l[a]);if(n.has(u)){let f=s.get(u);f||(f=new Set,s.set(u,f)),f.add(d),f.add(`~${u}`);}if(n.has(d)){let f=s.get(d);f||(f=new Set,s.set(d,f)),f.add(u),f.add(`~${d}`);}}return s}async function qn(t,e){let r=new Set,n=[];for(let s of e){if(r.has(s))continue;r.add(s);let o=await b$3(t,s);o&&n.push(Vn(o));}return n}function Vn(t){return {id:t.id,title:t.title,summary:t.summary,timestamp:t.timestamp,symbolsTouched:t.symbols_touched}}var le=".paradigm/personas",Yn="index.yaml";async function pe(t,e){let r=x.join(t,le);if(!h.existsSync(r))return [];let n=h.readdirSync(r).filter(o=>o.endsWith(".persona")),s=[];for(let o of n)try{let i=h.readFileSync(x.join(r,o),"utf8"),c=N.load(i);c&&c.id&&s.push(c);}catch{}return Jn(s,e)}async function me(t,e){let r=x.join(t,le,`${e}.persona`);if(!h.existsSync(r))return null;try{return N.load(h.readFileSync(r,"utf8"))}catch{return null}}function Jn(t,e){if(!e)return t;let r=t;return e.tag&&(r=r.filter(n=>n.tags?.includes(e.tag))),e.trigger_type&&(r=r.filter(n=>n.trigger.type===e.trigger_type)),e.gate&&(r=r.filter(n=>n.journey.some(s=>s.gates.includes(e.gate)))),e.flow&&(r=r.filter(n=>n.journey.some(s=>s.flow===e.flow))),e.limit&&(r=r.slice(0,e.limit)),r}async function _r(t,e){let r=x.join(t,le);h.mkdirSync(r,{recursive:true});let n=x.join(r,`${e.id}.persona`);if(h.existsSync(n))throw new Error(`Persona ${e.id} already exists`);let s=new Date().toISOString(),o={version:"1.0",id:e.id,name:e.name,description:e.description,traits:e.traits,trigger:e.trigger,fixtures:e.fixtures,tags:e.tags||[],journey:e.journey||[],created:s,updated:s};return h.writeFileSync(n,N.dump(o,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await ge(t),e.id}async function Lt(t,e,r){let n=await me(t,e);if(!n)return false;let s=x.join(t,le,`${e}.persona`),o={...n,...r,id:n.id,version:n.version,created:n.created,updated:new Date().toISOString()};return h.writeFileSync(s,N.dump(o,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await ge(t),true}async function vr(t,e){let r=x.join(t,le,`${e}.persona`);if(!h.existsSync(r))return {deleted:false,warnings:[]};let n=[],s=await pe(t);for(let o of s)if(o.id!==e){o.trigger.spawned_by?.startsWith(e+".")&&n.push(`Persona ${o.id} is spawned by ${e} \u2014 it will become orphaned`);for(let i of o.journey)i.spawns?.some(c=>c.persona===e)&&n.push(`Persona ${o.id} step ${i.id} spawns ${e} \u2014 spawn will break`);}return h.unlinkSync(r),await ge(t),{deleted:true,warnings:n}}async function kr(t,e,r,n){let s=await me(t,e);if(!s)return false;if(s.journey.some(o=>o.id===r.id))throw new Error(`Step ${r.id} already exists in persona ${e}`);if(n){let o=s.journey.findIndex(i=>i.id===n);if(o===-1)throw new Error(`Step ${n} not found in persona ${e}`);s.journey.splice(o+1,0,r);}else s.journey.push(r);return Lt(t,e,{journey:s.journey})}async function Rr(t,e,r){let n=await me(t,e);if(!n)return {removed:false,warnings:[]};let s=n.journey.findIndex(c=>c.id===r);if(s===-1)return {removed:false,warnings:[]};let o=n.journey[s],i=[];if(o.produces)for(let c of Object.keys(o.produces)){let a=`{{produces.${c}}}`;for(let l=s+1;l<n.journey.length;l++){let u=n.journey[l];JSON.stringify(u).includes(a)&&i.push(`Step ${u.id} consumes {{produces.${c}}} from this step`);}}if(o.spawns&&o.spawns.length>0)for(let c of o.spawns)i.push(`Step spawns persona ${c.persona} \u2014 spawn chain will break`);return n.journey.splice(s,1),await Lt(t,e,{journey:n.journey}),{removed:true,warnings:i}}var Kn=/^[a-z][a-z0-9-]*$/,Qn=/^[a-z][a-z0-9-]*$/,Zn=/^(GET|POST|PUT|PATCH|DELETE)\s+\//;async function Ir(t,e,r=false){let n=[],s=[];Kn.test(e.id)||n.push({type:"invalid-id",detail:`ID "${e.id}" must match /^[a-z][a-z0-9-]*$/`}),(!e.name||e.name.trim()==="")&&n.push({type:"missing-name",detail:"Name is required"}),(!e.trigger||!e.trigger.type)&&n.push({type:"missing-trigger",detail:"Trigger with type is required"}),e.trigger.type!=="root"&&!e.trigger.spawned_by&&n.push({type:"missing-spawned-by",detail:`Non-root trigger type "${e.trigger.type}" requires spawned_by`}),(!e.journey||e.journey.length===0)&&n.push({type:"empty-journey",detail:"Journey must have at least one step"});let o=new Set,i=new Set;for(let c of e.journey){Qn.test(c.id)||n.push({type:"invalid-step-id",step:c.id,detail:"Step ID must match /^[a-z][a-z0-9-]*$/"}),o.has(c.id)&&n.push({type:"duplicate-step-id",step:c.id,detail:`Duplicate step ID "${c.id}"`}),o.add(c.id),Zn.test(c.route)||n.push({type:"invalid-route",step:c.id,route:c.route,detail:'Route must match "METHOD /path" (e.g., "POST /api/auth/signup")'}),(!c.gates||c.gates.length===0)&&n.push({type:"missing-gates",step:c.id,detail:"Step must have at least one gate"}),(!c.expect||c.expect.status===void 0)&&n.push({type:"missing-expect",step:c.id,detail:"Step must have expect with status"});let l=JSON.stringify(c).match(/\{\{produces\.([^}]+)\}\}/g)||[];for(let u of l){let d=u.replace("{{produces.","").replace("}}","");i.has(d)||n.push({type:"unresolved-produces",step:c.id,key:d,detail:`{{produces.${d}}} used but not produced by a prior step`});}if(c.produces)for(let u of Object.keys(c.produces))i.add(u);}if(r){let c=x.join(t,"portal.yaml"),a=[],l=[];if(h.existsSync(c))try{let d=N.load(h.readFileSync(c,"utf8"));d.gates&&typeof d.gates=="object"&&(a=Object.keys(d.gates)),d.routes&&typeof d.routes=="object"&&(l=Object.keys(d.routes));}catch{}for(let d of e.journey)for(let f of d.gates)a.length>0&&!a.includes(f)&&n.push({type:"gate-not-found",step:d.id,gate:f,detail:`Gate ${f} not defined in portal.yaml`});for(let d of e.journey)if(l.length>0){let f=d.route;l.some(p=>Me(p,f))||s.push({type:"route-not-in-portal",detail:`Route "${f}" (step ${d.id}) not found in portal.yaml`});}for(let d of e.journey)if(d.spawns)for(let f of d.spawns)await me(t,f.persona)||n.push({type:"spawn-target-missing",step:d.id,detail:`Spawn target persona "${f.persona}" does not exist`});let u=await es(t,e.id);if(u&&n.push({type:"spawn-cycle",detail:`Circular spawn dependency: ${u.join(" \u2192 ")}`}),l.length>0||a.length>0){let d=await pe(t),f=new Set,g=new Set;for(let w of d)for(let P of w.journey){for(let $ of P.gates)f.add($);g.add(P.route);}let p=[],m=x.join(t,".paradigm","flow-index.json");if(h.existsSync(m))try{let w=JSON.parse(h.readFileSync(m,"utf8"));p=Object.keys(w.flows||{});}catch{}let y=new Set;for(let w of d)for(let P of w.journey)P.flow&&y.add(P.flow);return {persona:e.id,valid:n.length===0,errors:n,warnings:s,coverage:{routes:{covered:g.size,total:l.length,uncovered:l.filter(w=>!g.has(w))},gates:{covered:f.size,total:a.length,uncovered:a.filter(w=>!f.has(w))},flows:{covered:y.size,total:p.length,uncovered:p.filter(w=>!y.has(w))}}}}}return {persona:e.id,valid:n.length===0,errors:n,warnings:s}}function Me(t,e){let r=n=>n.replace(/:[a-zA-Z_]+/g,":param").replace(/\{\{[^}]+\}\}/g,":param");return r(t)===r(e)}async function es(t,e){let r=new Set,n=[];async function s(o){if(r.has(o)){let c=n.indexOf(o);return c!==-1?[...n.slice(c),o]:null}r.add(o),n.push(o);let i=await me(t,o);if(i){for(let c of i.journey)if(c.spawns)for(let a of c.spawns){let l=await s(a.persona);if(l)return l}}return n.pop(),null}return s(e)}async function ge(t){let e=x.join(t,le);h.mkdirSync(e,{recursive:true});let r=await pe(t),n={},s={},o={};for(let d of r){let f=new Set,g=new Set,p=[],m=new Set;for(let y of d.journey){for(let w of y.gates)f.add(w);if(y.flow&&g.add(y.flow),p.push(y.route),y.spawns)for(let w of y.spawns)m.add(w.persona);}n[d.id]={name:d.name,trigger:d.trigger.type,spawned_by:d.trigger.spawned_by,steps:d.journey.length,gates:[...f],flows:[...g],routes:p,spawns:[...m],tags:d.tags||[]};for(let y of f)s[y]||(s[y]=[]),s[y].push(d.id);for(let y of p)o[y]||(o[y]=[]),o[y].push(d.id);}let i=[],c=x.join(t,"portal.yaml");if(h.existsSync(c))try{let d=N.load(h.readFileSync(c,"utf8"));d.routes&&typeof d.routes=="object"&&(i=Object.keys(d.routes).filter(g=>!Object.keys(o).some(p=>Me(g,p))));}catch{}let a={},l=x.join(e,"chains");if(h.existsSync(l)){let d=h.readdirSync(l).filter(f=>f.endsWith(".yaml"));for(let f of d)try{let g=h.readFileSync(x.join(l,f),"utf8"),p=N.load(g);if(p&&p.id){let m=p.order.map(P=>P.persona),y=0,w=new Set;for(let P of m){let $=n[P];if($){y+=$.steps;for(let J of $.gates)w.add(J);}}a[p.id]={description:p.description||"",order:m,total_steps:y,total_gates:w.size};}}catch{}}let u={version:"1.0",generated:new Date().toISOString(),personas:n,chains:a,gate_coverage:s,route_coverage:o,uncovered_routes:i};return h.writeFileSync(x.join(e,Yn),N.dump(u,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),u}async function Pr(t){let e=await pe(t),r=new Set,n=new Set,s=new Set;for(let u of e)for(let d of u.journey){for(let f of d.gates)r.add(f);n.add(d.route),d.flow&&s.add(d.flow);}let o=[],i=[],c=x.join(t,"portal.yaml");if(h.existsSync(c))try{let u=N.load(h.readFileSync(c,"utf8"));u.gates&&typeof u.gates=="object"&&(o=Object.keys(u.gates)),u.routes&&typeof u.routes=="object"&&(i=Object.keys(u.routes));}catch{}let a=[],l=x.join(t,".paradigm","flow-index.json");if(h.existsSync(l))try{let u=JSON.parse(h.readFileSync(l,"utf8"));a=Object.keys(u.flows||{});}catch{}return {routes:{covered:n.size,total:i.length,uncovered:i.filter(u=>!Array.from(n).some(d=>Me(u,d)))},gates:{covered:r.size,total:o.length,uncovered:o.filter(u=>!r.has(u))},flows:{covered:s.size,total:a.length,uncovered:a.filter(u=>!s.has(u))},personas:e.length}}async function Cr(t,e){let r=await pe(t),n=[];for(let s of r){let o=[],i=[];for(let c of s.journey)if((c.gates.includes(e)||c.flow===e||c.route===e||c.signals?.includes(e))&&(o.push(c.id),c.spawns))for(let l of c.spawns)i.push(l.persona);o.length>0&&n.push({persona:s.id,steps:o,spawns_blocked:i});}return n}function ts(t,e){let r=e.split(/[.\[\]]+/).filter(Boolean),n=t;for(let s of r){if(n==null||typeof n!="object")return;n=n[s];}return n}function ns(t,e){let r=[];if(e.status!==t.expect.status&&r.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 n=e.body;for(let s of t.expect.body.has)(!n||typeof n!="object"||!(s in n))&&r.push({type:"body.has",field:s,expected:true,actual:false,message:`Step ${t.id}: body missing key '${s}'`});}if(t.expect.body?.match){let n=e.body;for(let[s,o]of Object.entries(t.expect.body.match)){let i=n?ts(n,s):void 0;JSON.stringify(i)!==JSON.stringify(o)&&r.push({type:"body.match",field:s,expected:o,actual:i??null,message:`Step ${t.id}: '${s}' is ${JSON.stringify(i??null)}, expected ${JSON.stringify(o)}`});}}if(t.signals&&t.signals.length>0){let n=e.signals_fired||[];for(let s of t.signals)n.includes(s)||r.push({type:"signal",field:"signals_fired",expected:s,actual:n,message:`Step ${t.id}: signal '${s}' was not fired`});}if(t.gates.length>0&&e.gates_traversed)for(let n of t.gates)e.gates_traversed.includes(n)||r.push({type:"gate",field:"gates_traversed",expected:n,actual:e.gates_traversed,message:`Step ${t.id}: gate '${n}' was not traversed`});return r}async function Ar(t,e={}){let r=[];try{let{SentinelStorage:c}=await import('./dist-W3XCATBJ.js'),a=new c,u=(a.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.complete",scopeValue:t.id,limit:500})||[]).filter(p=>{let m=JSON.parse(p.data_json||"{}");return !(e.run_id&&m.run_id!==e.run_id||e.chain_id&&m.chain_id!==e.chain_id||e.environment&&m.environment!==e.environment)}),f=(a.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.fail",scopeValue:t.id,limit:500})||[]).filter(p=>{let m=JSON.parse(p.data_json||"{}");return !(e.run_id&&m.run_id!==e.run_id||e.chain_id&&m.chain_id!==e.chain_id||e.environment&&m.environment!==e.environment)}),g=new Map;for(let p of [...u,...f]){let m=JSON.parse(p.data_json||"{}");m.step_id&&g.set(m.step_id,m);}for(let p of t.journey){let m=g.get(p.id);if(!m){r.push({step_id:p.id,matched:!1,assertions:[],message:`No Sentinel event found for step '${p.id}' \u2014 step was never exercised`});continue}let y=ns(p,{status:m.status,body:m.body,gates_traversed:m.gates_traversed,signals_fired:m.signals_fired});r.push({step_id:p.id,matched:!0,passed:y.length===0,assertions:y});}}catch{for(let c of t.journey)r.push({step_id:c.id,matched:false,assertions:[],message:"Sentinel unavailable \u2014 cannot validate events"});}let n=r.filter(c=>c.matched).length,s=r.filter(c=>c.passed).length,o=r.filter(c=>c.matched&&!c.passed).length,i=r.reduce((c,a)=>c+a.assertions.length,0);return {run_id:e.run_id,environment:e.environment,steps:r,summary:{total_steps:t.journey.length,matched:n,unmatched:t.journey.length-n,passed:s,failed:o,assertion_failures:i}}}var oe=".paradigm/protocols",jt="index.yaml";async function De(t){let e=x.join(t,oe);if(!h.existsSync(e))return [];let r=h.readdirSync(e).filter(s=>s.endsWith(".protocol")).sort(),n=[];for(let s of r)try{let o=h.readFileSync(x.join(e,s),"utf8"),i=N.load(o);i?.id&&i?.name&&n.push(i);}catch{}return n}async function ss(t,e){let r=e.replace(/^P-/,""),n=x.join(t,oe,`${r}.protocol`);if(h.existsSync(n))try{let o=h.readFileSync(n,"utf8");return N.load(o)}catch{return null}return (await De(t)).find(o=>o.id===e)||null}async function jr(t){let e=x.join(t,oe,jt);if(!h.existsSync(e))return null;try{let r=h.readFileSync(e,"utf8");return N.load(r)}catch{return null}}async function Or(t,e,r=3){let n=await De(t);if(n.length===0)return [];let s=os(e);if(s.length===0)return [];let o=[];for(let i of n){let c=0;for(let u of i.trigger){let d=u.toLowerCase();for(let f of s)d.includes(f)&&(c+=3);}for(let u of i.tags){let d=u.toLowerCase();for(let f of s)(d.includes(f)||f.includes(d))&&(c+=2);}let a=i.name.toLowerCase(),l=i.description.toLowerCase();for(let u of s)a.includes(u)&&(c+=1),l.includes(u)&&(c+=1);for(let u of i.steps)if(u.notes){let d=u.notes.toLowerCase();for(let f of s)d.includes(f)&&(c+=.5);}c>0&&o.push({protocol:i,score:c});}return o.sort((i,c)=>c.score-i.score),o.slice(0,r)}async function Fr(t,e){let r=x.join(t,oe);h.existsSync(r)||h.mkdirSync(r,{recursive:true});let n=as(e.name),s=`P-${n}`,o=new Date().toISOString(),i={id:s,name:e.name,description:e.description,trigger:e.trigger,tags:e.tags,symbols:e.symbols||[],exemplar:e.exemplar,steps:e.steps,recorded_from:e.recorded_from,recorded_at:o,last_verified:o,verified_by:e.verified_by||"claude-opus-4-6",status:"current"},c=x.join(r,`${n}.protocol`);return h.writeFileSync(c,N.dump(i,{lineWidth:-1,noRefs:true}),"utf8"),s}async function Nr(t,e,r,n=false){let s=await ss(t,e);if(!s)return false;r.name!==void 0&&(s.name=r.name),r.description!==void 0&&(s.description=r.description),r.trigger!==void 0&&(s.trigger=r.trigger),r.tags!==void 0&&(s.tags=r.tags),r.symbols!==void 0&&(s.symbols=r.symbols),r.exemplar!==void 0&&(s.exemplar=r.exemplar),r.steps!==void 0&&(s.steps=r.steps),r.status!==void 0&&(s.status=r.status),r.verified_by!==void 0&&(s.verified_by=r.verified_by),n&&(s.last_verified=new Date().toISOString(),s.verified_by=r.verified_by||"claude-opus-4-6");let o=e.replace(/^P-/,""),i=x.join(t,oe,`${o}.protocol`);return h.writeFileSync(i,N.dump(s,{lineWidth:-1,noRefs:true}),"utf8"),true}function rs(t,e){let r=[],n="current";if(e.exemplar){let s=x.join(t,e.exemplar);h.existsSync(s)?h.statSync(s).mtime.toISOString()>e.last_verified&&(r.push(`Exemplar modified since last verified: ${e.exemplar}`),n!=="broken"&&(n="stale")):(r.push(`Exemplar missing: ${e.exemplar}`),n="broken");}for(let s of e.steps){if(s.template_from){let o=x.join(t,s.template_from);h.existsSync(o)||(r.push(`Template file missing: ${s.template_from}`),n="broken");}if(s.action==="modify"&&s.target){let o=x.join(t,s.target);!s.target.includes("{")&&!h.existsSync(o)&&(r.push(`Modify target missing: ${s.target}`),n="broken");}}return {status:n,issues:r}}async function Ot(t){let e=await De(t),r=[],n=0,s=0,o=0;for(let a of e){let l=rs(t,a);if(a.status!==l.status){a.status=l.status;let u=a.id.replace(/^P-/,""),d=x.join(t,oe,`${u}.protocol`);h.existsSync(d)&&h.writeFileSync(d,N.dump(a,{lineWidth:-1,noRefs:true}),"utf8");}switch(l.status){case "current":n++;break;case "stale":s++;break;case "broken":o++;break}r.push({id:a.id,name:a.name,status:l.status,last_verified:a.last_verified,trigger:a.trigger,tags:a.tags});}let i={version:"1.0",generated:new Date().toISOString(),protocols:r,health:{total:e.length,current:n,stale:s,broken:o}},c=x.join(t,oe);if(e.length>0){h.existsSync(c)||h.mkdirSync(c,{recursive:true});let a=x.join(c,jt);h.writeFileSync(a,N.dump(i,{lineWidth:-1,noRefs:true}),"utf8");}return i}function $r(t,e,r){if(!e||e.length<2)return null;let n={};for(let s of e){let o=x.dirname(s);n[o]||(n[o]=[]),n[o].push(s);}for(let[s,o]of Object.entries(n)){if(o.length<2)continue;let i=x.join(t,s);if(!h.existsSync(i))continue;let a=h.readdirSync(i).filter(l=>{let u=x.extname(l);return [".ts",".tsx",".js",".jsx",".rs",".py"].includes(u)}).filter(l=>!o.some(u=>x.basename(u)===l));if(a.length>0){let l=x.join(s,a[0]),u=[...o.map(d=>({action:"create",target:d})),...r.map(d=>({action:"modify",target:d}))];return {hint:`This session created ${o.length} new files in ${s}/ following existing patterns. Consider recording a protocol.`,draft:{name:`Add a ${x.basename(s).replace(/s$/,"")}`,exemplar:l,steps:u}}}}return null}function os(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(e=>e.length>1).filter(e=>!is.has(e))}var is=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 as(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var Y="pack.yaml";var cs="PARADIGM_STRICT";function de(){let t=process.env[cs];if(t===void 0||t==="")return false;let e=t.toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}function ls(t){return h$1(t)}function $t(t,e){if(!h.existsSync(t))return {status:"missing"};let r;try{r=h.readFileSync(t,"utf-8");}catch{return Ue({status:"unparseable",errorClass:"other",detail:"file read error"},e)}let n;try{n=N.load(r);}catch(s){let{errorClass:o,detail:i}=ls(s);return Ue({status:"unparseable",errorClass:o,detail:i},e)}if(e?.schema){let s=e.schema.safeParse(n);if(!s.success){let o={status:"invalid",errorClass:"schema",detail:`schema validation failed (${s.error.issues.length} issue(s))`};return Ue(o,e)}return {status:"ok",data:s.data}}return {status:"ok",data:n}}function Ue(t,e){if(!(e?.strict??de())||t.status==="ok"||t.status==="missing")return t;throw new Error(`yaml load failed under PARADIGM_STRICT=1 (${t.errorClass}: ${t.detail})`)}b$1();var Mt=/^[a-z0-9][a-z0-9-]{0,63}$/,He=["track","index","chronological","featured"],ze=64,ds=z.object({id:z.string().regex(Mt,"invalid section id"),name:z.string().min(1).max(120),order:z.number().int().min(0).max(9999),style:z.enum(He,{errorMap:()=>({message:`section.style must be one of ${He.join("|")}`})}),description:z.string().max(1e3).optional(),default:z.boolean({invalid_type_error:"section.default must be a boolean"}).optional()}).strict(),We=z.array(ds).max(ze,`sections must contain \u2264${ze} entries`);z.object({sections:We.optional()}).passthrough();z.object({section:z.string().regex(Mt).optional(),order:z.number().int().min(0).max(9999).optional()}).passthrough();var Ut="@a-company/university",Ht=".paradigm/university",zt=".paradigm/cache/packs.json",j=class extends Error{constructor(r,n){super(`pack-load failed (${r}: ${n})`);this.errorClass=r;this.detail=n;this.name="PackLoadError";}},us=["id","name","version","schema_version","tenant_kind"],fs=new Set(["first-party","project","external"]),Dt={id:"main",name:"Curriculum",order:1,style:"track",default:true};function Ge(t){if(t==null)return [{...Dt}];if(Array.isArray(t)&&t.length===0)return [{...Dt}];let e=We.safeParse(t);if(!e.success){let o=e.error.issues[0],i=o?`${o.path.join(".")||"sections"}: ${o.message}`:"sections failed schema validation";throw new j("manifest-invalid",i)}let r=e.data.map(o=>({...o})),n=new Set;for(let o of r){if(n.has(o.id))throw new j("manifest-invalid",`duplicate section id "${o.id}"`);n.add(o.id);}r.length===1&&!r[0].default&&(r[0]={...r[0],default:true});let s=r.filter(o=>o.default===true);if(s.length>1)throw new j("manifest-invalid",`at most one section may set default: true (found ${s.length})`);return r.sort((o,i)=>o.order-i.order||o.id.localeCompare(i.id)),r}function ue(t){let e=x.join(t,Y),r=$t(e);switch(r.status){case "missing":throw new j("missing-manifest",`no ${Y} at pack root`);case "unparseable":throw new j("manifest-unparseable",r.detail);case "invalid":throw new j("manifest-invalid",r.detail);case "ok":{let n=r.data;if(!n||typeof n!="object")throw new j("manifest-invalid","manifest is not an object");for(let s of us){let o=n[s];if(o==null||o==="")throw new j("missing-required-field",`required field ${String(s)} is missing or empty`)}if(!fs.has(String(n.tenant_kind)))throw new j("missing-required-field","tenant_kind must be one of first-party|project|external");return n.sections=Ge(n.sections),n}}}function Wt(t){let e=gs(t);if(e)return e;let r=[],n=x.join(t,"node_modules",Ut);if(h.existsSync(x.join(n,Y)))try{let o=ue(n);r.push({manifest:o,rootDir:n,source:"first-party"});}catch(o){a$1.component("#pack-loader").warn("first-party pack manifest invalid",{errorClass:o instanceof j?o.errorClass:"other"});}for(let o of ps(t))try{let i=ue(o);r.push({manifest:i,rootDir:o,source:"npm"});}catch(i){a$1.component("#pack-loader").warn("npm pack manifest invalid",{errorClass:i instanceof j?i.errorClass:"other"});}let s=x.join(t,Ht);if(h.existsSync(s)&&h.statSync(s).isDirectory()){let o=x.join(s,Y),i;if(h.existsSync(o))try{i=ue(s),r.push({manifest:i,rootDir:s,source:"local"});}catch(a){a$1.component("#pack-loader").warn("local pack manifest invalid",{errorClass:a instanceof j?a.errorClass:"other"});}let c=i?.id??"project";for(let a of ms(s))try{let l=ue(a);r.push({manifest:l,rootDir:a,source:"local",parentPackId:c});}catch(l){a$1.component("#pack-loader").warn("discipline sub-pack manifest invalid",{errorClass:l instanceof j?l.errorClass:"other"});}}return hs(t,r),r}function ps(t){let e=x.join(t,"package.json");if(!h.existsSync(e))return [];let r;try{r=JSON.parse(h.readFileSync(e,"utf8"));}catch{return []}let n=new Set([...Object.keys(r.dependencies||{}),...Object.keys(r.devDependencies||{}),...Object.keys(r.peerDependencies||{})]);if(n.size===0)return [];let s=x.join(t,"node_modules");if(!h.existsSync(s))return [];let o=[];for(let i of n){if(i===Ut)continue;let c=x.join(s,i,"package.json");if(!h.existsSync(c))continue;let a;try{a=JSON.parse(h.readFileSync(c,"utf8"));}catch{continue}let l=a.paradigm?.universityPack;if(typeof l!="string"||l.length===0)continue;let u=x.resolve(x.dirname(c),l);h.existsSync(x.join(u,Y))&&o.push(u);}return o}function ms(t){let e=[],r;try{r=h.readdirSync(t,{withFileTypes:!0});}catch{return e}for(let n of r){if(!n.isDirectory()||n.name.startsWith("."))continue;let s=x.join(t,n.name);h.existsSync(x.join(s,Y))&&e.push(s);}return e}function Qr(t,e){if(typeof t!="string"||t.length===0)throw new Error("resolveEntryAddress: address must be a non-empty string");let r=t.indexOf(":");if(r!==-1){let s=t.slice(0,r),o=t.slice(r+1);if(!s||!o)throw new Error("resolveEntryAddress: malformed <pack-id>:<entry-id> address");return {packId:s,entryId:o}}let n=t;if(e.candidatePacks&&e.entryExistsIn){let s=e.candidatePacks.filter(o=>e.entryExistsIn(o,n));if(s.length>1){let o=s.map(i=>`${i}:${n}`).join(", ");throw new Error(`resolveEntryAddress: bare entry id "${n}" is ambiguous across packs. Candidates: ${o}`)}if(s.length===1)return {packId:s[0],entryId:n}}return {packId:e.activePack,entryId:n}}function Gt(t){try{return h.statSync(x.join(t,"node_modules")).mtime.getTime()}catch{return}}function Xt(t){try{return h.statSync(x.join(t,Ht)).mtime.getTime()}catch{return}}function gs(t){let e=x.join(t,zt);if(!h.existsSync(e))return null;let r;try{r=JSON.parse(h.readFileSync(e,"utf8"));}catch{return null}if(r.version!==1||!Array.isArray(r.packs))return null;let n=Gt(t),s=Xt(t);return r.node_modules_mtime_ms!==n||r.local_university_mtime_ms!==s?null:r.packs.map(o=>({manifest:o.manifest,rootDir:o.rootDir,source:o.source,...o.parentPackId?{parentPackId:o.parentPackId}:{}}))}function hs(t,e){let r=x.join(t,zt);try{h.mkdirSync(x.dirname(r),{recursive:!0});let n={version:1,node_modules_mtime_ms:Gt(t),local_university_mtime_ms:Xt(t),packs:e.map(s=>({manifest:s.manifest,rootDir:s.rootDir,source:s.source,...s.parentPackId?{parentPackId:s.parentPackId}:{}}))};h.writeFileSync(r,JSON.stringify(n,null,2),"utf8");}catch{}}b$1();var ie=".paradigm/university",ne="content",Be="notes",Ee="policies",Te="quizzes",_e="paths",Bt="diplomas",qt="index.yaml",ys="config.yaml";function qe(t){let e=x.join(t,ie);if(h.existsSync(e))return e;try{let n=Wt(t).find(s=>s.manifest.tenant_kind==="first-party");if(n)return n.rootDir}catch{}return e}function Ve(t){if(!h.existsSync(t))return null;let e=x.join(t,Y);if(h.existsSync(e))try{return ue(t)}catch(n){a$1.component("#university-loader").warn("pack manifest invalid, using implicit manifest",{errorClass:n instanceof j?n.errorClass:"other"});}let r=x.basename(t)||"project";return {id:r,name:r,version:"0.0.0",schema_version:"1",tenant_kind:"project",description:"Implicit project pack (pack.yaml not present \u2014 v5 layout)",origin_hint:"authored",sections:Ge(void 0)}}function Ss(t,e,r){return e?{...t,...t.pack_id?{}:{pack_id:e.id},...t.discipline||!r?{}:{discipline:r}}:t}var Vt={name:"Project University",tagline:"Learn the codebase",institution:"Paradigm"},Yt={primary:"#6366f1",secondary:"#8b5cf6",accent:"#f59e0b",background:"#0f172a",surface:"#1e293b",text:"#f8fafc",textMuted:"#94a3b8",success:"#22c55e",error:"#ef4444",font:"Inter, system-ui, sans-serif"},Xe={branding:Vt,theme:Yt,content:{categories:[],defaultDifficulty:"beginner",requireApproval:false},diplomas:{includeGlobalPLSAT:true,customCertStyle:null}};function Ye(t){let e=x.join(t,ie,ys);if(!h.existsSync(e))return {...Xe};try{let r=h.readFileSync(e,"utf8"),n=N.load(r);return n?{branding:{...Vt,...n.branding||{}},theme:{...Yt,...n.theme||{}},content:{categories:n.content?.categories||[],defaultDifficulty:n.content?.defaultDifficulty||"beginner",requireApproval:n.content?.requireApproval??!1,defaultCategory:n.content?.defaultCategory},diplomas:{includeGlobalPLSAT:n.diplomas?.includeGlobalPLSAT??!0,customCertStyle:n.diplomas?.customCertStyle??null}}:{...Xe}}catch{return {...Xe}}}function ve(t){let e=x.join(t,ie,qt);if(!h.existsSync(e))return null;try{let r=h.readFileSync(e,"utf8");return N.load(r)}catch{return null}}function Jt(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:N.load(e[1]),body:e[2].trim()}}catch{return null}}function ws(t,e){return `---
107
- ${N.dump(t,{lineWidth:-1,noRefs:true,sortKeys:false})}---
108
-
109
- ${e}
110
- `}function so(t,e,r){let n=Ke(t,e,".md",r);if(!n)return null;try{let s=h.readFileSync(n,"utf8"),o=Jt(s);if(!o)return null;let i=o.frontmatter;return {frontmatter:_s(i),body:o.body}}catch{return null}}function ro(t,e,r,n){let s=e.type==="policy"?Ee:Be,o=n??qe(t),i=x.join(o,ne,s);h.mkdirSync(i,{recursive:true});let c=Ve(o),a=Ss(e,c),l=x.join(i,`${a.id}.md`),u=ws(a,r);return h.writeFileSync(l,u,"utf8"),l}function bs(t,e,r){let n=Ke(t,e,".yaml",r);if(!n)return null;try{let s=h.readFileSync(n,"utf8"),o=N.load(s);return !o||!o.id?null:vs(o)}catch{return null}}function oo(t,e,r){let n=r??qe(t),s=x.join(n,ne,Te);h.mkdirSync(s,{recursive:true});let o=Ve(n),i={...e,...e.pack_id||!o?{}:{pack_id:o.id}},c=x.join(s,`${i.id}.yaml`);return h.writeFileSync(c,N.dump(i,{lineWidth:-1,noRefs:true}),"utf8"),c}function Kt(t,e,r){let n=Ke(t,e,".yaml",r);if(!n)return null;try{let s=h.readFileSync(n,"utf8"),o=N.load(s);return !o||!o.id?null:o}catch{return null}}function io(t,e,r){let n=r??qe(t),s=x.join(n,ne,_e);h.mkdirSync(s,{recursive:true});let o=x.join(s,`${e.id}.yaml`);return h.writeFileSync(o,N.dump(e,{lineWidth:-1,noRefs:true}),"utf8"),o}function Qt(t,e){let r=x.join(t,ie,Bt);if(!h.existsSync(r))return [];let n=[];try{let s=h.readdirSync(r).filter(o=>o.endsWith(".yaml"));for(let o of s)try{let i=h.readFileSync(x.join(r,o),"utf8"),c=N.load(i);if(!c||!c.id||e?.student&&c.student!==e.student||e?.type&&c.type!==e.type)continue;n.push(c);}catch{}}catch{}return n.sort((s,o)=>o.earnedAt.localeCompare(s.earnedAt))}function ao(t,e){let r=ve(t);if(!r)return [];let n=[...r.entries];if(e.type&&(n=n.filter(o=>o.type===e.type)),e.tag&&(n=n.filter(o=>o.tags.some(i=>i.startsWith(e.tag)))),e.difficulty&&(n=n.filter(o=>o.difficulty===e.difficulty)),e.symbol&&(n=n.filter(o=>o.symbols.some(i=>i===e.symbol))),e.author&&(n=n.filter(o=>o.author===e.author)),e.query){let o=e.query.toLowerCase();n=n.filter(i=>i.title.toLowerCase().includes(o)||i.id.toLowerCase().includes(o)||i.tags.some(c=>c.toLowerCase().includes(o)));}if(e.category&&(n=n.filter(o=>o.category===e.category)),e.section&&(n=n.filter(o=>o.section===e.section)),e.track){let o=Ye(t),i=new Map;for(let c of o.content.categories)i.set(c.id,c.track||"core");n=n.filter(c=>(c.category&&i.get(c.category)||"core")===e.track);}let s=e.limit||20;return n.slice(0,s)}function Je(t){let e=x.join(t,ie),r=x.join(e,ne),n=[];for(let u of [Be,Ee]){let d=x.join(r,u);if(h.existsSync(d))try{for(let f of h.readdirSync(d).filter(g=>g.endsWith(".md")))try{let g=h.readFileSync(x.join(d,f),"utf8"),p=Jt(g);if(!p)continue;let m=p.frontmatter;n.push({id:m.id||f.replace(".md",""),title:m.title||f,type:m.type||(u===Ee?"policy":"note"),author:m.author||"unknown",created:m.created||"",updated:m.updated||"",tags:Array.isArray(m.tags)?m.tags:[],symbols:Array.isArray(m.symbols)?m.symbols:[],difficulty:m.difficulty||"beginner",file:`${ne}/${u}/${f}`,...m.category?{category:m.category}:{},...typeof m.section=="string"&&m.section?{section:m.section}:{},...typeof m.order=="number"&&Number.isFinite(m.order)?{order:m.order}:{}});}catch{}}catch{}}let s=x.join(r,Te);if(h.existsSync(s))try{for(let u of h.readdirSync(s).filter(d=>d.endsWith(".yaml")))try{let d=h.readFileSync(x.join(s,u),"utf8"),f=N.load(d);if(!f||!f.id)continue;n.push({id:f.id,title:f.title||u,type:"quiz",author:f.author||"unknown",created:f.created||"",updated:f.updated||"",tags:f.tags||[],symbols:f.symbols||[],difficulty:f.difficulty||"beginner",file:`${ne}/${Te}/${u}`,...f.category?{category:f.category}:{},...typeof f.section=="string"&&f.section?{section:f.section}:{},...typeof f.order=="number"&&Number.isFinite(f.order)?{order:f.order}:{}});}catch{}}catch{}let o=x.join(r,_e);if(h.existsSync(o))try{for(let u of h.readdirSync(o).filter(d=>d.endsWith(".yaml")))try{let d=h.readFileSync(x.join(o,u),"utf8"),f=N.load(d);if(!f||!f.id)continue;n.push({id:f.id,title:f.title||u,type:"path",author:f.author||"unknown",created:f.created||"",updated:f.updated||"",tags:f.tags||[],symbols:[],file:`${ne}/${_e}/${u}`,...f.category?{category:f.category}:{},...typeof f.section=="string"&&f.section?{section:f.section}:{},...typeof f.order=="number"&&Number.isFinite(f.order)?{order:f.order}:{}});}catch{}}catch{}let i=0,c=x.join(e,Bt);if(h.existsSync(c))try{i=h.readdirSync(c).filter(u=>u.endsWith(".yaml")).length;}catch{}let a={version:"1.0",generatedAt:new Date().toISOString(),totalContent:n.length,entries:n,diplomaCount:i};h.mkdirSync(e,{recursive:true});let l=x.join(e,qt);return h.writeFileSync(l,N.dump(a,{lineWidth:-1,noRefs:true}),"utf8"),a}function co(t,e){let r=ve(t)||Je(t),n=[],s=r.entries;e?.id&&(s=s.filter(l=>l.id===e.id));let o=null;e?.deep&&(o=Zt(t));let i=new Set(r.entries.map(l=>l.id));for(let l of s){if(l.title||n.push({contentId:l.id,severity:"error",check:"missing-title",message:"Content is missing a title",fix:"Add a title field to the content frontmatter"}),l.type==="quiz"&&xs(t,l.id,n),l.type==="path"&&Es(t,l.id,i,n),o&&l.symbols.length>0){Ye(t).content.categories.find(g=>g.id===l.category)?.validationStrictness==="relaxed";for(let g of l.symbols)o.has(g)||n.push({contentId:l.id,severity:"warning",check:"broken-symbol-ref",message:`Symbol "${g}" not found in scan-index`,fix:`Remove or update the symbol reference in ${l.id}`});}e?.deep&&l.symbols.length>0&&l.updated&&Rs(t,l,n);}Ts(t,r,n);let c=Qt(t);for(let l of c)if(l.total>0&&l.percentage!==Math.round(l.score/l.total*1e4)/100){let u=Math.round(l.score/l.total*1e4)/100;Math.abs(l.percentage-u)>.1&&n.push({contentId:l.id,severity:"warning",check:"diploma-score-mismatch",message:`Diploma percentage ${l.percentage} doesn't match score ${l.score}/${l.total} (expected ${u})`});}let a=ks(t,r);return {status:n.some(l=>l.severity==="error")?"errors":n.length>0?"warnings":"healthy",totalContent:r.totalContent,checked:s.length,issues:n,symbolCoverage:a}}function xs(t,e,r){let n=bs(t,e);if(!n){r.push({contentId:e,severity:"error",check:"unreadable-quiz",message:"Quiz file could not be parsed"});return}(!n.passThreshold||n.passThreshold<0||n.passThreshold>1)&&r.push({contentId:e,severity:"warning",check:"invalid-pass-threshold",message:`passThreshold should be between 0 and 1, got ${n.passThreshold}`,fix:"Set passThreshold to a value between 0.0 and 1.0"});for(let s of n.questions){if(!s.choices||typeof s.choices!="object"){r.push({contentId:e,severity:"error",check:"invalid-quiz-choices",message:`Question ${s.id} has no choices defined`});continue}(!s.correct||!(s.correct in s.choices))&&r.push({contentId:e,severity:"error",check:"invalid-quiz-answer",message:`Question ${s.id}: correct answer "${s.correct}" not found in choices [${Object.keys(s.choices).join(", ")}]`,fix:`Set correct to one of: ${Object.keys(s.choices).join(", ")}`});}}function Es(t,e,r,n){let s=Kt(t,e);if(!s){n.push({contentId:e,severity:"error",check:"unreadable-path",message:"Learning path file could not be parsed"});return}for(let o of s.steps)o.content.startsWith("plsat:")||r.has(o.content)||n.push({contentId:e,severity:"error",check:"broken-path-step",message:`Learning path step references "${o.content}" which doesn't exist`,fix:`Create content with id "${o.content}" or remove this step`});}function Ts(t,e,r){let n=x.join(t,ie),s=Ve(n);if(!s||!s.sections||s.sections.length===0)return;let o=new Set(s.sections.map(a=>a.id)),i=s.sections.find(a=>a.default===true);for(let a of e.entries)a.section&&!o.has(a.section)&&r.push({contentId:a.id,severity:"warning",check:"dangling-section-ref",message:`Entry references section "${a.section}" which is not declared in pack.yaml`,fix:`Add a section with id "${a.section}" to pack.yaml, or remove the section field`});let c=new Map;for(let a of s.sections)c.set(a.id,0);for(let a of e.entries)a.section&&o.has(a.section)?c.set(a.section,(c.get(a.section)||0)+1):!a.section&&i&&c.set(i.id,(c.get(i.id)||0)+1);for(let a of s.sections)(c.get(a.id)||0)===0&&r.push({contentId:a.id,severity:"warning",check:"empty-section",message:`Section "${a.id}" has zero entries`,fix:`Add at least one entry with section: "${a.id}", or remove the section from pack.yaml`});}function lo(t,e){let r=ve(t);if(!r)return [];let n=[];for(let s of r.entries)if(s.symbols.includes(e)){let o=en(t,s,e);n.push({id:s.id,title:s.title,type:s.type,stale:o});}return n}function uo(t,e){let r=ve(t);if(!r)return {paths:[],suggestedContent:[],extracurricular:[],diplomaCount:0,totalContent:0};let n=Ye(t),s=new Set;for(let f of n.content.categories)f.excludeFromOnboarding&&s.add(f.id);let o=r.entries.filter(f=>!f.category||!s.has(f.category)),i=r.entries.filter(f=>f.category&&s.has(f.category)),c=o.filter(f=>f.type==="path"),a=e?Qt(t,{student:e}):[],l=new Set(a.map(f=>f.source)),u=c.map(f=>{let g=Kt(t,f.id);return {id:f.id,title:f.title,steps:g?.steps.length||0,completed:l.has(f.id)}}),d=o.filter(f=>f.type!=="path"&&(f.difficulty==="beginner"||f.tags.includes("onboarding"))).slice(0,10);return {paths:u,suggestedContent:d,extracurricular:i,diplomaCount:a.length,totalContent:r.totalContent}}function Ke(t,e,r,n){let s=n??x.join(t,ie),o=x.join(s,ne);for(let i of [Be,Ee,Te,_e]){let c=x.join(o,i,`${e}${r}`);if(h.existsSync(c))return c}return null}function _s(t){return {id:t.id||"",title:t.title||"",type:t.type||"note",author:t.author||"unknown",created:t.created||"",updated:t.updated||"",tags:Array.isArray(t.tags)?t.tags:[],symbols:Array.isArray(t.symbols)?t.symbols:[],difficulty:t.difficulty||"beginner",estimatedMinutes:t.estimatedMinutes,prerequisites:Array.isArray(t.prerequisites)?t.prerequisites:[],...t.category?{category:t.category}:{},...t.origin?{origin:t.origin}:{},...t.source?{source:t.source}:{},...t.pack_id?{pack_id:t.pack_id}:{},...t.discipline?{discipline:t.discipline}:{},...t.section?{section:t.section}:{},...typeof t.order=="number"?{order:t.order}:{}}}function vs(t){return {...t,tags:t.tags||[],symbols:t.symbols||[],difficulty:t.difficulty||"beginner",passThreshold:t.passThreshold??.7,questions:t.questions||[]}}function Zt(t){let e=new Set,r=x.join(t,".paradigm","scan-index.json");if(!h.existsSync(r))return e;try{let n=h.readFileSync(r,"utf8"),s=JSON.parse(n);if(s.symbols&&Array.isArray(s.symbols))for(let o of s.symbols)o.symbol&&e.add(o.symbol);}catch{}return e}function ks(t,e){let r=Zt(t),n=new Set;for(let o of e.entries)for(let i of o.symbols)r.has(i)&&n.add(i);let s=r.size;return {totalSymbols:s,coveredByContent:n.size,percentage:s>0?Math.round(n.size/s*100):0}}function en(t,e,r){if(!e.updated)return false;let n=new Date(e.updated).getTime();if(isNaN(n))return false;let s=x.join(t,".paradigm","scan-index.json");if(!h.existsSync(s))return false;try{let o=h.readFileSync(s,"utf8"),i=JSON.parse(o);if(i.symbols&&Array.isArray(i.symbols)){for(let c of i.symbols)if(c.symbol===r&&c.filePath){let a=x.join(t,c.filePath);if(h.existsSync(a)&&h.statSync(a).mtime.getTime()>n)return !0}}}catch{}return false}function Rs(t,e,r){for(let n of e.symbols)if(en(t,e,n)){r.push({contentId:e.id,severity:"warning",check:"stale-content",message:`Content may be stale: symbol "${n}" was updated after content was last modified`,fix:`Review and update ${e.id} to reflect changes to ${n}`});break}}var tn=new Set(["duplicate-key-detected"]);function Is(t){let e=t.trim();if(e.includes("/")||e.includes("\\")){let r=e.split(/[/\\]/);e=r[r.length-1]||"unknown";}return e.length>40&&(e=e.slice(0,40)),e||"unknown"}var ke=class{transforms=new Map;record(e,r,n=1){let s=Is(r),o=`${e}::${s}`,i=this.transforms.get(o);i?i.count+=n:this.transforms.set(o,{kind:e,surface:s,count:n});}report(){let e=Array.from(this.transforms.values()).sort((n,s)=>n.kind!==s.kind?n.kind.localeCompare(s.kind):n.surface.localeCompare(s.surface)),r=e.filter(n=>tn.has(n.kind)).reduce((n,s)=>n+s.count,0);return {reindex_ts:new Date().toISOString(),transformations:e,lossy_count:r,strict_mode:de()}}hasLossy(){for(let e of this.transforms.values())if(tn.has(e.kind))return true;return false}totalCount(){let e=0;for(let r of this.transforms.values())e+=r.count;return e}};b$1();var Ps={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},Cs={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/"]},As={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"]},Qe={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 Co(){return [{name:"paradigm_reindex",description:"Rebuild scan-index.json, navigator.yaml, and flow-index.json from .purpose files. Call after modifying paradigm files or at the end of a work session to ensure static index files are fresh. Returns counts of indexed symbols, files processed, and any errors. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:false,destructiveHint:true},aliases:["rebuild","refresh","rescan","regenerate index","update index"]}]}async function Ao(t,e,r,n){if(t!=="paradigm_reindex")return {handled:false,text:""};try{let s=await Ls(r.rootDir,r);await n(),pt.clear(),gt();let o=(s.integrityReport?.brokenReferences?.length||0)+(s.integrityReport?.duplicateSymbols?.length||0)+(s.componentAnchorIssues||0)+(s.crossFileIssues||0),i={success:!0,symbolCount:s.symbolCount,breakdown:s.breakdown,flowCount:s.flowCount,filesWritten:s.filesWritten.length,...s.aspectGraphStats?{aspects:s.aspectGraphStats.aspects,loreLinks:s.aspectGraphStats.loreLinks}:{},...s.protocolHealth?{protocols:s.protocolHealth.total,staleProtocols:s.protocolHealth.stale}:{},...o>0?{issues:o}:{}};s.consistency&&(i.consistency=s.consistency);let c=JSON.stringify(i,null,2);return Ae(c.length,t),{handled:!0,text:c}}catch(s){let o=JSON.stringify({error:s.message},null,2);return Ae(o.length,t),{handled:true,text:o}}}async function Ls(t,e){let r=[],n=new ke,s;e?s=e.aggregation:s=await i(t);let o=e?.projectName||x.basename(t),i$1=x.join(t,".paradigm");h.existsSync(i$1)||h.mkdirSync(i$1,{recursive:true}),js(t,n),Os(s.purposeFiles,n);let c=Pe({symbols:s.symbols,purposeFiles:s.purposeFiles,portalFiles:s.portalFiles},{projectName:o}),a=x.join(i$1,"scan-index.json");h.writeFileSync(a,Ce(c),"utf8"),r.push(".paradigm/scan-index.json");let l=Fs(t,s),u=x.join(i$1,"navigator.yaml");h.writeFileSync(u,N.dump(l,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),r.push(".paradigm/navigator.yaml");let d=Hs(t,s.purposeFiles),f$1=0;if(d&&Object.keys(d.flows).length>0){let S=x.join(i$1,"flow-index.json");h.writeFileSync(S,JSON.stringify(d,null,2),"utf8"),r.push(".paradigm/flow-index.json"),f$1=Object.keys(d.flows).length;}let g;try{let S=await kt(t);It(S,s.symbols,t);let I=await Ct(S,t),K=await At(S,t),Q=S.exec("SELECT COUNT(*) FROM aspects")[0]?.values[0]?.[0]??0,ae=S.exec("SELECT COUNT(*) FROM anchors")[0]?.values[0]?.[0]??0,he=S.exec("SELECT COUNT(*) FROM edges")[0]?.values[0]?.[0]??0;Rt(S,t),r.push(".paradigm/aspect-graph.db"),g={aspects:Q,anchors:ae,edges:he,loreLinks:I};}catch{}let p=0;try{let S=await ge(t);p=Object.keys(S.personas).length,p>0&&r.push(".paradigm/personas/index.yaml");}catch{}let m;try{let S=await Ot(t);S.health.total>0&&(m=S.health,r.push(".paradigm/protocols/index.yaml"));}catch{}let y;try{let S=x.join(t,".paradigm","university");if(h.existsSync(S)){let I=Je(t);(I.totalContent>0||I.diplomaCount>0)&&(y={totalContent:I.totalContent,diplomaCount:I.diplomaCount},r.push(".paradigm/university/index.yaml"));}}catch{}let w;try{w=a$2(s,t);}catch{}let P;try{let S=b$4(s.symbols,t),I=S.missing+S.outOfBounds;I>0&&(P=I);}catch{}let $;try{$=c$2(s.purposeFiles,t);}catch{}let J;try{let S=[];for(let I of s.purposeFiles){let K=a$3(I);K.data&&S.push({filePath:I,data:K.data});}if(S.length>0){let K=f(S).issues.length;K>0&&(J=K);}}catch{}let se={};for(let S of s.symbols)se[S.type]=(se[S.type]||0)+1;let _={};for(let S of s.symbols)S.type==="component"&&S.componentType&&(_[S.componentType]=(_[S.componentType]||0)+1);let E=n.report();try{let S=x.join(i$1,"manifest.consistency.json");h.writeFileSync(S,JSON.stringify(E,null,2),"utf-8"),r.push(".paradigm/manifest.consistency.json");}catch{a$1.component("#reindex").warn("failed to write consistency manifest",{stage:"manifest-write"});}if(de()&&n.hasLossy())throw new Error(`reindex aborted: ${E.lossy_count} lossy transformation(s) detected under PARADIGM_STRICT=1. See .paradigm/manifest.consistency.json.`);return {action:"reindex",filesWritten:r,symbolCount:s.symbols.length,breakdown:se,flowCount:f$1,aspectGraphStats:g,personaCount:p,protocolHealth:m,consistency:E,...Object.keys(_).length>0?{componentTypeBreakdown:_}:{},...y?{universityStats:y}:{},...w?{integrityReport:w}:{},...P!==void 0?{componentAnchorIssues:P}:{},...$?{purposeHealth:$}:{},...J!==void 0?{crossFileIssues:J}:{}}}function js(t,e){let r=x.join(t,"portal.yaml");if(!h.existsSync(r))return;let n;try{n=h.readFileSync(r,"utf-8");}catch{return}try{N.load(n);}catch(a){(a?.reason?.toLowerCase()||"").includes("duplicate")&&e.record("duplicate-key-detected","portal.yaml");return}let s;try{s=N.load(n,{schema:N.FAILSAFE_SCHEMA});}catch{return}if(!s||typeof s!="object")return;let o=s,i=o.gates;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=0;for(let l of Object.keys(i))l.startsWith("^")&&a++;a>0&&e.record("prefix-stripped","portal.yaml",a);}else Array.isArray(i)&&i.length>0&&e.record("array-coerced","portal.yaml");let c=o.routes;Array.isArray(c)&&c.length>0&&e.record("array-coerced","portal.yaml"),o.version||e.record("default-applied","portal.yaml");}function Os(t,e){for(let r of t){let n;try{n=h.readFileSync(r,"utf-8");}catch{continue}try{N.load(n);}catch(u){(u?.reason?.toLowerCase()||"").includes("duplicate")&&e.record("duplicate-key-detected","purpose.yaml");continue}let s;try{s=N.load(n,{schema:N.FAILSAFE_SCHEMA});}catch{continue}if(!s||typeof s!="object")continue;let o=s,i=["components","features","gates","signals","aspects","states"],c=0;for(let u of i)Array.isArray(o[u])&&c++;c>0&&e.record("array-coerced","purpose.yaml",c);let a=(u,d)=>{if(!u||typeof u!="object"||Array.isArray(u))return 0;let f=0;for(let g of Object.keys(u))g.startsWith(d)&&f++;return f},l=a(o.gates,"^")+a(o.signals,"!")+a(o.aspects,"~")+a(o.components,"#")+a(o.features,"#");l>0&&e.record("prefix-stripped","purpose.yaml",l);}}function Fs(t,e){let r={};for(let n of e.symbols)if(n.type==="component"&&n.componentType){let s=n.componentType;r[s]||(r[s]=[]),r[s].push(n.symbol);}return {version:"1.0",generated:new Date().toISOString(),structure:Ns(t),key_files:$s(t),skip_patterns:Ms(t),symbols:Us(e.symbols,e.purposeFiles),...Object.keys(r).length>0?{symbolsByComponentType:r}:{}}}function Ns(t){let e={};for(let[r,n]of Object.entries(Cs)){let s=n.filter(o=>h.existsSync(x.join(t,o)));if(s.length>0){let o=Object.values(Ps).find(i=>i.category===r);e[r]={paths:s,symbol:o?.prefix||"@"};}}return e}function $s(t){let e={};for(let[r,n]of Object.entries(As)){let s=n.filter(o=>h.existsSync(x.join(t,o)));s.length>0&&(e[r]=s);}return e.config||(e.config=[]),e.entry||(e.entry=[]),e.types||(e.types=[]),e}function Ms(t){let e={always:[...Qe.always],unless_testing:[...Qe.unless_testing],unless_docs:[...Qe.unless_docs]},r=x.join(t,".gitignore");if(h.existsSync(r))try{let s=h.readFileSync(r,"utf8").split(`
111
- `).map(o=>o.trim()).filter(o=>o&&!o.startsWith("#")).filter(o=>o.endsWith("/")||o.includes("*")||["node_modules","dist","build",".cache"].some(i=>o.includes(i))).slice(0,20);for(let o of s)e.always.includes(o)||e.always.push(o);}catch{}return e}function Ds(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 Us(t,e,r){let n={};for(let s of t){let i=`${Ds(s.type)}${s.id}`;if(s.filePath)n[i]=s.filePath;else {let c=e.find(a=>x.dirname(a).toLowerCase().includes(s.id.toLowerCase()));c&&(n[i]=x.dirname(c)+"/");}}return n}function Hs(t,e){let r={},n={};for(let s of e)try{let o=h.readFileSync(s,"utf8"),i=N.load(o);if(!i?.flows)continue;if(Array.isArray(i.flows))for(let c of i.flows){let a=c;if(!a.name)continue;let l=`$${a.name}`,u=nn(a.steps);u.length>0&&(r[l]={id:l,description:a.description||"",steps:u,definedIn:x.relative(t,s)},sn(l,u,n));}else for(let[c,a]of Object.entries(i.flows)){let l=c.startsWith("$")?c:`$${c}`,u=nn(a.steps);u.length>0&&(r[l]={id:l,description:a.description||"",trigger:a.trigger,steps:u,validation:a.validation,definedIn:x.relative(t,s)},sn(l,u,n));}}catch{}return Object.keys(r).length===0?null:{version:"1.0",generatedAt:new Date().toISOString(),flows:r,symbolToFlows:n}}function nn(t){if(!t||!Array.isArray(t))return [];let e=[];for(let r=0;r<t.length;r++){let n=t[r];if(typeof n=="object"&&n!==null){let s=n,o=s.action||s.description||s.component||"";o&&e.push({id:s.id||`step-${r+1}`,action:o,symbol:s.symbol||s.component,expect:s.expect});}}return e}function sn(t,e,r){for(let n of e)n.symbol&&(r[n.symbol]||(r[n.symbol]=[]),r[n.symbol].includes(t)||r[n.symbol].push(t));}export{Sr as $,so as A,ro as B,bs as C,oo as D,Kt as E,io as F,ao as G,Je as H,co as I,lo as J,uo as K,De as L,ss as M,jr as N,Or as O,Fr as P,Nr as Q,rs as R,$r as S,kt as T,Rt as U,fr as V,pr as W,mr as X,gr as Y,hr as Z,yr as _,Ae as a,wr as aa,Ks as b,Er as ba,Qs as c,Co as ca,Zs as d,Ao as da,er as e,Ls as ea,tr as f,mt as g,pt as h,pe as i,me as j,_r as k,Lt as l,vr as m,kr as n,Rr as o,Ir as p,Pr as q,Cr as r,Ar as s,de as t,$t as u,Wt as v,Qr as w,qe as x,Ve as y,Ye as z};
@@ -1,12 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a as a$1,j}from'./chunk-ERO4MJSH.js';import {d,b,a,c}from'./chunk-P344HV6Z.js';import'./chunk-5TAVYPOV.js';import t from'chalk';async function w(o){let s=process.cwd();if(!d(o)){let n=b(s);if(o.json){console.log(JSON.stringify({packs:n},null,2));return}if(n.length===0){console.log(t.yellow(`
3
- No content packs discovered.`)),console.log(t.gray(` Scaffold one with: paradigm university init
4
- `));return}console.log(t.blue(`
5
- Content packs (${n.length})
6
- `));for(let e of n){let r=e.tenantKind==="first-party"?t.cyan("first-party"):e.tenantKind==="project"?t.green("project"):t.yellow("external"),a$1=e.disciplines&&e.disciplines.length>0?t.gray(` [${e.disciplines.join(", ")}]`):"",d=a(e.packRoot),k=d.length>0?t.gray(` (${d.length} section${d.length===1?"":"s"})`):"";console.log(` ${t.white(e.id.padEnd(28))} ${r} ${e.entryCount} entries${k}${a$1}`),e.name&&e.name!==e.id&&console.log(t.gray(` ${e.name}`));}console.log(t.gray(`
7
- Tip: paradigm university list --project (list entries in project pack)`)),console.log("");return}let g=c(s,o),l=g.subPackId??g.packId,i=a$1(s);if(!i||i.totalContent===0){console.log(t.yellow(`
8
- No content found in pack "${l}".`)),console.log(t.gray(` Create content with: paradigm university add note --title "My Note"
9
- `));return}let c$1=j(s,{type:o.type,tag:o.tag,difficulty:o.difficulty,symbol:o.symbol,section:o.section,limit:o.limit?parseInt(o.limit,10):20});if(o.json){console.log(JSON.stringify({pack:l,results:c$1},null,2));return}console.log(t.blue(`
10
- University Content \u2014 pack: ${l} (${c$1.length} of ${i.totalContent})
11
- `));let h={note:"N",policy:"P",guide:"N",runbook:"N",quiz:"Q",path:"LP"};for(let n of c$1){let e=h[n.type]||"?",r=n.difficulty==="advanced"?t.red:n.difficulty==="intermediate"?t.yellow:t.green,a=n.tags.length>0?t.gray(` [${n.tags.join(", ")}]`):"";console.log(` ${t.cyan(e)} ${t.white(`${l}:${n.id}`)} \u2014 ${n.title}${a}`),n.difficulty&&console.log(` ${r(n.difficulty)} \xB7 ${n.author} \xB7 ${n.updated||n.created}`);}i.diplomaCount>0&&console.log(t.gray(`
12
- ${i.diplomaCount} diploma${i.diplomaCount>1?"s":""} earned`)),console.log();}export{w as universityListCommand};
@@ -1,10 +0,0 @@
1
- #!/usr/bin/env node
2
- import {c as c$1,h}from'./chunk-ERO4MJSH.js';import {c}from'./chunk-P344HV6Z.js';import'./chunk-5TAVYPOV.js';import o from'chalk';import*as q from'readline';import {execSync}from'child_process';import*as S from'os';function x(){try{return execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").slice(0,20)||"unknown"}catch{try{return S.userInfo().username}catch{return "unknown"}}}function P(e,n){return new Promise(r=>e.question(n,r))}function v(e){let n=e.indexOf(":");return n===-1?{entryId:e}:{packId:e.slice(0,n),entryId:e.slice(n+1)}}async function T(e,n={}){let r=process.cwd(),{packId:g,entryId:D}=v(e),d={...n};g&&(d.pack=g),c(r,d);let t=c$1(r,D);if(t||(console.error(o.red(`
3
- Quiz "${e}" not found
4
- `)),process.exit(1)),t.questions.length===0){console.log(o.yellow(`
5
- Quiz "${e}" has no questions.
6
- `));return}let m=q.createInterface({input:process.stdin,output:process.stdout});console.log(o.blue(`
7
- ${t.title}`)),t.description&&console.log(o.gray(` ${t.description}`)),console.log(o.gray(` ${t.questions.length} questions \xB7 Pass: ${t.passThreshold*100}%
8
- `));let i=0;for(let l=0;l<t.questions.length;l++){let s=t.questions[l];console.log(o.white(` ${l+1}. ${s.question}`));let u=Object.keys(s.choices).sort();for(let $ of u)console.log(` ${o.cyan($)}: ${s.choices[$]}`);let c="";for(;!u.includes(c.toUpperCase());)c=await P(m,o.gray(` Your answer (${u.join("/")}): `)),c=c.trim().toUpperCase();c===s.correct?(i++,console.log(o.green(" Correct!"))):console.log(o.red(` Wrong \u2014 correct answer: ${s.correct}`)),s.explanation&&console.log(o.gray(` \u2192 ${s.explanation}`)),console.log();}m.close();let a=t.questions.length,p=Math.round(i/a*1e4)/100,f=p/100>=t.passThreshold,y=x();console.log(o.blue(" \u2500\u2500\u2500 Results \u2500\u2500\u2500")),console.log(` Score: ${i}/${a} (${p}%)`),console.log(` Pass threshold: ${t.passThreshold*100}%`),console.log(f?o.green(" PASSED"):o.red(" FAILED"));let h$1=`D-${new Date().toISOString().slice(0,10)}-${y}-${e.replace(/^Q-/,"")}`,O={id:h$1,type:"quiz",student:y,earnedAt:new Date().toISOString(),source:e,score:i,total:a,percentage:p,passed:f};h(r,O),console.log(o.gray(`
9
- Diploma saved: ${h$1}
10
- `));}export{T as universityQuizCommand};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export{ca as getReindexToolsList,da as handleReindexTool,ea as rebuildStaticFiles}from'./chunk-QALPEMCU.js';import'./chunk-TMDPDIWA.js';import'./chunk-M4UMM6DC.js';import'./chunk-GRZQIKST.js';import'./chunk-6QXBXZF6.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-LAYBUKMB.js';import'./chunk-5TAVYPOV.js';
@@ -1,12 +0,0 @@
1
- #!/usr/bin/env node
2
- import {c,a}from'./chunk-P344HV6Z.js';import {a as a$1}from'./chunk-WR6D3SC6.js';import'./chunk-5TAVYPOV.js';import e from'chalk';import*as r from'path';import {fileURLToPath}from'url';var p=false,v=fileURLToPath(import.meta.url),d=r.dirname(v);async function U(h,n){let i=parseInt(n.port||"3839",10),m=n.open!==false,u=process.cwd(),o=!!(n.pack||n.project||n.discipline)?c(u,n):null;if(o&&!p){let t=o.subPackRoot??o.packRoot;a(t).length===0&&(a$1("Using implicit default section. v6.5 supports custom sections \u2014 see docs."),p=true);}console.log(e.cyan(`
3
- Opening the campus gates...
4
- `));try{let{startServer:t}=await import('./server-QOCW5RU6.js'),s=r.resolve(d,"university-content");o&&(s=r.join(o.subPackRoot??o.packRoot,"content"));let g=r.resolve(d,"university-ui");console.log(e.gray(`Port: ${i}`)),o&&console.log(e.gray(`Pack: ${o.subPackId??o.packId}`)),console.log(),await t({port:i,open:m,contentDir:s,uiDistPath:g,projectDir:process.cwd()}),console.log(e.green(`
5
- Paradigm University is running at http://localhost:${i}`)),console.log(e.gray(`
6
- Press Ctrl+C to stop
7
- `)),await new Promise(()=>{});}catch(t){t.code==="ERR_MODULE_NOT_FOUND"||t.code==="MODULE_NOT_FOUND"?(console.error(e.red(`
8
- @a-company/university is not installed.`)),console.log(e.gray(`Install it with: npm install @a-company/university
9
- `))):t.code==="EADDRINUSE"?(console.error(e.red(`
10
- Error: Port ${i} is already in use.`)),console.log(e.gray(`Try a different port with: paradigm university serve --port ${i+1}
11
- `))):console.error(e.red(`
12
- Failed to start Paradigm University:`),t),process.exit(1);}}export{U as universityServeCommand};
@@ -1,7 +0,0 @@
1
- #!/usr/bin/env node
2
- import'./chunk-5TAVYPOV.js';import w,{Router}from'express';import*as u from'path';import*as p from'fs';import {fileURLToPath}from'url';import j from'chalk';import*as D from'js-yaml';var R=new Set(["track","index","chronological","featured"]);function S(e,t,s){let i=j.magenta(`#${e}`),r=s?j.gray(` ${Object.entries(s).map(([a,o])=>`${a}=${o}`).join(" ")}`):"";console.log(`${j.yellow("\u26A0")} ${i} ${t}${r}`);}var k=[{id:"main",name:"Main",order:0,style:"track",default:true}];function F(e){if(!Array.isArray(e)||e.length===0)return [...k];let t=[];return e.forEach((s,i)=>{if(!s||typeof s!="object"){S("university-server","Dropping invalid section entry (not an object)",{index:i});return}let r=s,a=typeof r.id=="string"?r.id:null,o=typeof r.name=="string"?r.name:null,n=typeof r.style=="string"?r.style:null;if(!a||!o||!n){S("university-server","Dropping section: missing id/name/style",{index:i,id:String(a)});return}if(!R.has(n)){S("university-server","Dropping section: unknown style",{id:a,style:n});return}let l=n,c;typeof r.order=="number"&&Number.isFinite(r.order)?c=r.order:c=i;let d={id:a,name:o,order:c,style:l};typeof r.description=="string"&&(d.description=r.description),r.default===true&&(d.default=true),l!=="track"&&S("university-server","Section style not yet implemented \u2014 UI will fall back to track",{id:a,style:l}),t.push(d);}),t.length===0?[...k]:(t.sort((s,i)=>s.order-i.order),t)}function W(e){if(!p.existsSync(e))return [...k];try{let t=p.readFileSync(e,"utf-8"),s=D.load(t)??{};return F(s.sections)}catch{return S("university-server","Could not parse pack.yaml for sections \u2014 using implicit default",{path:e}),[...k]}}function V(e,t,s){return W(e==="project"&&s?u.join(s,".paradigm","university","pack.yaml"):u.join(t,"pack.yaml"))}function G(e,t){if(typeof e=="string"&&e.trim().length>0)return e.trim();let s=t.find(i=>i.default===true);return s?s.id:t.length===1?t[0].id:"main"}function H(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(!t)return null;try{return {fm:Z(t[1]),body:t[2].trim()}}catch{return null}}function Z(e){let t={},s=e.split(/\r?\n/);for(let i of s){if(!i.trim()||i.trim().startsWith("#"))continue;let r=i.match(/^([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/);if(!r)continue;let a=r[1],o=r[2],n=r[2].trim();if(n.startsWith("[")&&n.endsWith("]")){let l=n.slice(1,-1).trim();o=l.length===0?[]:l.split(",").map(c=>c.trim().replace(/^['"]|['"]$/g,""));}else n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?o=n.slice(1,-1):/^\d+$/.test(n)?o=parseInt(n,10):n==="true"||n==="false"?o=n==="true":o=n;t[a]=o;}return t}function O(e){try{let t=p.readFileSync(e,"utf-8");return D.load(t)}catch{return null}}function _(e){let t=u.join(e,"paths");if(!p.existsSync(t))return [];let s=p.readdirSync(t).filter(r=>r.startsWith("LP-")&&r.endsWith(".yaml")),i=[];for(let r of s){let a=O(u.join(t,r));a?.id&&i.push(a);}return i}function K(e,t,s){let i=s==="project"?[]:[e];if(!t)return i;let r=u.join(t,".paradigm","university");if(!p.existsSync(r))return i;p.existsSync(u.join(r,"paths"))&&i.push(r);try{for(let a of p.readdirSync(r,{withFileTypes:!0})){if(!a.isDirectory())continue;let o=u.join(r,a.name);p.existsSync(u.join(o,"paths"))&&i.push(o);}}catch{}return i}function N(e,t,s){let i=u.join(e,"notes"),r=u.join(e,"quizzes"),a=[],o=new Set,n=s.steps||[];for(let l of n){let c=l.content;if(!c.startsWith("N-")||o.has(c))continue;o.add(c);let d=c.slice(`N-${t}-`.length),m=u.join(i,`${c}.md`);if(!p.existsSync(m))continue;let f=p.readFileSync(m,"utf-8"),g=H(f);if(!g)continue;let y=g.fm,h={id:d,title:y.title||d,content:g.body,keyConcepts:Array.isArray(y.tags)?y.tags:[],quiz:[]},v=u.join(r,`Q-${t}-${d}.yaml`);if(p.existsSync(v)){let b=O(v);b?.questions&&(h.quiz=b.questions);}a.push(h);}return a}function A(e,t){let s=u.join(e,"paths",`LP-${t}.yaml`);if(!p.existsSync(s))return null;let i=O(s);if(!i?.id)return null;let r=N(e,t,i);return {id:t,title:i.title,description:i.description||"",lessons:r}}function Y(e,t,s){let i=Router(),r=K(e,t,s),a=V(s??"paradigm",e,t);return i.get("/",(o,n)=>{let l=new Set,c=[];for(let d of r){let m=_(d);for(let f of m){let g=f.id.startsWith("LP-")?f.id.slice(3):f.id;if(l.has(g))continue;l.add(g);let y=N(d,g,f);c.push({id:g,title:f.title,description:f.description||"",lessonCount:y.length,lessons:y.map(h=>({id:h.id,title:h.title})),section:G(f.section,a)});}}return c.sort((d,m)=>d.id.localeCompare(m.id)),n.json({courses:c})}),i.get("/:id",(o,n)=>{for(let l of r){let c=A(l,o.params.id);if(c)return n.json(c)}return n.status(404).json({error:`Course '${o.params.id}' not found`})}),i.get("/:id/lessons/:lessonId",(o,n)=>{for(let l of r){let c=A(l,o.params.id);if(!c)continue;let d=c.lessons.find(m=>m.id===o.params.lessonId);if(d)return n.json(d)}return n.status(404).json({error:`Lesson '${o.params.lessonId}' not found`})}),i}function q(e){try{let t=p.readFileSync(e,"utf-8");return D.load(t)}catch{return null}}function B(e){for(let t=e.length-1;t>0;t--){let s=Math.floor(Math.random()*(t+1));[e[t],e[s]]=[e[s],e[t]];}return e}function X(e){if(!e.variants||e.variants.length===0)return e;let t=[{id:e.id,scenario:e.scenario??"",question:e.question,choices:e.choices,correct:e.correct,explanation:e.explanation??""},...e.variants];return t[Math.floor(Math.random()*t.length)]}function ee(e){return e.questions.length}function te(e){let t={},s=[],i=new Map;for(let r of e.questions){let a=X(r),o={id:a.id,course:r.section??"",scenario:a.scenario??r.scenario??"",question:a.question,choices:a.choices,correct:a.correct,explanation:a.explanation??r.explanation??"",...r.passageId?{passageId:r.passageId}:{}};r.passageId?(r.passage&&(t[r.passageId]=r.passage),i.has(r.passageId)||i.set(r.passageId,[]),i.get(r.passageId).push(o)):s.push([o]);}for(let r of i.values())s.push(r);return B(s),{questions:s.flat(),passages:t}}function re(e,t){let s=Router(),i=u.join(e,"quizzes");return s.get("/",(r,a)=>{if(!p.existsSync(i))return a.json({versions:[]});let o=p.readdirSync(i).filter(n=>n.startsWith("Q-plsat-v")&&n.endsWith(".yaml")).map(n=>{let l=q(u.join(i,n));if(!l)return null;let c=n.match(/^Q-plsat-v(\d+)\.yaml$/);return {version:c?`${c[1]}.0`:"0.0",frameworkVersion:"2.0",questionCount:ee(l),timeLimit:l.timeLimit,passThreshold:l.passThreshold}}).filter(n=>n!==null);return o.sort((n,l)=>l.version.localeCompare(n.version)),a.json({versions:o})}),s.get("/:version",(r,a)=>{try{let o=r.params.version.split(".")[0],n=u.join(i,`Q-plsat-v${o}.yaml`);if(!p.existsSync(n))return a.status(404).json({error:`PLSAT version '${r.params.version}' not found`});let l=q(n);if(!l)return a.status(500).json({error:"Failed to parse PLSAT exam"});let{questions:c,passages:d}=te(l);return a.json({version:r.params.version,frameworkVersion:"2.0",timeLimit:l.timeLimit,passThreshold:l.passThreshold,title:l.title,description:l.description??"",questions:c,...Object.keys(d).length>0?{passages:d}:{}})}catch(o){let n=o instanceof Error?o.message:"Internal error";return a.status(500).json({error:`Failed to load PLSAT exam: ${n}`})}}),s.post("/diploma",(r,a)=>{if(!t)return a.status(400).json({error:"No project directory configured"});let o=u.join(t,".paradigm","university","diplomas");if(!p.existsSync(o))return a.json({saved:false,reason:"university directory not found"});try{let{student:n,version:l,score:c,total:d,percentage:m,passed:f}=r.body;if(!n||!l||c==null||d==null)return a.status(400).json({error:"Missing required fields: student, version, score, total"});let g=new Date().toISOString().slice(0,10),y=String(n).toLowerCase().replace(/[^a-z0-9-]/g,"-").slice(0,20),h=`D-${g}-${y}-plsat-v${l}`,v={id:h,type:"plsat",student:y,earnedAt:new Date().toISOString(),source:`plsat:v${l}`,score:c,total:d,percentage:m??(d>0?Math.round(c/d*1e4)/100:0),passed:f??!1,details:{plsatVersion:l}},b=u.join(o,`${h}.yaml`),M=Object.entries(v).map(([I,x])=>{if(typeof x=="object"&&x!==null){let z=Object.entries(x).map(([J,U])=>` ${J}: ${JSON.stringify(U)}`).join(`
3
- `);return `${I}:
4
- ${z}`}return `${I}: ${JSON.stringify(x)}`});return p.writeFileSync(b,M.join(`
5
- `)+`
6
- `,"utf8"),a.json({saved:!0,diplomaId:h})}catch(n){let l=n instanceof Error?n.message:"Internal error";return a.status(500).json({error:`Failed to save diploma: ${l}`})}}),s}var ne=fileURLToPath(import.meta.url),P=u.dirname(ne);function ie(e){let t=e;for(;t!==u.dirname(t);){if(p.existsSync(u.join(t,"package.json"))&&JSON.parse(p.readFileSync(u.join(t,"package.json"),"utf-8")).name==="@a-company/university")return t;t=u.dirname(t);}return e}var $={component(e){let t=j.magenta(`#${e}`);return {info:(s,i)=>{let r=i?j.gray(` ${Object.entries(i).map(([a,o])=>`${a}=${o}`).join(" ")}`):"";console.log(`${j.blue("\u2139")} ${t} ${s}${r}`);},success:(s,i)=>{let r=i?j.gray(` ${Object.entries(i).map(([a,o])=>`${a}=${o}`).join(" ")}`):"";console.log(`${j.green("\u2714")} ${t} ${s}${r}`);},warn:(s,i)=>{let r=i?j.gray(` ${Object.entries(i).map(([a,o])=>`${a}=${o}`).join(" ")}`):"";console.log(`${j.yellow("\u26A0")} ${t} ${s}${r}`);},error:(s,i)=>{let r=i?j.gray(` ${Object.entries(i).map(([a,o])=>`${a}=${o}`).join(" ")}`):"";console.error(`${j.red("\u2716")} ${t} ${s}${r}`);}}}};function se(e){if(e?.contentDir&&e?.uiDistPath)return {contentDir:e.contentDir,uiDistPath:e.uiDistPath};let t=u.join(P,"university-content"),s=u.join(P,"university-ui");if(p.existsSync(t)&&p.existsSync(s))return {contentDir:e?.contentDir||t,uiDistPath:e?.uiDistPath||s};let i=ie(P);return {contentDir:e?.contentDir||u.join(i,"src","content"),uiDistPath:e?.uiDistPath||u.join(i,"ui","dist")}}var C="6.4.0",L={name:"Paradigm University",tagline:"Lux in Codice",logo:null,institution:null,favicon:null,tabs:["campus","courses","plsat","library","certificates"],startCourse:null};function E(e){let t=w();t.use(w.json()),t.use((o,n,l)=>{n.header("Access-Control-Allow-Origin","*"),n.header("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),n.header("Access-Control-Allow-Headers","Content-Type"),l();});let{contentDir:s,uiDistPath:i}=se(e),r="paradigm",a;if(e?.projectDir){let o=u.join(e.projectDir,".paradigm","university","pack.yaml");p.existsSync(o)&&(r="project");}if(r==="project"&&e?.projectDir){let o=u.join(e.projectDir,".paradigm","university","pack.yaml"),n={};try{let v=p.readFileSync(o,"utf-8");n=D.load(v)??{};}catch{$.component("university-server").warn("Could not parse pack.yaml \u2014 using defaults",{path:o});}let l=n.branding??{},c=n.theme??null,d=typeof n.version=="string"?n.version:C,m=u.join(e.projectDir,".paradigm","university","reference.json"),f=p.existsSync(m),g=l.tabs,y={...L,...l};if(!g){let v=["campus","courses","certificates"];f&&v.splice(2,0,"library"),y.tabs=v;}let h=F(n.sections);a={mode:"project",branding:y,theme:c,version:d,hasProjectLibrary:f,sections:h},$.component("university-server").info("Project mode active",{pack:String(n.id??"unknown"),sections:h.length});}else {let o=W(u.join(s,"pack.yaml"));a={mode:"paradigm",branding:{...L},theme:null,version:C,hasProjectLibrary:false,sections:o};}return t.get("/api/pack-config",(o,n)=>{n.json(a);}),t.use("/api/courses",Y(s,e?.projectDir,r)),t.use("/api/plsat",re(s,e?.projectDir)),t.get("/api/reference",(o,n)=>{if(r==="project"&&e?.projectDir){let c=u.join(e.projectDir,".paradigm","university","reference.json");if(p.existsSync(c))try{let d=JSON.parse(p.readFileSync(c,"utf-8"));return n.json(d)}catch{return n.status(500).json({error:"Failed to parse project reference.json"})}return n.status(404).json({error:"No reference library configured for this project."})}let l=u.join(s,"reference.json");if(p.existsSync(l)){let c=JSON.parse(p.readFileSync(l,"utf-8"));return n.json(c)}return n.status(404).json({error:"Reference data not found"})}),t.get("/api/health",(o,n)=>{n.json({status:"ok",timestamp:new Date().toISOString()});}),p.existsSync(i)&&(t.use(w.static(i)),t.get("{*path}",(o,n)=>{o.path.startsWith("/api")||n.sendFile(u.join(i,"index.html"));})),t}async function oe(e){let t=E({contentDir:e.contentDir,uiDistPath:e.uiDistPath,projectDir:e.projectDir});return $.component("university-server").info("Starting server",{port:e.port}),new Promise((s,i)=>{t.listen(e.port,()=>{$.component("university-server").success("Server running",{url:`http://localhost:${e.port}`}),e.open&&import('open').then(r=>{r.default(`http://localhost:${e.port}`),$.component("university-server").info("Opened browser");}).catch(()=>{$.component("university-server").warn("Could not open browser automatically");}),s();}).on("error",r=>{r.code==="EADDRINUSE"?$.component("university-server").error("Port already in use",{port:e.port}):$.component("university-server").error("Server error",{error:r.message}),i(r);});})}
7
- export{E as createApp,oe as startServer};
@@ -1,7 +0,0 @@
1
- #!/usr/bin/env node
2
- import {b,c as c$1,d}from'./chunk-ERO4MJSH.js';import {c}from'./chunk-P344HV6Z.js';import'./chunk-5TAVYPOV.js';import o from'chalk';function h(l){let s=l.indexOf(":");return s===-1?{entryId:l}:{packId:l.slice(0,s),entryId:l.slice(s+1)}}async function S(l,s){let c$2=process.cwd(),{packId:f,entryId:g}=h(l),d$1={...s};f&&(d$1.pack=f),c(c$2,d$1);let e=b(c$2,g);if(e){if(s.json){console.log(JSON.stringify({...e.frontmatter,body:e.body},null,2));return}console.log(o.blue(`
3
- ${e.frontmatter.title}`)),console.log(o.gray(` ${e.frontmatter.type} \xB7 ${e.frontmatter.difficulty} \xB7 ${e.frontmatter.author}`)),e.frontmatter.tags.length>0&&console.log(o.gray(` Tags: ${e.frontmatter.tags.join(", ")}`)),e.frontmatter.symbols.length>0&&console.log(o.gray(` Symbols: ${e.frontmatter.symbols.join(", ")}`)),console.log(),console.log(e.body),console.log();return}let t=c$1(c$2,g);if(t){if(s.json){console.log(JSON.stringify(t,null,2));return}console.log(o.blue(`
4
- ${t.title}`)),console.log(o.gray(` quiz \xB7 ${t.difficulty} \xB7 ${t.questions.length} questions \xB7 pass: ${t.passThreshold*100}%`)),t.description&&console.log(o.gray(` ${t.description}`)),console.log();for(let n of t.questions){console.log(` ${o.cyan(n.id)}: ${n.question}`);for(let[i,a]of Object.entries(n.choices)){let m=i===n.correct?o.green("*"):" ";console.log(` ${m} ${i}: ${a}`);}n.explanation&&console.log(o.gray(` \u2192 ${n.explanation}`)),console.log();}return}let r=d(c$2,g);if(r){if(s.json){console.log(JSON.stringify(r,null,2));return}console.log(o.blue(`
5
- ${r.title}`)),console.log(o.gray(` learning path \xB7 ${r.steps.length} steps \xB7 ${r.ordered?"ordered":"unordered"}`)),r.description&&console.log(o.gray(` ${r.description}`)),console.log();for(let n=0;n<r.steps.length;n++){let i=r.steps[n],a=i.required?o.red("required"):o.gray("optional");console.log(` ${n+1}. ${o.cyan(i.content)} (${a})`),i.note&&console.log(o.gray(` ${i.note}`));}console.log();return}console.error(o.red(`
6
- Content "${l}" not found
7
- `)),process.exit(1);}export{S as universityShowCommand};
@@ -1,6 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a,e}from'./chunk-ERO4MJSH.js';import {c}from'./chunk-P344HV6Z.js';import'./chunk-5TAVYPOV.js';import t from'chalk';async function h(d){let g=process.cwd(),r=c(g,d),s=a(g);if(!s||s.totalContent===0){console.log(t.yellow(`
3
- No university content found.`)),console.log(t.gray(` Create content with: paradigm university add note --title "My Note"
4
- `));return}let n=e(g),a$1={},c$1={},l={};for(let o of s.entries){a$1[o.type]=(a$1[o.type]||0)+1,o.difficulty&&(l[o.difficulty]=(l[o.difficulty]||0)+1);for(let e of o.tags)c$1[e]=(c$1[e]||0)+1;}if(d.json){console.log(JSON.stringify({pack:r.subPackId??r.packId,totalContent:s.totalContent,typeCounts:a$1,difficultyCounts:l,tagCounts:c$1,diplomaCount:n.length},null,2));return}console.log(t.blue(`
5
- University Status \u2014 pack: ${r.subPackId??r.packId}
6
- `)),console.log(t.white(` Total content: ${s.totalContent}`));for(let[o,e]of Object.entries(a$1).sort())console.log(` ${t.cyan(o)}: ${e}`);if(Object.keys(l).length>0){console.log(),console.log(t.white(" By difficulty:"));for(let[o,e]of Object.entries(l)){let i=o==="advanced"?t.red:o==="intermediate"?t.yellow:t.green;console.log(` ${i(o)}: ${e}`);}}if(Object.keys(c$1).length>0){console.log(),console.log(t.white(" Top tags:"));let o=Object.entries(c$1).sort((e,i)=>i[1]-e[1]).slice(0,8);for(let[e,i]of o)console.log(` ${t.gray(e)}: ${i}`);}if(console.log(),console.log(t.white(` Diplomas earned: ${n.length}`)),n.length>0){for(let o of n.slice(0,5)){let e=o.passed?t.green("PASS"):t.red("FAIL");console.log(` ${e} ${o.source} \u2014 ${o.student} (${o.percentage}%) ${t.gray(o.earnedAt.slice(0,10))}`);}n.length>5&&console.log(t.gray(` ... and ${n.length-5} more`));}console.log();}export{h as universityStatusCommand};
@@ -1,9 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a,c as c$1,d as d$1}from'./chunk-ERO4MJSH.js';import {c}from'./chunk-P344HV6Z.js';import'./chunk-5TAVYPOV.js';import d from'chalk';import*as h from'fs';import*as p from'path';import*as I from'js-yaml';var v=/^[a-z0-9][a-z0-9-]{0,63}$/,x=new Set(["track","index","chronological","featured"]);function C(s){let a=p.join(s,"pack.yaml");if(!h.existsSync(a))return null;try{let i=h.readFileSync(a,"utf8"),n=I.load(i);return Array.isArray(n?.sections)?n.sections:null}catch{return null}}function j(s,a,i){let n=new Set,t=false;if(!s||s.length===0)return n.add("main"),{knownIds:n,hadValidationError:t};let f=new Set,u=0;for(let l=0;l<s.length;l++){let c=s[l],y=`sections[${l}]`;if(typeof c.id!="string"||!v.test(c.id)){i.push({contentId:"pack.yaml",severity:"error",check:"section-bad-id",message:`${y}.id must be kebab-case matching /^[a-z0-9][a-z0-9-]{0,63}$/`,fix:"Use lowercase letters, digits, and hyphens; start with a letter or digit"}),t=true;continue}if(f.has(c.id)){i.push({contentId:"pack.yaml",severity:"error",check:"section-duplicate-id",message:`duplicate section id "${c.id}"`,fix:"Each section id must be unique within the pack"}),t=true;continue}f.add(c.id),n.add(c.id),(typeof c.style!="string"||!x.has(c.style))&&(i.push({contentId:"pack.yaml",severity:"error",check:"section-bad-style",message:`${y}.style must be one of: ${Array.from(x).join(", ")}`}),t=true),c.default===true&&u++;}u>1&&(i.push({contentId:"pack.yaml",severity:"error",check:"section-multiple-defaults",message:`at most one section may set default: true (found ${u})`,fix:"Set default: true on exactly one section"}),t=true);for(let l of a)n.has(l)||i.push({contentId:"pack.yaml",severity:"warning",check:"section-unknown-ref",message:`entries reference unknown section "${l}"`,fix:`Declare section "${l}" in pack.yaml, or remove the section: field from those entries`});return {knownIds:n,hadValidationError:t}}async function R(s){let a$1=process.cwd(),i=c(a$1,s),n=a(a$1);if(!n||n.totalContent===0){console.log(d.yellow(`
3
- No university content to validate.
4
- `));return}let t=[],f=n.entries;s.id&&(f=f.filter(e=>e.id===s.id),f.length===0&&(console.error(d.red(`
5
- Content "${s.id}" not found
6
- `)),process.exit(1)));let u=null;if(s.deep){u=new Set;let e=p.join(a$1,".paradigm","scan-index.json");if(h.existsSync(e))try{let r=JSON.parse(h.readFileSync(e,"utf8"));if(r.symbols&&Array.isArray(r.symbols))for(let o of r.symbols)o.symbol&&u.add(o.symbol);}catch{}}let l=new Set(n.entries.map(e=>e.id)),c$2=i.subPackRoot??i.packRoot,y=C(c$2),k=new Set;for(let e of n.entries)e.section&&typeof e.section=="string"&&e.section.length>0&&k.add(e.section);j(y,k,t);for(let e of f){if(e.title||t.push({contentId:e.id,severity:"error",check:"missing-title",message:"Content is missing a title"}),e.type==="quiz"){let r=c$1(a$1,e.id);if(!r)t.push({contentId:e.id,severity:"error",check:"unreadable-quiz",message:"Quiz file could not be parsed"});else for(let o of r.questions)(!o.choices||!(o.correct in o.choices))&&t.push({contentId:e.id,severity:"error",check:"invalid-quiz-answer",message:`Question ${o.id}: correct "${o.correct}" not in choices [${Object.keys(o.choices||{}).join(", ")}]`,fix:`Set correct to one of: ${Object.keys(o.choices||{}).join(", ")}`});}if(e.type==="path"){let r=d$1(a$1,e.id);if(!r)t.push({contentId:e.id,severity:"error",check:"unreadable-path",message:"Learning path file could not be parsed"});else for(let o of r.steps)!o.content.startsWith("plsat:")&&!l.has(o.content)&&t.push({contentId:e.id,severity:"error",check:"broken-path-step",message:`Step references "${o.content}" which doesn't exist`,fix:`Create content with id "${o.content}"`});}if(u&&e.symbols.length>0)for(let r of e.symbols)u.has(r)||t.push({contentId:e.id,severity:"warning",check:"broken-symbol-ref",message:`Symbol "${r}" not found in scan-index`});}if(s.json){console.log(JSON.stringify({status:t.some(e=>e.severity==="error")?"errors":t.length>0?"warnings":"healthy",totalContent:n.totalContent,checked:f.length,issues:t},null,2));return}if(console.log(d.blue(`
7
- University Validation \u2014 pack: ${i.subPackId??i.packId} (${f.length} items${s.deep?", deep mode":""})
8
- `)),t.length===0){console.log(d.green(` All checks passed.
9
- `));return}let g=t.filter(e=>e.severity==="error"),m=t.filter(e=>e.severity==="warning");for(let e of g)console.log(d.red(` x ${e.contentId}: ${e.message}`)),e.fix&&console.log(d.gray(` Fix: ${e.fix}`));for(let e of m)console.log(d.yellow(` ! ${e.contentId}: ${e.message}`)),e.fix&&console.log(d.gray(` Fix: ${e.fix}`));console.log(),g.length>0&&console.log(d.red(` ${g.length} error${g.length>1?"s":""}`)),m.length>0&&console.log(d.yellow(` ${m.length} warning${m.length>1?"s":""}`)),console.log();}export{R as universityValidateCommand};