@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.
- package/dist/add-V6XR7DU5.js +12 -0
- package/dist/{chunk-FI66YM6G.js → chunk-3OXR6F65.js} +49 -49
- package/dist/chunk-EKNLG73M.js +6 -0
- package/dist/chunk-PMKZMCTS.js +111 -0
- package/dist/index.js +4 -4
- package/dist/list-NC3QGT75.js +12 -0
- package/dist/mcp.js +3 -3
- package/dist/quiz-TNV6APBM.js +10 -0
- package/dist/reindex-PTIQ2UGY.js +2 -0
- package/dist/serve-2PKJP65E.js +12 -0
- package/dist/server-4SYOUF6D.js +7 -0
- package/dist/show-N5LGB5B2.js +7 -0
- package/dist/status-ENAI35NL.js +6 -0
- package/dist/{tools-HQKF4Q3P.js → tools-PUSDXUYE.js} +1 -1
- package/dist/university-ui/assets/{index-BIQeax_b.js → index-DrtbBC21.js} +2 -2
- package/dist/university-ui/assets/{index-BIQeax_b.js.map → index-DrtbBC21.js.map} +1 -1
- package/dist/university-ui/index.html +1 -1
- package/dist/validate-IQG7DBFC.js +9 -0
- package/package.json +2 -1
- package/dist/add-CBDFTWST.js +0 -12
- package/dist/chunk-ERO4MJSH.js +0 -6
- package/dist/chunk-P344HV6Z.js +0 -2
- package/dist/chunk-QALPEMCU.js +0 -111
- package/dist/list-AXKTBXKJ.js +0 -12
- package/dist/quiz-G56CUN45.js +0 -10
- package/dist/reindex-F7BZCG4W.js +0 -2
- package/dist/serve-TJQ5BNKR.js +0 -12
- package/dist/server-QOCW5RU6.js +0 -7
- package/dist/show-MTPEQFXK.js +0 -7
- package/dist/status-REA6HUXE.js +0 -6
- package/dist/validate-742XMB42.js +0 -9
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {z as z$1}from'zod';import*as c from'fs';import*as u from'path';import*as m from'js-yaml';var It={warn(){}},xt=It;function C(){return xt}var k="pack.yaml";var G=/^[a-z0-9][a-z0-9-]{0,63}$/,q=["track","index","chronological","featured"],Q=64,jt=z$1.object({id:z$1.string().regex(G,"invalid section id"),name:z$1.string().min(1).max(120),order:z$1.number().int().min(0).max(9999),style:z$1.enum(q,{errorMap:()=>({message:`section.style must be one of ${q.join("|")}`})}),description:z$1.string().max(1e3).optional(),default:z$1.boolean({invalid_type_error:"section.default must be a boolean"}).optional()}).strict(),Y=z$1.array(jt).max(Q,`sections must contain \u2264${Q} entries`);z$1.object({sections:Y.optional()}).passthrough();z$1.object({section:z$1.string().regex(G).optional(),order:z$1.number().int().min(0).max(9999).optional()}).passthrough();var H="@a-company/university",J=".paradigm/university",V=".paradigm/cache/packs.json",h=class extends Error{constructor(t,e){super(`pack-load failed (${t}: ${e})`),this.errorClass=t,this.detail=e,this.name="PackLoadError";}},wt=["id","name","version","schema_version","tenant_kind"],_t=new Set(["first-party","project","external"]),B={id:"main",name:"Curriculum",order:1,style:"track",default:true};function X(t){if(t==null)return [{...B}];if(Array.isArray(t)&&t.length===0)return [{...B}];let e=Y.safeParse(t);if(!e.success){let r=e.error.issues[0],a=r?`${r.path.join(".")||"sections"}: ${r.message}`:"sections failed schema validation";throw new h("manifest-invalid",a)}let n=e.data.map(r=>({...r})),i=new Set;for(let r of n){if(i.has(r.id))throw new h("manifest-invalid",`duplicate section id "${r.id}"`);i.add(r.id);}n.length===1&&!n[0].default&&(n[0]={...n[0],default:true});let s=n.filter(r=>r.default===true);if(s.length>1)throw new h("manifest-invalid",`at most one section may set default: true (found ${s.length})`);return n.sort((r,a)=>r.order-a.order||r.id.localeCompare(a.id)),n}function At(t){if(t&&typeof t=="object"&&"name"in t&&typeof t.name=="string"){let e=t.name;return e==="YAMLException"?"yaml syntax error":e}return "parse error"}function j(t){let e=u.join(t,k);if(!c.existsSync(e))throw new h("missing-manifest",`no ${k} at pack root`);let n;try{n=c.readFileSync(e,"utf-8");}catch{throw new h("manifest-unparseable","file read error")}let i;try{i=m.load(n);}catch(r){throw new h("manifest-unparseable",At(r))}let s=i;if(!s||typeof s!="object")throw new h("manifest-invalid","manifest is not an object");for(let r of wt){let a=s[r];if(a==null||a==="")throw new h("missing-required-field",`required field ${String(r)} is missing or empty`)}if(!_t.has(String(s.tenant_kind)))throw new h("missing-required-field","tenant_kind must be one of first-party|project|external");return s.sections=X(s.sections),s}function Z(t){let e=u.join(t,k);if(!c.existsSync(e))return null;try{let n=m.load(c.readFileSync(e,"utf8"));return n&&typeof n.id=="string"&&n.id.length>0?n.id:null}catch{return null}}function Et(t){let e=Ft(t);if(e)return e;let n=[],i=u.join(t,"node_modules",H);if(c.existsSync(u.join(i,k)))try{let r=j(i);n.push({manifest:r,rootDir:i,source:"first-party"});}catch(r){C().warn("first-party pack manifest invalid",{errorClass:r instanceof h?r.errorClass:"other"});}for(let r of Tt(t))try{let a=j(r);n.push({manifest:a,rootDir:r,source:"npm"});}catch(a){C().warn("npm pack manifest invalid",{errorClass:a instanceof h?a.errorClass:"other"});}let s=u.join(t,J);if(c.existsSync(s)&&c.statSync(s).isDirectory()){let r=u.join(s,k),a;if(c.existsSync(r))try{a=j(s),n.push({manifest:a,rootDir:s,source:"local"});}catch(d){C().warn("local pack manifest invalid",{errorClass:d instanceof h?d.errorClass:"other"});}let o=a?.id??"project";for(let d of Nt(s))try{let f=j(d);n.push({manifest:f,rootDir:d,source:"local",parentPackId:o});}catch(f){C().warn("discipline sub-pack manifest invalid",{errorClass:f instanceof h?f.errorClass:"other"});}}return Mt(t,n),n}function Tt(t){let e=u.join(t,"package.json");if(!c.existsSync(e))return [];let n;try{n=JSON.parse(c.readFileSync(e,"utf8"));}catch{return []}let i=new Set([...Object.keys(n.dependencies||{}),...Object.keys(n.devDependencies||{}),...Object.keys(n.peerDependencies||{})]);if(i.size===0)return [];let s=u.join(t,"node_modules");if(!c.existsSync(s))return [];let r=[];for(let a of i){if(a===H)continue;let o=u.join(s,a,"package.json");if(!c.existsSync(o))continue;let d;try{d=JSON.parse(c.readFileSync(o,"utf8"));}catch{continue}let f=d.paradigm?.universityPack;if(typeof f!="string"||f.length===0)continue;let l=u.resolve(u.dirname(o),f);c.existsSync(u.join(l,k))&&r.push(l);}return r}function Nt(t){let e=[],n;try{n=c.readdirSync(t,{withFileTypes:!0});}catch{return e}for(let i of n){if(!i.isDirectory()||i.name.startsWith("."))continue;let s=u.join(t,i.name);c.existsSync(u.join(s,k))&&e.push(s);}return e}function tt(t){try{return c.statSync(u.join(t,"node_modules")).mtime.getTime()}catch{return}}function et(t){try{return c.statSync(u.join(t,J)).mtime.getTime()}catch{return}}function Ft(t){let e=u.join(t,V);if(!c.existsSync(e))return null;let n;try{n=JSON.parse(c.readFileSync(e,"utf8"));}catch{return null}if(n.version!==1||!Array.isArray(n.packs))return null;let i=tt(t),s=et(t);return n.node_modules_mtime_ms!==i||n.local_university_mtime_ms!==s?null:n.packs.map(r=>({manifest:r.manifest,rootDir:r.rootDir,source:r.source,...r.parentPackId?{parentPackId:r.parentPackId}:{}}))}function Mt(t,e){let n=u.join(t,V);try{c.mkdirSync(u.dirname(n),{recursive:!0});let i={version:1,node_modules_mtime_ms:tt(t),local_university_mtime_ms:et(t),packs:e.map(s=>({manifest:s.manifest,rootDir:s.rootDir,source:s.source,...s.parentPackId?{parentPackId:s.parentPackId}:{}}))};c.writeFileSync(n,JSON.stringify(i,null,2),"utf8");}catch{}}var b=".paradigm/university",I="content",T="notes",w="policies",_="quizzes",E="paths",$="diplomas",D="index.yaml",$t="config.yaml";function nt(t){return typeof t=="string"?{packRoot:t,stampPackId:true,resolveDefaultPack:true}:{packRoot:t?.packRoot,stampPackId:t?.stampPackId??true,resolveDefaultPack:t?.resolveDefaultPack??true}}function it(t,e,n){return e||(n?Dt(t):u.join(t,b))}function Dt(t){let e=u.join(t,b);if(c.existsSync(e))return e;try{let i=Et(t).find(s=>s.manifest.tenant_kind==="first-party");if(i)return i.rootDir}catch{}return e}function L(t){if(!c.existsSync(t))return null;let e=u.join(t,k);if(c.existsSync(e))try{return j(t)}catch(i){C().warn("pack manifest invalid, using implicit manifest",{errorClass:i instanceof h?i.errorClass:"other"});}let n=u.basename(t)||"project";return {id:n,name:n,version:"0.0.0",schema_version:"1",tenant_kind:"project",description:"Implicit project pack (pack.yaml not present \u2014 v5 layout)",origin_hint:"authored",sections:X(void 0)}}function Lt(t,e,n){return e?{...t,...t.pack_id?{}:{pack_id:e.id},...t.discipline||!n?{}:{discipline:n}}:t}var st={name:"Project University",tagline:"Learn the codebase",institution:"Paradigm"},rt={primary:"#6366f1",secondary:"#8b5cf6",accent:"#f59e0b",background:"#0f172a",surface:"#1e293b",text:"#f8fafc",textMuted:"#94a3b8",success:"#22c55e",error:"#ef4444",font:"Inter, system-ui, sans-serif"},F={branding:st,theme:rt,content:{categories:[],defaultDifficulty:"beginner",requireApproval:false},diplomas:{includeGlobalPLSAT:true,customCertStyle:null}};function Ot(t){let e=u.join(t,b,$t);if(!c.existsSync(e))return {...F};try{let n=c.readFileSync(e,"utf8"),i=m.load(n);return i?{branding:{...st,...i.branding||{}},theme:{...rt,...i.theme||{}},content:{categories:i.content?.categories||[],defaultDifficulty:i.content?.defaultDifficulty||"beginner",requireApproval:i.content?.requireApproval??!1,defaultCategory:i.content?.defaultCategory},diplomas:{includeGlobalPLSAT:i.diplomas?.includeGlobalPLSAT??!0,customCertStyle:i.diplomas?.customCertStyle??null}}:{...F}}catch{return {...F}}}function O(t){let e=u.join(t,b,D);if(!c.existsSync(e))return null;try{let n=c.readFileSync(e,"utf8");return m.load(n)}catch{return null}}function ot(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:m.load(e[1]),body:e[2].trim()}}catch{return null}}function Rt(t,e){return `---
|
|
3
|
+
${m.dump(t,{lineWidth:-1,noRefs:true,sortKeys:false})}---
|
|
4
|
+
|
|
5
|
+
${e}
|
|
6
|
+
`}function at(t,e,n){let i=K(t,e,".md",n);if(!i)return null;try{let s=c.readFileSync(i,"utf8"),r=ot(s);if(!r)return null;let a=r.frontmatter;return {frontmatter:zt(a),body:r.body}}catch{return null}}function ct(t,e,n,i){let{packRoot:s,stampPackId:r,resolveDefaultPack:a}=nt(i),o=e.type==="policy"?w:T,d=it(t,s,a),f=u.join(d,I,o);c.mkdirSync(f,{recursive:true});let l=r?L(d):null,v=Lt(e,l),W=u.join(f,`${v.id}.md`),Pt=Rt(v,n);return c.writeFileSync(W,Pt,"utf8"),W}function dt(t,e,n){let i=K(t,e,".yaml",n);if(!i)return null;try{let s=c.readFileSync(i,"utf8"),r=m.load(s);return !r||!r.id?null:Kt(r)}catch{return null}}function lt(t,e,n){let{packRoot:i,stampPackId:s,resolveDefaultPack:r}=nt(n),a=it(t,i,r),o=u.join(a,I,_);c.mkdirSync(o,{recursive:true});let d=s?L(a):null,f={...e,...e.pack_id||!d?{}:{pack_id:d.id}},l=u.join(o,`${f.id}.yaml`);return c.writeFileSync(l,m.dump(f,{lineWidth:-1,noRefs:true}),"utf8"),l}function ft(t,e,n){let i=K(t,e,".yaml",n);if(!i)return null;try{let s=c.readFileSync(i,"utf8"),r=m.load(s);return !r||!r.id?null:r}catch{return null}}function ut(t,e,n){let i=n??u.join(t,b),s=u.join(i,$);if(!c.existsSync(s))return [];let r=[];try{let a=c.readdirSync(s).filter(o=>o.endsWith(".yaml"));for(let o of a)try{let d=c.readFileSync(u.join(s,o),"utf8"),f=m.load(d);if(!f||!f.id||e?.student&&f.student!==e.student||e?.type&&f.type!==e.type)continue;r.push(f);}catch{}}catch{}return r.sort((a,o)=>o.earnedAt.localeCompare(a.earnedAt))}function pt(t,e,n){let i=n??u.join(t,b),s=u.join(i,$);c.mkdirSync(s,{recursive:true});let r=L(i),a={...e,...e.pack_id||!r?{}:{pack_id:r.id}},o=u.join(s,`${a.id}.yaml`);return c.writeFileSync(o,m.dump(a,{lineWidth:-1,noRefs:true}),"utf8"),o}function yt(t,e,n){return R(t,e,n).entries}function R(t,e,n){let i=n?z(n):O(t);if(!i)return {entries:[],total:0,returned:0};let s=[...i.entries];if(e.type&&(s=s.filter(d=>d.type===e.type)),e.tag&&(s=s.filter(d=>d.tags.some(f=>f.startsWith(e.tag)))),e.difficulty&&(s=s.filter(d=>d.difficulty===e.difficulty)),e.symbol&&(s=s.filter(d=>d.symbols.some(f=>f===e.symbol))),e.author&&(s=s.filter(d=>d.author===e.author)),e.query){let d=e.query.toLowerCase();s=s.filter(f=>f.title.toLowerCase().includes(d)||f.id.toLowerCase().includes(d)||f.tags.some(l=>l.toLowerCase().includes(d)));}if(e.category&&(s=s.filter(d=>d.category===e.category)),e.section&&(s=s.filter(d=>d.section===e.section)),e.track){let d=Ot(t),f=new Map;for(let l of d.content.categories)f.set(l.id,l.track||"core");s=s.filter(l=>(l.category&&f.get(l.category)||"core")===e.track);}let r=s.length,a=e.limit||20,o=s.slice(0,a);return {entries:o,total:r,returned:o.length}}var mt=[I,"src/content"],ht=[T,w,_,E];function Ut(t){if(!c.existsSync(t))return false;for(let e of ht){let n=u.join(t,e);if(c.existsSync(n))try{if(c.readdirSync(n).some(i=>i.endsWith(".md")||i.endsWith(".yaml")))return !0}catch{}}return false}function U(t){let e=gt(t);return e?u.join(t,e):null}function gt(t){let e=null;for(let n of mt){let i=u.join(t,n);if(c.existsSync(i)&&(e===null&&(e=n),Ut(i)))return n}return e}function x(t){for(let e of mt){let n=u.join(t,e);if(!c.existsSync(n))continue;let i=0;for(let s of ht){let r=u.join(n,s);if(c.existsSync(r))try{i+=c.readdirSync(r).filter(a=>a.endsWith(".md")||a.endsWith(".yaml")).length;}catch{}}if(i>0)return i}return 0}function St(t,e){let n=[];for(let r of [T,w]){let a=u.join(t,r);if(c.existsSync(a))try{for(let o of c.readdirSync(a).filter(d=>d.endsWith(".md")))try{let d=c.readFileSync(u.join(a,o),"utf8"),f=ot(d);if(!f)continue;let l=f.frontmatter;n.push({id:l.id||o.replace(".md",""),title:l.title||o,type:l.type||(r===w?"policy":"note"),author:l.author||"unknown",created:l.created||"",updated:l.updated||"",tags:Array.isArray(l.tags)?l.tags:[],symbols:Array.isArray(l.symbols)?l.symbols:[],difficulty:l.difficulty||"beginner",file:`${e}/${r}/${o}`,...l.category?{category:l.category}:{},...typeof l.section=="string"&&l.section?{section:l.section}:{},...typeof l.order=="number"&&Number.isFinite(l.order)?{order:l.order}:{}});}catch{}}catch{}}let i=u.join(t,_);if(c.existsSync(i))try{for(let r of c.readdirSync(i).filter(a=>a.endsWith(".yaml")))try{let a=c.readFileSync(u.join(i,r),"utf8"),o=m.load(a);if(!o||!o.id)continue;n.push({id:o.id,title:o.title||r,type:"quiz",author:o.author||"unknown",created:o.created||"",updated:o.updated||"",tags:o.tags||[],symbols:o.symbols||[],difficulty:o.difficulty||"beginner",file:`${e}/${_}/${r}`,...o.category?{category:o.category}:{},...typeof o.section=="string"&&o.section?{section:o.section}:{},...typeof o.order=="number"&&Number.isFinite(o.order)?{order:o.order}:{}});}catch{}}catch{}let s=u.join(t,E);if(c.existsSync(s))try{for(let r of c.readdirSync(s).filter(a=>a.endsWith(".yaml")))try{let a=c.readFileSync(u.join(s,r),"utf8"),o=m.load(a);if(!o||!o.id)continue;n.push({id:o.id,title:o.title||r,type:"path",author:o.author||"unknown",created:o.created||"",updated:o.updated||"",tags:o.tags||[],symbols:[],file:`${e}/${E}/${r}`,...o.category?{category:o.category}:{},...typeof o.section=="string"&&o.section?{section:o.section}:{},...typeof o.order=="number"&&Number.isFinite(o.order)?{order:o.order}:{}});}catch{}}catch{}return n}function vt(t){let e=u.join(t,b),n=u.join(e,I),i=St(n,I),s=0,r=u.join(e,$);if(c.existsSync(r))try{s=c.readdirSync(r).filter(d=>d.endsWith(".yaml")).length;}catch{}let a={version:"1.0",generatedAt:new Date().toISOString(),totalContent:i.length,entries:i,diplomaCount:s};c.mkdirSync(e,{recursive:true});let o=u.join(e,D);return c.writeFileSync(o,m.dump(a,{lineWidth:-1,noRefs:true}),"utf8"),a}function z(t,e){let n=u.join(t,D);if(c.existsSync(n))try{let a=c.readFileSync(n,"utf8"),o=m.load(a);if(o)return o}catch{}let i=gt(t);if(!i)return {version:"1.0",generatedAt:new Date().toISOString(),totalContent:0,entries:[],diplomaCount:0};let s=u.join(t,i),r=St(s,i);return {version:"1.0",generatedAt:new Date().toISOString(),totalContent:r.length,entries:r,diplomaCount:0}}function K(t,e,n,i){let s=i??u.join(t,b),r=U(s)??u.join(s,I);for(let a of [T,w,_,E]){let o=u.join(r,a,`${e}${n}`);if(c.existsSync(o))return o}return null}function zt(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 Kt(t){return {...t,tags:t.tags||[],symbols:t.symbols||[],difficulty:t.difficulty||"beginner",passThreshold:t.passThreshold??.7,questions:t.questions||[]}}var N=".paradigm/university",Wt="pack.yaml";function ee(t){let e=A(t);if(!e||!Array.isArray(e.sections))return [];let n=[];for(let i of e.sections)i&&typeof i.id=="string"&&i.id.length>0&&n.push({id:i.id,name:typeof i.name=="string"?i.name:void 0});return n}function A(t){let e=u.join(t,Wt);if(!c.existsSync(e))return null;try{let n=c.readFileSync(e,"utf8");return m.load(n)??null}catch{return null}}function qt(t){let e=[],n=u.join(t,"node_modules","@a-company","university"),i=A(n);i&&i.id&&i.tenant_kind&&e.push({id:i.id,name:i.name,tenantKind:i.tenant_kind,packRoot:n,disciplines:i.disciplines,entryCount:x(n)});let s=u.join(t,N);if(c.existsSync(s)){let r=A(s),a=r?.id??u.basename(t),o=r?.tenant_kind??"project";e.push({id:a,name:r?.name,tenantKind:o,packRoot:s,disciplines:r?.disciplines,entryCount:x(s)});try{let d=c.readdirSync(s,{withFileTypes:!0});for(let f of d){if(!f.isDirectory()||f.name.startsWith("."))continue;let l=u.join(s,f.name),v=A(l);!v||!v.id||e.push({id:v.id,name:v.name,tenantKind:v.tenant_kind??"project",packRoot:l,disciplines:v.disciplines,entryCount:x(l)});}}catch{}}return e}function ne(t,e){let n=qt(t),i;if(e.pack){let s=n.find(r=>r.id===e.pack);if(s)i={packId:s.id,packRoot:s.packRoot,tenantKind:s.tenantKind,hasManifest:true};else {let r=u.join(t,N);i={packId:e.pack,packRoot:r,hasManifest:false};}}else if(e.project){let s=n.find(a=>a.tenantKind==="project"&&!a.disciplines),r=u.join(t,N);s?i={packId:s.id,packRoot:s.packRoot,tenantKind:s.tenantKind,hasManifest:true}:i={packId:u.basename(t),packRoot:r,hasManifest:false};}else {let s=n.find(r=>r.tenantKind==="project");if(s)i={packId:s.id,packRoot:s.packRoot,tenantKind:s.tenantKind,hasManifest:true};else {let r=n.find(a=>a.tenantKind==="first-party");if(r)i={packId:r.id,packRoot:r.packRoot,tenantKind:r.tenantKind,hasManifest:true};else {let a=u.join(t,N);i={packId:u.basename(t),packRoot:a,hasManifest:false};}}}if(e.discipline){let s=u.join(i.packRoot,e.discipline),r=A(s);r&&r.id?(i.subPackRoot=s,i.subPackId=r.id):c.existsSync(s)&&(i.subPackRoot=s,i.subPackId=`${i.packId}-${e.discipline}`);}return i}function ie(t){return !!(t.pack||t.project||t.discipline)}function Qt(t){let e=U(t);return e&&x(t)>0?e:null}function Bt(t){return z(t)}function Gt(t,e,n,i){let s=bt(e,i);return ct(t,s,n,{packRoot:i,stampPackId:false,resolveDefaultPack:false})}function Yt(t,e,n){let i=bt(e,n);return lt(t,i,{packRoot:n,stampPackId:false,resolveDefaultPack:false})}function bt(t,e){if(!e)return t;let n=Z(e);return n&&!t.pack_id?{...t,pack_id:n}:t}export{O as a,at as b,dt as c,ft as d,ut as e,pt as f,yt as g,vt as h,ee as i,qt as j,ne as k,ie as l,Qt as m,Bt as n,Gt as o,Yt as p};
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {r,i,a as a$2,f}from'./chunk-TMDPDIWA.js';import {a as a$1,b as b$4,c as c$2}from'./chunk-M4UMM6DC.js';import {j,b as b$3,a as a$4}from'./chunk-GRZQIKST.js';import {j as j$1,a,c as c$1,b as b$2,k}from'./chunk-6QXBXZF6.js';import {b as b$1,a as a$3}from'./chunk-EK4ZRIFJ.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as m from'fs';import*as y from'path';import*as ee from'crypto';import {execSync}from'child_process';import*as O from'js-yaml';import*as xe from'os';import Hn from'sql.js';import {z}from'zod';var xt={};c(xt,{contentSearch:()=>Un,detectFileRename:()=>bt,generateFingerprint:()=>yt,levenshteinDistance:()=>wt,levenshteinSimilarity:()=>$e,searchSiblingFiles:()=>Et,slidingWindowSearch:()=>_e});function yt(t){let e=t.split(`
|
|
3
|
+
`).filter(r=>r.trim()!=="");return {firstLine:Te(e[0]||""),lastLine:Te(e[e.length-1]||""),lineCount:e.length,structuralHash:St(e)}}function St(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 ee.createHash("sha256").update(e).digest("hex").slice(0,16)}function Te(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function wt(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 a=1;a<=r;a++){let c=t[a-1]===e[i-1]?0:1;o[a]=Math.min(s[a]+1,o[a-1]+1,s[a-1]+c);}[s,o]=[o,s];}return s[r]}function $e(t,e){if(t.length===0&&e.length===0)return 1;let r=Math.max(t.length,e.length);return 1-wt(t,e)/r}function _e(t,e,r,n=3){let{lineCount:s}=e,o=Math.max(1,Math.floor(s*.8)),i=Math.ceil(s*1.2),a=[],c=Fe(r);for(let l of [s,o,i])if(!(l>t.length))for(let u=0;u<=t.length-l;u++){let f=t.slice(u,u+l),h=Dn(f,e,c);if(h>=.5){let p=f.join(`
|
|
4
|
+
`);a.push({windowStart:u+1,windowEnd:u+l,similarity:$e(Fe(p),c),score:h});}}let d=new Map;for(let l of a){let u=d.get(l.windowStart);(!u||l.score>u.score)&&d.set(l.windowStart,l);}return Array.from(d.values()).sort((l,u)=>u.score-l.score).slice(0,n)}function Dn(t,e,r){let n=t.filter(f=>f.trim()!=="");if(n.length===0)return 0;let s=0,o=Te(n[0]),i=Te(n[n.length-1]),a=0;o===e.firstLine&&(a+=.5),i===e.lastLine&&(a+=.5),s+=a*Nn,St(n)===e.structuralHash&&(s+=Fn);let d=n.join(`
|
|
5
|
+
`),l=$e(Fe(d),r);l>=.8&&(s+=(l-.8)/.2*$n);let u=n.length/e.lineCount;if(u>=.8&&u<=1.2){let f=1-Math.abs(1-u)/.2;s+=f*Mn;}return s}function Fe(t){return t.split(`
|
|
6
|
+
`).map(e=>e.trim()).filter(e=>e!=="").join(`
|
|
7
|
+
`)}function bt(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=y.isAbsolute(e)?e:y.join(t,e);if(!m.existsSync(o))return [];let i=[];try{let a=m.readdirSync(o).filter(c=>!c.startsWith(".")&&m.statSync(y.join(o,c)).isFile()).slice(0,s);for(let c of a)try{let l=m.readFileSync(y.join(o,c),"utf8").split(`
|
|
9
|
+
`),u=_e(l,r,n,1);if(u.length>0&&u[0].score>=.7){let f=y.relative(t,y.join(o,c));i.push({file:f,score:u[0].score,start:u[0].windowStart,end:u[0].windowEnd});}}catch{}}catch{return []}return i.sort((a,c)=>c.score-a.score)}function Un(t,e,r,n=true){let s=yt(r),o=y.isAbsolute(e)?e:y.join(t,e);if(m.existsSync(o)){let l=m.readFileSync(o,"utf8").split(`
|
|
10
|
+
`),u=_e(l,s,r);if(u.length>0){let f=u[0];return {found:f.score>=.7,score:f.score,suggestedStart:f.windowStart,suggestedEnd:f.windowEnd,similarity:f.similarity}}}let i=bt(t,e);if(i){let d=y.join(t,i);if(m.existsSync(d)){let u=m.readFileSync(d,"utf8").split(`
|
|
11
|
+
`),f=_e(u,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 a=y.dirname(e),c=Et(t,a,s,r);if(c.length>0&&c[0].score>=.7){let d=c[0];return {found:true,score:d.score,suggestedStart:d.start,suggestedEnd:d.end,suggestedPath:d.file!==e?d.file:void 0,similarity:d.score}}return {found:false,score:0}}var ht,Nn,Fn,$n,Mn,Tt=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 )/;Nn=.4,Fn=.3,$n=.2,Mn=.1;});var yn="0.1.0",Sn="1.0.0";function Le(t,e){let r={$meta:wn(e.projectName,t),components:{},features:{},flows:{},state:{},gates:{},signals:{},aspects:{},screens:{},symbolMap:{}};for(let s of t.symbols)bn(s,r,e);if(e.screenDefinitions)for(let[s,o]of Object.entries(e.screenDefinitions))r.screens[s]||(r.screens[s]={id:s,name:Q(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),Rn(r),r}function wn(t,e){return {version:Sn,project:t,generatedAt:new Date().toISOString(),paradigmVersion:yn,sources:{purposeFiles:e.purposeFiles.length,portalFiles:e.portalFiles.length,premiseFiles:e.symbols.filter(r=>r.source==="premise").length>0?1:0}}}function bn(t,e,r){let{type:n}=t;switch(n){case "component":En(t,e,r);break;case "feature":xn(t,e,r);break;case "flow":Tn(t,e);break;case "state":_n(t,e);break;case "gate":vn(t,e);break;case "signal":kn(t,e);break;case "aspect":In(t,e);break;}}function En(t,e,r){let n=se(t.symbol),s=dt(n,t.data,r.visualTagMappings),o={id:n,name:Q(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 xn(t,e,r){let n=se(t.symbol),s=dt(n,t.data,r.visualTagMappings),o={id:n,name:Q(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 Tn(t,e){let r=se(t.symbol),n=t.data,s=[];if(n?.steps)for(let i=0;i<n.steps.length;i++){let a=n.steps[i];s.push({id:`${r}-step-${i}`,name:a.action||`Step ${i+1}`,target:a.component,description:a.description,order:i});}let o={id:r,name:Q(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 _n(t,e){let r=se(t.symbol),n={id:r,name:Q(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 vn(t,e){let r=se(t.symbol),n={id:r,name:Q(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 kn(t,e){let r=se(t.symbol),n={id:r,name:Q(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 In(t,e){let r=se(t.symbol),n={id:r,name:Q(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 Rn(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 se(t){return t.slice(1)}function Q(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function dt(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 je(t){return JSON.stringify(t,null,2)}function Oe(t,e="unknown"){j$1().trackToolCall(e,t);}function gr(t,e="paradigm://unknown"){j$1().trackResourceRead(e,t);}function Pn(){k();}function Cn(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 yr(t,e){let r=j$1(),{summary:n,symbol:s}=Cn(t,e);r.addBreadcrumb("tool-call",n,{tool:t,symbol:s});}function Sr(){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 wr(t,e,r){let n=j$1();if(t==="paradigm_session_health"||t==="paradigm_context_check"){let s=e.contextWindowSize||2e5,o=e.estimatedTotalTokens,i=n.getStats(),{recommendation:a,message:c,usagePercent:d,signals:l}=n.getHandoffRecommendation(s,o),u=n.getDurationMinutes();return {handled:true,text:JSON.stringify({recommendation:a,message:c,stats:{sessionDurationMinutes:u,mcpToolCalls:i.totals.toolCallCount,mcpResourceReads:i.totals.resourceReadCount,estimatedMcpTokens:i.totals.totalTokens,estimatedTotalTokens:o||Math.round(i.totals.totalTokens*5),contextWindowSize:s,usagePercent:d},signals:l,action:a==="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",a$1=e.modifiedFiles||[],c=e.symbolsTouched||[],d=e.openQuestions||[],l=n.getStats(),u=n.getCostBreakdown(),f=`h${Date.now().toString(36)}`,h=new Date().toISOString(),p={id:f,timestamp:h,from:"current-session",to:i,summary:s,nextSteps:o,modifiedFiles:a$1,symbolsTouched:c,openQuestions:d,sessionStats:{duration:n.getDurationMinutes(),mcpCalls:l.totals.toolCallCount+l.totals.resourceReadCount,estimatedTokens:l.totals.totalTokens,estimatedCostUsd:u.total.costUsd,model:u.model},status:"pending"},g=false;try{a(r.rootDir,p),g=!0;}catch{}let S=`# Handoff: ${h}
|
|
12
|
+
|
|
13
|
+
## Session Summary
|
|
14
|
+
${s}
|
|
15
|
+
|
|
16
|
+
## Next Steps
|
|
17
|
+
${o.map((w,R)=>`${R+1}. ${w}`).join(`
|
|
18
|
+
`)||"(none specified)"}
|
|
19
|
+
|
|
20
|
+
## Key Context
|
|
21
|
+
- Modified files: ${a$1.length>0?a$1.join(", "):"(not specified)"}
|
|
22
|
+
- Symbols touched: ${c.length>0?c.join(", "):"(not specified)"}
|
|
23
|
+
- Open questions: ${d.length>0?d.join(", "):"(none)"}
|
|
24
|
+
`;return Pn(),{handled:true,text:JSON.stringify({handoff:p,markdownSummary:S,persisted:g,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}=ut(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 a={found:true};if(s){let d=Date.now()-s.timestamp,l=Math.round(d/6e4),u=Math.round(d/36e5);a.checkpoint={phase:s.phase,context:s.context,age:u>1?`${u} hours ago`:`${l} 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 d=Date.now()-i.lastActivity,l=Math.round(d/6e4),u=Math.round(d/36e5),h=i.breadcrumbs.slice(-10).map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}));a.previousSession={sessionId:i.sessionId,startTime:new Date(i.startTime).toISOString(),lastActivity:new Date(i.lastActivity).toISOString(),age:u>1?`${u} hours ago`:`${l} minutes ago`},a.context={symbolsModified:i.symbolsModified,filesExplored:i.filesExplored},a.recentActions=h;}if(o.length>0){a.pendingHandoffs=o.map(d=>({id:d.id,timestamp:d.timestamp,from:d.from,to:d.to,summary:d.summary,nextSteps:d.nextSteps,modifiedFiles:d.modifiedFiles,symbolsTouched:d.symbolsTouched,openQuestions:d.openQuestions}));for(let d of o)try{c$1(r.rootDir,d.id);}catch{}}let c="Continue where the previous session left off.";if(s)c=`Previous session was in "${s.phase}" phase: ${s.context}`,s.decisions?.length&&(c+=` Key decisions: ${s.decisions.slice(0,2).join("; ")}`);else if(o.length>0){let d=o[o.length-1];c=`Handoff received: "${d.summary}". `,d.nextSteps.length>0&&(c+=`Start with: ${d.nextSteps[0]}`);}else if(i){let d=i.breadcrumbs.slice(-10);if(d.length>0){let l=d[d.length-1];l.symbol&&(c=`Last work involved ${l.symbol}. Consider checking its current state with paradigm_ripple.`);}}return a.suggestion=c,a.agentInstruction="Present a brief summary of the previous session, then ask the user what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking.",n.markRecovered(),{handled:true,text:JSON.stringify(a,null,2)}}if(t==="paradigm_session_checkpoint"){n.setRootDir(r.rootDir);let s=e.phase,o=e.context,i=e.externalId,a=e.plan,c=e.modifiedFiles,d=e.symbolsTouched,l=e.decisions,{checkpoint:u,persisted:f}=n.saveCheckpoint({phase:s,context:o,externalId:i,plan:a,modifiedFiles:c,symbolsTouched:d,decisions:l}),h=f.local||f.global;return {handled:true,text:JSON.stringify({saved:h,persisted:f,checkpoint:{phase:u.phase,context:u.context,sessionId:u.sessionId,...u.externalId?{externalId:u.externalId}:{},timestamp:new Date(u.timestamp).toISOString(),modifiedFiles:u.modifiedFiles?.length||0,symbolsTouched:u.symbolsTouched?.length||0,decisions:u.decisions?.length||0,recentBreadcrumbs:u.recentBreadcrumbs?.length||0},...h?{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 ut(t){let e=j$1();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 br(t){let{checkpoint:e,pendingHandoffs:r}=ut(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),a=i>1?`${i}h ago`:`${o}m ago`;n.push(`Previous session was in "${e.phase}" phase (${a}): ${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 a=i.tags.length>0?` [${i.tags.join(", ")}]`:"";n.push(` [${i.priority}] ${i.id}: ${i.blurb}${a}`);}}}catch{}try{let{loadLoreEntries:s}=await import('./lore-loader-PXFKMKAN.js'),i=(await s(t,{limit:10})).filter(a=>a.tags?.some(c=>c.startsWith("arc:")));if(i.length>0){let a=new Map;for(let l of i){let u=l.tags?.find(f=>f.startsWith("arc:"))||"";a.set(u,(a.get(u)||0)+1);}let c=e?.symbolsTouched||[];if((c.length>0?i.filter(l=>l.symbols_touched?.some(u=>c.includes(u))):i.slice(0,3)).length>0||a.size>0){n.push(""),n.push("Active lore arcs:");for(let[l,u]of a)n.push(` ${l} (${u} 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 Ne=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}}},ft=new Ne(3e4);var An=300*1e3,le=null;function mt(){le=null;}function q(t,e){return m.existsSync(y.join(t,e))}function Z(t,e){return m.existsSync(y.join(t,e))}function Ln(t,e,r){let n=t;try{if(!m.existsSync(n))return !1;let s=m.readdirSync(n,{withFileTypes:!0});for(let o of s){if(o.isFile()&&o.name.endsWith(e))return !0;if(o.isDirectory())try{if(m.readdirSync(y.join(n,o.name)).some(a=>a.endsWith(e)))return !0}catch{}}}catch{}return false}var jn={wisdom:t=>q(t,".paradigm/wisdom"),history:t=>q(t,".paradigm/history"),lore:t=>q(t,".paradigm/lore"),habits:t=>Z(t,".paradigm/habits.yaml"),sentinel:t=>{try{let e=y.join(t,".paradigm","config.yaml");return m.existsSync(e)?m.readFileSync(e,"utf-8").includes("sentinel"):!1}catch{return false}},flows:t=>Z(t,".paradigm/flow-index.json")||Z(t,".paradigm/flows.yaml"),fixtures:t=>Z(t,".paradigm/fixtures.yaml"),orchestration:t=>Z(t,".paradigm/agents.yaml"),tasks:t=>q(t,".paradigm/tasks"),assessment:t=>q(t,".paradigm/lore"),personas:t=>Ln(t,".persona"),protocols:t=>q(t,".paradigm/protocols"),symphony:()=>{let t=y.join(xe.homedir(),".paradigm","score");return m.existsSync(t)},university:t=>q(t,".paradigm/university"),agents:t=>{let e=y.join(xe.homedir(),".paradigm","agents");return q(t,".paradigm/agents")||m.existsSync(e)},"aspect-graph":t=>Z(t,".paradigm/aspect-graph.db"),pan:t=>Z(t,".pan")||Z(t,"nevr.yaml"),notebooks:t=>{let e=y.join(xe.homedir(),".paradigm","notebooks");return q(t,".paradigm/notebooks")||m.existsSync(e)}},pt=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(le&&Date.now()-le.timestamp<An)return le.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||jn[r];if(s)try{s(this.rootDir)&&e.add(r);}catch{}else e.add(r);}return le={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,a]of this.modules)if(o.has(i))try{let c=await a.handleTool(e,r,n,s);if(c.handled)return c}catch(c){return {handled:true,text:JSON.stringify({error:`Tool handler error in module "${i}"`,message:c.message},null,2)}}return null}get size(){return this.modules.size}getRegistryInfo(){let e=this.detectActiveFeatures(),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 Me=null;async function zn(){return Me||(Me=await Hn()),Me}var Wn=[`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
|
+
)`],Gn=["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
|
+
)`],Bn="CREATE VIRTUAL TABLE IF NOT EXISTS aspects_fts USING fts5(id, description, enforcement, tags)";function W(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 Xn(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 vt(t){let e=await zn(),r=y.join(t,".paradigm"),n=y.join(r,"aspect-graph.db"),s;if(m.existsSync(n)){let o=m.readFileSync(n);s=new e.Database(o);}else m.existsSync(r)||m.mkdirSync(r,{recursive:true}),s=new e.Database;for(let o of Wn)s.run(o);try{s.run(Bn);}catch{}for(let o of Gn)try{s.run(o);}catch{}return s}function kt(t,e){if(e){let r=y.join(e,".paradigm");m.existsSync(r)||m.mkdirSync(r,{recursive:true});let n=y.join(r,"aspect-graph.db"),s=t.export();m.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 a=i.data??{},c=Vn(a,i),d=Kn(a,i),l=a.value!=null?String(a.value):null,u=i.enforcement??(a.enforcement!=null?String(a.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??"",c,d,l,u,i.filePath,f,i.created??s,i.modified??s]),i.anchors)for(let p of i.anchors){let{startLine:g,endLine:S}=Rt(p),w=Yn();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,g,S,w.exact,w.normalized,o,s,w.normalizedContent]);}let h=a.edges;if(Array.isArray(h))for(let p of h)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??"",u??"",f??""]);}catch{}}}function Ar(t,e){return Xn(t,"SELECT * FROM aspects WHERE id = ?",[e])}function Lr(t,e){return W(t,"SELECT * FROM anchors WHERE aspect_id = ?",[e])}function jr(t,e){return W(t,"SELECT * FROM edges WHERE source = ?",[e])}function Or(t,e){return W(t,"SELECT * FROM edges WHERE target = ?",[e])}function Nr(t,e){return W(t,"SELECT * FROM edges WHERE source = ? OR target = ?",[e,e])}function Fr(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 $r(t,e=20,r){return r?W(t,"SELECT * FROM heatmap WHERE access_type = ? ORDER BY count DESC LIMIT ?",[r,e]):W(t,"SELECT * FROM heatmap ORDER BY count DESC LIMIT ?",[e])}function Mr(t,e,r$1,n=true,s=.7,o=.85){let i=r$1?W(t,"SELECT * FROM anchors WHERE aspect_id = ?",[r$1]):W(t,"SELECT * FROM anchors"),a=[];for(let c of i){let l=W(t,"SELECT defined_in FROM aspects WHERE id = ?",[c.aspect_id])[0]?.defined_in,u=l?y.dirname(y.isAbsolute(l)?l:y.resolve(e,l)):e,f=r(c.file_path,u,e),h=f.resolvedPath;if(!f.exists){a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"missing",resolvedBy:"none",exists:false,drifted:true});continue}try{let g=m.readFileSync(h,"utf8").split(`
|
|
100
|
+
`),S=Math.max(0,c.start_line-1),w=Math.min(g.length,c.end_line),R=g.slice(S,w).join(`
|
|
101
|
+
`),x=ee.createHash("sha256").update(R).digest("hex");if(c.content_hash!=null&&x===c.content_hash){a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1}),c.drifted===1&&t.run("UPDATE anchors SET drifted = 0 WHERE id = ?",[c.id]);continue}let F=ee.createHash("sha256").update(Ue(R)).digest("hex");if(c.normalized_hash!=null&&F===c.normalized_hash){t.run("UPDATE anchors SET content_hash = ?, drifted = 0 WHERE id = ?",[x,c.id]),a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"cosmetic",resolvedBy:"normalized-hash",exists:!0,drifted:!1});continue}if(c.content_hash==null&&c.normalized_hash==null){t.run("UPDATE anchors SET content_hash = ?, normalized_hash = ?, drifted = 0 WHERE id = ?",[x,F,c.id]),a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1});continue}let H=!1;if(c.materialized_at_commit){let T=Jn(e,c.file_path,c.materialized_at_commit,c.start_line,c.end_line);if(T){let _=Math.max(0,T.currentStart-1),b=Math.min(g.length,T.currentEnd),C=g.slice(_,b).join(`
|
|
102
|
+
`),V=ee.createHash("sha256").update(C).digest("hex");if(c.content_hash!=null&&V===c.content_hash){let K=n;if(K){t.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[T.currentStart,T.currentEnd,c.id]);let ie=W(t,"SELECT defined_in FROM aspects WHERE id = ?",[c.aspect_id]);ie.length>0&&De(e,ie[0].defined_in,c.file_path,c.start_line,c.end_line,T.currentStart,T.currentEnd);}a.push({aspectId:c.aspect_id,path:c.file_path,startLine:K?T.currentStart:c.start_line,endLine:K?T.currentEnd:c.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:T.currentStart,suggestedEnd:T.currentEnd,autoHealed:K}),H=!0;}else {let K=ee.createHash("sha256").update(Ue(C)).digest("hex");if(c.normalized_hash!=null&&K===c.normalized_hash){if(n){let ie=ee.createHash("sha256").update(C).digest("hex");t.run("UPDATE anchors SET start_line = ?, end_line = ?, content_hash = ?, drifted = 0 WHERE id = ?",[T.currentStart,T.currentEnd,ie,c.id]);let be=W(t,"SELECT defined_in FROM aspects WHERE id = ?",[c.aspect_id]);be.length>0&&De(e,be[0].defined_in,c.file_path,c.start_line,c.end_line,T.currentStart,T.currentEnd);}a.push({aspectId:c.aspect_id,path:c.file_path,startLine:n?T.currentStart:c.start_line,endLine:n?T.currentEnd:c.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:T.currentStart,suggestedEnd:T.currentEnd,autoHealed:n}),H=!0;}}}}if(H)continue;if(c.original_content){let{contentSearch:T}=(Tt(),d(xt)),_=T(e,c.file_path,c.original_content,n);if(_.found&&_.score>=s){if(n&&_.score>=o&&!_.suggestedPath&&_.suggestedStart&&_.suggestedEnd){t.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[_.suggestedStart,_.suggestedEnd,c.id]);try{t.run(`INSERT INTO anchor_history (anchor_id, action, old_start, old_end, new_start, new_end, confidence, healed_at)
|
|
103
|
+
VALUES (?, 'relocated', ?, ?, ?, ?, ?, ?)`,[c.id,c.start_line,c.end_line,_.suggestedStart,_.suggestedEnd,_.score,new Date().toISOString()]);}catch{}let C=W(t,"SELECT defined_in FROM aspects WHERE id = ?",[c.aspect_id]);C.length>0&&De(e,C[0].defined_in,c.file_path,c.start_line,c.end_line,_.suggestedStart,_.suggestedEnd),a.push({aspectId:c.aspect_id,path:c.file_path,startLine:_.suggestedStart,endLine:_.suggestedEnd,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:_.similarity,suggestedStart:_.suggestedStart,suggestedEnd:_.suggestedEnd,autoHealed:!0,drifted:!1});continue}a.push({aspectId:c.aspect_id,path:_.suggestedPath||c.file_path,startLine:c.start_line,endLine:c.end_line,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:_.similarity,suggestedStart:_.suggestedStart,suggestedEnd:_.suggestedEnd,autoHealed:!1,drifted:!0});continue}}t.run("UPDATE anchors SET drifted = 1 WHERE id = ?",[c.id]),a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"modified",resolvedBy:"none",exists:!0,currentContent:R,drifted:!0});}catch{a.push({aspectId:c.aspect_id,path:c.file_path,startLine:c.start_line,endLine:c.end_line,status:"modified",resolvedBy:"none",exists:true,drifted:true});}}return a}function Rt(t){let{lines:e}=t;return typeof e=="number"?{startLine:e,endLine:e}:Array.isArray(e)?e.length===2?{startLine:e[0],endLine:e[1]}:{startLine:Math.min(...e),endLine:Math.max(...e)}:{startLine:1,endLine:1}}function qn(t){let e=[],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 Jn(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=qn(o),a=0;for(let c of i){if(c.oldStart+c.oldCount<=n){a+=c.newCount-c.oldCount;continue}if(c.oldStart<s)return null;break}return a===0?null:{originalStart:n,originalEnd:s,currentStart:n+a,currentEnd:s+a}}function De(t,e,r,n,s,o,i){let a=y.isAbsolute(e)?e:y.join(t,e);if(!m.existsSync(a))return false;try{let c=m.readFileSync(a,"utf8"),d=n===s?`${r}:${n}`:`${r}:${n}-${s}`,l=o===i?`${r}:${o}`:`${r}:${o}-${i}`;if(!c.includes(d))return !1;let u=c.replace(d,l);return m.writeFileSync(a,u,"utf8"),!0}catch{return false}}function Ue(t){return t.split(`
|
|
104
|
+
`).map(e=>e.trimEnd()).filter(e=>e.trim()!=="").map(e=>e.replace(/\s+/g," ")).join(`
|
|
105
|
+
`)}function Yn(t,e,r$1){return {exact:null,normalized:null,normalizedContent:null};}function Vn(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 Kn(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();var Qn=/L-\d{4}-\d{2}-\d{2}-\d{3}/g;async function Pt(t,e){t.run("DELETE FROM lore_links");let r=await a$4(e);if(r.length===0)return 0;let n=Zn(r),s=new Map;for(let d of r)s.set(d.id,d);let o=new Set,i=t.exec("SELECT id, enforcement FROM aspects");if(i.length>0){let{columns:d,values:l}=i[0],u=d.indexOf("id"),f=d.indexOf("enforcement");for(let h of l){let p=String(h[u]),g=h[f];if(g&&typeof g=="string"){let S=g.match(Qn);if(S)for(let w of S)s.has(w)&&o.add(`${p}\0${w}`);}}}let a=t.exec("SELECT source, target FROM edges");if(a.length>0&&i.length>0){let d=es(t,a);for(let[l,u]of d)for(let f of u){let h=n.get(f);if(h)for(let p of h)o.add(`${l}\0${p}`);}}if(o.size===0)return 0;let c=t.prepare("INSERT OR IGNORE INTO lore_links (aspect_id, lore_id) VALUES (?, ?)");try{for(let d of o){let[l,u]=d.split("\0");c.bind([l,u]),c.step(),c.reset();}}finally{c.free();}return o.size}async function Hr(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 ts(e,s)}async function Ct(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 c of n[0].values)s.add(String(c[0]));if(s.size<2)return 0;let o=new Date().toISOString(),i=0,a=t.prepare(`INSERT OR IGNORE INTO edges (source, target, relation, weight, origin, created_at)
|
|
106
|
+
VALUES (?, ?, 'related-to', 0.3, 'learned', ?)`);try{for(let c of r){if(!c.symbols_touched||c.symbols_touched.length<2)continue;let d=[];for(let l of c.symbols_touched){let u=l.startsWith("~")?l.slice(1):l;s.has(u)&&d.push(u);}for(let l=0;l<d.length;l++)for(let u=l+1;u<d.length;u++){let[f,h]=d[l]<d[u]?[d[l],d[u]]:[d[u],d[l]];a.bind([f,h,o]),a.step(),a.reset(),i++;}}}finally{a.free();}return i}function Zn(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 es(t,e){let r=t.exec("SELECT id FROM aspects"),n=new Set;if(r.length>0)for(let d of r[0].values)n.add(String(d[0]));let s=new Map;if(e.length===0)return s;let{columns:o,values:i}=e[0],a=o.indexOf("source"),c=o.indexOf("target");for(let d of i){let l=String(d[a]),u=String(d[c]);if(n.has(l)){let f=s.get(l);f||(f=new Set,s.set(l,f)),f.add(u),f.add(`~${l}`);}if(n.has(u)){let f=s.get(u);f||(f=new Set,s.set(u,f)),f.add(l),f.add(`~${u}`);}}return s}async function ts(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(ns(o));}return n}function ns(t){return {id:t.id,title:t.title,summary:t.summary,timestamp:t.timestamp,symbolsTouched:t.symbols_touched}}var ce=".paradigm/personas",ss="index.yaml";async function de(t,e){let r=y.join(t,ce);if(!m.existsSync(r))return [];let n=m.readdirSync(r).filter(o=>o.endsWith(".persona")),s=[];for(let o of n)try{let i=m.readFileSync(y.join(r,o),"utf8"),a=O.load(i);a&&a.id&&s.push(a);}catch{}return rs(s,e)}async function ue(t,e){let r=y.join(t,ce,`${e}.persona`);if(!m.existsSync(r))return null;try{return O.load(m.readFileSync(r,"utf8"))}catch{return null}}function rs(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 Wr(t,e){let r=y.join(t,ce);m.mkdirSync(r,{recursive:true});let n=y.join(r,`${e.id}.persona`);if(m.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 m.writeFileSync(n,O.dump(o,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await fe(t),e.id}async function At(t,e,r){let n=await ue(t,e);if(!n)return false;let s=y.join(t,ce,`${e}.persona`),o={...n,...r,id:n.id,version:n.version,created:n.created,updated:new Date().toISOString()};return m.writeFileSync(s,O.dump(o,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await fe(t),true}async function Gr(t,e){let r=y.join(t,ce,`${e}.persona`);if(!m.existsSync(r))return {deleted:false,warnings:[]};let n=[],s=await de(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(a=>a.persona===e)&&n.push(`Persona ${o.id} step ${i.id} spawns ${e} \u2014 spawn will break`);}return m.unlinkSync(r),await fe(t),{deleted:true,warnings:n}}async function Br(t,e,r,n){let s=await ue(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 At(t,e,{journey:s.journey})}async function Xr(t,e,r){let n=await ue(t,e);if(!n)return {removed:false,warnings:[]};let s=n.journey.findIndex(a=>a.id===r);if(s===-1)return {removed:false,warnings:[]};let o=n.journey[s],i=[];if(o.produces)for(let a of Object.keys(o.produces)){let c=`{{produces.${a}}}`;for(let d=s+1;d<n.journey.length;d++){let l=n.journey[d];JSON.stringify(l).includes(c)&&i.push(`Step ${l.id} consumes {{produces.${a}}} from this step`);}}if(o.spawns&&o.spawns.length>0)for(let a of o.spawns)i.push(`Step spawns persona ${a.persona} \u2014 spawn chain will break`);return n.journey.splice(s,1),await At(t,e,{journey:n.journey}),{removed:true,warnings:i}}var os=/^[a-z][a-z0-9-]*$/,is=/^[a-z][a-z0-9-]*$/,as=/^(GET|POST|PUT|PATCH|DELETE)\s+\//;async function qr(t,e,r=false){let n=[],s=[];os.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 a of e.journey){is.test(a.id)||n.push({type:"invalid-step-id",step:a.id,detail:"Step ID must match /^[a-z][a-z0-9-]*$/"}),o.has(a.id)&&n.push({type:"duplicate-step-id",step:a.id,detail:`Duplicate step ID "${a.id}"`}),o.add(a.id),as.test(a.route)||n.push({type:"invalid-route",step:a.id,route:a.route,detail:'Route must match "METHOD /path" (e.g., "POST /api/auth/signup")'}),(!a.gates||a.gates.length===0)&&n.push({type:"missing-gates",step:a.id,detail:"Step must have at least one gate"}),(!a.expect||a.expect.status===void 0)&&n.push({type:"missing-expect",step:a.id,detail:"Step must have expect with status"});let d=JSON.stringify(a).match(/\{\{produces\.([^}]+)\}\}/g)||[];for(let l of d){let u=l.replace("{{produces.","").replace("}}","");i.has(u)||n.push({type:"unresolved-produces",step:a.id,key:u,detail:`{{produces.${u}}} used but not produced by a prior step`});}if(a.produces)for(let l of Object.keys(a.produces))i.add(l);}if(r){let a=y.join(t,"portal.yaml"),c=[],d=[];if(m.existsSync(a))try{let u=O.load(m.readFileSync(a,"utf8"));u.gates&&typeof u.gates=="object"&&(c=Object.keys(u.gates)),u.routes&&typeof u.routes=="object"&&(d=Object.keys(u.routes));}catch{}for(let u of e.journey)for(let f of u.gates)c.length>0&&!c.includes(f)&&n.push({type:"gate-not-found",step:u.id,gate:f,detail:`Gate ${f} not defined in portal.yaml`});for(let u of e.journey)if(d.length>0){let f=u.route;d.some(p=>He(p,f))||s.push({type:"route-not-in-portal",detail:`Route "${f}" (step ${u.id}) not found in portal.yaml`});}for(let u of e.journey)if(u.spawns)for(let f of u.spawns)await ue(t,f.persona)||n.push({type:"spawn-target-missing",step:u.id,detail:`Spawn target persona "${f.persona}" does not exist`});let l=await cs(t,e.id);if(l&&n.push({type:"spawn-cycle",detail:`Circular spawn dependency: ${l.join(" \u2192 ")}`}),d.length>0||c.length>0){let u=await de(t),f=new Set,h=new Set;for(let w of u)for(let R of w.journey){for(let x of R.gates)f.add(x);h.add(R.route);}let p=[],g=y.join(t,".paradigm","flow-index.json");if(m.existsSync(g))try{let w=JSON.parse(m.readFileSync(g,"utf8"));p=Object.keys(w.flows||{});}catch{}let S=new Set;for(let w of u)for(let R of w.journey)R.flow&&S.add(R.flow);return {persona:e.id,valid:n.length===0,errors:n,warnings:s,coverage:{routes:{covered:h.size,total:d.length,uncovered:d.filter(w=>!h.has(w))},gates:{covered:f.size,total:c.length,uncovered:c.filter(w=>!f.has(w))},flows:{covered:S.size,total:p.length,uncovered:p.filter(w=>!S.has(w))}}}}}return {persona:e.id,valid:n.length===0,errors:n,warnings:s}}function He(t,e){let r=n=>n.replace(/:[a-zA-Z_]+/g,":param").replace(/\{\{[^}]+\}\}/g,":param");return r(t)===r(e)}async function cs(t,e){let r=new Set,n=[];async function s(o){if(r.has(o)){let a=n.indexOf(o);return a!==-1?[...n.slice(a),o]:null}r.add(o),n.push(o);let i=await ue(t,o);if(i){for(let a of i.journey)if(a.spawns)for(let c of a.spawns){let d=await s(c.persona);if(d)return d}}return n.pop(),null}return s(e)}async function fe(t){let e=y.join(t,ce);m.mkdirSync(e,{recursive:true});let r=await de(t),n={},s={},o={};for(let u of r){let f=new Set,h=new Set,p=[],g=new Set;for(let S of u.journey){for(let w of S.gates)f.add(w);if(S.flow&&h.add(S.flow),p.push(S.route),S.spawns)for(let w of S.spawns)g.add(w.persona);}n[u.id]={name:u.name,trigger:u.trigger.type,spawned_by:u.trigger.spawned_by,steps:u.journey.length,gates:[...f],flows:[...h],routes:p,spawns:[...g],tags:u.tags||[]};for(let S of f)s[S]||(s[S]=[]),s[S].push(u.id);for(let S of p)o[S]||(o[S]=[]),o[S].push(u.id);}let i=[],a=y.join(t,"portal.yaml");if(m.existsSync(a))try{let u=O.load(m.readFileSync(a,"utf8"));u.routes&&typeof u.routes=="object"&&(i=Object.keys(u.routes).filter(h=>!Object.keys(o).some(p=>He(h,p))));}catch{}let c={},d=y.join(e,"chains");if(m.existsSync(d)){let u=m.readdirSync(d).filter(f=>f.endsWith(".yaml"));for(let f of u)try{let h=m.readFileSync(y.join(d,f),"utf8"),p=O.load(h);if(p&&p.id){let g=p.order.map(R=>R.persona),S=0,w=new Set;for(let R of g){let x=n[R];if(x){S+=x.steps;for(let F of x.gates)w.add(F);}}c[p.id]={description:p.description||"",order:g,total_steps:S,total_gates:w.size};}}catch{}}let l={version:"1.0",generated:new Date().toISOString(),personas:n,chains:c,gate_coverage:s,route_coverage:o,uncovered_routes:i};return m.writeFileSync(y.join(e,ss),O.dump(l,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),l}async function Jr(t){let e=await de(t),r=new Set,n=new Set,s=new Set;for(let l of e)for(let u of l.journey){for(let f of u.gates)r.add(f);n.add(u.route),u.flow&&s.add(u.flow);}let o=[],i=[],a=y.join(t,"portal.yaml");if(m.existsSync(a))try{let l=O.load(m.readFileSync(a,"utf8"));l.gates&&typeof l.gates=="object"&&(o=Object.keys(l.gates)),l.routes&&typeof l.routes=="object"&&(i=Object.keys(l.routes));}catch{}let c=[],d=y.join(t,".paradigm","flow-index.json");if(m.existsSync(d))try{let l=JSON.parse(m.readFileSync(d,"utf8"));c=Object.keys(l.flows||{});}catch{}return {routes:{covered:n.size,total:i.length,uncovered:i.filter(l=>!Array.from(n).some(u=>He(l,u)))},gates:{covered:r.size,total:o.length,uncovered:o.filter(l=>!r.has(l))},flows:{covered:s.size,total:c.length,uncovered:c.filter(l=>!s.has(l))},personas:e.length}}async function Yr(t,e){let r=await de(t),n=[];for(let s of r){let o=[],i=[];for(let a of s.journey)if((a.gates.includes(e)||a.flow===e||a.route===e||a.signals?.includes(e))&&(o.push(a.id),a.spawns))for(let d of a.spawns)i.push(d.persona);o.length>0&&n.push({persona:s.id,steps:o,spawns_blocked:i});}return n}function ls(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 ds(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?ls(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 Vr(t,e={}){let r=[];try{let{SentinelStorage:a}=await import('./dist-W3XCATBJ.js'),c=new a,l=(c.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.complete",scopeValue:t.id,limit:500})||[]).filter(p=>{let g=JSON.parse(p.data_json||"{}");return !(e.run_id&&g.run_id!==e.run_id||e.chain_id&&g.chain_id!==e.chain_id||e.environment&&g.environment!==e.environment)}),f=(c.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.fail",scopeValue:t.id,limit:500})||[]).filter(p=>{let g=JSON.parse(p.data_json||"{}");return !(e.run_id&&g.run_id!==e.run_id||e.chain_id&&g.chain_id!==e.chain_id||e.environment&&g.environment!==e.environment)}),h=new Map;for(let p of [...l,...f]){let g=JSON.parse(p.data_json||"{}");g.step_id&&h.set(g.step_id,g);}for(let p of t.journey){let g=h.get(p.id);if(!g){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 S=ds(p,{status:g.status,body:g.body,gates_traversed:g.gates_traversed,signals_fired:g.signals_fired});r.push({step_id:p.id,matched:!0,passed:S.length===0,assertions:S});}}catch{for(let a of t.journey)r.push({step_id:a.id,matched:false,assertions:[],message:"Sentinel unavailable \u2014 cannot validate events"});}let n=r.filter(a=>a.matched).length,s=r.filter(a=>a.passed).length,o=r.filter(a=>a.matched&&!a.passed).length,i=r.reduce((a,c)=>a+c.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 re=".paradigm/protocols",Lt="index.yaml";async function ze(t){let e=y.join(t,re);if(!m.existsSync(e))return [];let r=m.readdirSync(e).filter(s=>s.endsWith(".protocol")).sort(),n=[];for(let s of r)try{let o=m.readFileSync(y.join(e,s),"utf8"),i=O.load(o);i?.id&&i?.name&&n.push(i);}catch{}return n}async function us(t,e){let r=e.replace(/^P-/,""),n=y.join(t,re,`${r}.protocol`);if(m.existsSync(n))try{let o=m.readFileSync(n,"utf8");return O.load(o)}catch{return null}return (await ze(t)).find(o=>o.id===e)||null}async function Qr(t){let e=y.join(t,re,Lt);if(!m.existsSync(e))return null;try{let r=m.readFileSync(e,"utf8");return O.load(r)}catch{return null}}async function Zr(t,e,r=3){let n=await ze(t);if(n.length===0)return [];let s=ps(e);if(s.length===0)return [];let o=[];for(let i of n){let a=0;for(let l of i.trigger){let u=l.toLowerCase();for(let f of s)u.includes(f)&&(a+=3);}for(let l of i.tags){let u=l.toLowerCase();for(let f of s)(u.includes(f)||f.includes(u))&&(a+=2);}let c=i.name.toLowerCase(),d=i.description.toLowerCase();for(let l of s)c.includes(l)&&(a+=1),d.includes(l)&&(a+=1);for(let l of i.steps)if(l.notes){let u=l.notes.toLowerCase();for(let f of s)u.includes(f)&&(a+=.5);}a>0&&o.push({protocol:i,score:a});}return o.sort((i,a)=>a.score-i.score),o.slice(0,r)}async function eo(t,e){let r=y.join(t,re);m.existsSync(r)||m.mkdirSync(r,{recursive:true});let n=hs(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"},a=y.join(r,`${n}.protocol`);return m.writeFileSync(a,O.dump(i,{lineWidth:-1,noRefs:true}),"utf8"),s}async function to(t,e,r,n=false){let s=await us(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=y.join(t,re,`${o}.protocol`);return m.writeFileSync(i,O.dump(s,{lineWidth:-1,noRefs:true}),"utf8"),true}function fs(t,e){let r=[],n="current";if(e.exemplar){let s=y.join(t,e.exemplar);m.existsSync(s)?m.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=y.join(t,s.template_from);m.existsSync(o)||(r.push(`Template file missing: ${s.template_from}`),n="broken");}if(s.action==="modify"&&s.target){let o=y.join(t,s.target);!s.target.includes("{")&&!m.existsSync(o)&&(r.push(`Modify target missing: ${s.target}`),n="broken");}}return {status:n,issues:r}}async function jt(t){let e=await ze(t),r=[],n=0,s=0,o=0;for(let c of e){let d=fs(t,c);if(c.status!==d.status){c.status=d.status;let l=c.id.replace(/^P-/,""),u=y.join(t,re,`${l}.protocol`);m.existsSync(u)&&m.writeFileSync(u,O.dump(c,{lineWidth:-1,noRefs:true}),"utf8");}switch(d.status){case "current":n++;break;case "stale":s++;break;case "broken":o++;break}r.push({id:c.id,name:c.name,status:d.status,last_verified:c.last_verified,trigger:c.trigger,tags:c.tags});}let i={version:"1.0",generated:new Date().toISOString(),protocols:r,health:{total:e.length,current:n,stale:s,broken:o}},a=y.join(t,re);if(e.length>0){m.existsSync(a)||m.mkdirSync(a,{recursive:true});let c=y.join(a,Lt);m.writeFileSync(c,O.dump(i,{lineWidth:-1,noRefs:true}),"utf8");}return i}function no(t,e,r){if(!e||e.length<2)return null;let n={};for(let s of e){let o=y.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=y.join(t,s);if(!m.existsSync(i))continue;let c=m.readdirSync(i).filter(d=>{let l=y.extname(d);return [".ts",".tsx",".js",".jsx",".rs",".py"].includes(l)}).filter(d=>!o.some(l=>y.basename(l)===d));if(c.length>0){let d=y.join(s,c[0]),l=[...o.map(u=>({action:"create",target:u})),...r.map(u=>({action:"modify",target:u}))];return {hint:`This session created ${o.length} new files in ${s}/ following existing patterns. Consider recording a protocol.`,draft:{name:`Add a ${y.basename(s).replace(/s$/,"")}`,exemplar:d,steps:l}}}}return null}function ps(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(e=>e.length>1).filter(e=>!ms.has(e))}var ms=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 hs(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var gs={warn(){}},$t=gs;function ro(t){$t=t;}function pe(){return $t}var te="pack.yaml";var ys="paradigm.universityPack";var Mt=/^[a-z0-9][a-z0-9-]{0,63}$/,Ot=["track","index","chronological","featured"],Nt=64,Ss=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(Ot,{errorMap:()=>({message:`section.style must be one of ${Ot.join("|")}`})}),description:z.string().max(1e3).optional(),default:z.boolean({invalid_type_error:"section.default must be a boolean"}).optional()}).strict(),Dt=z.array(Ss).max(Nt,`sections must contain \u2264${Nt} entries`);z.object({sections:Dt.optional()}).passthrough();z.object({section:z.string().regex(Mt).optional(),order:z.number().int().min(0).max(9999).optional()}).passthrough();var Ht="@a-company/university",zt=".paradigm/university",Wt=".paradigm/cache/packs.json",M=class extends Error{constructor(t,e){super(`pack-load failed (${t}: ${e})`),this.errorClass=t,this.detail=e,this.name="PackLoadError";}},ws=["id","name","version","schema_version","tenant_kind"],bs=new Set(["first-party","project","external"]),Ft={id:"main",name:"Curriculum",order:1,style:"track",default:true};function Gt(t){if(t==null)return [{...Ft}];if(Array.isArray(t)&&t.length===0)return [{...Ft}];let e=Dt.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 M("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 M("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 M("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 Es(t){if(t&&typeof t=="object"&&"name"in t&&typeof t.name=="string"){let e=t.name;return e==="YAMLException"?"yaml syntax error":e}return "parse error"}function me(t){let e=y.join(t,te);if(!m.existsSync(e))throw new M("missing-manifest",`no ${te} at pack root`);let r;try{r=m.readFileSync(e,"utf-8");}catch{throw new M("manifest-unparseable","file read error")}let n;try{n=O.load(r);}catch(o){throw new M("manifest-unparseable",Es(o))}let s=n;if(!s||typeof s!="object")throw new M("manifest-invalid","manifest is not an object");for(let o of ws){let i=s[o];if(i==null||i==="")throw new M("missing-required-field",`required field ${String(o)} is missing or empty`)}if(!bs.has(String(s.tenant_kind)))throw new M("missing-required-field","tenant_kind must be one of first-party|project|external");return s.sections=Gt(s.sections),s}function xs(t){let e=vs(t);if(e)return e;let r=[],n=y.join(t,"node_modules",Ht);if(m.existsSync(y.join(n,te)))try{let o=me(n);r.push({manifest:o,rootDir:n,source:"first-party"});}catch(o){pe().warn("first-party pack manifest invalid",{errorClass:o instanceof M?o.errorClass:"other"});}for(let o of Ts(t))try{let i=me(o);r.push({manifest:i,rootDir:o,source:"npm"});}catch(i){pe().warn("npm pack manifest invalid",{errorClass:i instanceof M?i.errorClass:"other"});}let s=y.join(t,zt);if(m.existsSync(s)&&m.statSync(s).isDirectory()){let o=y.join(s,te),i;if(m.existsSync(o))try{i=me(s),r.push({manifest:i,rootDir:s,source:"local"});}catch(c){pe().warn("local pack manifest invalid",{errorClass:c instanceof M?c.errorClass:"other"});}let a=i?.id??"project";for(let c of _s(s))try{let d=me(c);r.push({manifest:d,rootDir:c,source:"local",parentPackId:a});}catch(d){pe().warn("discipline sub-pack manifest invalid",{errorClass:d instanceof M?d.errorClass:"other"});}}return ks(t,r),r}function Ts(t){let e=y.join(t,"package.json");if(!m.existsSync(e))return [];let r;try{r=JSON.parse(m.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=y.join(t,"node_modules");if(!m.existsSync(s))return [];let o=[];for(let i of n){if(i===Ht)continue;let a=y.join(s,i,"package.json");if(!m.existsSync(a))continue;let c;try{c=JSON.parse(m.readFileSync(a,"utf8"));}catch{continue}let d=c.paradigm?.universityPack;if(typeof d!="string"||d.length===0)continue;let l=y.resolve(y.dirname(a),d);m.existsSync(y.join(l,te))&&o.push(l);}return o}function _s(t){let e=[],r;try{r=m.readdirSync(t,{withFileTypes:!0});}catch{return e}for(let n of r){if(!n.isDirectory()||n.name.startsWith("."))continue;let s=y.join(t,n.name);m.existsSync(y.join(s,te))&&e.push(s);}return e}function Bt(t){try{return m.statSync(y.join(t,"node_modules")).mtime.getTime()}catch{return}}function Xt(t){try{return m.statSync(y.join(t,zt)).mtime.getTime()}catch{return}}function vs(t){let e=y.join(t,Wt);if(!m.existsSync(e))return null;let r;try{r=JSON.parse(m.readFileSync(e,"utf8"));}catch{return null}if(r.version!==1||!Array.isArray(r.packs))return null;let n=Bt(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 ks(t,e){let r=y.join(t,Wt);try{m.mkdirSync(y.dirname(r),{recursive:!0});let n={version:1,node_modules_mtime_ms:Bt(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}:{}}))};m.writeFileSync(r,JSON.stringify(n,null,2),"utf8");}catch{}}var ne=".paradigm/university",oe="content",ve="notes",he="policies",ge="quizzes",ye="paths",qt="diplomas",Ge="index.yaml",Jt="config.yaml";function Yt(t){return typeof t=="string"?{packRoot:t,stampPackId:true,resolveDefaultPack:true}:{packRoot:t?.packRoot,stampPackId:t?.stampPackId??true,resolveDefaultPack:t?.resolveDefaultPack??true}}function Vt(t,e,r){return e||(r?Be(t):y.join(t,ne))}function Be(t){let e=y.join(t,ne);if(m.existsSync(e))return e;try{let n=xs(t).find(s=>s.manifest.tenant_kind==="first-party");if(n)return n.rootDir}catch{}return e}function Se(t){if(!m.existsSync(t))return null;let e=y.join(t,te);if(m.existsSync(e))try{return me(t)}catch(n){pe().warn("pack manifest invalid, using implicit manifest",{errorClass:n instanceof M?n.errorClass:"other"});}let r=y.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:Gt(void 0)}}function Is(t,e,r){return e?{...t,...t.pack_id?{}:{pack_id:e.id},...t.discipline||!r?{}:{discipline:r}}:t}var Xe={name:"Project University",tagline:"Learn the codebase",institution:"Paradigm"},qe={primary:"#6366f1",secondary:"#8b5cf6",accent:"#f59e0b",background:"#0f172a",surface:"#1e293b",text:"#f8fafc",textMuted:"#94a3b8",success:"#22c55e",error:"#ef4444",font:"Inter, system-ui, sans-serif"},We={branding:Xe,theme:qe,content:{categories:[],defaultDifficulty:"beginner",requireApproval:false},diplomas:{includeGlobalPLSAT:true,customCertStyle:null}};function ke(t){let e=y.join(t,ne,Jt);if(!m.existsSync(e))return {...We};try{let r=m.readFileSync(e,"utf8"),n=O.load(r);return n?{branding:{...Xe,...n.branding||{}},theme:{...qe,...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}}:{...We}}catch{return {...We}}}function Kt(t){let e=y.join(t,Jt);if(!m.existsSync(e))return null;try{let r=m.readFileSync(e,"utf8"),n=O.load(r);return n?{branding:{...Xe,...n.branding||{}},theme:{...qe,...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}}:null}catch{return null}}function Qt(t){let e=y.join(t,te);if(!m.existsSync(e))return false;try{let r=m.readFileSync(e,"utf8"),n=O.load(r);return !n||!Array.isArray(n.sections)?!1:n.sections.some(s=>s&&typeof s.id=="string"&&s.id.length>0)}catch{return false}}function we(t){let e=y.join(t,ne,Ge);if(!m.existsSync(e))return null;try{let r=m.readFileSync(e,"utf8");return O.load(r)}catch{return null}}function Zt(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:O.load(e[1]),body:e[2].trim()}}catch{return null}}function Rs(t,e){return `---
|
|
107
|
+
${O.dump(t,{lineWidth:-1,noRefs:true,sortKeys:false})}---
|
|
108
|
+
|
|
109
|
+
${e}
|
|
110
|
+
`}function Ps(t,e,r){let n=Ve(t,e,".md",r);if(!n)return null;try{let s=m.readFileSync(n,"utf8"),o=Zt(s);if(!o)return null;let i=o.frontmatter;return {frontmatter:zs(i),body:o.body}}catch{return null}}function Cs(t,e,r,n){let{packRoot:s,stampPackId:o,resolveDefaultPack:i}=Yt(n),a=e.type==="policy"?he:ve,c=Vt(t,s,i),d=y.join(c,oe,a);m.mkdirSync(d,{recursive:true});let l=o?Se(c):null,u=Is(e,l),f=y.join(d,`${u.id}.md`),h=Rs(u,r);return m.writeFileSync(f,h,"utf8"),f}function en(t,e,r){let n=Ve(t,e,".yaml",r);if(!n)return null;try{let s=m.readFileSync(n,"utf8"),o=O.load(s);return !o||!o.id?null:Ws(o)}catch{return null}}function As(t,e,r){let{packRoot:n,stampPackId:s,resolveDefaultPack:o}=Yt(r),i=Vt(t,n,o),a=y.join(i,oe,ge);m.mkdirSync(a,{recursive:true});let c=s?Se(i):null,d={...e,...e.pack_id||!c?{}:{pack_id:c.id}},l=y.join(a,`${d.id}.yaml`);return m.writeFileSync(l,O.dump(d,{lineWidth:-1,noRefs:true}),"utf8"),l}function Je(t,e,r){let n=Ve(t,e,".yaml",r);if(!n)return null;try{let s=m.readFileSync(n,"utf8"),o=O.load(s);return !o||!o.id?null:o}catch{return null}}function Ls(t,e,r){let n=r??Be(t),s=y.join(n,oe,ye);m.mkdirSync(s,{recursive:true});let o=y.join(s,`${e.id}.yaml`);return m.writeFileSync(o,O.dump(e,{lineWidth:-1,noRefs:true}),"utf8"),o}function Ye(t,e,r){let n=r??y.join(t,ne),s=y.join(n,qt);if(!m.existsSync(s))return [];let o=[];try{let i=m.readdirSync(s).filter(a=>a.endsWith(".yaml"));for(let a of i)try{let c=m.readFileSync(y.join(s,a),"utf8"),d=O.load(c);if(!d||!d.id||e?.student&&d.student!==e.student||e?.type&&d.type!==e.type)continue;o.push(d);}catch{}}catch{}return o.sort((i,a)=>a.earnedAt.localeCompare(i.earnedAt))}function js(t,e,r){let n=r?Re(r):we(t);if(!n)return {entries:[],total:0,returned:0};let s=[...n.entries];if(e.type&&(s=s.filter(c=>c.type===e.type)),e.tag&&(s=s.filter(c=>c.tags.some(d=>d.startsWith(e.tag)))),e.difficulty&&(s=s.filter(c=>c.difficulty===e.difficulty)),e.symbol&&(s=s.filter(c=>c.symbols.some(d=>d===e.symbol))),e.author&&(s=s.filter(c=>c.author===e.author)),e.query){let c=e.query.toLowerCase();s=s.filter(d=>d.title.toLowerCase().includes(c)||d.id.toLowerCase().includes(c)||d.tags.some(l=>l.toLowerCase().includes(c)));}if(e.category&&(s=s.filter(c=>c.category===e.category)),e.section&&(s=s.filter(c=>c.section===e.section)),e.track){let c=ke(t),d=new Map;for(let l of c.content.categories)d.set(l.id,l.track||"core");s=s.filter(l=>(l.category&&d.get(l.category)||"core")===e.track);}let o=s.length,i=e.limit||20,a=s.slice(0,i);return {entries:a,total:o,returned:a.length}}var tn=[oe,"src/content"],nn=[ve,he,ge,ye];function Os(t){if(!m.existsSync(t))return false;for(let e of nn){let r=y.join(t,e);if(m.existsSync(r))try{if(m.readdirSync(r).some(n=>n.endsWith(".md")||n.endsWith(".yaml")))return !0}catch{}}return false}function sn(t){let e=rn(t);return e?y.join(t,e):null}function rn(t){let e=null;for(let r of tn){let n=y.join(t,r);if(m.existsSync(n)&&(e===null&&(e=r),Os(n)))return r}return e}function Ns(t){for(let e of tn){let r=y.join(t,e);if(!m.existsSync(r))continue;let n=0;for(let s of nn){let o=y.join(r,s);if(m.existsSync(o))try{n+=m.readdirSync(o).filter(i=>i.endsWith(".md")||i.endsWith(".yaml")).length;}catch{}}if(n>0)return n}return 0}function on(t,e){let r=[];for(let o of [ve,he]){let i=y.join(t,o);if(m.existsSync(i))try{for(let a of m.readdirSync(i).filter(c=>c.endsWith(".md")))try{let c=m.readFileSync(y.join(i,a),"utf8"),d=Zt(c);if(!d)continue;let l=d.frontmatter;r.push({id:l.id||a.replace(".md",""),title:l.title||a,type:l.type||(o===he?"policy":"note"),author:l.author||"unknown",created:l.created||"",updated:l.updated||"",tags:Array.isArray(l.tags)?l.tags:[],symbols:Array.isArray(l.symbols)?l.symbols:[],difficulty:l.difficulty||"beginner",file:`${e}/${o}/${a}`,...l.category?{category:l.category}:{},...typeof l.section=="string"&&l.section?{section:l.section}:{},...typeof l.order=="number"&&Number.isFinite(l.order)?{order:l.order}:{}});}catch{}}catch{}}let n=y.join(t,ge);if(m.existsSync(n))try{for(let o of m.readdirSync(n).filter(i=>i.endsWith(".yaml")))try{let i=m.readFileSync(y.join(n,o),"utf8"),a=O.load(i);if(!a||!a.id)continue;r.push({id:a.id,title:a.title||o,type:"quiz",author:a.author||"unknown",created:a.created||"",updated:a.updated||"",tags:a.tags||[],symbols:a.symbols||[],difficulty:a.difficulty||"beginner",file:`${e}/${ge}/${o}`,...a.category?{category:a.category}:{},...typeof a.section=="string"&&a.section?{section:a.section}:{},...typeof a.order=="number"&&Number.isFinite(a.order)?{order:a.order}:{}});}catch{}}catch{}let s=y.join(t,ye);if(m.existsSync(s))try{for(let o of m.readdirSync(s).filter(i=>i.endsWith(".yaml")))try{let i=m.readFileSync(y.join(s,o),"utf8"),a=O.load(i);if(!a||!a.id)continue;r.push({id:a.id,title:a.title||o,type:"path",author:a.author||"unknown",created:a.created||"",updated:a.updated||"",tags:a.tags||[],symbols:[],file:`${e}/${ye}/${o}`,...a.category?{category:a.category}:{},...typeof a.section=="string"&&a.section?{section:a.section}:{},...typeof a.order=="number"&&Number.isFinite(a.order)?{order:a.order}:{}});}catch{}}catch{}return r}function Ie(t){let e=y.join(t,ne),r=y.join(e,oe),n=on(r,oe),s=0,o=y.join(e,qt);if(m.existsSync(o))try{s=m.readdirSync(o).filter(c=>c.endsWith(".yaml")).length;}catch{}let i={version:"1.0",generatedAt:new Date().toISOString(),totalContent:n.length,entries:n,diplomaCount:s};m.mkdirSync(e,{recursive:true});let a=y.join(e,Ge);return m.writeFileSync(a,O.dump(i,{lineWidth:-1,noRefs:true}),"utf8"),i}function Re(t,e){let r=y.join(t,Ge);if(m.existsSync(r))try{let i=m.readFileSync(r,"utf8"),a=O.load(i);if(a)return a}catch{}let n=rn(t);if(!n)return {version:"1.0",generatedAt:new Date().toISOString(),totalContent:0,entries:[],diplomaCount:0};let s=y.join(t,n),o=on(s,n);return {version:"1.0",generatedAt:new Date().toISOString(),totalContent:o.length,entries:o,diplomaCount:0}}function Fs(t,e,r){let n=r?Re(r):we(t)||Ie(t),s=[],o=n.entries;e?.id&&(o=o.filter(l=>l.id===e.id));let i=null;e?.deep&&(i=an(t));let a=new Set(n.entries.map(l=>l.id));for(let l of o){if(l.title||s.push({contentId:l.id,severity:"error",check:"missing-title",message:"Content is missing a title",fix:"Add a title field to the content frontmatter"}),l.type==="quiz"&&$s(t,l.id,s,r),l.type==="path"&&Ms(t,l.id,a,s,r),i&&l.symbols.length>0){ke(t).content.categories.find(p=>p.id===l.category)?.validationStrictness==="relaxed";for(let p of l.symbols)i.has(p)||s.push({contentId:l.id,severity:"warning",check:"broken-symbol-ref",message:`Symbol "${p}" not found in scan-index`,fix:`Remove or update the symbol reference in ${l.id}`});}e?.deep&&l.symbols.length>0&&l.updated&&Bs(t,l,s);}Ds(t,n,s,r);let c=Ye(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&&s.push({contentId:l.id,severity:"warning",check:"diploma-score-mismatch",message:`Diploma percentage ${l.percentage} doesn't match score ${l.score}/${l.total} (expected ${u})`});}let d=Gs(t,n);return {status:s.some(l=>l.severity==="error")?"errors":s.length>0?"warnings":"healthy",totalContent:n.totalContent,checked:o.length,issues:s,symbolCoverage:d}}function $s(t,e,r,n){let s=en(t,e,n);if(!s){r.push({contentId:e,severity:"error",check:"unreadable-quiz",message:"Quiz file could not be parsed"});return}(!s.passThreshold||s.passThreshold<0||s.passThreshold>1)&&r.push({contentId:e,severity:"warning",check:"invalid-pass-threshold",message:`passThreshold should be between 0 and 1, got ${s.passThreshold}`,fix:"Set passThreshold to a value between 0.0 and 1.0"});for(let o of s.questions){if(!o.choices||typeof o.choices!="object"){r.push({contentId:e,severity:"error",check:"invalid-quiz-choices",message:`Question ${o.id} has no choices defined`});continue}(!o.correct||!(o.correct in o.choices))&&r.push({contentId:e,severity:"error",check:"invalid-quiz-answer",message:`Question ${o.id}: correct answer "${o.correct}" not found in choices [${Object.keys(o.choices).join(", ")}]`,fix:`Set correct to one of: ${Object.keys(o.choices).join(", ")}`});}}function Ms(t,e,r,n,s){let o=Je(t,e,s);if(!o){n.push({contentId:e,severity:"error",check:"unreadable-path",message:"Learning path file could not be parsed"});return}for(let i of o.steps)i.content.startsWith("plsat:")||r.has(i.content)||n.push({contentId:e,severity:"error",check:"broken-path-step",message:`Learning path step references "${i.content}" which doesn't exist`,fix:`Create content with id "${i.content}" or remove this step`});}function Ds(t,e,r,n){let s=n??y.join(t,ne),o=Se(s);if(!o||!o.sections||o.sections.length===0)return;let i=new Set(o.sections.map(d=>d.id)),a=o.sections.find(d=>d.default===true);for(let d of e.entries)d.section&&!i.has(d.section)&&r.push({contentId:d.id,severity:"warning",check:"dangling-section-ref",message:`Entry references section "${d.section}" which is not declared in pack.yaml`,fix:`Add a section with id "${d.section}" to pack.yaml, or remove the section field`});let c=new Map;for(let d of o.sections)c.set(d.id,0);for(let d of e.entries)d.section&&i.has(d.section)?c.set(d.section,(c.get(d.section)||0)+1):!d.section&&a&&c.set(a.id,(c.get(a.id)||0)+1);for(let d of o.sections)(c.get(d.id)||0)===0&&r.push({contentId:d.id,severity:"warning",check:"empty-section",message:`Section "${d.id}" has zero entries`,fix:`Add at least one entry with section: "${d.id}", or remove the section from pack.yaml`});}function Us(t,e){let r=we(t);if(!r)return [];let n=[];for(let s of r.entries)if(s.symbols.includes(e)){let o=cn(t,s,e);n.push({id:s.id,title:s.title,type:s.type,stale:o});}return n}function Hs(t,e,r){let n=r?Re(r):we(t);if(!n)return {paths:[],suggestedContent:[],extracurricular:[],diplomaCount:0,totalContent:0};let s=r&&Kt(r)||ke(t),o=new Set;for(let p of s.content.categories)p.excludeFromOnboarding&&o.add(p.id);let i=n.entries.filter(p=>!p.category||!o.has(p.category)),a=n.entries.filter(p=>p.category&&o.has(p.category)),c=i.filter(p=>p.type==="path"),d=e?Ye(t,{student:e},r):[],l=new Set(d.map(p=>p.source)),u=c.map(p=>{let g=Je(t,p.id,r);return {id:p.id,title:p.title,steps:g?.steps.length||0,completed:l.has(p.id)}}),f=i.filter(p=>p.type!=="path"&&(p.difficulty==="beginner"||p.tags.includes("onboarding"))).slice(0,10),h={paths:u,suggestedContent:f,extracurricular:a,diplomaCount:d.length,totalContent:n.totalContent};if(r&&Qt(r)){let g=(Se(r)?.sections??[]).slice().sort((S,w)=>S.order-w.order||S.id.localeCompare(w.id));if(g.length>0){let S=g.find(x=>x.default===true)??g[0],w=new Map;for(let x of g)w.set(x.id,[]);for(let x of n.entries){let F=x.section&&w.has(x.section)?x.section:S.id,H=w.get(F);H&&H.push(x);}let R=(x,F)=>{let H=typeof x.order=="number"?x.order:Number.POSITIVE_INFINITY,T=typeof F.order=="number"?F.order:Number.POSITIVE_INFINITY;return H-T||x.id.localeCompare(F.id)};h.sections=g.map(x=>({id:x.id,name:x.name,entries:(w.get(x.id)??[]).sort(R)}));}}return h}function Ve(t,e,r,n){let s=n??y.join(t,ne),o=sn(s)??y.join(s,oe);for(let i of [ve,he,ge,ye]){let a=y.join(o,i,`${e}${r}`);if(m.existsSync(a))return a}return null}function zs(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 Ws(t){return {...t,tags:t.tags||[],symbols:t.symbols||[],difficulty:t.difficulty||"beginner",passThreshold:t.passThreshold??.7,questions:t.questions||[]}}function an(t){let e=new Set,r=y.join(t,".paradigm","scan-index.json");if(!m.existsSync(r))return e;try{let n=m.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 Gs(t,e){let r=an(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 cn(t,e,r){if(!e.updated)return false;let n=new Date(e.updated).getTime();if(isNaN(n))return false;let s=y.join(t,".paradigm","scan-index.json");if(!m.existsSync(s))return false;try{let o=m.readFileSync(s,"utf8"),i=JSON.parse(o);if(i.symbols&&Array.isArray(i.symbols)){for(let a of i.symbols)if(a.symbol===r&&a.filePath){let c=y.join(t,a.filePath);if(m.existsSync(c)&&m.statSync(c).mtime.getTime()>n)return !0}}}catch{}return false}function Bs(t,e,r){for(let n of e.symbols)if(cn(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 Xs="PARADIGM_STRICT";function Pe(){let t=process.env[Xs];if(t===void 0||t==="")return false;let e=t.toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}var ln=new Set(["duplicate-key-detected"]);function qs(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 Ce=class{transforms=new Map;record(e,r,n=1){let s=qs(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=>ln.has(n.kind)).reduce((n,s)=>n+s.count,0);return {reindex_ts:new Date().toISOString(),transformations:e,lossy_count:r,strict_mode:Pe()}}hasLossy(){for(let e of this.transforms.values())if(ln.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 Js={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},Ys={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/"]},Vs={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"]},Ke={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 Oo(){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 No(t,e,r,n){if(t!=="paradigm_reindex")return {handled:false,text:""};try{let s=await Ks(r.rootDir,r);await n(),ft.clear(),mt();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 a=JSON.stringify(i,null,2);return Oe(a.length,t),{handled:!0,text:a}}catch(s){let o=JSON.stringify({error:s.message},null,2);return Oe(o.length,t),{handled:true,text:o}}}async function Ks(t,e){let r=[],n=new Ce,s;e?s=e.aggregation:s=await i(t);let o=e?.projectName||y.basename(t),i$1=y.join(t,".paradigm");m.existsSync(i$1)||m.mkdirSync(i$1,{recursive:true}),Qs(t,n),Zs(s.purposeFiles,n);let a=Le({symbols:s.symbols,purposeFiles:s.purposeFiles,portalFiles:s.portalFiles},{projectName:o}),c=y.join(i$1,"scan-index.json");m.writeFileSync(c,je(a),"utf8"),r.push(".paradigm/scan-index.json");let d=er(t,s),l=y.join(i$1,"navigator.yaml");m.writeFileSync(l,O.dump(d,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),r.push(".paradigm/navigator.yaml");let u=ir(t,s.purposeFiles),f$1=0;if(u&&Object.keys(u.flows).length>0){let b=y.join(i$1,"flow-index.json");m.writeFileSync(b,JSON.stringify(u,null,2),"utf8"),r.push(".paradigm/flow-index.json"),f$1=Object.keys(u.flows).length;}let h;try{let b=await vt(t);It(b,s.symbols,t);let C=await Pt(b,t),V=await Ct(b,t),K=b.exec("SELECT COUNT(*) FROM aspects")[0]?.values[0]?.[0]??0,ie=b.exec("SELECT COUNT(*) FROM anchors")[0]?.values[0]?.[0]??0,be=b.exec("SELECT COUNT(*) FROM edges")[0]?.values[0]?.[0]??0;kt(b,t),r.push(".paradigm/aspect-graph.db"),h={aspects:K,anchors:ie,edges:be,loreLinks:C};}catch{}let p=0;try{let b=await fe(t);p=Object.keys(b.personas).length,p>0&&r.push(".paradigm/personas/index.yaml");}catch{}let g;try{let b=await jt(t);b.health.total>0&&(g=b.health,r.push(".paradigm/protocols/index.yaml"));}catch{}let S;try{let b=y.join(t,".paradigm","university");if(m.existsSync(b)){let C=Ie(t);(C.totalContent>0||C.diplomaCount>0)&&(S={totalContent:C.totalContent,diplomaCount:C.diplomaCount},r.push(".paradigm/university/index.yaml"));}}catch{}let w;try{w=a$1(s,t);}catch{}let R;try{let b=b$4(s.symbols,t),C=b.missing+b.outOfBounds;C>0&&(R=C);}catch{}let x;try{x=c$2(s.purposeFiles,t);}catch{}let F;try{let b=[];for(let C of s.purposeFiles){let V=a$2(C);V.data&&b.push({filePath:C,data:V.data});}if(b.length>0){let V=f(b).issues.length;V>0&&(F=V);}}catch{}let H={};for(let b of s.symbols)H[b.type]=(H[b.type]||0)+1;let T={};for(let b of s.symbols)b.type==="component"&&b.componentType&&(T[b.componentType]=(T[b.componentType]||0)+1);let _=n.report();try{let b=y.join(i$1,"manifest.consistency.json");m.writeFileSync(b,JSON.stringify(_,null,2),"utf-8"),r.push(".paradigm/manifest.consistency.json");}catch{a$3.component("#reindex").warn("failed to write consistency manifest",{stage:"manifest-write"});}if(Pe()&&n.hasLossy())throw new Error(`reindex aborted: ${_.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:H,flowCount:f$1,aspectGraphStats:h,personaCount:p,protocolHealth:g,consistency:_,...Object.keys(T).length>0?{componentTypeBreakdown:T}:{},...S?{universityStats:S}:{},...w?{integrityReport:w}:{},...R!==void 0?{componentAnchorIssues:R}:{},...x?{purposeHealth:x}:{},...F!==void 0?{crossFileIssues:F}:{}}}function Qs(t,e){let r=y.join(t,"portal.yaml");if(!m.existsSync(r))return;let n;try{n=m.readFileSync(r,"utf-8");}catch{return}try{O.load(n);}catch(c){(c?.reason?.toLowerCase()||"").includes("duplicate")&&e.record("duplicate-key-detected","portal.yaml");return}let s;try{s=O.load(n,{schema:O.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 c=0;for(let d of Object.keys(i))d.startsWith("^")&&c++;c>0&&e.record("prefix-stripped","portal.yaml",c);}else Array.isArray(i)&&i.length>0&&e.record("array-coerced","portal.yaml");let a=o.routes;Array.isArray(a)&&a.length>0&&e.record("array-coerced","portal.yaml"),o.version||e.record("default-applied","portal.yaml");}function Zs(t,e){for(let r of t){let n;try{n=m.readFileSync(r,"utf-8");}catch{continue}try{O.load(n);}catch(l){(l?.reason?.toLowerCase()||"").includes("duplicate")&&e.record("duplicate-key-detected","purpose.yaml");continue}let s;try{s=O.load(n,{schema:O.FAILSAFE_SCHEMA});}catch{continue}if(!s||typeof s!="object")continue;let o=s,i=["components","features","gates","signals","aspects","states"],a=0;for(let l of i)Array.isArray(o[l])&&a++;a>0&&e.record("array-coerced","purpose.yaml",a);let c=(l,u)=>{if(!l||typeof l!="object"||Array.isArray(l))return 0;let f=0;for(let h of Object.keys(l))h.startsWith(u)&&f++;return f},d=c(o.gates,"^")+c(o.signals,"!")+c(o.aspects,"~")+c(o.components,"#")+c(o.features,"#");d>0&&e.record("prefix-stripped","purpose.yaml",d);}}function er(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:tr(t),key_files:nr(t),skip_patterns:sr(t),symbols:or(e.symbols,e.purposeFiles),...Object.keys(r).length>0?{symbolsByComponentType:r}:{}}}function tr(t){let e={};for(let[r,n]of Object.entries(Ys)){let s=n.filter(o=>m.existsSync(y.join(t,o)));if(s.length>0){let o=Object.values(Js).find(i=>i.category===r);e[r]={paths:s,symbol:o?.prefix||"@"};}}return e}function nr(t){let e={};for(let[r,n]of Object.entries(Vs)){let s=n.filter(o=>m.existsSync(y.join(t,o)));s.length>0&&(e[r]=s);}return e.config||(e.config=[]),e.entry||(e.entry=[]),e.types||(e.types=[]),e}function sr(t){let e={always:[...Ke.always],unless_testing:[...Ke.unless_testing],unless_docs:[...Ke.unless_docs]},r=y.join(t,".gitignore");if(m.existsSync(r))try{let s=m.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 rr(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 or(t,e,r){let n={};for(let s of t){let i=`${rr(s.type)}${s.id}`;if(s.filePath)n[i]=s.filePath;else {let a=e.find(c=>y.dirname(c).toLowerCase().includes(s.id.toLowerCase()));a&&(n[i]=y.dirname(a)+"/");}}return n}function ir(t,e){let r={},n={};for(let s of e)try{let o=m.readFileSync(s,"utf8"),i=O.load(o);if(!i?.flows)continue;if(Array.isArray(i.flows))for(let a of i.flows){let c=a;if(!c.name)continue;let d=`$${c.name}`,l=dn(c.steps);l.length>0&&(r[d]={id:d,description:c.description||"",steps:l,definedIn:y.relative(t,s)},un(d,l,n));}else for(let[a,c]of Object.entries(i.flows)){let d=a.startsWith("$")?a:`$${a}`,l=dn(c.steps);l.length>0&&(r[d]={id:d,description:c.description||"",trigger:c.trigger,steps:l,validation:c.validation,definedIn:y.relative(t,s)},un(d,l,n));}}catch{}return Object.keys(r).length===0?null:{version:"1.0",generatedAt:new Date().toISOString(),flows:r,symbolToFlows:n}}function dn(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 un(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{Fr as $,Cs as A,en as B,As as C,Je as D,Ls as E,js as F,Ns as G,Ie as H,Fs as I,Us as J,Hs as K,ze as L,us as M,Qr as N,Zr as O,eo as P,to as Q,fs as R,no as S,Pe as T,vt as U,kt as V,Ar as W,Lr as X,jr as Y,Or as Z,Nr as _,Oe as a,$r as aa,gr as b,Mr as ba,yr as c,Hr as ca,Sr as d,Oo as da,wr as e,No as ea,br as f,Ks as fa,pt as g,ft as h,de as i,ue as j,Wr as k,At as l,Gr as m,Br as n,Xr as o,qr as p,Jr as q,Yr as r,Vr as s,ro as t,te as u,ys as v,Be as w,Se as x,ke as y,Ps as z};
|