@a-company/paradigm 5.37.8 → 5.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/{accept-orchestration-SBZVK3H4.js → accept-orchestration-OATWIRHP.js} +1 -1
  2. package/dist/{aggregate-W66DM3GA.js → aggregate-A5S5MTCC.js} +1 -1
  3. package/dist/{beacon-5QVYV5DF.js → beacon-QVUD3MGP.js} +1 -1
  4. package/dist/{chunk-SI6SV76D.js → chunk-3DZK54RU.js} +72 -19
  5. package/dist/{chunk-KFNHCQ4R.js → chunk-4L7665QV.js} +1 -1
  6. package/dist/chunk-4VKSEOXZ.js +6 -0
  7. package/dist/{chunk-CHVQNRRT.js → chunk-5QOCKWK5.js} +1 -1
  8. package/dist/chunk-HOBHJPTL.js +24 -0
  9. package/dist/{chunk-T6IDXUUA.js → chunk-LWAIVOSF.js} +1 -1
  10. package/dist/chunk-NQ47TA6C.js +111 -0
  11. package/dist/{chunk-G7XFK2GI.js → chunk-RBLK34IA.js} +1 -1
  12. package/dist/chunk-RN4VE6P3.js +521 -0
  13. package/dist/{chunk-SUU6M4JH.js → chunk-TOYQ2QCB.js} +1 -1
  14. package/dist/{chunk-LBQBWIEX.js → chunk-Y4P4SGZV.js} +1 -1
  15. package/dist/chunk-ZJQY5PPP.js +7 -0
  16. package/dist/{commands-LMUD5L6R.js → commands-ANRJNG2W.js} +1 -1
  17. package/dist/compliance-D7GD6ZYC.js +6 -0
  18. package/dist/{constellation-CG7C4WFE.js → constellation-NWLXYATA.js} +1 -1
  19. package/dist/{cost-IDNVMAEV.js → cost-24UZSS2P.js} +1 -1
  20. package/dist/{diff-JVEYCXUC.js → diff-YGHBIJY5.js} +1 -1
  21. package/dist/dist-JZZJLVMR.js +2 -0
  22. package/dist/{dist-3ZCH25SG.js → dist-OG6MM4VY.js} +1 -1
  23. package/dist/dist-SE67SOXB.js +2 -0
  24. package/dist/doctor-WMVULMQD.js +2 -0
  25. package/dist/{flow-POQP27WA.js → flow-FVZR3YJ4.js} +1 -1
  26. package/dist/{hooks-IG2GOAHP.js → hooks-TFMMMB2H.js} +1 -1
  27. package/dist/index.js +5 -5
  28. package/dist/init-XYB62Q3X.js +2 -0
  29. package/dist/{integrity-UYDOOJDP.js → integrity-ROO3G43N.js} +1 -1
  30. package/dist/mcp.js +18 -10
  31. package/dist/{migrate-IBDE7VK4.js → migrate-Z5UQN57G.js} +1 -1
  32. package/dist/{orchestrate-RCAMBOIB.js → orchestrate-M5PBZBJQ.js} +1 -1
  33. package/dist/portal-check-ZMLVBIGW.js +8 -0
  34. package/dist/portal-compliance-6YR27IQU.js +2 -0
  35. package/dist/{probe-B22G2JKF.js → probe-3FTG6LYO.js} +1 -1
  36. package/dist/{reindex-FO5VMZVQ.js → reindex-I6LPAKCC.js} +1 -1
  37. package/dist/{review-6UAH6V3R.js → review-VMSX2PKI.js} +1 -1
  38. package/dist/{ripple-ZGDITCGB.js → ripple-FNZI47SH.js} +1 -1
  39. package/dist/sentinel.js +1 -1
  40. package/dist/{setup-3F5IK7MO.js → setup-FEWSYS3Y.js} +2 -2
  41. package/dist/{shift-CZMQWZWP.js → shift-PC6C7NUX.js} +4 -4
  42. package/dist/{snapshot-L2G56RPL.js → snapshot-3IYB67D4.js} +1 -1
  43. package/dist/{status-77M3SDIF.js → status-DB3KNLW3.js} +1 -1
  44. package/dist/{summary-LXLHFRN7.js → summary-PYTEIJ4U.js} +1 -1
  45. package/dist/{team-NSP6PMPS.js → team-PDK64JXI.js} +1 -1
  46. package/dist/{test-BQJMS4Y2.js → test-WLEPZQFC.js} +1 -1
  47. package/dist/{tools-BZUAEUSQ.js → tools-5ITPEPSV.js} +1 -1
  48. package/dist/{validate-VZXTJHGO.js → validate-BB6LRWIY.js} +1 -1
  49. package/dist/workspace-VMSPYIBV.js +2 -0
  50. package/package.json +2 -1
  51. package/templates/paradigm/specs/symbols.md +4 -2
  52. package/dist/chunk-3TR6LLXP.js +0 -111
  53. package/dist/chunk-3VF3CMCF.js +0 -521
  54. package/dist/chunk-J6KWGCHN.js +0 -24
  55. package/dist/chunk-QT2LKB3P.js +0 -7
  56. package/dist/chunk-SHD27BQX.js +0 -6
  57. package/dist/compliance-WJINB5DM.js +0 -6
  58. package/dist/dist-R3RWD35F.js +0 -2
  59. package/dist/dist-VXCZWVVJ.js +0 -2
  60. package/dist/doctor-QJ47XAUP.js +0 -2
  61. package/dist/init-HIBRSVUB.js +0 -2
  62. package/dist/portal-check-Z3OCQEQR.js +0 -8
  63. package/dist/portal-compliance-4MG5F2GI.js +0 -2
  64. package/dist/workspace-MKSQN7B2.js +0 -2
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-LBQBWIEX.js';import {a}from'./chunk-LKAT7IAK.js';import*as r from'fs';import*as i from'path';import e from'chalk';import W from'ora';import*as u from'js-yaml';async function v(l={}){let c=process.cwd(),o=i.join(c,".paradigm-workspace");console.log(e.blue(`
2
+ import {b}from'./chunk-Y4P4SGZV.js';import {a}from'./chunk-LKAT7IAK.js';import*as r from'fs';import*as i from'path';import e from'chalk';import W from'ora';import*as u from'js-yaml';async function v(l={}){let c=process.cwd(),o=i.join(c,".paradigm-workspace");console.log(e.blue(`
3
3
  \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510`)),console.log(e.blue("\u2502")+e.white.bold(" paradigm workspace init ")+e.blue("\u2502")),console.log(e.blue("\u2502")+e.gray(" Create a multi-project workspace ")+e.blue("\u2502")),console.log(e.blue(`\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
4
4
  `));let n=a.command("workspace-init").start("Creating workspace",{cwd:c});if(r.existsSync(o)&&!l.force){console.log(e.yellow(` .paradigm-workspace already exists. Use --force to overwrite.
5
5
  `)),n.success("Workspace already exists");return}let s=c,t=r.readdirSync(s,{withFileTypes:true}),a$1=[];for(let p of t){if(!p.isDirectory()||p.name.startsWith(".")||p.name==="node_modules")continue;let g=i.join(s,p.name),k=r.existsSync(i.join(g,".paradigm")),y=r.existsSync(i.join(g,".purpose"));if(k||y){let w=j(p.name,g);a$1.push({name:p.name,path:`./${p.name}`,...w&&{role:w}});}}if(a$1.length===0){console.log(e.yellow(" No sibling projects with .paradigm/ or .purpose found.")),console.log(e.gray(` Create .purpose files in sibling directories first.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {a,b}from'./chunk-4TXOVRWD.js';import {b as b$1}from'./chunk-VCKKJDLP.js';import {m}from'./chunk-T6IDXUUA.js';import*as u from'fs';import*as p from'path';import*as $ from'js-yaml';import g from'chalk';import q from'ora';var _={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},N={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/"]},z={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"]},G={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*"]};async function A(o,t,n={}){let r=n.quiet?null:q();r?.start("Generating navigator.yaml...");let s=M(o),e=L(o),c=H(o),i=U(t.symbols,t.purposeFiles),f={version:"1.0",generated:new Date().toISOString(),structure:s,key_files:e,skip_patterns:c,symbols:i},a=p.join(o,".paradigm"),l=p.join(a,"navigator.yaml");u.existsSync(a)||u.mkdirSync(a,{recursive:true}),u.writeFileSync(l,$.dump(f,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),r?.succeed(g.green("Navigator generated")),n.quiet||(console.log(g.gray(` Output: ${l}`)),console.log(g.gray(` Structure categories: ${Object.keys(s).length}`)),console.log(g.gray(` Symbol mappings: ${Object.keys(i).length}`)),console.log());}function M(o){let t={};for(let[n,r]of Object.entries(N)){let s=r.filter(e=>{let c=p.join(o,e);return u.existsSync(c)});if(s.length>0){let e=Object.values(_).find(c=>c.category===n);t[n]={paths:s,symbol:e?.prefix||"@"};}}return t}function L(o){let t={};for(let[n,r]of Object.entries(z)){let s=r.filter(e=>{let c=p.join(o,e);return u.existsSync(c)});s.length>0&&(t[n]=s);}return t.config||(t.config=[]),t.entry||(t.entry=[]),t.types||(t.types=[]),t}function H(o){let t={...G},n=p.join(o,".gitignore");if(u.existsSync(n))try{let s=u.readFileSync(n,"utf8").split(`
2
+ import {a,b}from'./chunk-4TXOVRWD.js';import {b as b$1}from'./chunk-VCKKJDLP.js';import {m}from'./chunk-LWAIVOSF.js';import*as u from'fs';import*as p from'path';import*as $ from'js-yaml';import g from'chalk';import q from'ora';var _={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},N={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/"]},z={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"]},G={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*"]};async function A(o,t,n={}){let r=n.quiet?null:q();r?.start("Generating navigator.yaml...");let s=M(o),e=L(o),c=H(o),i=U(t.symbols,t.purposeFiles),f={version:"1.0",generated:new Date().toISOString(),structure:s,key_files:e,skip_patterns:c,symbols:i},a=p.join(o,".paradigm"),l=p.join(a,"navigator.yaml");u.existsSync(a)||u.mkdirSync(a,{recursive:true}),u.writeFileSync(l,$.dump(f,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),r?.succeed(g.green("Navigator generated")),n.quiet||(console.log(g.gray(` Output: ${l}`)),console.log(g.gray(` Structure categories: ${Object.keys(s).length}`)),console.log(g.gray(` Symbol mappings: ${Object.keys(i).length}`)),console.log());}function M(o){let t={};for(let[n,r]of Object.entries(N)){let s=r.filter(e=>{let c=p.join(o,e);return u.existsSync(c)});if(s.length>0){let e=Object.values(_).find(c=>c.category===n);t[n]={paths:s,symbol:e?.prefix||"@"};}}return t}function L(o){let t={};for(let[n,r]of Object.entries(z)){let s=r.filter(e=>{let c=p.join(o,e);return u.existsSync(c)});s.length>0&&(t[n]=s);}return t.config||(t.config=[]),t.entry||(t.entry=[]),t.types||(t.types=[]),t}function H(o){let t={...G},n=p.join(o,".gitignore");if(u.existsSync(n))try{let s=u.readFileSync(n,"utf8").split(`
3
3
  `).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")).filter(e=>e.endsWith("/")||e.includes("*")||["node_modules","dist","build",".cache"].some(c=>e.includes(c))).slice(0,20);for(let e of s)t.always.includes(e)||t.always.push(e);}catch{}return t}function U(o,t,n){let r={},s=new Map;for(let e of t){let c=p.dirname(e);s.set(e,c);}for(let e of o){let i=`${W(e.type)}${e.id}`;if(e.path)r[i]=e.path;else if(e.directory)r[i]=e.directory;else {let f=t.find(a=>{let l=p.dirname(a),y=e.id.toLowerCase();return l.toLowerCase().includes(y)});f&&(r[i]=p.dirname(f)+"/");}}return r}function W(o){switch(o){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 "~";default:return "@"}}function P(o){return $.load(o)}async function ce(o,t){let n=o?p.resolve(o):process.cwd(),r=p.basename(n),s=q(),e=p.join(n,".paradigm"),c=u.existsSync(e)&&u.statSync(e).isFile(),i;t.output?i=p.resolve(t.output):c?i=p.join(n,".paradigm-scan-index.json"):(i=p.join(n,".paradigm","scan-index.json"),u.existsSync(p.dirname(i))||u.mkdirSync(p.dirname(i),{recursive:true})),t.quiet||console.log(g.blue(`
4
4
  \u{1F52D} Generating Paradigm Scan Index
5
5
  `));let f,a$1,l,y=[p.join(n,".paradigm"),p.join(n,".paradigm","config.yaml")];for(let h of y)if(u.existsSync(h)&&u.statSync(h).isFile())try{let m=u.readFileSync(h,"utf8"),F=P(m);f=F.scan,a$1=F.graph,l=F.context?.tiers;break}catch{}s.start("Aggregating symbols from purpose and portal files...");let d;try{d=await m(n);}catch(h){s.fail(g.red("Failed to aggregate symbols")),console.error(g.gray(h.message)),process.exit(1);}if(s.succeed(`Found ${d.symbols.length} symbols`),!t.quiet){let h={components:d.symbols.filter(m=>m.type==="component").length,flows:d.symbols.filter(m=>m.type==="flow").length,gates:d.symbols.filter(m=>m.type==="gate").length,signals:d.symbols.filter(m=>m.type==="signal").length,aspects:d.symbols.filter(m=>m.type==="aspect").length};console.log(g.gray(" Breakdown:"));for(let[m,S]of Object.entries(h))S>0&&console.log(g.gray(` ${m}: ${S}`));console.log();}s.start("Generating scan index...");let b$2=a({symbols:d.symbols,purposeFiles:d.purposeFiles,portalFiles:d.portalFiles},{projectName:r,visualTagMappings:f?.visualTagMappings,screenDefinitions:f?.screens});K(b$2,{hot:l?.["hot-threshold"],warm:l?.["warm-threshold"]});try{u.writeFileSync(i,b(b$2),"utf8"),s.succeed(g.green("Scan index generated"));}catch(h){s.fail(g.red("Failed to write scan index")),console.error(g.gray(h.message)),process.exit(1);}await A(n,d,{quiet:t.quiet});let j=await Y(n,d.purposeFiles,{quiet:t.quiet});if(j&&Object.keys(j.flows).length>0){let h=p.join(n,".paradigm","flow-index.json");u.writeFileSync(h,JSON.stringify(j,null,2),"utf8"),t.quiet||s.succeed(g.green(`Flow index generated (${Object.keys(j.flows).length} flows)`));}if(a$1?.["auto-generate"]!==false)try{let h=b$1(n),m=p.join(n,".paradigm","graphs");u.existsSync(m)||u.mkdirSync(m,{recursive:!0});let S=p.join(m,"auto.graph.json");u.writeFileSync(S,JSON.stringify(h,null,2),"utf8"),t.quiet||s.succeed(g.green(`Symbol graph updated (${h.nodes.length} nodes)`));}catch{t.quiet||s.warn(g.yellow("Could not auto-generate symbol graph"));}return t.quiet||(console.log(g.gray(`
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import*as l from'fs';import*as p from'path';import*as c from'js-yaml';import {glob}from'glob';var v={visualizerPort:42195,watcherPort:42196,autoConnect:true};async function F(e){let t=p.resolve(e),i=p.dirname(t);if(!l.existsSync(t))throw new Error(`Gate config not found: ${t}`);let s=l.readFileSync(t,"utf8"),n=c.load(s);if(!n.version)throw new Error('Gate config missing required "version" field');let o=[],a=n,h=n.gates||a.portals;if(h)for(let[r,d]of Object.entries(h)){let f=r.startsWith("^")?r.slice(1):r;o.push(u(f,d));}if(n.include)for(let r of n.include){let d=p.join(i,r),f=await glob(d.replace(/\\/g,"/"));for(let w of f){let $=await k(w);o.push(...$);}}let g=[];if(n.flows)for(let[r,d]of Object.entries(n.flows))g.push(b(r,d));return {version:n.version,gates:o,flows:g,settings:{dev:{...v,...n.settings?.dev}}}}async function k(e){let t=l.readFileSync(e,"utf8"),i=c.load(t);if(i.id){let s=i.id,n=s.startsWith("^")?s.slice(1):s;return [u(n,i)]}if(i.gates){let s=[];for(let[n,o]of Object.entries(i.gates)){let a=n.startsWith("^")?n.slice(1):n;s.push(u(a,o));}return s}return []}function u(e,t){let i=[];if(t.locks)for(let n of t.locks)i.push(z(n));let s=[];if(t.prizes)for(let n of t.prizes)s.push(x(n));return {id:e,description:t.description,locks:i,prizes:s,position:t.position}}function z(e){let t=e,i=[];if(t.keys){for(let s of t.keys)if(typeof s=="string")i.push({expression:s});else if(s.expression){let n=s;i.push({expression:n.expression,description:n.description});}}return {id:t.id,description:t.description,keys:i,mode:t.mode||"all"}}function x(e){let t=e;return {id:t.id,oneTime:t.oneTime??false,metadata:t.metadata}}function b(e,t){return {id:e,description:t.description,gates:t.gates||[],forkable:t.forkable}}function S(e){let t={version:e.version,gates:{},flows:{},settings:{dev:e.settings.dev}};for(let i of e.gates){let{id:s,...n}=i;t.gates[s]=n;}for(let i of e.flows){let{id:s,...n}=i;t.flows[s]=n;}return c.dump(t,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function E(){return c.dump({version:"1.0.0",gates:{"example-gate":{description:"An example gate to get you started",locks:[{id:"example-lock",description:"Requires user to be authenticated",keys:[{expression:"user.isAuthenticated === true"}]}],prizes:[{id:"example-prize",oneTime:true,metadata:{event:"first_access"}}]}},flows:{"example-flow":{description:"An example user journey",gates:["example-gate"]}},settings:{dev:{visualizerPort:42195,watcherPort:42196,autoConnect:true}}},{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}async function P(e){let t=p.resolve(e);return await glob("**/portal.yaml",{cwd:t,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})}function A(e){let t=[];e.version||t.push({type:"error",message:'Missing required "version" field',path:"version"});let i=new Set;for(let s of e.gates)D(s,i,t),i.add(s.id);for(let s of e.flows)C(s,i,t);return {valid:t.filter(s=>s.type==="error").length===0,issues:t}}function D(e,t,i){let s=`gates.${e.id}`;t.has(e.id)&&i.push({type:"error",message:`Duplicate gate ID: "${e.id}"`,path:s}),/^[a-z][a-z0-9-]*$/.test(e.id)||i.push({type:"warning",message:`Gate ID "${e.id}" should use kebab-case (e.g., "my-gate")`,path:s});let n=new Set;for(let a of e.locks)I(a,n,`${s}.locks`,i),n.add(a.id);let o=new Set;for(let a of e.prizes)o.has(a.id)&&i.push({type:"error",message:`Duplicate prize ID "${a.id}" in gate "${e.id}"`,path:`${s}.prizes`}),o.add(a.id),/^[a-z][a-z0-9-]*$/.test(a.id)||i.push({type:"warning",message:`Prize ID "${a.id}" should use kebab-case`,path:`${s}.prizes`});e.locks.length===0&&i.push({type:"warning",message:`Gate "${e.id}" has no locks - any entity can pass through`,path:s});}function I(e,t,i,s){let n=`${i}.${e.id}`;t.has(e.id)&&s.push({type:"error",message:`Duplicate lock ID: "${e.id}"`,path:n}),/^[a-z][a-z0-9-]*$/.test(e.id)||s.push({type:"warning",message:`Lock ID "${e.id}" should use kebab-case`,path:n}),e.keys.length===0&&s.push({type:"error",message:`Lock "${e.id}" has no keys - it can never be opened`,path:n});for(let o of e.keys)(!o.expression||o.expression.trim()==="")&&s.push({type:"error",message:`Key in lock "${e.id}" has empty expression`,path:`${n}.keys`}),o.expression.includes("==")&&!o.expression.includes("===")&&s.push({type:"warning",message:'Key expression uses "==" instead of "===" - consider using strict equality',path:`${n}.keys`});e.mode&&!["all","any"].includes(e.mode)&&s.push({type:"error",message:`Invalid lock mode "${e.mode}" - must be "all" or "any"`,path:n});}function C(e,t,i){let s=`flows.${e.id}`;/^[a-z][a-z0-9-]*$/.test(e.id)||i.push({type:"warning",message:`Flow ID "${e.id}" should use kebab-case`,path:s});for(let o of e.gates)t.has(o)||i.push({type:"error",message:`Flow "${e.id}" references unknown gate "${o}"`,path:`${s}.gates`});e.gates.length===0&&i.push({type:"warning",message:`Flow "${e.id}" has no gates`,path:s});let n=new Set;for(let o of e.gates)n.has(o)&&i.push({type:"warning",message:`Flow "${e.id}" contains duplicate gate "${o}"`,path:`${s}.gates`}),n.add(o);}function L(e){if(e.valid&&e.issues.length===0)return "\u2705 Configuration is valid";let t=[],i=e.issues.filter(n=>n.type==="error"),s=e.issues.filter(n=>n.type==="warning");if(i.length>0){t.push(`
3
+ \u274C ${i.length} error(s):`);for(let n of i)t.push(` \u2022 ${n.message}${n.path?` (${n.path})`:""}`);}if(s.length>0){t.push(`
4
+ \u26A0\uFE0F ${s.length} warning(s):`);for(let n of s)t.push(` \u2022 ${n.message}${n.path?` (${n.path})`:""}`);}return e.valid?t.push(`
5
+ \u2705 Configuration is valid (with warnings)`):t.push(`
6
+ \u274C Configuration is invalid`),t.join(`
7
+ `)}function R(e){if(e instanceof c.YAMLException){let t=(e.reason||"").toLowerCase();return t.includes("duplicated mapping key")||t.includes("duplicate mapping key")?{errorClass:"duplicate-key",detail:"duplicate mapping key"}:["unexpected","expected","bad indentation","mapping values","cannot read a block mapping entry","end of the stream","while scanning","while parsing"].some(s=>t.includes(s))?{errorClass:"syntax",detail:"yaml syntax error"}:{errorClass:"other",detail:"yaml parse error"}}return {errorClass:"other",detail:"yaml parse error"}}export{F as a,k as b,S as c,E as d,P as e,A as f,L as g,R as h};
@@ -421,7 +421,7 @@ import m from'chalk';import Ze from'sql.js';import {v4}from'uuid';import*as S fr
421
421
  SELECT id FROM events ORDER BY timestamp ASC LIMIT ?
422
422
  )`,[t]),this.save(),t}rowToGenericEvent(e,n){let t={};return e.forEach((s,r)=>{t[s]=n[r];}),{id:t.id,schemaId:t.schema_id,eventType:t.event_type,category:t.category,timestamp:t.timestamp,scopeValue:t.scope_value||void 0,scopeOrdinal:t.scope_ordinal!=null?t.scope_ordinal:void 0,sessionId:t.session_id||void 0,service:t.service,data:t.data_json?JSON.parse(t.data_json):void 0,severity:t.severity||"info",parentEventId:t.parent_event_id||void 0,depth:t.depth||0}}close(){this.db&&(this.save(),this.db.close(),this.db=null);}};var nt={minScore:30,maxResults:5,boostConfidence:true},q=class{constructor(e){this.storage=e;}match(e,n={}){let{minScore:t,maxResults:s,boostConfidence:r}={...nt,...n},i=this.storage.getAllPatterns({includePrivate:true}),a=[];for(let c of i){if(!this.matchEnvironment(c,e))continue;let{score:l,matchedCriteria:d}=this.scoreMatch(c,e);if(l>=t){let u=l;if(r){let g=c.confidence.score/100;u=l*(.5+.5*g);}a.push({pattern:c,score:l,matchedCriteria:d,confidence:Math.round(u)}),this.storage.updatePatternConfidence(c.id,"matched");}}return a.sort((c,l)=>l.confidence-c.confidence).slice(0,s)}testPattern(e,n=100){let t=this.storage.getRecentIncidents({limit:n}),s=[],r=0;for(let i of t){if(!this.matchEnvironment(e,i))continue;let{score:a}=this.scoreMatch(e,i);a>=30&&(s.push(i),r+=a);}return {wouldMatch:s,matchCount:s.length,avgScore:s.length>0?Math.round(r/s.length):0}}scoreMatch(e,n){let t=0,s={symbols:[],errorKeywords:[],missingSignals:[]},r=this.matchSymbols(e.pattern.symbols,n.symbols,s.symbols);t+=Math.min(r,50);let i=this.matchErrorText(e,n,s.errorKeywords);t+=Math.min(i,25);let a=this.matchMissingSignals(e,n,s.missingSignals);return t+=Math.min(a,25),t=Math.min(t,100),{score:t,matchedCriteria:s}}matchSymbols(e,n,t){let s=0,r=["feature","component","flow","gate","signal","state","integration"];for(let i of r){let a=e[i],c=n[i];if(!(!a||!c)){if(typeof a=="string")this.matchSingleSymbol(a,c)&&(s+=a.includes("*")?5:10,t.push(i));else if(Array.isArray(a)){for(let l of a)if(this.matchSingleSymbol(l,c)){s+=7,t.push(i);break}}}}return s}matchSingleSymbol(e,n){if(e==="*")return true;if(e.endsWith("*")){let t=e.slice(0,-1);return n.startsWith(t)}if(e.startsWith("*")){let t=e.slice(1);return n.endsWith(t)}return e.includes("*")?new RegExp("^"+e.replace(/\*/g,".*")+"$").test(n):e===n}matchErrorText(e,n,t){let s=0,r=n.error.message.toLowerCase(),i=n.error.type?.toLowerCase();if(e.pattern.errorContains)for(let a of e.pattern.errorContains)r.includes(a.toLowerCase())&&(s+=5,t.push(a));if(e.pattern.errorMatches)try{new RegExp(e.pattern.errorMatches,"i").test(n.error.message)&&(s+=10,t.push(`regex:${e.pattern.errorMatches}`));}catch{}if(e.pattern.errorType&&i)for(let a of e.pattern.errorType)i.includes(a.toLowerCase())&&(s+=5,t.push(`type:${a}`));return s}matchMissingSignals(e,n,t){if(!e.pattern.missingSignals||!n.flowPosition?.missing)return 0;let s=0;for(let r of e.pattern.missingSignals)for(let i of n.flowPosition.missing)if(this.matchSingleSymbol(r,i)){s+=12,t.push(i);break}return s}matchEnvironment(e,n){return !e.pattern.environment||e.pattern.environment.length===0?true:e.pattern.environment.includes(n.environment)}};var G=class{constructor(e){this.storage=e;}getStats(e=7){let n=new Date().toISOString(),t=new Date(Date.now()-e*24*60*60*1e3).toISOString();return this.storage.getStats({start:t,end:n})}getSymbolHealth(e){return this.storage.getSymbolHealth(e)}getTrendingIssues(e=7){let n=Date.now(),t=e*24*60*60*1e3/2,s=new Date(n-e*24*60*60*1e3).toISOString(),r=new Date(n-t).toISOString(),i=new Date(n).toISOString(),a=this.storage.getRecentIncidents({dateFrom:s,dateTo:r,limit:1e3}),c=this.storage.getRecentIncidents({dateFrom:r,dateTo:i,limit:1e3}),l=this.countSymbols(a),d=this.countSymbols(c),u=[],g=new Set([...l.keys(),...d.keys()]);for(let p of g){let y=l.get(p)||0,f=d.get(p)||0;if(y===0&&f>0)u.push({symbol:p,trend:f*100});else if(y>0){let T=(f-y)/y*100;u.push({symbol:p,trend:T});}}return u.filter(p=>p.trend>0).sort((p,y)=>y.trend-p.trend).slice(0,10)}getResolutionMetrics(){let e=this.getStats(30);return {avgTimeToResolve:e.resolution.avgTimeToResolve,resolvedWithPattern:e.resolution.resolvedWithPattern,resolvedManually:e.resolution.resolvedManually,totalResolved:e.incidents.resolved,resolutionRate:e.resolution.resolutionRate}}getPatternEffectiveness(){return this.storage.getAllPatterns({includePrivate:true}).filter(n=>n.confidence.timesMatched>0).map(n=>({patternId:n.id,name:n.name,matches:n.confidence.timesMatched,resolutions:n.confidence.timesResolved,recurrences:n.confidence.timesRecurred,effectiveness:n.confidence.timesMatched>0?Math.round((n.confidence.timesResolved-n.confidence.timesRecurred)/n.confidence.timesMatched*100):0})).sort((n,t)=>t.effectiveness-n.effectiveness)}getIncidentsByHour(e=7){let n=new Date(Date.now()-e*24*60*60*1e3).toISOString(),t=this.storage.getRecentIncidents({dateFrom:n,limit:1e4}),s=new Map;for(let r=0;r<24;r++)s.set(r,0);for(let r of t){let i=new Date(r.timestamp).getHours();s.set(i,(s.get(i)||0)+1);}return Array.from(s.entries()).map(([r,i])=>({hour:r,count:i}))}getIncidentsByEnvironment(){let e=this.getStats(30),n=e.incidents.total;return Object.entries(e.incidents.byEnvironment).map(([t,s])=>({environment:t,count:s,percentage:n>0?Math.round(s/n*100):0})).sort((t,s)=>s.count-t.count)}getSymbolCorrelation(){let e=this.storage.getRecentIncidents({limit:1e3}),n=new Map,t=new Map;for(let r of e){let i=this.getSymbolsFromIncident(r);for(let a of i)t.set(a,(t.get(a)||0)+1);for(let a=0;a<i.length;a++)for(let c=a+1;c<i.length;c++){let l=[i[a],i[c]].sort().join("|");n.set(l,(n.get(l)||0)+1);}}let s=[];for(let[r,i]of n){let[a,c]=r.split("|"),l=t.get(a)||1,d=t.get(c)||1,u=i/Math.max(l,d);u>.3&&s.push({symbol1:a,symbol2:c,correlation:Math.round(u*100)/100});}return s.sort((r,i)=>i.correlation-r.correlation).slice(0,20)}generateDashboard(e=7){let n=this.getStats(e),t=[];t.push("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),t.push("\u2551 PARADIGM SENTINEL DASHBOARD \u2551"),t.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");let s=n.incidents.byDay[n.incidents.byDay.length-1]?.count||0;t.push(`\u2551 Open: ${String(n.incidents.open).padEnd(4)} \u2502 Investigating: ${String(n.incidents.total-n.incidents.open-n.incidents.resolved).padEnd(3)} \u2502 Resolved: ${String(n.incidents.resolved).padEnd(4)} \u2502 Today: +${s} \u2551`),t.push("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),t.push(""),t.push("Incidents by Day (last 7 days):"),t.push("\u2500".repeat(50));let r=Math.max(...n.incidents.byDay.map(i=>i.count),1);for(let i of n.incidents.byDay.slice(-7)){let a=Math.round(i.count/r*30),c="\u2588".repeat(a);t.push(`${i.date.substring(5)} ${c} ${i.count}`);}t.push(""),t.push("Most Affected Symbols:"),t.push("\u2500".repeat(50));for(let{symbol:i,count:a}of n.symbols.mostIncidents.slice(0,5))t.push(` ${i.padEnd(25)} ${a} incidents`);t.push(""),t.push("Top Patterns:"),t.push("\u2500".repeat(50));for(let{patternId:i,resolvedCount:a}of n.patterns.mostEffective.slice(0,5))t.push(` ${i.padEnd(25)} ${a} resolved`);return t.push(""),t.push("Resolution Stats:"),t.push("\u2500".repeat(50)),t.push(` Resolution rate: ${Math.round(n.resolution.resolutionRate)}%`),t.push(` With pattern: ${n.resolution.resolvedWithPattern}`),t.push(` Manual: ${n.resolution.resolvedManually}`),t.join(`
423
423
  `)}countSymbols(e){let n=new Map;for(let t of e)for(let[,s]of Object.entries(t.symbols))s&&n.set(s,(n.get(s)||0)+1);return n}getSymbolsFromIncident(e){let n=[];for(let[,t]of Object.entries(e.symbols))t&&n.push(t);return n}};var W=class{build(e){if(!e.flowPosition)return null;let n=[],t=new Date(e.timestamp).getTime();n.push({timestamp:new Date(t-5e3).toISOString(),symbol:e.flowPosition.flowId,type:"flow-started"});let s=1e3;for(let i of e.flowPosition.actual){let a=this.inferEventType(i);n.push({timestamp:new Date(t-4e3+s).toISOString(),symbol:i,type:a}),s+=Math.random()*1e3+500;}let r=e.flowPosition.failedAt||e.flowPosition.missing[0]||e.symbols.gate||e.symbols.signal||"unknown";return n.push({timestamp:e.timestamp,symbol:r,type:"error",data:{message:e.error.message,missing:e.flowPosition.missing}}),{incidentId:e.id,flowId:e.flowPosition.flowId,events:n,failure:{at:e.timestamp,symbol:r,reason:e.error.message}}}renderAscii(e){let n=[];n.push(`${e.flowId} Timeline`),n.push("\u2550".repeat(40)),n.push("");for(let s of e.events){let r=this.formatTime(s.timestamp),i=this.getEventIcon(s.type),a=this.getEventStatus(s.type),c=`${r} ${i} ${s.symbol}`;a&&(c+=` (${a})`),n.push(c),s.type==="error"&&s.data&&(n.push(` \u2514\u2500 ${s.data.message}`),s.data.missing&&Array.isArray(s.data.missing)&&s.data.missing.length>0&&n.push(` \u2514\u2500 Expected: ${s.data.missing.join(", ")}`));}let t=e.events.find(s=>s.type==="error")?.data?.missing;return t&&t.length>0&&(n.push(""),n.push(`Missing signals: ${t.join(", ")}`)),n.join(`
424
- `)}renderStructured(e){return {incidentId:e.incidentId,flow:{id:e.flowId,eventCount:e.events.length},events:e.events.map(n=>({time:this.formatTime(n.timestamp),symbol:n.symbol,type:n.type,status:this.getEventStatus(n.type),data:n.data})),failure:{at:this.formatTime(e.failure.at),symbol:e.failure.symbol,reason:e.failure.reason}}}inferEventType(e){return e.startsWith("^")?"gate-passed":e.startsWith("!")?"signal-emitted":e.startsWith("%")?"state-changed":"signal-emitted"}getEventIcon(e){switch(e){case "flow-started":return "\u25B6";case "flow-ended":return "\u25A0";case "gate-passed":return "\u2713";case "gate-failed":return "\u2717";case "signal-emitted":return "\u26A1";case "state-changed":return "\u25C6";case "error":return "\u2717";default:return "\u2022"}}getEventStatus(e){switch(e){case "gate-passed":return "PASSED";case "gate-failed":return "FAILED";case "signal-emitted":return "EMITTED";case "state-changed":return "CHANGED";case "error":return "ERROR";default:return ""}}formatTime(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),s=String(n.getMinutes()).padStart(2,"0"),r=String(n.getSeconds()).padStart(2,"0"),i=String(n.getMilliseconds()).padStart(3,"0");return `${t}:${s}:${r}.${i}`}};var rt=fileURLToPath(import.meta.url),Ne=S.dirname(rt);function it(){let o=S.join(Ne,"universal-patterns.json"),e=E.readFileSync(o,"utf-8");return JSON.parse(e)}function ot(){let o=S.join(Ne,"paradigm-patterns.json"),e=E.readFileSync(o,"utf-8");return JSON.parse(e)}function Oe(){let o=it(),e=ot();return {version:"1.0.0",exportedAt:new Date().toISOString(),patterns:[...o.patterns,...e.patterns]}}var at=process.env.SENTINEL_LOG_LEVEL||process.env.LOG_LEVEL||"info",xe={debug:0,info:1,warn:2,error:3};function A(o){return xe[o]>=xe[at]}function P(o){if(!o)return "";let e=Object.entries(o).map(([n,t])=>`${n}=${typeof t=="string"?t:JSON.stringify(t)}`).join(" ");return m.gray(` ${e}`)}var v={component(o){let e=m.magenta(`#${o}`);return {debug:(n,t)=>{A("debug")&&console.log(`${m.gray("\u25CB")} ${e} ${n}${P(t)}`);},info:(n,t)=>{A("info")&&console.log(`${m.blue("\u2139")} ${e} ${n}${P(t)}`);},warn:(n,t)=>{A("warn")&&console.log(`${m.yellow("\u26A0")} ${e} ${n}${P(t)}`);},error:(n,t)=>{A("error")&&console.error(`${m.red("\u2716")} ${e} ${n}${P(t)}`);}}},flow(o){let e=m.yellow(`$${o}`);return {debug:(n,t)=>{A("debug")&&console.log(`${m.gray("\u25CB")} ${e} ${n}${P(t)}`);},info:(n,t)=>{A("info")&&console.log(`${m.blue("\u2139")} ${e} ${n}${P(t)}`);},warn:(n,t)=>{A("warn")&&console.log(`${m.yellow("\u26A0")} ${e} ${n}${P(t)}`);},error:(n,t)=>{A("error")&&console.error(`${m.red("\u2716")} ${e} ${n}${P(t)}`);}}}},Le=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);async function Q(o){let e=S.join(o,".paradigm","config.yaml");if(!E.existsSync(e)){let n=S.join(o,"package.json");if(E.existsSync(n))try{return {name:JSON.parse(E.readFileSync(n,"utf-8")).name}}catch{}return {}}try{let n=E.readFileSync(e,"utf-8"),t={},s=n.match(/^name:\s*(.+)$/m);s&&(t.name=s[1].trim().replace(/^["']|["']$/g,""));let r=n.match(/^discipline:\s*(.+)$/m);r&&(t.discipline=r[1].trim());let i=n.match(/^version:\s*(.+)$/m);return i&&(t.version=i[1].trim()),t}catch(n){return v.component("config-loader").error("Failed to load Paradigm config",{error:String(n)}),{}}}async function ct(o){try{let{aggregateFromDirectory:e}=await import('./dist-R3RWD35F.js');v.flow("load-symbols").info("Using premise-core aggregator",{path:o});let n=await e(o),t={};for(let s of n.symbols)t[s.type]=(t[s.type]||0)+1;if(v.flow("load-symbols").info("Aggregation complete",{total:n.symbols.length,...t,purposeFiles:n.purposeFiles.length,portalFiles:n.portalFiles.length}),n.errors.length>0)for(let s of n.errors)v.component("aggregator").warn("Aggregation error",{source:s.source,file:s.filePath,message:s.message});for(let s of n.purposeFiles)v.component("purpose-loader").info("Loaded .purpose file",{file:S.relative(o,s)});for(let s of n.portalFiles)v.component("gate-loader").info("Loaded portal.yaml",{file:S.relative(o,s)});return n.symbols}catch(e){return v.component("premise-core").warn("premise-core not available, using fallback scanner",{error:e instanceof Error?e.message:String(e)}),null}}async function $(o){v.flow("load-symbols").info("Loading symbols",{projectDir:o});let e=S.join(o,".paradigm","index.json");if(E.existsSync(e))try{v.component("index-loader").info("Found cached index",{path:e});let t=E.readFileSync(e,"utf-8"),s=JSON.parse(t),r=Array.isArray(s.entries)?s.entries:Array.isArray(s)?s:null;if(r)return v.flow("load-symbols").info("Loaded from cached index",{count:r.length}),r}catch(t){v.component("index-loader").error("Failed to load cached index",{error:String(t)});}let n=await ct(o);return n||(v.flow("load-symbols").info("Using fallback scanner"),lt(o))}async function lt(o){let e=[],n=new Set,t=["src","lib","packages","apps","."];for(let r of t){let i=S.join(o,r);E.existsSync(i)&&await we(i,e,n,o);}let s=S.join(o,"portal.yaml");if(E.existsSync(s)){v.component("gate-loader").debug("Found portal.yaml",{path:"portal.yaml"});try{let i=E.readFileSync(s,"utf-8").match(/^gates:\s*\n((?: .+\n)*)/m);if(i){let a=i[1].matchAll(/^ ([a-z][a-z0-9-]*):/gm);for(let c of a){let l=c[1],d=`gate-${l}`;n.has(d)||(n.add(d),e.push({id:d,symbol:`^${l}`,type:"gate",source:"portal",filePath:"portal.yaml",data:{},references:[],referencedBy:[]}),v.component("gate-loader").debug("Extracted gate",{symbol:`^${l}`}));}}}catch(r){v.component("gate-loader").error("Failed to parse portal.yaml",{error:String(r)});}}return v.flow("load-symbols").info("Fallback scan complete",{count:e.length}),e}async function we(o,e,n,t){let s=["node_modules",".git","dist","build",".paradigm","coverage",".next",".svelte-kit"],r;try{r=E.readdirSync(o,{withFileTypes:!0});}catch{return}for(let i of r){let a=S.join(o,i.name);if(i.isDirectory())s.includes(i.name)||await we(a,e,n,t);else if(i.name===".purpose"){let c=S.relative(t,a);v.component("purpose-loader").debug("Scanning .purpose file",{path:c});try{let l=E.readFileSync(a,"utf-8"),d=ut(l,a,t);for(let u of d)n.has(u.id)||(n.add(u.id),e.push(u),v.component("purpose-loader").debug("Extracted symbol",{symbol:u.symbol,type:u.type,file:c}));}catch(l){v.component("purpose-loader").error("Failed to parse .purpose file",{path:c,error:String(l)});}}}}function ut(o,e,n){let t=[],s=S.relative(n,e),r=o.matchAll(/(?:^|\s)#([a-z][a-z0-9-]*)/gm);for(let d of r){let u=d[1];t.push({id:`component-${u}`,symbol:`#${u}`,type:"component",source:"purpose",filePath:s,data:{},description:dt(o,`#${u}`),references:mt(o),referencedBy:[],tags:gt(o)});}let i=o.matchAll(/\$([a-z][a-z0-9-]*)/gm);for(let d of i){let u=d[1],g=`$${u}`;if(Le.has(g)){v.component("purpose-loader").debug("Skipping blocklisted symbol",{symbol:g});continue}t.find(p=>p.symbol===g)||t.push({id:`flow-${u}`,symbol:g,type:"flow",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}let a=o.matchAll(/!([a-z][a-z0-9-]*)/gm);for(let d of a){let u=d[1];t.find(g=>g.symbol===`!${u}`)||t.push({id:`signal-${u}`,symbol:`!${u}`,type:"signal",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}let c=o.matchAll(/\^([a-z][a-z0-9-]*)/gm);for(let d of c){let u=d[1];t.find(g=>g.symbol===`^${u}`)||t.push({id:`gate-${u}`,symbol:`^${u}`,type:"gate",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}let l=o.matchAll(/~([a-z][a-z0-9-]*)/gm);for(let d of l){let u=d[1];t.find(g=>g.symbol===`~${u}`)||t.push({id:`aspect-${u}`,symbol:`~${u}`,type:"aspect",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}return t}function dt(o,e){let n=new RegExp(`${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[-:]?\\s*(.+)`,"m"),t=o.match(n);if(t&&t[1])return t[1].trim()}function mt(o){let e=new Set,n=o.matchAll(/[@#$!^~]([a-z][a-z0-9-]*)/g);for(let t of n){let s=t[0];Le.has(s)||e.add(s);}return Array.from(e)}function gt(o){let e=o.match(/tags:\s*\[([^\]]+)\]/);return e?e[1].split(",").map(n=>n.trim().replace(/^["']|["']$/g,"")):[]}async function Z(o){return (await $(o)).length}async function Ce(o,e,n){let s=(await $(o)).find(i=>i.id===e);if(!s)return {success:false,error:"Symbol not found"};let r=S.join(o,s.filePath);if(!E.existsSync(r))return {success:false,error:"Source file not found"};try{let i=E.readFileSync(r,"utf-8"),a=!1;if(n.description!==void 0){let c=s.symbol.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`(${c})\\s*[-:]?\\s*(.*)`,"m");if(i.match(l)){let u=n.description?`${s.symbol}: ${n.description}`:s.symbol;i=i.replace(l,u),a=!0;}}if(n.tags!==void 0){let c=n.tags.length>0?`tags: [${n.tags.map(d=>`"${d}"`).join(", ")}]`:"",l=/^tags:\s*\[[^\]]*\]\s*$/m;if(l.test(i))c?i=i.replace(l,c):i=i.replace(l,""),a=!0;else if(c){let d=s.symbol.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=new RegExp(`(${d}[^\\n]*\\n)`,"m");i.match(u)&&(i=i.replace(u,`$1${c}
424
+ `)}renderStructured(e){return {incidentId:e.incidentId,flow:{id:e.flowId,eventCount:e.events.length},events:e.events.map(n=>({time:this.formatTime(n.timestamp),symbol:n.symbol,type:n.type,status:this.getEventStatus(n.type),data:n.data})),failure:{at:this.formatTime(e.failure.at),symbol:e.failure.symbol,reason:e.failure.reason}}}inferEventType(e){return e.startsWith("^")?"gate-passed":e.startsWith("!")?"signal-emitted":e.startsWith("%")?"state-changed":"signal-emitted"}getEventIcon(e){switch(e){case "flow-started":return "\u25B6";case "flow-ended":return "\u25A0";case "gate-passed":return "\u2713";case "gate-failed":return "\u2717";case "signal-emitted":return "\u26A1";case "state-changed":return "\u25C6";case "error":return "\u2717";default:return "\u2022"}}getEventStatus(e){switch(e){case "gate-passed":return "PASSED";case "gate-failed":return "FAILED";case "signal-emitted":return "EMITTED";case "state-changed":return "CHANGED";case "error":return "ERROR";default:return ""}}formatTime(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),s=String(n.getMinutes()).padStart(2,"0"),r=String(n.getSeconds()).padStart(2,"0"),i=String(n.getMilliseconds()).padStart(3,"0");return `${t}:${s}:${r}.${i}`}};var rt=fileURLToPath(import.meta.url),Ne=S.dirname(rt);function it(){let o=S.join(Ne,"universal-patterns.json"),e=E.readFileSync(o,"utf-8");return JSON.parse(e)}function ot(){let o=S.join(Ne,"paradigm-patterns.json"),e=E.readFileSync(o,"utf-8");return JSON.parse(e)}function Oe(){let o=it(),e=ot();return {version:"1.0.0",exportedAt:new Date().toISOString(),patterns:[...o.patterns,...e.patterns]}}var at=process.env.SENTINEL_LOG_LEVEL||process.env.LOG_LEVEL||"info",xe={debug:0,info:1,warn:2,error:3};function A(o){return xe[o]>=xe[at]}function P(o){if(!o)return "";let e=Object.entries(o).map(([n,t])=>`${n}=${typeof t=="string"?t:JSON.stringify(t)}`).join(" ");return m.gray(` ${e}`)}var v={component(o){let e=m.magenta(`#${o}`);return {debug:(n,t)=>{A("debug")&&console.log(`${m.gray("\u25CB")} ${e} ${n}${P(t)}`);},info:(n,t)=>{A("info")&&console.log(`${m.blue("\u2139")} ${e} ${n}${P(t)}`);},warn:(n,t)=>{A("warn")&&console.log(`${m.yellow("\u26A0")} ${e} ${n}${P(t)}`);},error:(n,t)=>{A("error")&&console.error(`${m.red("\u2716")} ${e} ${n}${P(t)}`);}}},flow(o){let e=m.yellow(`$${o}`);return {debug:(n,t)=>{A("debug")&&console.log(`${m.gray("\u25CB")} ${e} ${n}${P(t)}`);},info:(n,t)=>{A("info")&&console.log(`${m.blue("\u2139")} ${e} ${n}${P(t)}`);},warn:(n,t)=>{A("warn")&&console.log(`${m.yellow("\u26A0")} ${e} ${n}${P(t)}`);},error:(n,t)=>{A("error")&&console.error(`${m.red("\u2716")} ${e} ${n}${P(t)}`);}}}},Le=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);async function Q(o){let e=S.join(o,".paradigm","config.yaml");if(!E.existsSync(e)){let n=S.join(o,"package.json");if(E.existsSync(n))try{return {name:JSON.parse(E.readFileSync(n,"utf-8")).name}}catch{}return {}}try{let n=E.readFileSync(e,"utf-8"),t={},s=n.match(/^name:\s*(.+)$/m);s&&(t.name=s[1].trim().replace(/^["']|["']$/g,""));let r=n.match(/^discipline:\s*(.+)$/m);r&&(t.discipline=r[1].trim());let i=n.match(/^version:\s*(.+)$/m);return i&&(t.version=i[1].trim()),t}catch(n){return v.component("config-loader").error("Failed to load Paradigm config",{error:String(n)}),{}}}async function ct(o){try{let{aggregateFromDirectory:e}=await import('./dist-JZZJLVMR.js');v.flow("load-symbols").info("Using premise-core aggregator",{path:o});let n=await e(o),t={};for(let s of n.symbols)t[s.type]=(t[s.type]||0)+1;if(v.flow("load-symbols").info("Aggregation complete",{total:n.symbols.length,...t,purposeFiles:n.purposeFiles.length,portalFiles:n.portalFiles.length}),n.errors.length>0)for(let s of n.errors)v.component("aggregator").warn("Aggregation error",{source:s.source,file:s.filePath,message:s.message});for(let s of n.purposeFiles)v.component("purpose-loader").info("Loaded .purpose file",{file:S.relative(o,s)});for(let s of n.portalFiles)v.component("gate-loader").info("Loaded portal.yaml",{file:S.relative(o,s)});return n.symbols}catch(e){return v.component("premise-core").warn("premise-core not available, using fallback scanner",{error:e instanceof Error?e.message:String(e)}),null}}async function $(o){v.flow("load-symbols").info("Loading symbols",{projectDir:o});let e=S.join(o,".paradigm","index.json");if(E.existsSync(e))try{v.component("index-loader").info("Found cached index",{path:e});let t=E.readFileSync(e,"utf-8"),s=JSON.parse(t),r=Array.isArray(s.entries)?s.entries:Array.isArray(s)?s:null;if(r)return v.flow("load-symbols").info("Loaded from cached index",{count:r.length}),r}catch(t){v.component("index-loader").error("Failed to load cached index",{error:String(t)});}let n=await ct(o);return n||(v.flow("load-symbols").info("Using fallback scanner"),lt(o))}async function lt(o){let e=[],n=new Set,t=["src","lib","packages","apps","."];for(let r of t){let i=S.join(o,r);E.existsSync(i)&&await we(i,e,n,o);}let s=S.join(o,"portal.yaml");if(E.existsSync(s)){v.component("gate-loader").debug("Found portal.yaml",{path:"portal.yaml"});try{let i=E.readFileSync(s,"utf-8").match(/^gates:\s*\n((?: .+\n)*)/m);if(i){let a=i[1].matchAll(/^ ([a-z][a-z0-9-]*):/gm);for(let c of a){let l=c[1],d=`gate-${l}`;n.has(d)||(n.add(d),e.push({id:d,symbol:`^${l}`,type:"gate",source:"portal",filePath:"portal.yaml",data:{},references:[],referencedBy:[]}),v.component("gate-loader").debug("Extracted gate",{symbol:`^${l}`}));}}}catch(r){v.component("gate-loader").error("Failed to parse portal.yaml",{error:String(r)});}}return v.flow("load-symbols").info("Fallback scan complete",{count:e.length}),e}async function we(o,e,n,t){let s=["node_modules",".git","dist","build",".paradigm","coverage",".next",".svelte-kit"],r;try{r=E.readdirSync(o,{withFileTypes:!0});}catch{return}for(let i of r){let a=S.join(o,i.name);if(i.isDirectory())s.includes(i.name)||await we(a,e,n,t);else if(i.name===".purpose"){let c=S.relative(t,a);v.component("purpose-loader").debug("Scanning .purpose file",{path:c});try{let l=E.readFileSync(a,"utf-8"),d=ut(l,a,t);for(let u of d)n.has(u.id)||(n.add(u.id),e.push(u),v.component("purpose-loader").debug("Extracted symbol",{symbol:u.symbol,type:u.type,file:c}));}catch(l){v.component("purpose-loader").error("Failed to parse .purpose file",{path:c,error:String(l)});}}}}function ut(o,e,n){let t=[],s=S.relative(n,e),r=o.matchAll(/(?:^|\s)#([a-z][a-z0-9-]*)/gm);for(let d of r){let u=d[1];t.push({id:`component-${u}`,symbol:`#${u}`,type:"component",source:"purpose",filePath:s,data:{},description:dt(o,`#${u}`),references:mt(o),referencedBy:[],tags:gt(o)});}let i=o.matchAll(/\$([a-z][a-z0-9-]*)/gm);for(let d of i){let u=d[1],g=`$${u}`;if(Le.has(g)){v.component("purpose-loader").debug("Skipping blocklisted symbol",{symbol:g});continue}t.find(p=>p.symbol===g)||t.push({id:`flow-${u}`,symbol:g,type:"flow",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}let a=o.matchAll(/!([a-z][a-z0-9-]*)/gm);for(let d of a){let u=d[1];t.find(g=>g.symbol===`!${u}`)||t.push({id:`signal-${u}`,symbol:`!${u}`,type:"signal",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}let c=o.matchAll(/\^([a-z][a-z0-9-]*)/gm);for(let d of c){let u=d[1];t.find(g=>g.symbol===`^${u}`)||t.push({id:`gate-${u}`,symbol:`^${u}`,type:"gate",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}let l=o.matchAll(/~([a-z][a-z0-9-]*)/gm);for(let d of l){let u=d[1];t.find(g=>g.symbol===`~${u}`)||t.push({id:`aspect-${u}`,symbol:`~${u}`,type:"aspect",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}return t}function dt(o,e){let n=new RegExp(`${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[-:]?\\s*(.+)`,"m"),t=o.match(n);if(t&&t[1])return t[1].trim()}function mt(o){let e=new Set,n=o.matchAll(/[@#$!^~]([a-z][a-z0-9-]*)/g);for(let t of n){let s=t[0];Le.has(s)||e.add(s);}return Array.from(e)}function gt(o){let e=o.match(/tags:\s*\[([^\]]+)\]/);return e?e[1].split(",").map(n=>n.trim().replace(/^["']|["']$/g,"")):[]}async function Z(o){return (await $(o)).length}async function Ce(o,e,n){let s=(await $(o)).find(i=>i.id===e);if(!s)return {success:false,error:"Symbol not found"};let r=S.join(o,s.filePath);if(!E.existsSync(r))return {success:false,error:"Source file not found"};try{let i=E.readFileSync(r,"utf-8"),a=!1;if(n.description!==void 0){let c=s.symbol.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`(${c})\\s*[-:]?\\s*(.*)`,"m");if(i.match(l)){let u=n.description?`${s.symbol}: ${n.description}`:s.symbol;i=i.replace(l,u),a=!0;}}if(n.tags!==void 0){let c=n.tags.length>0?`tags: [${n.tags.map(d=>`"${d}"`).join(", ")}]`:"",l=/^tags:\s*\[[^\]]*\]\s*$/m;if(l.test(i))c?i=i.replace(l,c):i=i.replace(l,""),a=!0;else if(c){let d=s.symbol.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=new RegExp(`(${d}[^\\n]*\\n)`,"m");i.match(u)&&(i=i.replace(u,`$1${c}
425
425
  `),a=!0);}}if(a){i=i.replace(/\n{3,}/g,`
426
426
 
427
427
  `),E.writeFileSync(r,i,"utf-8"),v.component("symbol-updater").info("Updated symbol",{symbol:s.symbol,file:s.filePath});let c=S.join(o,".paradigm","index.json");if(E.existsSync(c))try{let l=E.readFileSync(c,"utf-8"),d=JSON.parse(l),u=Array.isArray(d.entries)?d.entries:d,g=u.findIndex(p=>p.id===e);g>=0&&(n.description!==void 0&&(u[g].description=n.description),n.tags!==void 0&&(u[g].tags=n.tags),Array.isArray(d.entries)?(d.entries=u,E.writeFileSync(c,JSON.stringify(d,null,2),"utf-8")):E.writeFileSync(c,JSON.stringify(u,null,2),"utf-8"));}catch{}return {success:!0}}return {success:!0}}catch(i){return v.component("symbol-updater").error("Failed to update symbol",{error:String(i)}),{success:false,error:"Failed to write file"}}}var ft=process.env.SENTINEL_LOG_LEVEL||process.env.LOG_LEVEL||"info",Ae=o=>{let e={debug:0,info:1,warn:2,error:3};return e[o]>=e[ft]},M={gate(o){let e=m.cyan(`^${o}`);return {info:(n,t)=>{if(Ae("info")){let s=t?m.gray(` ${Object.entries(t).map(([r,i])=>`${r}=${i}`).join(" ")}`):"";console.log(`${m.blue("\u2139")} ${e} ${n}${s}`);}},error:(n,t)=>{if(Ae("error")){let s=t?m.gray(` ${Object.entries(t).map(([r,i])=>`${r}=${i}`).join(" ")}`):"";console.error(`${m.red("\u2716")} ${e} ${n}${s}`);}}}}};function ee(o){let e=Router();return e.get("/",async(n,t)=>{try{let s=await $(o);M.gate("api-symbols").info("Symbols loaded",{count:s.length}),t.json({symbols:s});}catch(s){M.gate("api-symbols").error("Failed to load symbols",{error:String(s)}),t.status(500).json({error:"Failed to load symbols"});}}),e.put("/:id",async(n,t)=>{try{let{id:s}=n.params,r=n.body;if(M.gate("api-symbols").info("Update requested",{id:s,updates:JSON.stringify(r)}),r.tags&&!Array.isArray(r.tags)){t.status(400).json({error:"Tags must be an array"});return}let i=await Ce(o,s,r);if(i.success){let c=(await $(o)).find(l=>l.id===s);M.gate("api-symbols").info("Symbol updated",{id:s}),t.json({success:!0,symbol:c});}else M.gate("api-symbols").error("Update failed",{id:s,error:i.error}),t.status(400).json({success:!1,error:i.error});}catch(s){M.gate("api-symbols").error("Failed to update symbol",{error:String(s)}),t.status(500).json({error:"Failed to update symbol"});}}),e}function te(o){let e=Router();return e.get("/",async(n,t)=>{try{let s=await Q(o),r=await Z(o);t.json({projectName:s.name||null,discipline:s.discipline||null,symbolCount:r,projectDir:o});}catch(s){console.error("Failed to load project info:",s),t.status(500).json({error:"Failed to load project info"});}}),e}function vt(o){let e=new Set;for(let n of o){if(n.endsWith(".purpose")){let r=S.dirname(n),i=S.basename(r);r.includes("features/")||r.includes("routes/")||r.includes("api/")?e.add(`@${i}`):r.includes("components/")||r.includes("lib/")||r.includes("utils/")?e.add(`#${i}`):r.includes("middleware/")||r.includes("auth/")||r.includes("guards/")?e.add(`^${i}`):(r.includes("flows/")||r.includes("workflows/"))&&e.add(`$${i}`);}n.includes("portal.yaml")&&e.add("^portal");let t=n.match(/features\/([^/]+)/);t&&e.add(`@${t[1]}`);let s=n.match(/components\/([^/]+)/);s&&e.add(`#${s[1]}`);}return Array.from(e)}async function ne(o,e={}){let n=ht(o);if(!await n.checkIsRepo())return [];try{let s={maxCount:e.limit||100};e.since&&(s["--since"]=e.since);let r=await n.log(s),i=[];for(let a of r.all){let c=[],l=[];try{c=(await n.diffSummary([`${a.hash}^`,a.hash])).files.map(u=>u.file),l=vt(c);}catch{}i.push({hash:a.hash,shortHash:a.hash.slice(0,7),date:a.date,author:a.author_name,message:a.message.split(`
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import {a,e,d}from'./chunk-QO7YPQXC.js';import'./chunk-5TAVYPOV.js';import*as u from'fs';import*as m from'path';import {execSync}from'child_process';import n from'chalk';import*as w from'js-yaml';function $(s){return s.match(/(?:^|\s)((?:\/|\.\/|[a-zA-Z0-9_-]+\/)[^\s,;:'"]+\.[a-zA-Z]{1,10})\b/)?.[1]}async function R(s,a$1){try{let r=a(s),d$1=[];try{d$1=execSync("git diff --name-only HEAD",{cwd:s,encoding:"utf8",timeout:5e3}).trim().split(`
3
+ `).filter(Boolean);}catch{}let l;try{l=execSync("git status --porcelain",{cwd:s,encoding:"utf8",timeout:5e3}).trim()==="";}catch{}let c=m.join(s,"portal.yaml"),f=!1;if(u.existsSync(c))try{let t=u.readFileSync(c,"utf8"),e=w.load(t);f=e?.routes!=null&&Object.keys(e.routes).length>0;}catch{}let i=e({toolsCalled:[],filesModified:d$1,symbolsTouched:[],loreRecorded:!1,hasPortalRoutes:f,taskAddsRoutes:!1,gitClean:l}),o=d(r,a$1,i),g=0;if(o.evaluations.length>0)try{let t=m.join(s,".paradigm","sentinel");if(u.existsSync(t)){let{SentinelStorage:e}=await import('./dist-VGFSP3XM.js'),p=new e(t);for(let b of o.evaluations)p.recordPracticeEvent({habitId:b.habit.id,habitCategory:b.habit.category,result:b.result,engineer:"agent",sessionId:`cli-${Date.now().toString(36)}`,symbolsTouched:[],filesModified:d$1,notes:b.reason}),g++;}}catch{}let h=m.join(s,".paradigm",".habits-blocking");try{if(a$1==="on-stop"&&o.blocksCompletion){let t=o.evaluations.filter(e=>e.result==="skipped"&&e.habit.severity==="block").map(e=>`${e.habit.name}: ${e.reason}`);u.writeFileSync(h,t.join(`
4
+ `),"utf8");}else a$1==="on-stop"&&u.existsSync(h)&&u.unlinkSync(h);}catch{}return {trigger:a$1,evaluation:{total:o.summary.total,followed:o.summary.followed,skipped:o.summary.skipped,partial:o.summary.partial,blockingViolations:o.summary.blockingViolations,blocksCompletion:o.blocksCompletion},habits:o.evaluations.map(t=>({id:t.habit.id,name:t.habit.name,category:t.habit.category,severity:t.habit.severity,result:t.result,reason:t.reason,evidence:t.evidence})),recorded:g}}catch{return null}}async function P(s,a){let r=m.join(s,".paradigm","aspect-graph.db");if(!u.existsSync(r))return {driftedCount:0,healedCount:0,cleanCount:0,missingCount:0,details:[]};try{let{driftCheckCommand:d}=await import('./drift-ILZE5BFJ.js'),l="",c=console.log;console.log=f=>{l=f;};try{await d({json:!0,autoHeal:a});}finally{console.log=c;}return l?JSON.parse(l):null}catch{return null}}async function B(s){if(!u.existsSync(m.join(s,"portal.yaml")))return null;try{let{checkPortalCompliance:a}=await import('./portal-compliance-6YR27IQU.js'),r=await a(s);return {status:r.status,declaredButUnusedCount:r.declaredButUnused.length,usedButUndeclaredCount:r.usedButUndeclared.length,properlyDeclaredCount:r.properlyDeclared.length,declaredButUnused:r.declaredButUnused,usedButUndeclared:r.usedButUndeclared,properlyDeclared:r.properlyDeclared,portalError:r.portalError,...r.nearMatches&&r.nearMatches.length>0?{suggestions:r.nearMatches.map(d=>({gate:d.gate,didYouMean:d.didYouMean,distance:d.distance}))}:{}}}catch{return null}}async function j(s){try{let{runPostflightLearning:a}=await import('./ambient-WTLYUAQM.js');return await a(s)}catch{return null}}async function A(s){let a=process.cwd(),r=s.trigger||"on-stop",d=s.autoHeal!==false,l=[],c=[],f=await R(a,r),i=await P(a,d),o=await B(a);if(f?.evaluation.blocksCompletion){let t=f.habits.filter(e=>e.result==="skipped"&&e.severity==="block");for(let e of t){let p=`Blocking habit not satisfied: ${e.name} \u2014 ${e.reason}`;l.push(p),c.push({message:p,source:"habits",file:$(e.reason),severity:"blocking"});}}if(i&&i.driftedCount>0){let t=`${i.driftedCount} aspect anchor(s) have drifted (content genuinely changed). Run paradigm_aspect_check to review.`;l.push(t);for(let e of i.details.filter(p=>p.status==="drifted"))c.push({message:`Aspect ~${e.aspectId} drifted at lines ${e.startLine}-${e.endLine}`,source:"drift",file:e.path,severity:"advisory"});c.filter(e=>e.source==="drift").length===0&&c.push({message:t,source:"drift",severity:"advisory"});}if(o&&o.portalError?.kind==="unparseable"){let e=`portal.yaml unparseable: ${o.portalError.errorClass} \u2014 run 'paradigm doctor' for details`;l.push(e),c.push({message:e,source:"portal",file:"portal.yaml",severity:"blocking"});}else if(o&&o.usedButUndeclaredCount>0){let t=o.usedButUndeclared.filter(e=>e!=="__portal_unparseable__");if(t.length>0){let e=`${t.length} gate(s) used in code but not declared in portal.yaml: ${t.join(", ")}`;l.push(e);for(let p of t)c.push({message:`Gate ^${p} used in code but not declared in portal.yaml`,source:"portal",file:"portal.yaml",severity:"blocking"});}}let g=null;s.learn&&(g=await j(a));let h={habits:f,drift:i,portal:o,violations:l,structuredViolations:c,postflight:s.learn?g:void 0};if(s.json)console.log(JSON.stringify(h));else {if(console.log(n.magenta(`
5
+ Paradigm Compliance Check
6
+ `)),f){let{evaluation:t}=f,e=t.blocksCompletion?n.red:n.green;console.log(n.white(" Habits:")),console.log(` ${e(`${t.followed} followed, ${t.skipped} skipped, ${t.partial} partial`)}`),t.blockingViolations>0&&console.log(n.red(` ${t.blockingViolations} blocking violation(s)`)),console.log();}if(i&&(console.log(n.white(" Drift:")),i.healedCount>0&&console.log(n.green(` Auto-healed: ${i.healedCount} shifted anchor(s)`)),i.cleanCount>0&&console.log(n.green(` Clean: ${i.cleanCount} anchor(s)`)),i.driftedCount>0&&console.log(n.red(` Drifted: ${i.driftedCount} anchor(s)`)),i.missingCount>0&&console.log(n.yellow(` Missing: ${i.missingCount} anchor file(s)`)),console.log()),o){console.log(n.white(" Portal:"));let t=o.status==="compliant"?n.green:o.status==="warnings"?n.yellow:n.red;console.log(` Status: ${t(o.status)}`),o.usedButUndeclaredCount>0&&console.log(n.red(` ${o.usedButUndeclaredCount} undeclared gate(s)`)),console.log();}if(g){if(console.log(n.white(" Postflight Learning:")),g.journalsWritten>0){console.log(n.green(` Journals written: ${g.journalsWritten}`));for(let[t,e]of Object.entries(g.journalsByAgent))e>0&&console.log(n.gray(` ${t}: ${e} entries`));}else console.log(n.gray(" No verdicts to learn from"));g.promoted>0&&console.log(n.green(` Promoted to notebooks: ${g.promoted}`)),console.log();}if(l.length>0){console.log(n.red(` ${l.length} violation(s):`));for(let t of l)console.log(n.red(` - ${t}`));}else console.log(n.green(" All checks passed."));console.log();}l.length>0&&(process.exitCode=1);}export{A as complianceCheckCommand};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {m as m$1,o,C,B,r}from'./chunk-T6IDXUUA.js';import'./chunk-JIXHEBGK.js';import'./chunk-QT2LKB3P.js';import {a}from'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';import*as u from'fs';import*as m from'path';import e from'chalk';import F from'ora';function I(t){let o={gates:[],signals:[],components:[],flows:[],aspects:[]};for(let r of t){if(!r||r.length<2)continue;switch(r[0]){case "^":o.gates.push(r);break;case "!":o.signals.push(r);break;case "#":o.components.push(r);break;case "$":o.flows.push(r);break;case "~":o.aspects.push(r);break}}return o}function T(t,o){let r$1={},g={},l=B(t),a=C(t);for(let s of a){let n=I(s.references),i={type:s.type,path:s.filePath,references:s.references,referencedBy:s.referencedBy};s.description&&(i.description=s.description),s.tags&&s.tags.length>0&&(i.tags=s.tags),n.gates.length>0&&(i.gates=n.gates),n.signals.length>0&&(i.signals=n.signals),n.components.length>0&&(i.components=n.components),n.flows.length>0&&(i.flows=n.flows),n.aspects.length>0&&(i.aspects=n.aspects),r$1[s.symbol]=i;}let y=r(t,"flow");for(let s of y){let n=s.data,i=n?.sequence||n?.gates||s.references;g[s.symbol]={description:s.description,sequence:i};}return {version:"1.0",generated:new Date().toISOString(),project:o,stats:{components:l.component,flows:l.flow,gates:l.gate,signals:l.signal,aspects:l.aspect,total:Object.values(l).reduce((s,n)=>s+n,0)},stars:r$1,orbits:g}}async function z(t,o$1={}){let r=process.cwd(),g=t?m.resolve(r,t):r,l=m.basename(g),a$1=o$1.format||"json";o$1.quiet||console.log(e.blue(`
2
+ import {m as m$1,o,C,B,r}from'./chunk-LWAIVOSF.js';import'./chunk-JIXHEBGK.js';import'./chunk-ZJQY5PPP.js';import {a}from'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';import*as u from'fs';import*as m from'path';import e from'chalk';import F from'ora';function I(t){let o={gates:[],signals:[],components:[],flows:[],aspects:[]};for(let r of t){if(!r||r.length<2)continue;switch(r[0]){case "^":o.gates.push(r);break;case "!":o.signals.push(r);break;case "#":o.components.push(r);break;case "$":o.flows.push(r);break;case "~":o.aspects.push(r);break}}return o}function T(t,o){let r$1={},g={},l=B(t),a=C(t);for(let s of a){let n=I(s.references),i={type:s.type,path:s.filePath,references:s.references,referencedBy:s.referencedBy};s.description&&(i.description=s.description),s.tags&&s.tags.length>0&&(i.tags=s.tags),n.gates.length>0&&(i.gates=n.gates),n.signals.length>0&&(i.signals=n.signals),n.components.length>0&&(i.components=n.components),n.flows.length>0&&(i.flows=n.flows),n.aspects.length>0&&(i.aspects=n.aspects),r$1[s.symbol]=i;}let y=r(t,"flow");for(let s of y){let n=s.data,i=n?.sequence||n?.gates||s.references;g[s.symbol]={description:s.description,sequence:i};}return {version:"1.0",generated:new Date().toISOString(),project:o,stats:{components:l.component,flows:l.flow,gates:l.gate,signals:l.signal,aspects:l.aspect,total:Object.values(l).reduce((s,n)=>s+n,0)},stars:r$1,orbits:g}}async function z(t,o$1={}){let r=process.cwd(),g=t?m.resolve(r,t):r,l=m.basename(g),a$1=o$1.format||"json";o$1.quiet||console.log(e.blue(`
3
3
  \u2728 Building Constellation...
4
4
  `));let y=F("Aggregating symbols...").start(),s=a.command("constellation").start("Building constellation",{project:l});try{let n=await m$1(g),i=o(n);a.operation("aggregate").debug("Symbols aggregated",{count:C(i).length}),y.text="Building constellation...";let p=T(i,l),$=m.join(g,".paradigm");u.existsSync($)||u.mkdirSync($,{recursive:!0});let h=o$1.output||m.join($,`constellation.${a$1}`),S;if(a$1==="yaml"?S=d(p):S=JSON.stringify(p,null,2),u.writeFileSync(h,S,"utf8"),a.component("constellation-file").success("Constellation written",{path:h,format:a$1}),y.succeed("Constellation built"),s.success("Constellation built",{path:h,stars:Object.keys(p.stars).length}),!o$1.quiet){console.log(e.white(`
5
5
  Constellation Stats`)),console.log(e.gray("\u2500".repeat(40)));let f=p.stats,q=[{symbol:"#",name:"Components",count:f.components,color:e.green},{symbol:"$",name:"Flows",count:f.flows,color:e.yellow},{symbol:"^",name:"Gates",count:f.gates,color:e.red},{symbol:"!",name:"Signals",count:f.signals,color:e.cyan},{symbol:"~",name:"Aspects",count:f.aspects,color:e.magenta}];for(let{symbol:c,name:R,count:O,color:E}of q)O>0&&console.log(` ${E(c)} ${R.padEnd(12)} ${e.cyan(O.toString())}`);console.log(e.gray("\u2500".repeat(40))),console.log(` Total stars: ${e.cyan(f.total.toString())}`),console.log(` Total orbits: ${e.cyan(Object.keys(p.orbits).length.toString())}`),console.log(e.gray(`
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {e}from'./chunk-JIXHEBGK.js';import {e as e$1}from'./chunk-QT2LKB3P.js';import'./chunk-5TAVYPOV.js';import*as v from'fs';import*as l from'path';import o from'chalk';import D from'ora';function Q(t){let a=t.length;return Math.ceil(a/3.5)}function f(t,a){try{let s=v.readFileSync(t,"utf8"),m=Buffer.byteLength(s,"utf8"),C=Q(s),r=l.relative(a,t);return {path:t,relativePath:r,tokens:C,bytes:m}}catch{return null}}function i(t){return t<1e3?t.toString():`${(t/1e3).toFixed(1)}k`}async function L(t,a){let s=t?l.resolve(t):process.cwd(),m=D();a.json||console.log(o.blue(`
2
+ import {e}from'./chunk-JIXHEBGK.js';import {e as e$1}from'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as v from'fs';import*as l from'path';import o from'chalk';import D from'ora';function Q(t){let a=t.length;return Math.ceil(a/3.5)}function f(t,a){try{let s=v.readFileSync(t,"utf8"),m=Buffer.byteLength(s,"utf8"),C=Q(s),r=l.relative(a,t);return {path:t,relativePath:r,tokens:C,bytes:m}}catch{return null}}function i(t){return t<1e3?t.toString():`${(t/1e3).toFixed(1)}k`}async function L(t,a){let s=t?l.resolve(t):process.cwd(),m=D();a.json||console.log(o.blue(`
3
3
  \u{1F4B0} Paradigm Cost Analysis
4
4
  `)),m.start("Analyzing context files...");let C=await e(s),r=[];for(let e of C){let n=f(e,s);n&&r.push(n);}let A=await e$1(s),y=[];for(let e of A){let n=f(e,s);n&&y.push(n);}let R=l.join(s,".paradigm","scan-index.json"),h=f(R,s),I=l.join(s,".cursorrules"),q=l.join(s,".cursor","rules","paradigm.mdc"),g=f(I,s);g||(g=f(q,s)),m.stop();let x=r.reduce((e,n)=>e+n.tokens,0),F=y.reduce((e,n)=>e+n.tokens,0),b=h?.tokens||0,P=g?.tokens||0,w=x+F+b,u=w+P,T=150,k=T*7,c=u>0?Math.round((1-k/u)*100):0,d=[],M=r.filter(e=>e.tokens>500);M.length>0&&d.push(`${M.length} .purpose file(s) exceed 500 tokens. Consider splitting large features.`);let N=l.join(s,".cursor","mcp.json"),$=v.existsSync(N);$||d.push("MCP not configured. Run `paradigm mcp setup` to enable dynamic context (80%+ savings)."),h||d.push("No scan-index.json found. Run `paradigm index` for visual discovery support."),r.length<3&&d.push("Few .purpose files found. Add more context for better AI understanding.");let O={static:{purposeFiles:r,portalFiles:y,scanIndex:h,cursorrules:g,total:u},dynamic:{avgQueryTokens:T,typicalConversation:k},savings:{percentage:Math.max(0,c),description:c>0?`${c}% fewer tokens with MCP vs static context`:"MCP provides on-demand context loading"},recommendations:d};if(a.json){console.log(JSON.stringify(O,null,2));return}if(console.log(o.white("Context Token Analysis")),console.log(o.gray("\u2500".repeat(50))),console.log(o.cyan(`
5
5
  Static Context (loaded every conversation):`)),console.log(` .purpose files (${r.length}):`.padEnd(35)+o.yellow(i(x)+" tokens")),console.log(` portal.yaml (${y.length}):`.padEnd(35)+o.yellow(i(F)+" tokens")),h&&console.log(" scan-index.json:".padEnd(35)+o.yellow(i(b)+" tokens")),g&&console.log(" .cursorrules:".padEnd(35)+o.yellow(i(P)+" tokens")),console.log(o.gray("\u2500".repeat(50))),console.log(" Static Total:".padEnd(35)+o.yellow.bold(i(u)+" tokens")),console.log(o.cyan(`
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-J6KWGCHN.js';import'./chunk-TYWB5IQJ.js';import'./chunk-ORDKEGII.js';import'./chunk-BV5PRPLB.js';import'./chunk-AO7ZSRME.js';import'./chunk-FYDRENK7.js';import'./chunk-EKZDFEJW.js';import'./chunk-SHD27BQX.js';import'./chunk-T6IDXUUA.js';import'./chunk-JIXHEBGK.js';import'./chunk-QT2LKB3P.js';import'./chunk-5TAVYPOV.js';import*as i from'fs';import*as a from'path';import o from'chalk';async function D(l,f,t){let d=f?a.resolve(f):process.cwd();if(!l){t.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(o.red(`
2
+ import {b}from'./chunk-HOBHJPTL.js';import'./chunk-TYWB5IQJ.js';import'./chunk-ORDKEGII.js';import'./chunk-BV5PRPLB.js';import'./chunk-AO7ZSRME.js';import'./chunk-FYDRENK7.js';import'./chunk-EKZDFEJW.js';import'./chunk-4VKSEOXZ.js';import'./chunk-LWAIVOSF.js';import'./chunk-JIXHEBGK.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as i from'fs';import*as a from'path';import o from'chalk';async function D(l,f,t){let d=f?a.resolve(f):process.cwd();if(!l){t.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(o.red(`
3
3
  Orchestration ID required.`)),console.log(o.gray(`Usage: paradigm team diff <orchestration-id>
4
4
  `)));return}let e=new b(d).getOrchestration(l);if(!e){t.json?console.log(JSON.stringify({error:"Orchestration not found",id:l})):console.log(o.red(`
5
5
  Orchestration not found: ${l}
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import*as P from'fs';import*as j from'js-yaml';import {z as z$1}from'zod';import*as S from'path';import {glob}from'glob';var O=z$1.object({description:z$1.string(),type:z$1.string().optional(),parent:z$1.string().optional(),anchors:z$1.array(z$1.string()).optional(),tags:z$1.array(z$1.string()).optional(),endpoints:z$1.array(z$1.string()).optional(),tests:z$1.array(z$1.string()).optional(),rules:z$1.record(z$1.unknown()).optional(),aspects:z$1.array(z$1.string()).optional(),flows:z$1.array(z$1.string()).optional(),gates:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional(),states:z$1.array(z$1.string()).optional(),components:z$1.array(z$1.string()).optional(),location:z$1.string().optional(),locations:z$1.array(z$1.string()).optional(),uses:z$1.array(z$1.string()).optional(),"used-by":z$1.array(z$1.string()).optional(),"used-for":z$1.array(z$1.string()).optional(),exports:z$1.array(z$1.string()).optional(),status:z$1.string().optional(),properties:z$1.record(z$1.unknown()).optional(),handles:z$1.array(z$1.string()).optional()}).passthrough(),L=O.extend({id:z$1.string()}),fe=z$1.object({description:z$1.string().optional(),category:z$1.string().optional(),severity:z$1.enum(["info","warn","error"]).optional(),emitters:z$1.array(z$1.string()).optional(),related:z$1.array(z$1.string()).optional(),data:z$1.record(z$1.unknown()).optional()}),le=z$1.union([fe,z$1.string().transform(e=>({description:e}))]),ue=z$1.object({from:z$1.string(),to:z$1.string(),type:z$1.string(),description:z$1.string().optional()}),de=z$1.union([ue,z$1.string()]),me=z$1.object({component:z$1.string(),action:z$1.string(),description:z$1.string().optional()}),W=z$1.union([me,z$1.string()]),ge=z$1.object({name:z$1.string(),description:z$1.string().optional(),steps:z$1.array(W)}),he=z$1.object({description:z$1.string().optional(),gates:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional(),components:z$1.array(z$1.string()).optional(),steps:z$1.array(W).optional()}),ye=z$1.object({description:z$1.string().optional(),requires:z$1.array(z$1.string()).optional(),keys:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional()}),$e=z$1.object({description:z$1.string().optional(),default:z$1.unknown().optional(),type:z$1.string().optional()}),we=z$1.object({description:z$1.string().optional(),tags:z$1.array(z$1.string()).optional(),anchors:z$1.array(z$1.string()).optional(),"applies-to":z$1.array(z$1.string()).optional(),enforcement:z$1.string().optional()}),be=z$1.object({target:z$1.string(),type:z$1.string(),path:z$1.string()}),Se=z$1.object({version:z$1.string().optional(),description:z$1.string().optional(),apiSpec:z$1.string().optional(),context:z$1.array(z$1.string()).optional(),rules:z$1.record(z$1.unknown()).optional(),features:z$1.union([z$1.array(L),z$1.record(O)]).optional(),components:z$1.union([z$1.array(L),z$1.record(O)]).optional(),gates:z$1.record(ye).optional(),states:z$1.record($e).optional(),signals:z$1.record(le).optional(),aspects:z$1.record(we).optional(),relationships:z$1.array(de).optional(),flows:z$1.union([z$1.array(ge),z$1.record(he)]).optional(),references:z$1.array(be).optional()});function ve(e){let t=xe(e);return {data:t.data,errors:t.errors}}function xe(e){let t=[],o=[],n;try{n=P.readFileSync(e,"utf8");}catch(l){let p=`Cannot read file: ${l.message}`;return t.push(p),o.push({message:p,type:"file"}),{data:null,errors:t,detailedErrors:o,rawContent:void 0,isYamlValid:false}}let r=n.replace(/^([#~!$^][\w-]+):/gm,'"$1":').replace(/^(\s*-\s+)([!#][\w-]+)$/gm,'$1"$2"'),a=null;try{a=j.load(r);}catch(l){let p=l,f=p.mark?.line?p.mark.line+1:void 0,u=`YAML syntax error: ${p.reason||l.message}`;return t.push(`${u}${f?` (line ${f})`:""}`),o.push({message:u,line:f,type:"yaml"}),{data:null,errors:t,detailedErrors:o,rawContent:n,isYamlValid:false}}if(a==null)return {data:{},errors:[],detailedErrors:[],rawContent:n,isYamlValid:true};if(typeof a=="object"&&a!==null){let l=a,p={"#":"components",$:"flows","^":"gates","!":"signals","~":"aspects"};for(let f of Object.keys(l)){let u=f[0],g=p[u];if(!g||f.length<2)continue;let h=f.slice(1),w=l[f];if(typeof w!="object"||w===null)continue;let v=l[g]||{};g in l||(l[g]=v),h in v||(v[h]=w),delete l[f];}}let i=Se.safeParse(a);if(!i.success){for(let l of i.error.issues){let p=l.path.join("."),f=l.message;t.push(`Schema error at ${p||"/"}: ${f}`),o.push({message:f,path:p||"/",type:"schema"});}return {data:a,errors:t,detailedErrors:o,rawContent:n,isYamlValid:true}}return {data:i.data,errors:[],detailedErrors:[],rawContent:n,isYamlValid:true}}function C(e){return e?Array.isArray(e)?e.map(t=>[t.id,t]):Object.entries(e):[]}async function ke(e){let t=S.resolve(e);return (await glob("**/.purpose",{cwd:t,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})).sort((n,r)=>{let a=n.split(S.sep).length,i=r.split(S.sep).length;return a-i})}async function Y(e){let t=await ke(e),o=[];for(let n of t){let{data:r,errors:a}=ve(n);r&&(o.push({filePath:n,data:r}),a.length>0&&console.warn(`Warnings parsing ${n}:`,a));}return o}function B(e){let t=new Map;for(let{filePath:o,data:n}of e){let r=C(n.features);for(let[a,i]of r)t.set(a,{item:i,filePath:o});}return t}function V(e){let t=new Map;for(let{filePath:o,data:n}of e){let r=C(n.components);for(let[a,i]of r)t.set(a,{item:i,filePath:o});}return t}function _(e){let t=new Map;for(let{filePath:o,data:n}of e)if(n.gates)for(let[r,a]of Object.entries(n.gates))t.set(r,{item:a,filePath:o});return t}function N(e){let t=new Map;for(let{filePath:o,data:n}of e)if(n.states)for(let[r,a]of Object.entries(n.states))t.set(r,{item:a,filePath:o});return t}function K(e){let t=new Map;for(let{filePath:o,data:n}of e)if(n.flows)if(Array.isArray(n.flows))for(let r of n.flows)t.set(r.name,{item:{id:r.name,description:r.description,steps:r.steps},filePath:o});else for(let[r,a]of Object.entries(n.flows))t.set(r,{item:{id:r,description:a.description,gates:a.gates,signals:a.signals,components:a.components,steps:a.steps},filePath:o});return t}function q(e){let t=new Map;for(let{filePath:o,data:n}of e)if(n.signals)for(let[r,a]of Object.entries(n.signals))t.set(r,{item:a,filePath:o});return t}function Z(e){let t=new Map;for(let{filePath:o,data:n}of e)if(n.aspects)for(let[r,a]of Object.entries(n.aspects))t.set(r,{item:a,filePath:o});return t}function U(e){let t=[],o=new Set;for(let{filePath:n,data:r}of e){let a=C(r.features);for(let[l,p]of a)M(`#${l}`,p,n,t,o);let i=C(r.components);for(let[l,p]of i)M(`#${l}`,p,n,t,o);}return t}function M(e,t,o,n,r){if(t.flows)for(let a of t.flows){let i=a.startsWith("$")?a:`$${a}`;r.has(i)||(r.add(i),n.push({symbol:i,type:"flow",sourceSymbol:e,filePath:o}));}if(t.gates)for(let a of t.gates){let i=a.startsWith("^")?a:`^${a}`;r.has(i)||(r.add(i),n.push({symbol:i,type:"gate",sourceSymbol:e,filePath:o}));}if(t.signals)for(let a of t.signals){let i=a.startsWith("!")?a:`!${a}`;r.has(i)||(r.add(i),n.push({symbol:i,type:"signal",sourceSymbol:e,filePath:o}));}if(t.states)for(let a of t.states){let i=a.startsWith("#")?a:a.startsWith("%")?`#${a.slice(1)}`:`#${a}`;r.has(i)||(r.add(i),n.push({symbol:i,type:"component",sourceSymbol:e,filePath:o}));}if(t.components)for(let a of t.components){let i=a.startsWith("#")?a:`#${a}`;r.has(i)||(r.add(i),n.push({symbol:i,type:"component",sourceSymbol:e,filePath:o}));}if(t.aspects)for(let a of t.aspects){let i=a.startsWith("~")?a:`~${a}`;r.has(i)||(r.add(i),n.push({symbol:i,type:"aspect",sourceSymbol:e,filePath:o}));}if(t.description){let a=je(t.description);for(let{symbol:i,type:l}of a)r.has(i)||(r.add(i),n.push({symbol:i,type:l,sourceSymbol:e,filePath:o}));}}var Ce=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function je(e){let t=[],o=/([$^!#~%])([a-zA-Z][a-zA-Z0-9._-]*)/g,n;for(;(n=o.exec(e))!==null;){let r=n[1],a=n[2],i,l;switch(r){case "#":l="component",i=`#${a}`;break;case "$":l="flow",i=`$${a}`;break;case "^":l="gate",i=`^${a}`;break;case "!":l="signal",i=`!${a}`;break;case "~":l="aspect",i=`~${a}`;break;case "%":l="component",i=`#${a}`;break;default:continue}Ce.has(i)||t.push({symbol:i,type:l});}return t}var Ie={visualizerPort:42195,watcherPort:42196,autoConnect:true};async function I(e){let t=S.resolve(e),o=S.dirname(t);if(!P.existsSync(t))throw new Error(`Gate config not found: ${t}`);let n=P.readFileSync(t,"utf8"),r=j.load(n);if(!r.version)throw new Error('Gate config missing required "version" field');let a=[],i=r,l=r.gates||i.portals;if(l)for(let[f,u]of Object.entries(l)){let g=f.startsWith("^")?f.slice(1):f;a.push(F(g,u));}if(r.include)for(let f of r.include){let u=S.join(o,f),g=await glob(u.replace(/\\/g,"/"));for(let h of g){let w=await Ae(h);a.push(...w);}}let p=[];if(r.flows)for(let[f,u]of Object.entries(r.flows))p.push(Oe(f,u));return {version:r.version,gates:a,flows:p,settings:{dev:{...Ie,...r.settings?.dev}}}}async function Ae(e){let t=P.readFileSync(e,"utf8"),o=j.load(t);if(o.id){let n=o.id,r=n.startsWith("^")?n.slice(1):n;return [F(r,o)]}if(o.gates){let n=[];for(let[r,a]of Object.entries(o.gates)){let i=r.startsWith("^")?r.slice(1):r;n.push(F(i,a));}return n}return []}function F(e,t){let o=[];if(t.locks)for(let r of t.locks)o.push(De(r));let n=[];if(t.prizes)for(let r of t.prizes)n.push(ze(r));return {id:e,description:t.description,locks:o,prizes:n,position:t.position}}function De(e){let t=e,o=[];if(t.keys){for(let n of t.keys)if(typeof n=="string")o.push({expression:n});else if(n.expression){let r=n;o.push({expression:r.expression,description:r.description});}}return {id:t.id,description:t.description,keys:o,mode:t.mode||"all"}}function ze(e){let t=e;return {id:t.id,oneTime:t.oneTime??false,metadata:t.metadata}}function Oe(e,t){return {id:e,description:t.description,gates:t.gates||[],forkable:t.forkable}}async function H(e){let t=S.resolve(e);return await glob("**/portal.yaml",{cwd:t,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})}var Fe={component:"#",flow:"$",gate:"^",signal:"!",aspect:"~"},Te={"#":"component",$:"flow","^":"gate","!":"signal","~":"aspect"},Re=["#","$","^","!","~"];function Le(e){return Re.includes(e)}var Me=z$1.object({x:z$1.number(),y:z$1.number()}),Ge=z$1.object({x:z$1.number(),y:z$1.number(),zoom:z$1.number()}),J=z$1.object({path:z$1.string(),include:z$1.array(z$1.string()).optional(),exclude:z$1.array(z$1.string()).optional()}),ee=z$1.object({id:z$1.string(),symbol:z$1.string(),type:z$1.enum(["feature","component","flow","state","aspect","gate","signal","idea"]),content:z$1.string().optional(),position:Me,tags:z$1.array(z$1.string()).optional(),created:z$1.string(),modified:z$1.string().optional()}),te=z$1.object({from:z$1.string(),to:z$1.string(),label:z$1.string().optional(),type:z$1.string().optional()}),We=z$1.object({id:z$1.string(),name:z$1.string(),nodes:z$1.array(z$1.string()),color:z$1.string().optional()}),oe=z$1.object({viewport:Ge,groups:z$1.array(We).optional()}),Ye=z$1.object({nodes:z$1.array(ee),connections:z$1.array(te),layout:oe}),Be=z$1.object({id:z$1.string(),name:z$1.string(),timestamp:z$1.string(),description:z$1.string().optional(),state:Ye}),Ve=z$1.object({version:z$1.string(),metadata:z$1.object({name:z$1.string(),created:z$1.string(),modified:z$1.string()}),sources:z$1.object({purpose:z$1.array(J).optional(),portal:z$1.array(J).optional()}),nodes:z$1.array(ee),connections:z$1.array(te),layout:oe,snapshots:z$1.array(Be).optional()});function rt(e){let t=[],o;try{o=P.readFileSync(e,"utf8");}catch(n){return t.push(`Cannot read file: ${n.message}`),{data:null,errors:t,rawContent:void 0}}return _e(o)}function _e(e){let t=[],o=null;try{o=j.load(e);}catch(r){let a=r,i=a.mark?.line?a.mark.line+1:void 0;return t.push(`YAML syntax error: ${a.reason||r.message}${i?` (line ${i})`:""}`),{data:null,errors:t,rawContent:e}}if(o==null)return {data:se(),errors:[],rawContent:e};let n=Ve.safeParse(o);if(!n.success){for(let r of n.error.issues){let a=r.path.join(".");t.push(`Schema error at ${a||"/"}: ${r.message}`);}return {data:o,errors:t,rawContent:e}}return {data:n.data,errors:[],rawContent:e}}function se(e="Untitled"){let t=new Date().toISOString();return {version:"1.0.0",metadata:{name:e,created:t,modified:t},sources:{purpose:[{path:"./"}],portal:[{path:"./portal.yaml"}]},nodes:[],connections:[],layout:{viewport:{x:0,y:0,zoom:1}}}}function Ne(e){return e.metadata.modified=new Date().toISOString(),j.dump(e,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function at(e="My Project"){return Ne(se(e))}function it(e,t){return {...e,nodes:[...e.nodes,t],metadata:{...e.metadata,modified:new Date().toISOString()}}}function ct(e,t,o){return {...e,nodes:e.nodes.map(n=>n.id===t?{...n,position:o,modified:new Date().toISOString()}:n),metadata:{...e.metadata,modified:new Date().toISOString()}}}function pt(e,t){return e.connections.some(n=>n.from===t.from&&n.to===t.to)?e:{...e,connections:[...e.connections,t],metadata:{...e.metadata,modified:new Date().toISOString()}}}function ft(e,t,o){let n={id:`snap-${Date.now()}`,name:t,timestamp:new Date().toISOString(),description:o,state:{nodes:[...e.nodes],connections:[...e.connections],layout:{...e.layout}}};return {...e,snapshots:[...e.snapshots||[],n],metadata:{...e.metadata,modified:new Date().toISOString()}}}async function Ke(e,t){let o=[],n=[],r=[],a=[];if(e.sources.purpose)for(let p of e.sources.purpose){let f=S.resolve(t,p.path);try{let u=await Y(f);r.push(...u.map(d=>d.filePath));let g=B(u);for(let[d,{item:m,filePath:y}]of g){let x=["feature",...m.tags||[]];o.push($({id:`purpose-feature-${d}`,symbol:`#${d}`,type:"component",source:"purpose",filePath:y,data:m,description:m.description,tags:x,componentType:m.type,parentSymbol:m.parent,anchors:m.anchors?.map(pe=>T(pe))}));}let h=V(u);for(let[d,{item:m,filePath:y}]of h)o.push($({id:`purpose-component-${d}`,symbol:`#${d}`,type:"component",source:"purpose",filePath:y,data:m,description:m.description,tags:m.tags,componentType:m.type,parentSymbol:m.parent,anchors:m.anchors?.map(x=>T(x))}));let w=_(u);for(let[d,{item:m,filePath:y}]of w)o.push($({id:`purpose-gate-${d}`,symbol:`^${d}`,type:"gate",source:"purpose",filePath:y,data:m,description:m.description}));let v=N(u);for(let[d,{item:m,filePath:y}]of v)o.push($({id:`purpose-state-${d}`,symbol:`#${d}`,type:"component",source:"purpose",filePath:y,data:m,description:m.description,tags:["state"]}));let re=K(u);for(let[d,{item:m,filePath:y}]of re)o.push($({id:`purpose-flow-${d}`,symbol:`$${d}`,type:"flow",source:"purpose",filePath:y,data:m,description:m.description}));let ae=q(u);for(let[d,{item:m,filePath:y}]of ae)o.push($({id:`purpose-signal-${d}`,symbol:`!${d}`,type:"signal",source:"purpose",filePath:y,data:m,description:m.description}));let ie=Z(u);for(let[d,{item:m,filePath:y}]of ie)o.push($({id:`purpose-aspect-${d}`,symbol:`~${d}`,type:"aspect",source:"purpose",filePath:y,data:m,description:m.description,anchors:m.anchors?.map(x=>T(x)),appliesTo:m["applies-to"],tags:m.tags,enforcement:m.enforcement}));let ce=U(u),R=new Set(o.map(d=>d.symbol));for(let d of ce)R.has(d.symbol)||(R.add(d.symbol),o.push($({id:`purpose-ref-${d.type}-${d.symbol.slice(1)}`,symbol:d.symbol,type:d.type,source:"purpose",filePath:d.filePath,data:{referencedFrom:d.sourceSymbol},description:`Referenced from ${d.sourceSymbol}`})));}catch(u){n.push({source:"purpose",filePath:f,message:u.message});}}if(e.sources.portal)for(let p of e.sources.portal){let f=S.resolve(t,p.path);try{let u;if(f.endsWith(".yaml")||f.endsWith(".yml"))u=await I(f),a.push(f);else {let g=await H(f);if(a.push(...g),g.length>0){u=await I(g[0]);for(let h=1;h<g.length;h++){let w=await I(g[h]);u.gates.push(...w.gates),u.flows.push(...w.flows);}}else continue}for(let g of u.gates){o.push(qe(g,f));for(let h of g.prizes)o.push($({id:`gate-signal-${g.id}-${h.id}`,symbol:`!${h.id}`,type:"signal",source:"portal",filePath:f,data:h,description:`Signal from gate ${g.id}`}));}for(let g of u.flows)o.push(Ze(g,f));}catch(u){n.push({source:"portal",filePath:f,message:u.message});}}for(let p of e.nodes){let f=p.tags?.includes("idea");if(!p.content&&!f){let u=o.find(g=>g.symbol===p.symbol);if(u){u.position=p.position,u.tags=p.tags;continue}}o.push($({id:p.id,symbol:p.symbol,type:p.type,source:"premise",filePath:".premise",data:p,description:p.content,position:p.position,tags:p.tags,created:p.created,modified:p.modified}));}Xe(o);let i=new Map;for(let p of o){let f=i.get(p.symbol)||[];f.includes(p.filePath)||f.push(p.filePath),i.set(p.symbol,f);}let l=[];for(let[p,f]of i)f.length>1&&l.push({symbol:p,files:f});return {symbols:o,purposeFiles:r,portalFiles:a,errors:n,timestamp:Date.now(),...l.length>0?{duplicateSymbols:l}:{}}}function $(e){return {...e,data:e.data??null,references:e.references??[],referencedBy:e.referencedBy??[]}}function qe(e,t){let o=e.id.startsWith("^")?e.id.slice(1):e.id;return $({id:`gate-${o}`,symbol:`^${o}`,type:"gate",source:"portal",filePath:t,data:e,description:e.description,position:e.position})}function Ze(e,t){return $({id:`gate-flow-${e.id}`,symbol:`$${e.id}`,type:"flow",source:"portal",filePath:t,data:e,description:e.description})}function T(e){let t=e.lastIndexOf(":");if(t===-1||t===e.length-1)return {path:e,lines:0,raw:e};let o=e.slice(t+1),n=e.slice(0,t);if(!/^[\d,\- ]+$/.test(o))return {path:e,lines:0,raw:e};if(o.includes("-")){let[r,a]=o.split("-").map(Number);return {path:n,lines:[r,a],raw:e}}else if(o.includes(",")){let r=o.split(",").map(Number);return {path:n,lines:r,raw:e}}else return {path:n,lines:Number(o),raw:e}}var Ue=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function Xe(e){let t=new Map(e.map(o=>[o.symbol,o]));for(let o of e){let n=JSON.stringify(o.data),r=/(?:\?[@#$%~^!]|[@#$%~^!?])[a-zA-Z][\w-]*/g,a=(n.match(r)||[]).filter(i=>!Ue.has(i));for(let i of a)if(i!==o.symbol&&t.has(i)){o.references.includes(i)||o.references.push(i);let l=t.get(i);l&&!l.referencedBy.includes(o.symbol)&&l.referencedBy.push(o.symbol);}}}async function dt(e){let t={metadata:{name:S.basename(e),created:new Date().toISOString(),modified:new Date().toISOString()},sources:{purpose:[{path:"./"}],portal:[{path:"./"}]},nodes:[]};return Ke(t,e)}function He(){return {entries:new Map,byType:new Map,bySource:new Map,timestamp:0}}function mt(e){let t=He();t.timestamp=e.timestamp;for(let o of e.symbols)t.entries.set(o.id,o),t.byType.has(o.type)||t.byType.set(o.type,[]),t.byType.get(o.type).push(o),t.bySource.has(o.source)||t.bySource.set(o.source,[]),t.bySource.get(o.source).push(o);return t}function A(e,t){for(let o of e.entries.values())if(o.symbol===t)return o}function gt(e,t){return e.entries.get(t)}function z(e,t){return e.byType.get(t)||[]}function ht(e,t){return e.bySource.get(t)||[]}function Je(e,t){let o=t.toLowerCase(),n=[];for(let r of e.entries.values()){if(r.symbol.toLowerCase().includes(o)){n.push(r);continue}if(r.description?.toLowerCase().includes(o)){n.push(r);continue}if(r.tags?.some(a=>a.toLowerCase().includes(o))){n.push(r);continue}if(r.componentType?.toLowerCase().includes(o)){n.push(r);continue}}return n}function yt(e,t){return z(e,"component").filter(n=>n.componentType===t)}function $t(e){let t=new Set,o=z(e,"component");for(let n of o)n.componentType&&t.add(n.componentType);return Array.from(t).sort()}function wt(e,t){return z(e,"component").filter(n=>n.parentSymbol===t)}function bt(e,t){let o=A(e,t);return o?o.referencedBy.map(n=>A(e,n)).filter(n=>n!==void 0):[]}function St(e,t){let o=A(e,t);return o?o.references.map(n=>A(e,n)).filter(n=>n!==void 0):[]}function vt(e,t){let o=[];for(let n of e.entries.values())n.tags?.includes(t)&&o.push(n);return o}function xt(e){let t=new Set;for(let o of e.entries.values())for(let n of o.tags||[])t.add(n);return Array.from(t).sort()}function Pt(e){let t={component:0,flow:0,gate:0,signal:0,aspect:0};for(let[o,n]of e.byType)o in t&&(t[o]=n.length);return t}function kt(e){return Array.from(e.entries.values())}function ne(e){if(e.length<2)return null;let t=e[0],o=e.slice(1);return Le(t)?{type:Te[t],name:o}:null}function Ct(e,t){return `${Fe[e]}${t}`}function jt(e){return ne(e)!==null}function It(e,t,o=10){let n=t.toLowerCase(),r=ne(t);return r?z(e,r.type).filter(i=>i.symbol.toLowerCase().includes(n)).slice(0,o):Je(e,t).slice(0,o)}export{Te as PREFIX_TO_TYPE,Fe as SYMBOL_PREFIXES,pt as addConnection,it as addPremiseNode,dt as aggregateFromDirectory,Ke as aggregateFromPremise,mt as buildSymbolIndex,se as createEmptyPremiseFile,ft as createSnapshot,He as createSymbolIndex,Ct as createSymbolString,$t as getAllComponentTypes,kt as getAllSymbols,xt as getAllTags,It as getAutocompleteSuggestions,wt as getChildComponents,yt as getComponentsByType,at as getDefaultPremiseContent,St as getReferencesFrom,bt as getReferencesTo,A as getSymbol,gt as getSymbolById,Pt as getSymbolCounts,ht as getSymbolsBySource,vt as getSymbolsByTag,z as getSymbolsByType,jt as isValidSymbol,_e as parsePremiseContent,rt as parsePremiseFile,ne as parseSymbol,Je as searchSymbols,Ne as serializePremiseFile,ct as updateNodePosition};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- export{b as PREFIX_TO_TYPE,a as SYMBOL_PREFIXES,j as addConnection,h as addPremiseNode,m as aggregateFromDirectory,l as aggregateFromPremise,o as buildSymbolIndex,e as createEmptyPremiseFile,k as createSnapshot,n as createSymbolIndex,E as createSymbolString,v as getAllComponentTypes,C as getAllSymbols,A as getAllTags,G as getAutocompleteSuggestions,w as getChildComponents,u as getComponentsByType,g as getDefaultPremiseContent,y as getReferencesFrom,x as getReferencesTo,p as getSymbol,q as getSymbolById,B as getSymbolCounts,s as getSymbolsBySource,z as getSymbolsByTag,r as getSymbolsByType,F as isValidSymbol,d as parsePremiseContent,c as parsePremiseFile,D as parseSymbol,t as searchSymbols,f as serializePremiseFile,i as updateNodePosition}from'./chunk-T6IDXUUA.js';import'./chunk-JIXHEBGK.js';import'./chunk-QT2LKB3P.js';import'./chunk-5TAVYPOV.js';
2
+ export{b as PREFIX_TO_TYPE,a as SYMBOL_PREFIXES,j as addConnection,h as addPremiseNode,m as aggregateFromDirectory,l as aggregateFromPremise,o as buildSymbolIndex,e as createEmptyPremiseFile,k as createSnapshot,n as createSymbolIndex,E as createSymbolString,v as getAllComponentTypes,C as getAllSymbols,A as getAllTags,G as getAutocompleteSuggestions,w as getChildComponents,u as getComponentsByType,g as getDefaultPremiseContent,y as getReferencesFrom,x as getReferencesTo,p as getSymbol,q as getSymbolById,B as getSymbolCounts,s as getSymbolsBySource,z as getSymbolsByTag,r as getSymbolsByType,F as isValidSymbol,d as parsePremiseContent,c as parsePremiseFile,D as parseSymbol,t as searchSymbols,f as serializePremiseFile,i as updateNodePosition}from'./chunk-LWAIVOSF.js';import'./chunk-JIXHEBGK.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export{h as classifyYamlError,e as findGateFiles,g as formatValidationResult,d as getDefaultGateConfig,a as parseGateConfig,b as parseGateFile,c as serializeGateConfig,f as validateGateConfig}from'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export{a as doctorCommand}from'./chunk-RBLK34IA.js';import'./chunk-DOCDDDTD.js';import'./chunk-JQKKVAAN.js';import'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import'./chunk-SHD27BQX.js';import {a}from'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';import*as g from'fs';import*as u from'path';import l from'chalk';import*as m from'js-yaml';import {execSync}from'child_process';function y(e){return Object.entries(e.flows).map(([s,t])=>({id:s,...t}))}function w(e){let s=u.join(e,".paradigm","flows.yaml");if(!g.existsSync(s))return null;try{let t=g.readFileSync(s,"utf-8");return m.load(t)}catch{return null}}function b(e){let s=[];try{let t=execSync(`find "${e}" -name ".purpose" -not -path "*/node_modules/*" -not -path "*/.git/*" 2>/dev/null || true`,{encoding:"utf-8"});for(let i of t.split(`
2
+ import'./chunk-4VKSEOXZ.js';import'./chunk-ZJQY5PPP.js';import {a}from'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';import*as g from'fs';import*as u from'path';import l from'chalk';import*as m from'js-yaml';import {execSync}from'child_process';function y(e){return Object.entries(e.flows).map(([s,t])=>({id:s,...t}))}function w(e){let s=u.join(e,".paradigm","flows.yaml");if(!g.existsSync(s))return null;try{let t=g.readFileSync(s,"utf-8");return m.load(t)}catch{return null}}function b(e){let s=[];try{let t=execSync(`find "${e}" -name ".purpose" -not -path "*/node_modules/*" -not -path "*/.git/*" 2>/dev/null || true`,{encoding:"utf-8"});for(let i of t.split(`
3
3
  `).filter(Boolean))try{let n=g.readFileSync(i,"utf-8").match(/flows:\s*\n([\s\S]*?)(?=\n[a-z_]+:|$)/);if(n){let r=m.load(`flows:
4
4
  ${n[1]}`);if(r&&typeof r=="object"&&"flows"in r){let c=r.flows;for(let[a,d]of Object.entries(c))s.push({id:a,...d,definedIn:u.relative(e,i)});}}}catch{}}catch{}return s}function F(e){let s=[],t=w(e);if(t){let o=y(t);for(let n of o)n.definedIn=".paradigm/flows.yaml",s.push(n);}let i=b(e);for(let o of i)s.some(n=>n.id===o.id)||s.push(o);return s}function $(e){let s=[];s.push("```mermaid"),s.push("flowchart TD"),s.push(` START([${p(e.trigger)}])`);let t="START";for(let i=0;i<e.steps.length;i++){let o=e.steps[i],n=`S${i}`,r=p(o.symbol);switch(o.type){case "gate":{let c=o;if(s.push(` ${n}{${r}}`),s.push(` ${t} --> ${n}`),c.failResponse||o.errorSignal){let a=`DENY${i}`,d=c.failResponse||o.errorSignal||"Denied";s.push(` ${a}[/${p(d)}/]`),s.push(` ${n} -->|deny| ${a}`);}break}case "action":s.push(` ${n}[${r}]`),s.push(` ${t} -->|${o.optional?"optional":"allow"}| ${n}`);break;case "signal":s.push(` ${n}([${r}])`),s.push(` ${t} --> ${n}`);break}t=n;}e.successSignal&&(s.push(` SUCCESS([${p(e.successSignal)}])`),s.push(` ${t} --> SUCCESS`)),s.push(""),s.push(" classDef gate fill:#f9d71c,stroke:#333,color:#000"),s.push(" classDef action fill:#4a90d9,stroke:#333,color:#fff"),s.push(" classDef signal fill:#50c878,stroke:#333,color:#fff");for(let i=0;i<e.steps.length;i++){let o=e.steps[i];s.push(` class S${i} ${o.type}`);}return s.push("```"),s.join(`
5
5
  `)}function p(e){return e.replace(/"/g,'\\"').replace(/[[\]{}()]/g,"")}async function L(e,s){let t=process.cwd();w(t)||(console.log(l.red(`
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- export{a as hooksInstallCommand,c as hooksStatusCommand,b as hooksUninstallCommand}from'./chunk-SI6SV76D.js';import'./chunk-5TAVYPOV.js';
2
+ export{a as hooksInstallCommand,c as hooksStatusCommand,b as hooksUninstallCommand}from'./chunk-3DZK54RU.js';import'./chunk-5TAVYPOV.js';