@a-company/paradigm 6.6.3 → 7.0.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 (112) hide show
  1. package/dist/{accept-orchestration-JHDCVHB2.js → accept-orchestration-YO2V2WYA.js} +1 -1
  2. package/dist/add-V6XR7DU5.js +12 -0
  3. package/dist/{agents-suggest-IKY6VD2R.js → agents-suggest-WZEGQT5E.js} +1 -1
  4. package/dist/ambient-7HBJHJL2.js +2 -0
  5. package/dist/{ambient-FNNFB4AP.js → ambient-OX7YJ4PJ.js} +1 -1
  6. package/dist/ambient-SST5CLEC.js +35 -0
  7. package/dist/captain-YUP3KVCA.js +2 -0
  8. package/dist/chunk-33ERV2MW.js +18 -0
  9. package/dist/chunk-3MZ4J2LF.js +2 -0
  10. package/dist/chunk-47YPID6H.js +142 -0
  11. package/dist/chunk-6AKNXD22.js +32 -0
  12. package/dist/chunk-6HVOZANP.js +4 -0
  13. package/dist/chunk-ACJWUOMA.js +3 -0
  14. package/dist/chunk-B5KLSBOZ.js +2 -0
  15. package/dist/chunk-DLMDHS2X.js +10 -0
  16. package/dist/chunk-EKNLG73M.js +6 -0
  17. package/dist/chunk-FRQRREJ6.js +29 -0
  18. package/dist/{chunk-5RFISGUW.js → chunk-G6DK3ND3.js} +250 -25
  19. package/dist/{chunk-XKNJSPB5.js → chunk-JCGCPAHF.js} +1 -1
  20. package/dist/chunk-K54L6CFR.js +25 -0
  21. package/dist/chunk-QBIQ2FYB.js +20 -0
  22. package/dist/chunk-QEQCPVF5.js +4 -0
  23. package/dist/chunk-ROU3F2HZ.js +6 -0
  24. package/dist/chunk-S4J337EQ.js +504 -0
  25. package/dist/chunk-V6MIKLMY.js +18 -0
  26. package/dist/chunk-WROJSWAO.js +93 -0
  27. package/dist/{chunk-TQOT2LBO.js → chunk-YXLGVOZO.js} +1 -1
  28. package/dist/chunk-ZSWXLFN7.js +12 -0
  29. package/dist/{compliance-J3VOV445.js → compliance-MLG4W6S4.js} +1 -1
  30. package/dist/{diff-ANKTFDRA.js → diff-MC6AXLKX.js} +1 -1
  31. package/dist/{docs-TSAAS4W3.js → docs-3YFNNZRV.js} +1 -1
  32. package/dist/doctor-CBZYYQQH.js +2 -0
  33. package/dist/{hooks-45WDP6QS.js → hooks-AXBWYJ5V.js} +1 -1
  34. package/dist/index.js +6 -6
  35. package/dist/list-NC3QGT75.js +12 -0
  36. package/dist/mcp.js +3 -3
  37. package/dist/{migrate-R64OQGSM.js → migrate-5M4KUQ2L.js} +1 -1
  38. package/dist/{nomination-engine-NCLTGMAK.js → nomination-engine-AQHU2KBU.js} +1 -1
  39. package/dist/notebook-loader-6DYFMNJ2.js +2 -0
  40. package/dist/orchestrate-GMYEBA5T.js +8 -0
  41. package/dist/orchestration-G5MAY6IA.js +2 -0
  42. package/dist/propose-block-ZEMEWJQF.js +2 -0
  43. package/dist/{providers-TBPOE4DI.js → providers-5EHD45C6.js} +1 -1
  44. package/dist/quiz-TNV6APBM.js +10 -0
  45. package/dist/reindex-XTRF23F7.js +2 -0
  46. package/dist/serve-2PKJP65E.js +12 -0
  47. package/dist/{serve-3FMUWW5K.js → serve-SMGWGJLM.js} +1 -1
  48. package/dist/server-4SYOUF6D.js +7 -0
  49. package/dist/session-tracker-BZ7FU4AT.js +2 -0
  50. package/dist/session-work-log-QXPAXY5K.js +2 -0
  51. package/dist/session-work-log-T2IE4Y4T.js +2 -0
  52. package/dist/{shift-TNA2E5O7.js → shift-JBCEDCGA.js} +2 -2
  53. package/dist/show-N5LGB5B2.js +7 -0
  54. package/dist/solo-OWR3MX74.js +3 -0
  55. package/dist/{spawn-KKDDR6UR.js → spawn-PHA2SVQ3.js} +1 -1
  56. package/dist/status-ENAI35NL.js +6 -0
  57. package/dist/task-loader-IGQQ6ZFL.js +2 -0
  58. package/dist/task-settlement-NW4XMJGJ.js +3 -0
  59. package/dist/{team-PEGP6F7S.js → team-J2YXPEGX.js} +1 -1
  60. package/dist/team-funnel-RAJ6EDG3.js +2 -0
  61. package/dist/tools-HNJ7D5IO.js +2 -0
  62. package/dist/university-content/notes/N-para-801-cid-becomes-real.md +60 -0
  63. package/dist/university-content/notes/N-para-801-falsifiable-self-improvement.md +66 -0
  64. package/dist/university-content/notes/N-para-801-honest-routing-and-the-method.md +57 -0
  65. package/dist/university-content/notes/N-para-801-orchestration-emits-dag.md +60 -0
  66. package/dist/university-content/notes/N-para-801-settlement-closes-the-loop.md +64 -0
  67. package/dist/university-content/notes/N-para-801-the-task-dag.md +93 -0
  68. package/dist/university-content/paths/LP-para-801.yaml +43 -0
  69. package/dist/university-content/quizzes/Q-para-801-cid-becomes-real.yaml +54 -0
  70. package/dist/university-content/quizzes/Q-para-801-falsifiable-self-improvement.yaml +54 -0
  71. package/dist/university-content/quizzes/Q-para-801-honest-routing-and-the-method.yaml +54 -0
  72. package/dist/university-content/quizzes/Q-para-801-orchestration-emits-dag.yaml +54 -0
  73. package/dist/university-content/quizzes/Q-para-801-settlement-closes-the-loop.yaml +54 -0
  74. package/dist/university-content/quizzes/Q-para-801-the-task-dag.yaml +54 -0
  75. package/dist/university-ui/assets/{index-BIQeax_b.js → index-B8hm_MdR.js} +2 -2
  76. package/dist/university-ui/assets/{index-BIQeax_b.js.map → index-B8hm_MdR.js.map} +1 -1
  77. package/dist/university-ui/index.html +1 -1
  78. package/dist/validate-IQG7DBFC.js +9 -0
  79. package/package.json +2 -1
  80. package/dist/add-CBDFTWST.js +0 -12
  81. package/dist/ambient-AI42BOM5.js +0 -35
  82. package/dist/chunk-4N56FRNE.js +0 -29
  83. package/dist/chunk-6QXBXZF6.js +0 -3
  84. package/dist/chunk-AMLD7IYC.js +0 -10
  85. package/dist/chunk-DVZWCXB6.js +0 -2
  86. package/dist/chunk-ERO4MJSH.js +0 -6
  87. package/dist/chunk-F6E3HW45.js +0 -14
  88. package/dist/chunk-FI66YM6G.js +0 -666
  89. package/dist/chunk-K7X3Z3GL.js +0 -4
  90. package/dist/chunk-LAYBUKMB.js +0 -14
  91. package/dist/chunk-MU5YWTNE.js +0 -24
  92. package/dist/chunk-P344HV6Z.js +0 -2
  93. package/dist/chunk-QALPEMCU.js +0 -111
  94. package/dist/chunk-XQLO5URP.js +0 -11
  95. package/dist/doctor-L5XZENCF.js +0 -2
  96. package/dist/list-AXKTBXKJ.js +0 -12
  97. package/dist/notebook-loader-3J2OFMS3.js +0 -2
  98. package/dist/orchestrate-UG5QXNAU.js +0 -8
  99. package/dist/quiz-G56CUN45.js +0 -10
  100. package/dist/reindex-F7BZCG4W.js +0 -2
  101. package/dist/serve-TJQ5BNKR.js +0 -12
  102. package/dist/server-QOCW5RU6.js +0 -7
  103. package/dist/session-tracker-HHNY6J4I.js +0 -2
  104. package/dist/session-work-log-MEJ33TYD.js +0 -2
  105. package/dist/session-work-log-ZVVJGO7X.js +0 -2
  106. package/dist/show-MTPEQFXK.js +0 -7
  107. package/dist/status-REA6HUXE.js +0 -6
  108. package/dist/task-loader-NZFDTUQ5.js +0 -2
  109. package/dist/tools-HQKF4Q3P.js +0 -2
  110. package/dist/validate-742XMB42.js +0 -9
  111. /package/dist/{chunk-HXGYVS2N.js → chunk-ECLUYHAR.js} +0 -0
  112. /package/dist/{platform-server-ANOALDPL.js → platform-server-WIBVYHIV.js} +0 -0
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env node
2
- import {c,b}from'./chunk-5TAVYPOV.js';import*as i from'fs';import*as l from'path';import*as k from'os';import*as g from'js-yaml';var $={};c($,{addNotebookEntry:()=>N,classifyNotebookScope:()=>w,incrementApplied:()=>P,loadNotebookEntries:()=>S,promoteFromLore:()=>_,searchNotebooks:()=>O});function S(e,t,n){let r=new Map,a=l.join(u,e);h(a,r);let o=l.join(t,d,e);h(o,r);let c=Array.from(r.values());if(n?.concepts&&n.concepts.length>0){let p=new Set(n.concepts.map(s=>s.toLowerCase()));c=c.filter(s=>s.concepts.some(f=>p.has(f.toLowerCase())));}if(n?.tags&&n.tags.length>0){let p=new Set(n.tags.map(s=>s.toLowerCase()));c=c.filter(s=>s.tags.some(f=>p.has(f.toLowerCase())));}return c.sort((p,s)=>s.appliedCount-p.appliedCount)}function h(e,t){if(i.existsSync(e))try{let n=i.readdirSync(e).filter(r=>r.startsWith(L)&&r.endsWith(y));for(let r of n)try{let a=i.readFileSync(l.join(e,r),"utf-8"),o=g.load(a);o?.id&&t.set(o.id,o);}catch{}}catch{}}function O(e,t,n){let r=S(e,n),a=t.toLowerCase();return r.filter(o=>o.context.toLowerCase().includes(a)||o.snippet.toLowerCase().includes(a)||o.concepts.some(c=>c.toLowerCase().includes(a))||o.tags.some(c=>c.toLowerCase().includes(a)))}function w(e){let t=[e.context,e.snippet,...e.concepts,...e.tags].join(" ").toLowerCase();return ["paradigm","mcp_","mcp tool",".paradigm/","lore entry","lore record","aspect","^gate","portal.yaml",".purpose","sentinel","symphony","ambient nomination","paradigm_"," pan ","agent notebook","concept anchor","symbol system","work log","knowledge stream","nevr.land","neverland"].some(r=>t.includes(r))?"platform-specific":/[#$^!~][a-z][a-z0-9-]{2,}/.test(t)||/\/[a-z0-9_-]{2,}\/[a-z0-9_-]/.test(t)?"project-specific":"generalizable"}function N(e,t,n,r){let a=new Date().toISOString(),o=(t.concepts[0]||t.context.split(" ").slice(0,4).join(" ")||"entry").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40),p=`nb-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}-${o}`,s=t.scope??w({context:t.context,snippet:t.snippet,concepts:t.concepts,tags:t.tags}),f={...t,id:p,scope:s,publishable:t.publishable??true,appliedCount:0,created:a,updated:a},m=n==="global"?l.join(u,e):l.join(r||process.cwd(),d,e);i.existsSync(m)||i.mkdirSync(m,{recursive:true});let E=`${p}${y}`,b=l.join(m,E),C=g.dump(f,{lineWidth:120,noRefs:true,sortKeys:false});return i.writeFileSync(b,C,"utf-8"),{entry:f,filePath:b}}async function _(e,t,n,r="global"){let{loadLoreEntry:a}=await import('./lore-loader-PXFKMKAN.js'),o=await a(n,t);if(!o)return null;let c=[];if(o.symbols_touched)for(let f of o.symbols_touched){let m=f.replace(/^[#$^!~]/,"").toLowerCase();c.push(m);}let p=o.summary||"";o.body&&(p+=`
3
-
4
- `+o.body);let s={source:"lore",loreEntryId:t,originProject:l.basename(n),createdBy:e};return N(e,{context:o.title||`Promoted from ${t}`,snippet:p,provenance:s,confidence:o.confidence??.7,concepts:c,tags:o.tags||[]},r,n)}function P(e,t,n){let r=l.join(n,d,e),a=l.join(u,e);for(let o of [r,a]){let c=l.join(o,`${t}${y}`);if(i.existsSync(c))try{let p=i.readFileSync(c,"utf-8"),s=g.load(p);if(s)return s.appliedCount=(s.appliedCount||0)+1,s.updated=new Date().toISOString(),i.writeFileSync(c,g.dump(s,{lineWidth:120,noRefs:!0,sortKeys:!1}),"utf-8"),!0}catch{}}return false}var u,d,L,y,v=b(()=>{u=l.join(k.homedir(),".paradigm","notebooks"),d=".paradigm/notebooks",L="nb-",y=".yaml";});export{S as a,O as b,w as c,N as d,_ as e,P as f,$ as g,v as h};
@@ -1,14 +0,0 @@
1
- #!/usr/bin/env node
2
- import {c,b}from'./chunk-5TAVYPOV.js';import*as e from'fs';import*as o from'path';var D={};c(D,{appendSessionWorkEntry:()=>C,appendVerdictEntry:()=>N,clearActivityMetrics:()=>j,clearSessionWorkLog:()=>I,countNotebookReferences:()=>w,getAgentEntries:()=>S,getAgentVerdicts:()=>P,getContributingAgents:()=>A,getNotebookReferences:()=>h,getSessionActivitySummary:()=>W,markVerdictsConsumed:()=>O,readPendingVerdicts:()=>M,readSessionWorkLog:()=>g,recordActivityMetric:()=>F,recordNotebookReference:()=>R});function C(i,n){try{let t=o.join(i,y),r=o.dirname(t);if(e.existsSync(r)||e.mkdirSync(r,{recursive:!0}),e.existsSync(t)&&e.readFileSync(t,"utf8").trim().split(`
3
- `).filter(a=>a.trim()).length>=x)return;let f=JSON.stringify(n)+`
4
- `;e.appendFileSync(t,f,"utf8"),n.type==="user-verdict"&&n.agent&&n.symbols?.length&&import('./agent-loader-W3RQJVW7.js').then(({loadAgentProfile:c,saveAgentProfile:s})=>{try{let a=c(i,n.agent);if(a?.expertise){let u=n.verdict==="accepted"?.03:n.verdict==="dismissed"?-.02:n.verdict==="revised"?-.01:0;if(u!==0){for(let v of n.symbols){let l=a.expertise.find(k=>k.symbol===v);l&&(l.confidence=Math.max(0,Math.min(1,l.confidence+u)),l.sessions=(l.sessions||0)+1,l.lastTouch=new Date().toISOString());}s(n.agent,a,"global");}}}catch{}}).catch(()=>{});}catch{}}function g(i){try{let n=o.join(i,y);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
5
- `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null):[]}catch{return []}}function I(i){try{let n=o.join(i,y);e.existsSync(n)&&e.writeFileSync(n,"","utf8");}catch{}}function N(i,n){try{let t=o.join(i,p),r=o.dirname(t);e.existsSync(r)||e.mkdirSync(r,{recursive:!0}),e.appendFileSync(t,JSON.stringify(n)+`
6
- `,"utf8");}catch{}}function M(i){try{let n=o.join(i,p);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
7
- `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&!t.consumed):[]}catch{return []}}function O(i,n){try{let t=o.join(i,p);if(!e.existsSync(t))return;let r=new Set(n),c=e.readFileSync(t,"utf8").trim().split(`
8
- `).filter(s=>s.trim()).map(s=>{try{let a=JSON.parse(s);return a.nominationId&&r.has(a.nominationId)?JSON.stringify({...a,consumed:!0}):s}catch{return s}});e.writeFileSync(t,c.join(`
9
- `)+`
10
- `,"utf8");}catch{}}function A(i){let n=g(i),t=new Set;for(let r of n)r.agent&&t.add(r.agent);return Array.from(t)}function S(i,n){return g(i).filter(t=>t.agent===n)}function P(i,n){let t=S(i,n),r=t.filter(s=>s.type==="agent-contribution"),f=t.filter(s=>s.type==="user-verdict"),c=[];for(let s of r)c.push({contribution:s});for(let s of f){let a=c.find(u=>!u.verdict&&u.contribution);a?a.verdict=s:c.push({verdict:s});}return c}function F(i,n){try{let t=o.join(i,d),r=o.dirname(t);e.existsSync(r)||e.mkdirSync(r,{recursive:!0});let f={timestamp:new Date().toISOString(),type:"activity",...n},c=JSON.stringify(f)+`
11
- `;e.appendFileSync(t,c,"utf8");}catch{}}function B(i){try{let n=o.join(i,d);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
12
- `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="activity"):[]}catch{return []}}function W(i){let n=B(i),t={toolCallCount:0,responsePayloadBytes:0,sessionDurationMs:0,agentBreakdown:{}};for(let r of n)if(r.toolCallCount!=null&&(t.toolCallCount+=r.toolCallCount),r.responsePayloadBytes!=null&&(t.responsePayloadBytes+=r.responsePayloadBytes),r.sessionDurationMs!=null&&(t.sessionDurationMs=Math.max(t.sessionDurationMs,r.sessionDurationMs)),r.agentId){t.agentBreakdown[r.agentId]||(t.agentBreakdown[r.agentId]={toolCalls:0,payloadBytes:0});let f=t.agentBreakdown[r.agentId];r.toolCallCount!=null&&(f.toolCalls+=r.toolCallCount),r.responsePayloadBytes!=null&&(f.payloadBytes+=r.responsePayloadBytes);}return t}function j(i){try{let n=o.join(i,d);e.existsSync(n)&&e.writeFileSync(n,"","utf8");}catch{}}function R(i,n,t,r){try{if(t.length===0)return;let f=o.join(i,m),c=o.dirname(f);e.existsSync(c)||e.mkdirSync(c,{recursive:!0});let s={timestamp:new Date().toISOString(),type:"notebook-reference",agentId:n,notebookEntryIds:t,...r?{orchestrationId:r}:{}},a=JSON.stringify(s)+`
13
- `;e.appendFileSync(f,a,"utf8");}catch{}}function h(i){try{let n=o.join(i,m);return e.existsSync(n)?e.readFileSync(n,"utf8").trim().split(`
14
- `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null&&t.type==="notebook-reference"):[]}catch{return []}}function w(i){return h(i).length}var y,d,p,x,m,J=b(()=>{y=".paradigm/events/session-log.jsonl",d=".paradigm/events/session-metrics.jsonl",p=".paradigm/events/verdicts.jsonl",x=200,m=".paradigm/events/notebook-refs.jsonl";});export{C as a,g as b,I as c,N as d,M as e,O as f,A as g,S as h,P as i,F as j,W as k,j as l,R as m,h as n,w as o,D as p,J as q};
@@ -1,24 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a as a$3}from'./chunk-TYWB5IQJ.js';import {b,a as a$1}from'./chunk-AMLD7IYC.js';import {a}from'./chunk-FYDRENK7.js';import {e}from'./chunk-TQOT2LBO.js';import {b as b$1}from'./chunk-EKZDFEJW.js';import {a as a$2,b as b$2}from'./chunk-LPBCQM5Y.js';import {o,t,x}from'./chunk-4GC35IFF.js';import'minimatch';import*as w from'fs';import*as A from'path';import*as F from'js-yaml';import {spawn}from'child_process';var ee=["should","what","how","why","recommend","analyze","compare","evaluate","assess","review","explain","describe","investigate","which","best practice","trade-off","tradeoff","pros and cons","decision"],te=["document","write docs","readme",".purpose","purpose file","jsdoc","tsdoc","comments","docstring","api docs","changelog","architecture doc"],se=["bug","fix","broken","not working","issue","error","crash","fails","failing","wrong","incorrect","doesn't work","doesn't","cant","can't","regression","patch"],re=["rename","refactor","migrate","restructure","move","reorganize","clean up","cleanup","consolidate","extract","inline","simplify","modularize","decouple","split","merge"],ne=["auth","authentication","authorization","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","api key","role","access","gate","portal","sensitive","private","security","vulnerability","xss","sql injection","csrf"],oe=/[@#$%^!?&~][a-zA-Z0-9_-]+/g,Y={analysis:{agents:["architect"],models:{architect:"opus"},costMultiplier:{min:.3,max:.5}},documentation:{agents:["architect"],models:{architect:"sonnet"},costMultiplier:{min:.25,max:.45}},bugfix:{agents:["security","builder"],models:{security:"opus",builder:"haiku"},costMultiplier:{min:.5,max:.8}},refactor:{agents:["architect","builder"],models:{architect:"opus",builder:"haiku"},costMultiplier:{min:.6,max:.85}},feature:{agents:["architect","security","builder","tester"],models:{architect:"opus",security:"opus",builder:"haiku",tester:"haiku"},costMultiplier:{min:.8,max:1.2}}};function ie(p){let s=p.match(oe)||[];return [...new Set(s)]}function $(p,s){let e=p.toLowerCase();return s.filter(t=>e.includes(t.toLowerCase()))}function ae(p,s,e,t){let n=0;e.length>=5?n+=2:e.length>=2&&(n+=1);let o=p.split(/\s+/).length;o>=100?n+=2:o>=50&&(n+=1);let r=new Set(e.map(a=>a[0]));return r.size>=4?n+=2:r.size>=2&&(n+=1),e.some(a=>a.startsWith("^"))&&(n+=1),e.some(a=>a.startsWith("$"))&&(n+=1),s==="feature"&&(n+=1),s==="refactor"&&(n+=1),n>=5?"high":n>=2?"medium":"low"}function le(p,s,e){if($(p,ne).length>0||s.some(n=>n.startsWith("^")))return true;return false}function K(p,s){let e=ie(p),t=$(p,ee),n=$(p,te),o=$(p,se),r=$(p,re),a,i;t.length>0&&o.length===0&&r.length===0?(a="analysis",i=t):n.length>0&&o.length===0?(a="documentation",i=n):o.length>0?(a="bugfix",i=o):r.length>0?(a="refactor",i=r):(a="feature",i=[]);let c=Y[a],d=le(p,e),u=[...c.agents];d&&!u.includes("security")&&(u=["security",...u]);let m=ae(p,a,e),g={...c.costMultiplier};return m==="high"?(g.min*=1.2,g.max*=1.3):m==="low"&&(g.min*=.8,g.max*=.9),d&&!c.agents.includes("security")&&(g.min+=.15,g.max+=.2),{type:a,complexity:m,recommendedAgents:u,securityRequired:d,costMultiplier:g,matchedKeywords:i,symbols:e}}function B(p,s){let e=Y[s.type];return p==="security"&&s.securityRequired?"opus":e.models[p]||"sonnet"}var ce=/[@#$%^!?&~][a-zA-Z][a-zA-Z0-9_-]*/g,ue=[/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/export\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)/gi,/\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]/gi],de=["endpoint","route","api","handler","get","post","put","patch","delete","rest","crud","controller"];function V(p,s,e$1){let t$1=p.toLowerCase(),n=p.match(ce)||[],o=[...new Set(n)],r=o.map(l=>{let y=t(e$1,l),k=y.length>0?y[0]:null;return {symbol:l,exists:!!k,type:k?.type,description:k?.description}}),a=r.filter(l=>l.exists).map(l=>{let y=x(e$1,l.symbol),k=new Set;for(let S of y){let x$1=x(e$1,S.symbol);for(let P of x$1)P.symbol!==l.symbol&&!y.find(O=>O.symbol===P.symbol)&&k.add(P.symbol);}let f=y.length+k.size,b="low";return f>10?b="high":f>3&&(b="medium"),{symbol:l.symbol,directDependents:y.length,indirectDependents:k.size,impact:b}}),i=a$2(s),c=i.status==="ok"?i.data:null,d={exists:i.status!=="missing",gateCount:c?b$2(c).length:0,gates:c?b$2(c).map(l=>`^${l}`):[],routeCount:c?.routes?Object.keys(c.routes).length:0},u=de.some(l=>t$1.includes(l)),m=e(s),g=m?a$3(p,m.agents).map(l=>({name:l.name,confidence:l.confidence,reason:l.reason})):[],h=[];return r.some(l=>l.exists)&&h.push("ripple-analysis"),u&&h.push("portal-compliance"),o.some(l=>l.startsWith("^"))&&h.push("gate-validation"),o.some(l=>l.startsWith("!"))&&h.push("signal-registration"),h.push("purpose-coverage"),{affectedSymbols:r,rippleAnalysis:a,portalStatus:d,taskAddsRoutes:u,suggestedAgents:g,requiredChecks:h}}function H(p,s,e,t$1){let n=[],o=a$2(e),r=o.status==="ok"?o.data:null,a=r?b$2(r):[],i=r?.routes?Object.keys(r.routes):[];for(let g of p){let h=A.isAbsolute(g)?g:A.join(e,g);if(!w.existsSync(h))continue;let l;try{l=w.readFileSync(h,"utf-8");}catch{continue}for(let y of ue){y.lastIndex=0;let k;for(;(k=y.exec(l))!==null;){let f=k[2]||k[0];f&&f.startsWith("/")&&(!i.some(S=>S.replace(/\s+(GET|POST|PUT|PATCH|DELETE)\s*$/,"").trim()===f)&&r?n.push({type:"missing-portal-gate",severity:"warning",message:`Route "${f}" found in ${A.relative(e,h)} but not declared in portal.yaml`,file:A.relative(e,h),suggestion:"Add this route to portal.yaml with appropriate ^gates. Run paradigm_gates_for_route to get suggestions."}):!r&&f.startsWith("/api/")&&n.push({type:"missing-portal-gate",severity:"warning",message:`API route "${f}" found but no portal.yaml exists`,file:A.relative(e,h),suggestion:"Create portal.yaml to declare gates for API routes. Run: paradigm portal init"}));}}}for(let g of s)t(t$1,g).length===0&&n.push({type:"unregistered-symbol",severity:"error",message:`Symbol "${g}" was touched but is not registered in any .purpose file`,suggestion:`Add "${g}" to the nearest .purpose file. Use paradigm_purpose_add_component or paradigm_purpose_add_signal.`});for(let g of s)if(g.startsWith("^")){let h=g.slice(1);a.includes(h)||n.push({type:"missing-portal-gate",severity:"error",message:`Gate "${g}" is referenced but not declared in portal.yaml`,suggestion:`Add ${g} to portal.yaml with description and check expression.`});}p.length>=5&&s.length>=3&&n.push({type:"uncaptured-wisdom",severity:"warning",message:`Large change (${p.length} files, ${s.length} symbols) \u2014 consider recording architectural decisions`,suggestion:"Use paradigm_wisdom_record to capture any decisions or antipatterns discovered during this task."});let c=n.filter(g=>g.severity==="error").length,d=n.filter(g=>g.severity==="warning").length,u=4,m="pass";return c>0?m="violations":d>0&&(m="warnings"),{status:m,violations:n,summary:{totalChecks:u,passed:u-(c>0?1:0)-(d>0?1:0),warnings:d,errors:c},blocksCompletion:c>0}}var pe={architect:"opus",security:"opus",reviewer:"sonnet",builder:"haiku",tester:"haiku"},he=["auth","permission","admin","delete","purge","password","credential","token","secret","key","encrypt","decrypt","hash","session","oauth","jwt","role","access control","vulnerability","injection","xss","csrf"];function me(p,s){let e=p.toLowerCase(),t=he.some(r=>e.includes(r.toLowerCase())),n=p.includes("^"),o=false;return t||n||o}var ye=["rename","refactor","migrate","restructure","move","reorganize"];function be(p){let s=p.toLowerCase();return ye.some(e=>s.includes(e))}var E=class{spawner;auditLogger;rootDir;constructor(s){this.rootDir=s,this.spawner=new b(s),this.auditLogger=new a(s);}async initialize(){await this.spawner.initialize();}async orchestrate(s,e={}){let t=e.mode||"faceted",n=Date.now(),o$1=this.generateOrchestrationId(),r={success:false,mode:t,orchestrationId:o$1,task:s,agentsSpawned:0,totalTokens:{input:0,output:0,total:0},totalCost:0,duration_ms:0,agentResults:[]};try{let a;if(e.pmGovernance?.enabled)try{let{aggregateFromDirectory:c}=await import('./dist-TNE4GFT7.js'),d=await c(this.rootDir),u=o(d);a=V(s,this.rootDir,u);}catch{}if(t==="solo"){let c=await this.runSoloMode(s,e);r.agentsSpawned=1,r.agentResults=[c],r.success=c.success,c.relay&&(r.totalTokens=c.relay.metrics.tokens_used,r.totalCost=b$1(r.totalTokens,e.orchestratorModel||"opus"));}else {let c=await this.runFacetedMode(s,e);r.agentsSpawned=c.results.length,r.agentResults=c.results,r.totalTokens=c.totalTokens,r.totalCost=c.totalCost,r.success=c.success,r.parallelBuilderStats=c.parallelBuilderStats;}if(e.pmGovernance?.enabled&&a)try{let{aggregateFromDirectory:c}=await import('./dist-TNE4GFT7.js'),d=await c(this.rootDir),u=o(d),m=[],g=[];for(let l of r.agentResults)l.relay?.outputs?.artifacts&&m.push(...l.relay.outputs.artifacts.map(y=>y.path));for(let l of a.affectedSymbols)g.push(l.symbol);let h=H(m,g,this.rootDir,u);r.complianceReport={preflight:a,postflight:h},e.pmGovernance.blockOnViolations&&h.blocksCompletion&&(r.success=!1);}catch{r.complianceReport={preflight:a};}r.duration_ms=Date.now()-n;let i=this.auditLogger.startOrchestration(o$1,s,t);return i.completed=new Date().toISOString(),i.status=r.success?"success":"failed",i.totals={duration_ms:r.duration_ms,tokens:r.totalTokens.total,cost_usd:r.totalCost,agents_spawned:r.agentsSpawned,files_created:0,files_modified:0},this.auditLogger.saveOrchestration(i),r.log=i,r}catch(a){return r.error=a instanceof Error?a.message:String(a),r.duration_ms=Date.now()-n,r}}async compare(s,e={}){let t=await this.orchestrate(s,{...e,mode:"solo"}),n=await this.orchestrate(s,{...e,mode:"faceted"}),o=t.totalTokens.total-n.totalTokens.total,r=t.totalCost-n.totalCost,a=t.duration_ms-n.duration_ms,i="tie";return n.success&&!t.success?i="faceted":t.success&&!n.success?i="solo":n.totalCost<t.totalCost*.8?i="faceted":t.totalCost<n.totalCost*.8&&(i="solo"),{solo:t,faceted:n,comparison:{winner:i,tokensSaved:o,costDiff:r,timeDiff:a,soloSucceeded:t.success,facetedSucceeded:n.success}}}async runSoloMode(s,e$1){let n=e(this.rootDir)?.team.default_agent||"architect",o=e$1.orchestratorModel||"opus",r={model:o,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.budget,onMessage:e$1.onMessage?i=>e$1.onMessage("solo",i):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart("solo",s,o);let a=await this.spawner.spawn(n,s,r);return e$1.onAgentComplete&&e$1.onAgentComplete("solo",a,o),a}async runFacetedMode(s,e$1){let t=e(this.rootDir);if(!t)return {success:false,results:[],totalTokens:{input:0,output:0,total:0},totalCost:0};let n="";if(be(s)){let h=a$1(s);if(h.length>0){let l=[];l.push(`## Auto-Ripple Analysis
3
- `),l.push("The following symbols are affected by this refactoring:"),l.push("");for(let y of h.slice(0,5))l.push(`- **${y}**: Check dependencies before renaming/moving`);l.push(""),l.push("**Recommendation:** Run `paradigm_ripple` for each symbol before making changes."),n=l.join(`
4
- `);}}let o=this.planAgentSequence(s,t.agents),r=this.groupByStage(o),a=[],i={input:0,output:0,total:0},c=0,d=new Map,u=true,m,g=Array.from(r.keys()).sort((h,l)=>h-l);for(let h of g){let l=r.get(h)||[];if(l.length===0)continue;if(e$1.checkpoints?.beforeAgentSpawn&&e$1.onCheckpoint){let f=l.map(S=>S.agent).join(", ");if(!await e$1.onCheckpoint(`Stage ${h}: Spawn ${f}${l.length>1?" (parallel)":""}`)){u=false;break}}let y=l.map(async f=>{let b=e$1.agentBudgets?.[f.agent]?.maxTokens?"haiku":f.model||pe[f.agent]||"sonnet",S="";if(f.dependsOn.length>0){let R=f.dependsOn.map(I=>d.get(I)).filter(Boolean);R.length>0&&(S=R.join(`
5
-
6
- ---
7
-
8
- `));}let x=S;f.agent==="architect"&&n&&(x=n+(S?`
9
-
10
- ---
11
-
12
- `+S:""));let P=x?`${f.subtask}
13
-
14
- ## Context from previous agents:
15
- ${x}`:f.subtask,O={model:b,workingDirectory:e$1.workingDirectory||this.rootDir,mcpServerPath:e$1.mcpServerPath,budget:e$1.agentBudgets?.[f.agent]||e$1.budget,onMessage:e$1.onMessage?R=>e$1.onMessage(f.agent,R):void 0,onCheckpoint:e$1.onCheckpoint};e$1.onAgentStart&&e$1.onAgentStart(f.agent,f.subtask,b);let C=await this.spawner.spawn(f.agent,P,O);return e$1.onAgentComplete&&e$1.onAgentComplete(f.agent,C,b),{step:f,result:C,model:b}}),k=await Promise.all(y);for(let{step:f,result:b,model:S}of k){if(a.push(b),b.relay){i.input+=b.relay.metrics.tokens_used.input,i.output+=b.relay.metrics.tokens_used.output,i.total+=b.relay.metrics.tokens_used.total,c+=b$1(b.relay.metrics.tokens_used,S);let x=b.relay.handoff?.context||`${f.agent} completed: ${b.relay.outputs.decisions.join(", ")||"task done"}`;if(d.set(f.agent,x),f.agent==="architect"&&b.relay){let P=this.extractFilePlanFromRelay(b);if(P&&P.length>0){let O=this.planBuilderStages(P);if(O.hasFilePlan&&O.totalBuilders>1){let C=await this.runParallelBuilders(O,d.get("architect")||"",e$1);a.push(...C.results),i.input+=C.totalTokens.input,i.output+=C.totalTokens.output,i.total+=C.totalTokens.total,c+=C.totalCost,C.success||(u=false),m={usedFilePlan:true,totalSubPhases:O.stages.length,totalParallelBuilders:O.totalBuilders,filesCreated:O.totalFiles};for(let[R,I]of r){let X=I.filter(Q=>Q.agent!=="builder");r.set(R,X);}}}}}!b.success&&f.required&&(u=false);}if(!u||e$1.checkpoints?.afterAgentComplete&&e$1.onCheckpoint&&!await e$1.onCheckpoint(`Stage ${h} completed. Continue to next stage?`))break}return {success:u,results:a,totalTokens:i,totalCost:c,parallelBuilderStats:m}}extractFilePlanFromRelay(s){if(!s.relay)return;let e=s.relay.handoff?.context||"";if(e.includes("filePlan:"))return this.parseFilePlanFromText(e)}parseFilePlanFromText(s){let e=[],t=s.match(/filePlan:\s*\n([\s\S]*?)(?=\n[a-z_]+:|$)/);if(!t)return;let o=t[1].split(`
16
- `),r=null,a=false,i={};for(let c of o){let d=c.trim();if(!(!d||d.startsWith("#"))){if(d.startsWith("- group:")){r&&(i.path&&(r.files.push({path:i.path,description:i.description||""}),i={}),e.push(r)),r={group:d.split(":")[1].trim(),subPhase:0,files:[]},a=false;continue}if(r){if(d.startsWith("subPhase:")){r.subPhase=parseInt(d.split(":")[1].trim(),10)||0;continue}if(d==="files:"){a=true;continue}if(a){if(d.startsWith("- path:")){i.path&&r.files.push({path:i.path,description:i.description||""}),i={path:d.split(":").slice(1).join(":").trim().replace(/^["']|["']$/g,"")};continue}if(d.startsWith("description:")){i.description=d.split(":").slice(1).join(":").trim().replace(/^["']|["']$/g,"");continue}}}}}return i.path&&r&&r.files.push({path:i.path,description:i.description||""}),r&&e.push(r),e.length>0?e:void 0}planAgentSequence(s,e){let t=a$1(s),n=s.toLowerCase(),o=K(s),r=[],a=me(s);if(o.type==="analysis")return e.architect&&r.push({agent:"architect",subtask:`Analyze and recommend: ${s}`,required:true,stage:0,dependsOn:[],model:"opus"}),r;if(o.type==="documentation")return e.architect&&r.push({agent:"architect",subtask:`Document: ${s}`,required:true,stage:0,dependsOn:[],model:"sonnet"}),r;let i=n.includes("design")||n.includes("architect")||n.includes("plan")||n.includes("spec"),c=a||n.includes("auth")||n.includes("security")||n.includes("gate")||t.some(l=>l.startsWith("^"));if(i&&e.architect&&r.push({agent:"architect",subtask:`Design and specify: ${s}`,required:true,stage:0,dependsOn:[],model:"opus"}),c&&e.security&&r.push({agent:"security",subtask:`Review security aspects of: ${s}`,required:a,stage:0,dependsOn:[],model:"opus"}),(n.includes("build")||n.includes("implement")||n.includes("create")||n.includes("add")||n.includes("fix"))&&e.builder){let l=i&&e.architect?["architect"]:[];r.push({agent:"builder",subtask:`Implement: ${s}`,required:true,stage:l.length>0?1:0,dependsOn:l,model:"haiku"});}let u=n.includes("review")||n.includes("check"),m=n.includes("test")||n.includes("verify")||n.includes("validate"),g=r.some(l=>l.agent==="builder"),h=g?2:i?1:0;if(u&&e.reviewer&&r.push({agent:"reviewer",subtask:`Review: ${s}`,required:false,stage:h,dependsOn:g?["builder"]:[],model:"sonnet"}),m&&e.tester&&r.push({agent:"tester",subtask:`Test and validate: ${s}`,required:false,stage:h,dependsOn:g?["builder"]:[],model:"haiku"}),r.length===0){let l=o.recommendedAgents;if(l.includes("architect")&&e.architect&&r.push({agent:"architect",subtask:`Design: ${s}`,required:true,stage:0,dependsOn:[],model:B("architect",o)}),(l.includes("security")||a)&&e.security&&r.push({agent:"security",subtask:`Security review: ${s}`,required:a,stage:0,dependsOn:[],model:"opus"}),l.includes("builder")&&e.builder){let y=r.length>0;r.push({agent:"builder",subtask:`Implement: ${s}`,required:true,stage:y?1:0,dependsOn:r.filter(k=>k.stage===0).map(k=>k.agent),model:B("builder",o)});}if(l.includes("tester")&&e.tester){let y=r.find(k=>k.agent==="builder")?.stage??0;r.push({agent:"tester",subtask:`Test: ${s}`,required:false,stage:y+1,dependsOn:e.builder?["builder"]:[],model:B("tester",o)});}}return r.sort((l,y)=>l.stage-y.stage)}groupByStage(s){let e=new Map;for(let t of s){let n=e.get(t.stage)||[];n.push({agent:t.agent,subtask:t.subtask,required:t.required,dependsOn:t.dependsOn}),e.set(t.stage,n);}return e}generateOrchestrationId(){let s=new Date().toISOString().slice(0,10),e=Math.random().toString(36).substring(2,8);return `orch-${s}-${e}`}planBuilderStages(s){if(!s||s.length===0)return {hasFilePlan:false,stages:[{subPhase:0,builders:[{agent:"builder",group:"all",files:[],availableFiles:[]}]}],totalFiles:0,totalBuilders:1};let e=new Map;for(let i of s){let c=e.get(i.subPhase)||[];c.push(i),e.set(i.subPhase,c);}let t=[],n=[...e.keys()].sort((i,c)=>i-c),o=[],r=0,a=0;for(let i of n){let c=e.get(i),d=[];for(let u=0;u<c.length;u++){let m=c[u];a+=m.files.length,r++,d.push({agent:`builder-${i}-${u}`,group:m.group,files:m.files,availableFiles:[...o]});}t.push({subPhase:i,builders:d});for(let u of c)for(let m of u.files)o.push(m.path);}return {hasFilePlan:true,stages:t,totalFiles:a,totalBuilders:r}}buildParallelBuilderPrompt(s,e,t,n){let o=[];o.push(`You are a BUILDER agent responsible for implementing the **${n}** group.`),o.push(""),o.push("## Your Assignment"),o.push(""),o.push("### Files to Create:");for(let r of s)o.push(`- \`${r.path}\`: ${r.description}`);if(o.push(""),e.length>0){o.push("### Available Files (already created):"),o.push("These files exist and you can import from them:");for(let r of e)o.push(`- \`${r}\``);o.push("");}return t&&(o.push("### Context from Architect:"),o.push(t),o.push("")),o.push("### Instructions:"),o.push("1. Create ONLY the files assigned to you"),o.push("2. You can import from available files (already created)"),o.push("3. Follow existing patterns in the codebase"),o.push("4. Use the Paradigm logger (not console.log)"),o.push("5. End with the standard Agent Relay block"),o.join(`
17
- `)}async runParallelBuilders(s,e,t){let n=[],o={input:0,output:0,total:0},r=0,a=true;for(let i of s.stages){if(t.checkpoints?.beforeAgentSpawn&&t.onCheckpoint){let u=i.builders.map(g=>g.group).join(", ");if(!await t.onCheckpoint(`Builder Sub-phase ${i.subPhase}: ${u}${i.builders.length>1?" (parallel)":""}`)){a=false;break}}let c=i.builders.map(async u=>{let m=this.buildParallelBuilderPrompt(u.files,u.availableFiles,e,u.group),g={model:"haiku",workingDirectory:t.workingDirectory||this.rootDir,mcpServerPath:t.mcpServerPath,budget:t.budget,onMessage:t.onMessage?l=>t.onMessage(u.agent,l):void 0,onCheckpoint:t.onCheckpoint};t.onAgentStart&&t.onAgentStart(u.agent,`Implement ${u.group}`,"haiku");let h=await this.spawner.spawn("builder",m,g);return t.onAgentComplete&&t.onAgentComplete(u.agent,h,"haiku"),{builder:u,result:h}}),d=await Promise.all(c);for(let{result:u}of d)n.push(u),u.relay&&(o.input+=u.relay.metrics.tokens_used.input,o.output+=u.relay.metrics.tokens_used.output,o.total+=u.relay.metrics.tokens_used.total,r+=b$1(u.relay.metrics.tokens_used,"haiku")),u.success||(a=false);if(!a||t.checkpoints?.afterAgentComplete&&t.onCheckpoint&&!await t.onCheckpoint(`Sub-phase ${i.subPhase} complete. Continue to next sub-phase?`))break}return {success:a,results:n,totalTokens:o,totalCost:r}}};var J=class{rootDir;orchestrationsDir;constructor(s){this.rootDir=s,this.orchestrationsDir=A.join(s,".paradigm","orchestrations"),this.ensureOrchestrationDir();}async startBackground(s,e={}){let t=this.generateId(),n=A.join(this.orchestrationsDir,`${t}.output`),o=A.join(this.orchestrationsDir,`${t}.log`),r={id:t,task:s,status:"pending",mode:e.mode||"faceted",created:new Date().toISOString(),outputFile:n,logFile:o,artifacts:[]};return this.saveOrchestration(r),this.spawnOrchestration(t,s,e),r}getOrchestration(s){let e=A.join(this.orchestrationsDir,`${s}.yaml`);if(!w.existsSync(e))return null;try{let t=w.readFileSync(e,"utf-8");return F.load(t)}catch{return null}}listOrchestrations(s={}){let e=w.readdirSync(this.orchestrationsDir).filter(n=>n.endsWith(".yaml")&&!n.includes("output")&&!n.includes("log")).sort().reverse(),t=[];for(let n of e){if(s.limit&&t.length>=s.limit)break;let o=A.join(this.orchestrationsDir,n);try{let r=w.readFileSync(o,"utf-8"),a=F.load(r);if(s.status&&!(Array.isArray(s.status)?s.status:[s.status]).includes(a.status))continue;t.push(a);}catch{}}return t}getRunning(){return this.listOrchestrations({status:"running"})}getOutput(s,e={}){let t=this.getOrchestration(s);if(!t||!w.existsSync(t.outputFile))return "";let n=w.readFileSync(t.outputFile,"utf-8");return e.lines?n.split(`
18
- `).slice(-e.lines).join(`
19
- `):n}async accept(s,e={}){let t=this.getOrchestration(s);if(!t)return false;if(t.status!=="completed")throw new Error(`Cannot accept orchestration in '${t.status}' status`);return t.status="accepted",this.saveOrchestration(t),true}async reject(s,e={}){let t=this.getOrchestration(s);if(!t)return false;if(t.status!=="completed")throw new Error(`Cannot reject orchestration in '${t.status}' status`);if(t.status="rejected",t.error=e.reason,this.saveOrchestration(t),e.cleanup&&t.artifacts.length>0){for(let n of t.artifacts)if(n.action==="created"){let o=A.join(this.rootDir,n.path);w.existsSync(o)&&w.unlinkSync(o);}}return true}async getDiff(s){let e=this.getOrchestration(s);if(!e)return "";if(e.artifacts.length===0)return "No file changes in this orchestration.";let t=[];t.push(`Orchestration: ${s}`),t.push(`Task: ${e.task}`),t.push(`Status: ${e.status}`),t.push(""),t.push("Files:");for(let n of e.artifacts){let o=n.action==="created"?"+":n.action==="modified"?"~":"-";t.push(` ${o} ${n.path}`);}return t.join(`
20
- `)}markComplete(s,e){let t=this.getOrchestration(s);if(t){t.status=e.success?"completed":"failed",t.completed=new Date().toISOString(),t.result=e,t.parallelBuilderStats=e.parallelBuilderStats;for(let n of e.agentResults)if(n.relay?.outputs.artifacts)for(let o of n.relay.outputs.artifacts)t.artifacts.push(o);this.saveOrchestration(t);}}async notify(s,e=["bell"]){let t=this.getOrchestration(s);if(t)for(let n of e)switch(n){case "bell":process.stdout.write("\x07");break;case "desktop":try{process.platform==="darwin"?spawn("osascript",["-e",`display notification "Orchestration ${t.status}: ${t.task.slice(0,50)}" with title "Paradigm"`]):spawn("notify-send",["Paradigm",`Orchestration ${t.status}: ${t.task.slice(0,50)}`]);}catch{}break;case "file":let o=A.join(this.orchestrationsDir,`${s}.status`);w.writeFileSync(o,JSON.stringify({id:s,status:t.status,completed:t.completed,task:t.task}));break;}}ensureOrchestrationDir(){w.existsSync(this.orchestrationsDir)||w.mkdirSync(this.orchestrationsDir,{recursive:true});}generateId(){let s=new Date().toISOString().slice(0,10),e=Date.now().toString(36),t=Math.random().toString(36).substring(2,6);return `orch-${s}-${e}-${t}`}saveOrchestration(s){let e=A.join(this.orchestrationsDir,`${s.id}.yaml`);w.writeFileSync(e,F.dump(s));}spawnOrchestration(s,e,t){let n=this.getOrchestration(s);n&&(n.status="running",n.started=new Date().toISOString(),this.saveOrchestration(n)),(async()=>{try{let o=new E(this.rootDir);await o.initialize();let r=w.createWriteStream(n.outputFile,{flags:"a"}),a=await o.orchestrate(e,{...t,onMessage:(i,c)=>{c.type==="text"&&r.write(`[${i}] ${c.content}
21
- `),t.onMessage?.(i,c);},onAgentStart:(i,c,d)=>{r.write(`
22
- \u25B6 ${i}: ${c}
23
- `),t.onAgentStart?.(i,c,d);},onAgentComplete:(i,c,d)=>{let u=c.success?"\u2713":"\u2717";r.write(`${u} ${i} completed
24
- `),t.onAgentComplete?.(i,c,d);}});r.end(),this.markComplete(s,a),t.notify&&await this.notify(s,t.notifyMethods||["bell"]);}catch(o){let r=this.getOrchestration(s);r&&(r.status="failed",r.error=o instanceof Error?o.message:String(o),r.completed=new Date().toISOString(),this.saveOrchestration(r));}})();}};export{E as a,J as b};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import*as r from'fs';import*as o from'path';import*as m from'js-yaml';var f=".paradigm/university",g="pack.yaml";function j(s){let e=p(s);if(!e||!Array.isArray(e.sections))return [];let a=[];for(let t of e.sections)t&&typeof t.id=="string"&&t.id.length>0&&a.push({id:t.id,name:typeof t.name=="string"?t.name:void 0});return a}function p(s){let e=o.join(s,g);if(!r.existsSync(e))return null;try{let a=r.readFileSync(e,"utf8");return m.load(a)??null}catch{return null}}function R(s){let e=[],a=o.join(s,"node_modules","@a-company","university"),t=p(a);t&&t.id&&t.tenant_kind&&e.push({id:t.id,name:t.name,tenantKind:t.tenant_kind,packRoot:a,disciplines:t.disciplines,entryCount:k(a)});let n=o.join(s,f);if(r.existsSync(n)){let i=p(n),c=i?.id??o.basename(s),y=i?.tenant_kind??"project";e.push({id:c,name:i?.name,tenantKind:y,packRoot:n,disciplines:i?.disciplines,entryCount:k(n)});try{let h=r.readdirSync(n,{withFileTypes:!0});for(let l of h){if(!l.isDirectory()||l.name.startsWith("."))continue;let u=o.join(n,l.name),d=p(u);!d||!d.id||e.push({id:d.id,name:d.name,tenantKind:d.tenant_kind??"project",packRoot:u,disciplines:d.disciplines,entryCount:k(u)});}}catch{}}return e}function k(s){for(let e of ["content","src/content"]){let a=o.join(s,e);if(!r.existsSync(a))continue;let t=0;for(let n of ["notes","policies","quizzes","paths"]){let i=o.join(a,n);if(r.existsSync(i))try{t+=r.readdirSync(i).filter(c=>c.endsWith(".md")||c.endsWith(".yaml")).length;}catch{}}if(t>0)return t}return 0}function b(s,e){let a=R(s),t;if(e.pack){let n=a.find(i=>i.id===e.pack);if(n)t={packId:n.id,packRoot:n.packRoot,tenantKind:n.tenantKind,hasManifest:true};else {let i=o.join(s,f);t={packId:e.pack,packRoot:i,hasManifest:false};}}else if(e.project){let n=a.find(c=>c.tenantKind==="project"&&!c.disciplines),i=o.join(s,f);n?t={packId:n.id,packRoot:n.packRoot,tenantKind:n.tenantKind,hasManifest:true}:t={packId:o.basename(s),packRoot:i,hasManifest:false};}else {let n=a.find(i=>i.tenantKind==="project");if(n)t={packId:n.id,packRoot:n.packRoot,tenantKind:n.tenantKind,hasManifest:true};else {let i=a.find(c=>c.tenantKind==="first-party");if(i)t={packId:i.id,packRoot:i.packRoot,tenantKind:i.tenantKind,hasManifest:true};else {let c=o.join(s,f);t={packId:o.basename(s),packRoot:c,hasManifest:false};}}}if(e.discipline){let n=o.join(t.packRoot,e.discipline),i=p(n);i&&i.id?(t.subPackRoot=n,t.subPackId=i.id):r.existsSync(n)&&(t.subPackRoot=n,t.subPackId=`${t.packId}-${e.discipline}`);}return t}function x(s){return !!(s.pack||s.project||s.discipline)}export{j as a,R as b,b as c,x as d};
@@ -1,111 +0,0 @@
1
- #!/usr/bin/env node
2
- import {r,i,a as a$3,f,h as h$1}from'./chunk-TMDPDIWA.js';import {a as a$2,b as b$4,c as c$2}from'./chunk-M4UMM6DC.js';import {j as j$1,b as b$3,a as a$4}from'./chunk-GRZQIKST.js';import {j as j$2,a,c as c$1,b as b$2,k}from'./chunk-6QXBXZF6.js';import {b as b$1,a as a$1}from'./chunk-EK4ZRIFJ.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as h from'fs';import*as x from'path';import*as te from'crypto';import {execSync}from'child_process';import*as N from'js-yaml';import*as Se from'os';import jn from'sql.js';import {z}from'zod';var Tt={};c(Tt,{contentSearch:()=>Ln,detectFileRename:()=>xt,generateFingerprint:()=>St,levenshteinDistance:()=>bt,levenshteinSimilarity:()=>Oe,searchSiblingFiles:()=>Et,slidingWindowSearch:()=>be});function St(t){let e=t.split(`
3
- `).filter(r=>r.trim()!=="");return {firstLine:we(e[0]||""),lastLine:we(e[e.length-1]||""),lineCount:e.length,structuralHash:wt(e)}}function wt(t){let e=t.map(r=>r.trim()).filter(r=>ht.test(r)).map(r=>{let n=r.match(ht);return n?n[1].trim():""}).join("|");return te.createHash("sha256").update(e).digest("hex").slice(0,16)}function we(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function bt(t,e){if(t===e)return 0;if(t.length===0)return e.length;if(e.length===0)return t.length;t.length>e.length&&([t,e]=[e,t]);let r=t.length,n=e.length;if(r>5e3||n>5e3)return Math.abs(r-n);let s=new Array(r+1),o=new Array(r+1);for(let i=0;i<=r;i++)s[i]=i;for(let i=1;i<=n;i++){o[0]=i;for(let c=1;c<=r;c++){let a=t[c-1]===e[i-1]?0:1;o[c]=Math.min(s[c]+1,o[c-1]+1,s[c-1]+a);}[s,o]=[o,s];}return s[r]}function Oe(t,e){if(t.length===0&&e.length===0)return 1;let r=Math.max(t.length,e.length);return 1-bt(t,e)/r}function be(t,e,r,n=3){let{lineCount:s}=e,o=Math.max(1,Math.floor(s*.8)),i=Math.ceil(s*1.2),c=[],a=je(r);for(let u of [s,o,i])if(!(u>t.length))for(let d=0;d<=t.length-u;d++){let f=t.slice(d,d+u),g=An(f,e,a);if(g>=.5){let p=f.join(`
4
- `);c.push({windowStart:d+1,windowEnd:d+u,similarity:Oe(je(p),a),score:g});}}let l=new Map;for(let u of c){let d=l.get(u.windowStart);(!d||u.score>d.score)&&l.set(u.windowStart,u);}return Array.from(l.values()).sort((u,d)=>d.score-u.score).slice(0,n)}function An(t,e,r){let n=t.filter(f=>f.trim()!=="");if(n.length===0)return 0;let s=0,o=we(n[0]),i=we(n[n.length-1]),c=0;o===e.firstLine&&(c+=.5),i===e.lastLine&&(c+=.5),s+=c*Rn,wt(n)===e.structuralHash&&(s+=In);let l=n.join(`
5
- `),u=Oe(je(l),r);u>=.8&&(s+=(u-.8)/.2*Pn);let d=n.length/e.lineCount;if(d>=.8&&d<=1.2){let f=1-Math.abs(1-d)/.2;s+=f*Cn;}return s}function je(t){return t.split(`
6
- `).map(e=>e.trim()).filter(e=>e!=="").join(`
7
- `)}function xt(t,e){try{let r=execSync(`git log --follow --diff-filter=R --name-status --format="" -- "${e}"`,{cwd:t,encoding:"utf8",timeout:5e3}).trim();if(!r)return null;let n=r.split(`
8
- `);for(let s of n){let o=s.split(" ");if(o.length>=3&&o[0].startsWith("R"))return o[2]}return null}catch{return null}}function Et(t,e,r,n,s=10){let o=x.isAbsolute(e)?e:x.join(t,e);if(!h.existsSync(o))return [];let i=[];try{let c=h.readdirSync(o).filter(a=>!a.startsWith(".")&&h.statSync(x.join(o,a)).isFile()).slice(0,s);for(let a of c)try{let u=h.readFileSync(x.join(o,a),"utf8").split(`
9
- `),d=be(u,r,n,1);if(d.length>0&&d[0].score>=.7){let f=x.relative(t,x.join(o,a));i.push({file:f,score:d[0].score,start:d[0].windowStart,end:d[0].windowEnd});}}catch{}}catch{return []}return i.sort((c,a)=>a.score-c.score)}function Ln(t,e,r,n=true){let s=St(r),o=x.isAbsolute(e)?e:x.join(t,e);if(h.existsSync(o)){let u=h.readFileSync(o,"utf8").split(`
10
- `),d=be(u,s,r);if(d.length>0){let f=d[0];return {found:f.score>=.7,score:f.score,suggestedStart:f.windowStart,suggestedEnd:f.windowEnd,similarity:f.similarity}}}let i=xt(t,e);if(i){let l=x.join(t,i);if(h.existsSync(l)){let d=h.readFileSync(l,"utf8").split(`
11
- `),f=be(d,s,r);if(f.length>0&&f[0].score>=.7)return {found:true,score:f[0].score,suggestedStart:f[0].windowStart,suggestedEnd:f[0].windowEnd,suggestedPath:i,similarity:f[0].similarity}}}let c=x.dirname(e),a=Et(t,c,s,r);if(a.length>0&&a[0].score>=.7){let l=a[0];return {found:true,score:l.score,suggestedStart:l.start,suggestedEnd:l.end,suggestedPath:l.file!==e?l.file:void 0,similarity:l.score}}return {found:false,score:0}}var ht,Rn,In,Pn,Cn,_t=b(()=>{ht=/^\s*(function |class |if |else |for |while |switch |case |return |export |import |const |let |var |async |await |try |catch |throw |struct |enum |protocol |guard |def |fn )/;Rn=.4,In=.3,Pn=.2,Cn=.1;});var ln="0.1.0",dn="1.0.0";function Pe(t,e){let r={$meta:un(e.projectName,t),components:{},features:{},flows:{},state:{},gates:{},signals:{},aspects:{},screens:{},symbolMap:{}};for(let s of t.symbols)fn(s,r,e);if(e.screenDefinitions)for(let[s,o]of Object.entries(e.screenDefinitions))r.screens[s]||(r.screens[s]={id:s,name:Z(s),route:o.route,path:"",components:o.components,features:o.features});let n={};for(let s of Object.values(r.components))s.componentType&&(n[s.componentType]=(n[s.componentType]||0)+1);for(let s of Object.values(r.features))s.componentType&&(n[s.componentType]=(n[s.componentType]||0)+1);return Object.keys(n).length>0&&(r.$meta.componentTypes=n),bn(r),r}function un(t,e){return {version:dn,project:t,generatedAt:new Date().toISOString(),paradigmVersion:ln,sources:{purposeFiles:e.purposeFiles.length,portalFiles:e.portalFiles.length,premiseFiles:e.symbols.filter(r=>r.source==="premise").length>0?1:0}}}function fn(t,e,r){let{type:n}=t;switch(n){case "component":pn(t,e,r);break;case "feature":mn(t,e,r);break;case "flow":gn(t,e);break;case "state":hn(t,e);break;case "gate":yn(t,e);break;case "signal":Sn(t,e);break;case "aspect":wn(t,e);break;}}function pn(t,e,r){let n=re(t.symbol),s=ut(n,t.data,r.visualTagMappings),o={id:n,name:Z(n),symbol:t.symbol,category:"components",path:t.filePath,description:t.description,visualTags:s,related:t.references,componentType:t.componentType,parent:t.parentSymbol};e.components[n]=o,e.symbolMap[t.symbol]={category:"components",id:n};}function mn(t,e,r){let n=re(t.symbol),s=ut(n,t.data,r.visualTagMappings),o={id:n,name:Z(n),symbol:t.symbol,category:"features",path:t.filePath,description:t.description,visualTags:s,related:t.references,componentType:t.componentType,parent:t.parentSymbol};e.features[n]=o,e.symbolMap[t.symbol]={category:"features",id:n};}function gn(t,e){let r=re(t.symbol),n=t.data,s=[];if(n?.steps)for(let i=0;i<n.steps.length;i++){let c=n.steps[i];s.push({id:`${r}-step-${i}`,name:c.action||`Step ${i+1}`,target:c.component,description:c.description,order:i});}let o={id:r,name:Z(r),symbol:t.symbol,path:t.filePath,description:t.description,steps:s};e.flows[r]=o,e.symbolMap[t.symbol]={category:"flows",id:r};}function hn(t,e){let r=re(t.symbol),n={id:r,name:Z(r),symbol:t.symbol,path:t.filePath,description:t.description,consumers:t.referencedBy};e.state[r]=n,e.symbolMap[t.symbol]={category:"state",id:r};}function yn(t,e){let r=re(t.symbol),n={id:r,name:Z(r),symbol:t.symbol,category:"gates",path:t.filePath,description:t.description,related:t.references};e.gates[r]=n,e.symbolMap[t.symbol]={category:"gates",id:r};}function Sn(t,e){let r=re(t.symbol),n={id:r,name:Z(r),symbol:t.symbol,category:"signals",path:t.filePath,description:t.description,related:t.references};e.signals[r]=n,e.symbolMap[t.symbol]={category:"signals",id:r};}function wn(t,e){let r=re(t.symbol),n={id:r,name:Z(r),symbol:t.symbol,category:"aspects",path:t.filePath,description:t.description,related:t.references};e.aspects[r]=n,e.symbolMap[t.symbol]={category:"aspects",id:r};}function bn(t){for(let e of Object.values(t.screens))if(e.components)for(let r of e.components){let n=t.components[r];n&&(n.screens=n.screens||[],n.screens.includes(e.id)||n.screens.push(e.id));}}function re(t){return t.slice(1)}function Z(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function ut(t,e,r){let n=[];if(r?.[t])return r[t];let s=[[/button/i,"button"],[/btn/i,"button"],[/form/i,"form"],[/input/i,"input"],[/field/i,"input"],[/select/i,"input"],[/card/i,"card"],[/list/i,"list"],[/table/i,"list"],[/modal/i,"modal"],[/dialog/i,"modal"],[/drawer/i,"modal"],[/nav/i,"nav"],[/menu/i,"menu"],[/dropdown/i,"menu"],[/header/i,"header"],[/footer/i,"footer"],[/sidebar/i,"sidebar"],[/hero/i,"hero"],[/grid/i,"grid"],[/chart/i,"chart"],[/graph/i,"chart"],[/icon/i,"icon"],[/image/i,"image"],[/avatar/i,"avatar"],[/badge/i,"badge"],[/tag/i,"badge"],[/tab/i,"tab"],[/accordion/i,"accordion"],[/toast/i,"toast"],[/notification/i,"toast"],[/alert/i,"toast"],[/spinner/i,"spinner"],[/loader/i,"spinner"],[/loading/i,"spinner"],[/skeleton/i,"skeleton"]];for(let[o,i]of s)o.test(t)&&n.push(i);return n}function Ce(t){return JSON.stringify(t,null,2)}function Ae(t,e="unknown"){j$2().trackToolCall(e,t);}function Ks(t,e="paradigm://unknown"){j$2().trackResourceRead(e,t);}function xn(){k();}function En(t,e){switch(t){case "paradigm_search":return {summary:`Searched for "${e.query}"${e.type?` (type: ${e.type})`:""}`,symbol:e.query};case "paradigm_ripple":return {summary:`Ripple analysis on ${e.symbol}${e.depth?` (depth: ${e.depth})`:""}`,symbol:e.symbol};case "paradigm_related":return {summary:`Checked relations for ${e.symbol}`,symbol:e.symbol};case "paradigm_status":return {summary:"Checked project status"};case "paradigm_navigate":{let r=e.intent,n=e.target,s=e.task;return r==="context"&&s?{summary:`Navigate context: "${s}"`}:n?{summary:`Navigate ${r||"find"}: ${n}`,symbol:n}:{summary:`Navigate (${r||"unknown"})`}}case "paradigm_gates_for_route":return {summary:`Gate suggestions for ${e.method||"GET"} ${e.route}`};case "paradigm_wisdom_context":return {summary:`Checked wisdom for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_context":return {summary:`Checked history for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_record":return {summary:`Recorded ${e.type}: ${(e.description||"").slice(0,60)}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_fragility":return {summary:`Checked fragility for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_flows_affected":return {summary:`Checked flows affected by ${e.symbol}`,symbol:e.symbol};case "paradigm_reindex":return {summary:"Rebuilt static index files"};case "paradigm_session_checkpoint":return {summary:`Checkpoint: phase=${e.phase}, ${(e.context||"").slice(0,60)}`};case "paradigm_task_create":return {summary:`Created task: "${(e.blurb||"").slice(0,60)}"`};case "paradigm_task_done":return {summary:`Completed task ${e.id}`};case "paradigm_task_shelve":return {summary:`Shelved task ${e.id}`};case "paradigm_task_list":return {summary:`Listed tasks (status: ${e.status||"open"})`};case "paradigm_task_update":return {summary:`Updated task ${e.id}`};case "paradigm_assessment_record":return {summary:`Assessment: ${(e.title||"").slice(0,60)} \u2192 ${e.arc_id}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_assessment_list":return {summary:e.arc_id?`Listed entries in ${e.arc_id}`:"Listed assessment arcs"};case "paradigm_assessment_search":return {summary:`Searched assessments${e.symbol?` for ${e.symbol}`:""}`,symbol:e.symbol};case "paradigm_assessment_arc_create":return {summary:`Created arc: ${e.id}`};case "paradigm_assessment_arc_close":return {summary:`Closed arc: ${e.arc_id}`};default:{let r=t.replace(/^paradigm_/,""),n=Object.values(e).find(s=>typeof s=="string"&&s.length>0);return {summary:n?`${r}: ${n.slice(0,60)}`:r,symbol:e.symbol||void 0}}}}function Qs(t,e){let r=j$2(),{summary:n,symbol:s}=En(t,e);r.addBreadcrumb("tool-call",n,{tool:t,symbol:s});}function Zs(){return [{name:"paradigm_session_health",description:"Check if context handoff is recommended based on session activity. Call this periodically during long sessions. Returns usage percentage and recommendation (continue, consider-handoff, handoff-recommended, handoff-urgent). ~100 tokens.",inputSchema:{type:"object",properties:{estimatedTotalTokens:{type:"number",description:"Optional: Your estimate of total conversation tokens (if available)"},contextWindowSize:{type:"number",description:"Context window size in tokens (default: 200000)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_context_check",description:"DEPRECATED: renamed to paradigm_session_health. This alias will be removed in a future version.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_handoff_prepare",description:"Prepare a handoff summary. Generates a structured handoff file with markdown summary and recovery instructions. Returns structured markdown with summary, modified files, and next steps. ~300 tokens.",inputSchema:{type:"object",properties:{summary:{type:"string",description:"Brief summary of work done in this session"},nextSteps:{type:"array",items:{type:"string"},description:"List of next steps for the continuing session"},agent:{type:"string",description:'Target agent role (e.g., "builder", "architect")'},modifiedFiles:{type:"array",items:{type:"string"},description:"List of files modified in this session"},symbolsTouched:{type:"array",items:{type:"string"},description:"List of symbols (@feature, #component, etc.) touched"},openQuestions:{type:"array",items:{type:"string"},description:"Unresolved questions or decisions needed"}},required:["summary"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_session_stats",description:"Get current session statistics (MCP interactions, estimated tokens). Returns tool call count, estimated tokens used, and cost breakdown. ~100 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_session_recover",description:"Load previous session breadcrumbs for continuity. Call this at the start of a new session to understand what was done before. Returns symbols modified, files explored, recent actions, and suggestions for continuity. ~200 tokens. NOTE: Recovery data is automatically surfaced as a preamble on the first tool call of each session \u2014 explicit calls are retained for direct inspection or forcing a second recovery pass.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["resume","pick up","continue","what was I doing","last session","recover"]},{name:"paradigm_session_checkpoint",description:"Save a cognitive-transition checkpoint for crash recovery. Call when transitioning between phases (planning \u2192 implementing \u2192 validating \u2192 complete). ~100 tokens.",inputSchema:{type:"object",properties:{phase:{type:"string",enum:["planning","implementing","validating","complete"],description:"Current workflow phase"},context:{type:"string",description:"What's top-of-mind right now (1-3 sentences)"},externalId:{type:"string",description:'Optional: deterministic ID from external source for automatic session recovery (e.g. "linear:PROJ-123", "github:owner/repo#42")'},plan:{type:"string",description:"Optional: the current plan or approach"},modifiedFiles:{type:"array",items:{type:"string"},description:"Optional: files modified so far"},symbolsTouched:{type:"array",items:{type:"string"},description:"Optional: symbols touched so far"},decisions:{type:"array",items:{type:"string"},description:"Optional: key decisions made so far"}},required:["phase","context"]},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function er(t,e,r){let n=j$2();if(t==="paradigm_session_health"||t==="paradigm_context_check"){let s=e.contextWindowSize||2e5,o=e.estimatedTotalTokens,i=n.getStats(),{recommendation:c,message:a,usagePercent:l,signals:u}=n.getHandoffRecommendation(s,o),d=n.getDurationMinutes();return {handled:true,text:JSON.stringify({recommendation:c,message:a,stats:{sessionDurationMinutes:d,mcpToolCalls:i.totals.toolCallCount,mcpResourceReads:i.totals.resourceReadCount,estimatedMcpTokens:i.totals.totalTokens,estimatedTotalTokens:o||Math.round(i.totals.totalTokens*5),contextWindowSize:s,usagePercent:l},signals:u,action:c==="continue"?null:"Call paradigm_handoff_prepare to create handoff file"},null,2)}}if(t==="paradigm_handoff_prepare"){let s=e.summary,o=e.nextSteps||[],i=e.agent||"builder",c=e.modifiedFiles||[],a$1=e.symbolsTouched||[],l=e.openQuestions||[],u=n.getStats(),d=n.getCostBreakdown(),f=`h${Date.now().toString(36)}`,g=new Date().toISOString(),p={id:f,timestamp:g,from:"current-session",to:i,summary:s,nextSteps:o,modifiedFiles:c,symbolsTouched:a$1,openQuestions:l,sessionStats:{duration:n.getDurationMinutes(),mcpCalls:u.totals.toolCallCount+u.totals.resourceReadCount,estimatedTokens:u.totals.totalTokens,estimatedCostUsd:d.total.costUsd,model:d.model},status:"pending"},m=false;try{a(r.rootDir,p),m=!0;}catch{}let y=`# Handoff: ${g}
12
-
13
- ## Session Summary
14
- ${s}
15
-
16
- ## Next Steps
17
- ${o.map((w,P)=>`${P+1}. ${w}`).join(`
18
- `)||"(none specified)"}
19
-
20
- ## Key Context
21
- - Modified files: ${c.length>0?c.join(", "):"(not specified)"}
22
- - Symbols touched: ${a$1.length>0?a$1.join(", "):"(not specified)"}
23
- - Open questions: ${l.length>0?l.join(", "):"(none)"}
24
- `;return xn(),{handled:true,text:JSON.stringify({handoff:p,markdownSummary:y,persisted:m,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(t==="paradigm_session_stats"){let s=n.getStats(),o=n.getCostBreakdown(),i=n.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(s.startTime).toISOString(),durationMinutes:i,lastActivity:new Date(s.lastActivity).toISOString()},model:{name:o.model,id:o.modelId,pricing:{inputPerMillion:`$${o.pricing.input.toFixed(2)}`,outputPerMillion:`$${o.pricing.output.toFixed(2)}`}},interactions:{toolCalls:s.totals.toolCallCount,resourceReads:s.totals.resourceReadCount,totalInteractions:s.totals.toolCallCount+s.totals.resourceReadCount},tokens:{total:s.totals.totalTokens,byCategory:{resources:o.resources.tokens,tools:o.tools.tokens}},cost:{totalUsd:`$${o.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${o.resources.costUsd.toFixed(4)}`,tools:`$${o.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:o.resources.byType,toolsByName:o.tools.byName}},null,2)}}if(t==="paradigm_session_recover"){let{checkpoint:s,pendingHandoffs:o,previousSession:i}=ft(r.rootDir);if(!i&&o.length===0&&!s)return {handled:true,text:JSON.stringify({found:false,message:"No previous session breadcrumbs, checkpoints, or pending handoffs found.",tip:"Breadcrumbs persist to ~/.paradigm/sessions/ and handoffs persist via paradigm_handoff_prepare. Checkpoints persist via paradigm_session_checkpoint."},null,2)};let c={found:true};if(s){let l=Date.now()-s.timestamp,u=Math.round(l/6e4),d=Math.round(l/36e5);c.checkpoint={phase:s.phase,context:s.context,age:d>1?`${d} hours ago`:`${u} minutes ago`,timestamp:new Date(s.timestamp).toISOString(),sessionId:s.sessionId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:s.recentBreadcrumbs?.map(f=>({time:new Date(f.timestamp).toISOString(),action:f.action,tool:f.tool,symbol:f.symbol,summary:f.summary}))};}if(i){let l=Date.now()-i.lastActivity,u=Math.round(l/6e4),d=Math.round(l/36e5),g=i.breadcrumbs.slice(-10).map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}));c.previousSession={sessionId:i.sessionId,startTime:new Date(i.startTime).toISOString(),lastActivity:new Date(i.lastActivity).toISOString(),age:d>1?`${d} hours ago`:`${u} minutes ago`},c.context={symbolsModified:i.symbolsModified,filesExplored:i.filesExplored},c.recentActions=g;}if(o.length>0){c.pendingHandoffs=o.map(l=>({id:l.id,timestamp:l.timestamp,from:l.from,to:l.to,summary:l.summary,nextSteps:l.nextSteps,modifiedFiles:l.modifiedFiles,symbolsTouched:l.symbolsTouched,openQuestions:l.openQuestions}));for(let l of o)try{c$1(r.rootDir,l.id);}catch{}}let a="Continue where the previous session left off.";if(s)a=`Previous session was in "${s.phase}" phase: ${s.context}`,s.decisions?.length&&(a+=` Key decisions: ${s.decisions.slice(0,2).join("; ")}`);else if(o.length>0){let l=o[o.length-1];a=`Handoff received: "${l.summary}". `,l.nextSteps.length>0&&(a+=`Start with: ${l.nextSteps[0]}`);}else if(i){let l=i.breadcrumbs.slice(-10);if(l.length>0){let u=l[l.length-1];u.symbol&&(a=`Last work involved ${u.symbol}. Consider checking its current state with paradigm_ripple.`);}}return c.suggestion=a,c.agentInstruction="Present a brief summary of the previous session, then ask the user what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking.",n.markRecovered(),{handled:true,text:JSON.stringify(c,null,2)}}if(t==="paradigm_session_checkpoint"){n.setRootDir(r.rootDir);let s=e.phase,o=e.context,i=e.externalId,c=e.plan,a=e.modifiedFiles,l=e.symbolsTouched,u=e.decisions,{checkpoint:d,persisted:f}=n.saveCheckpoint({phase:s,context:o,externalId:i,plan:c,modifiedFiles:a,symbolsTouched:l,decisions:u}),g=f.local||f.global;return {handled:true,text:JSON.stringify({saved:g,persisted:f,checkpoint:{phase:d.phase,context:d.context,sessionId:d.sessionId,...d.externalId?{externalId:d.externalId}:{},timestamp:new Date(d.timestamp).toISOString(),modifiedFiles:d.modifiedFiles?.length||0,symbolsTouched:d.symbolsTouched?.length||0,decisions:d.decisions?.length||0,recentBreadcrumbs:d.recentBreadcrumbs?.length||0},...g?{note:"Checkpoint saved. Recovery data will be auto-surfaced on the first tool call of the next session."}:{warning:"Checkpoint was NOT persisted to disk. Both local and global writes failed. Check MCP server stderr for details."}},null,2)}}return {handled:false,text:""}}function ft(t){let e=j$2();e.setRootDir(t);let r=e.loadCheckpoint(),n=e.loadPreviousSession(),s=[];try{s=b$2(t);}catch{}return {checkpoint:r,pendingHandoffs:s,previousSession:n}}async function tr(t){let{checkpoint:e,pendingHandoffs:r}=ft(t);if(!e&&r.length===0)return null;let n=[];if(n.push("--- SESSION RECOVERY ---"),e){let s=Date.now()-e.timestamp,o=Math.round(s/6e4),i=Math.round(s/36e5),c=i>1?`${i}h ago`:`${o}m ago`;n.push(`Previous session was in "${e.phase}" phase (${c}): ${e.context}`),e.modifiedFiles?.length&&n.push(`Modified files: ${e.modifiedFiles.join(", ")}`),e.symbolsTouched?.length&&n.push(`Symbols: ${e.symbolsTouched.join(", ")}`),e.decisions?.length&&n.push(`Decisions: ${e.decisions.join("; ")}`),e.plan&&n.push(`Plan: ${e.plan.slice(0,200)}`);}if(r.length>0){let s=r[r.length-1];n.push(`Pending handoff: "${s.summary}"`),s.nextSteps.length>0&&n.push(`Next steps: ${s.nextSteps.slice(0,3).join(", ")}`);}try{let{loadTasks:s}=await import('./task-loader-NZFDTUQ5.js'),o=await s(t,{status:"open",limit:5});if(o.length>0){n.push(""),n.push("Open tasks:");for(let i of o){let c=i.tags.length>0?` [${i.tags.join(", ")}]`:"";n.push(` [${i.priority}] ${i.id}: ${i.blurb}${c}`);}}}catch{}try{let{loadLoreEntries:s}=await import('./lore-loader-PXFKMKAN.js'),i=(await s(t,{limit:10})).filter(c=>c.tags?.some(a=>a.startsWith("arc:")));if(i.length>0){let c=new Map;for(let u of i){let d=u.tags?.find(f=>f.startsWith("arc:"))||"";c.set(d,(c.get(d)||0)+1);}let a=e?.symbolsTouched||[];if((a.length>0?i.filter(u=>u.symbols_touched?.some(d=>a.includes(d))):i.slice(0,3)).length>0||c.size>0){n.push(""),n.push("Active lore arcs:");for(let[u,d]of c)n.push(` ${u} (${d} entries)`);}}}catch{}try{let{loadNominations:s}=await import('./nomination-engine-NCLTGMAK.js'),o=s(t,{pending_only:!0}).filter(i=>i.urgency==="critical"||i.urgency==="high");if(o.length>0){n.push(""),n.push("Ambient nominations (urgent):");for(let i of o.slice(0,5))n.push(` [${i.urgency}] ${i.brief}`);o.length>5&&n.push(` ... and ${o.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return n.push(""),n.push("IMPORTANT: Present a brief summary of this recovery data to the user, then ask what they would like to do: (1) Continue \u2014 pick up where the last session left off, (2) Discard \u2014 ignore the previous session and start fresh, or (3) let them describe what they want to work on instead. Do NOT automatically continue without asking."),n.push("---"),n.join(`
25
- `)}var Le=class{cache=new Map;ttlMs;constructor(e=3e4){this.ttlMs=e;}async getOrCompute(e,r){let n=this.cache.get(e);if(n&&Date.now()-n.createdAt<this.ttlMs)return n.data;let s=await r();return this.cache.set(e,{data:s,createdAt:Date.now()}),s}invalidate(e){this.cache.delete(e);}invalidatePrefix(e){for(let r of this.cache.keys())r.startsWith(e)&&this.cache.delete(r);}clear(){this.cache.clear();}stats(){return {size:this.cache.size,ttlMs:this.ttlMs}}},pt=new Le(3e4);var Tn=300*1e3,fe=null;function gt(){fe=null;}function B(t,e){return h.existsSync(x.join(t,e))}function ee(t,e){return h.existsSync(x.join(t,e))}function _n(t,e,r){let n=t;try{if(!h.existsSync(n))return !1;let s=h.readdirSync(n,{withFileTypes:!0});for(let o of s){if(o.isFile()&&o.name.endsWith(e))return !0;if(o.isDirectory())try{if(h.readdirSync(x.join(n,o.name)).some(c=>c.endsWith(e)))return !0}catch{}}}catch{}return false}var vn={wisdom:t=>B(t,".paradigm/wisdom"),history:t=>B(t,".paradigm/history"),lore:t=>B(t,".paradigm/lore"),habits:t=>ee(t,".paradigm/habits.yaml"),sentinel:t=>{try{let e=x.join(t,".paradigm","config.yaml");return h.existsSync(e)?h.readFileSync(e,"utf-8").includes("sentinel"):!1}catch{return false}},flows:t=>ee(t,".paradigm/flow-index.json")||ee(t,".paradigm/flows.yaml"),fixtures:t=>ee(t,".paradigm/fixtures.yaml"),orchestration:t=>ee(t,".paradigm/agents.yaml"),tasks:t=>B(t,".paradigm/tasks"),assessment:t=>B(t,".paradigm/lore"),personas:t=>_n(t,".persona"),protocols:t=>B(t,".paradigm/protocols"),symphony:()=>{let t=x.join(Se.homedir(),".paradigm","score");return h.existsSync(t)},university:t=>B(t,".paradigm/university"),agents:t=>{let e=x.join(Se.homedir(),".paradigm","agents");return B(t,".paradigm/agents")||h.existsSync(e)},"aspect-graph":t=>ee(t,".paradigm/aspect-graph.db"),pan:t=>ee(t,".pan")||ee(t,"nevr.yaml"),notebooks:t=>{let e=x.join(Se.homedir(),".paradigm","notebooks");return B(t,".paradigm/notebooks")||h.existsSync(e)}},mt=class{modules=new Map;activatedAdvanced=new Set;rootDir;constructor(e){this.rootDir=e;}register(e){this.modules.set(e.key,e);}registerAll(e){for(let r of e)this.register(r);}detectActiveFeatures(){if(fe&&Date.now()-fe.timestamp<Tn)return fe.features;let e=new Set;for(let[r,n]of this.modules){if(n.tier==="core"){e.add(r);continue}if(n.tier==="advanced"){this.activatedAdvanced.has(r)&&e.add(r);continue}let s=n.detect||vn[r];if(s)try{s(this.rootDir)&&e.add(r);}catch{}else e.add(r);}return fe={features:e,timestamp:Date.now()},e}getActiveTools(){let e=this.detectActiveFeatures(),r=[];for(let[n,s]of this.modules)e.has(n)&&r.push(...s.getToolsList());return r}activateAdvanced(e){let r=this.modules.get(e);return !r||r.tier!=="advanced"?null:(this.activatedAdvanced.add(e),r.getToolsList())}getAvailableAdvanced(){let e=[];for(let[r,n]of this.modules)n.tier==="advanced"&&!this.activatedAdvanced.has(r)&&e.push({key:r,toolCount:n.getToolsList().length});return e}async dispatch(e,r,n,s){let o=this.detectActiveFeatures();for(let[i,c]of this.modules)if(o.has(i))try{let a=await c.handleTool(e,r,n,s);if(a.handled)return a}catch(a){return {handled:true,text:JSON.stringify({error:`Tool handler error in module "${i}"`,message:a.message},null,2)}}return null}get size(){return this.modules.size}getRegistryInfo(){let e=this.detectActiveFeatures(),r={core:0,feature:0,advanced:0};for(let n of this.modules.values())r[n.tier]++;return {total:this.modules.size,byTier:r,activeFeatures:[...e],availableAdvanced:[...this.modules.entries()].filter(([n,s])=>s.tier==="advanced"&&!this.activatedAdvanced.has(n)).map(([n])=>n)}}};var Fe=null;async function On(){return Fe||(Fe=await jn()),Fe}var Fn=[`CREATE TABLE IF NOT EXISTS aspects (
26
- id TEXT PRIMARY KEY,
27
- description TEXT NOT NULL,
28
- category TEXT DEFAULT 'rule',
29
- severity TEXT DEFAULT 'medium',
30
- value TEXT,
31
- enforcement TEXT,
32
- defined_in TEXT NOT NULL,
33
- tags TEXT,
34
- created_at TEXT NOT NULL,
35
- updated_at TEXT NOT NULL
36
- )`,`CREATE TABLE IF NOT EXISTS anchors (
37
- id INTEGER PRIMARY KEY AUTOINCREMENT,
38
- aspect_id TEXT NOT NULL REFERENCES aspects(id) ON DELETE CASCADE,
39
- file_path TEXT NOT NULL,
40
- start_line INTEGER NOT NULL,
41
- end_line INTEGER NOT NULL,
42
- content_hash TEXT,
43
- normalized_hash TEXT,
44
- materialized_at_commit TEXT,
45
- last_verified TEXT,
46
- drifted INTEGER DEFAULT 0
47
- )`,"CREATE INDEX IF NOT EXISTS idx_anchors_file ON anchors(file_path)","CREATE INDEX IF NOT EXISTS idx_anchors_aspect ON anchors(aspect_id)",`CREATE TABLE IF NOT EXISTS edges (
48
- id INTEGER PRIMARY KEY AUTOINCREMENT,
49
- source TEXT NOT NULL,
50
- target TEXT NOT NULL,
51
- relation TEXT NOT NULL,
52
- weight REAL DEFAULT 1.0,
53
- origin TEXT DEFAULT 'explicit',
54
- created_at TEXT NOT NULL
55
- )`,"CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)",`CREATE TABLE IF NOT EXISTS lore_links (
56
- aspect_id TEXT NOT NULL,
57
- lore_id TEXT NOT NULL,
58
- PRIMARY KEY (aspect_id, lore_id)
59
- )`,`CREATE TABLE IF NOT EXISTS search_log (
60
- id INTEGER PRIMARY KEY AUTOINCREMENT,
61
- query TEXT NOT NULL,
62
- results_returned TEXT NOT NULL,
63
- selected_result TEXT,
64
- timestamp TEXT NOT NULL
65
- )`,"CREATE INDEX IF NOT EXISTS idx_search_query ON search_log(query)",`CREATE TABLE IF NOT EXISTS search_weights (
66
- query_normalized TEXT NOT NULL,
67
- aspect_id TEXT NOT NULL,
68
- weight REAL DEFAULT 1.0,
69
- hit_count INTEGER DEFAULT 1,
70
- last_hit TEXT NOT NULL,
71
- PRIMARY KEY (query_normalized, aspect_id)
72
- )`,`CREATE TABLE IF NOT EXISTS heatmap (
73
- aspect_id TEXT NOT NULL,
74
- access_type TEXT NOT NULL,
75
- count INTEGER DEFAULT 0,
76
- last_accessed TEXT NOT NULL,
77
- PRIMARY KEY (aspect_id, access_type)
78
- )`],Nn=["ALTER TABLE anchors ADD COLUMN original_content TEXT",`CREATE TABLE IF NOT EXISTS anchor_history (
79
- id INTEGER PRIMARY KEY AUTOINCREMENT,
80
- anchor_id INTEGER NOT NULL,
81
- action TEXT NOT NULL,
82
- old_start INTEGER,
83
- old_end INTEGER,
84
- new_start INTEGER,
85
- new_end INTEGER,
86
- old_path TEXT,
87
- new_path TEXT,
88
- confidence REAL,
89
- commit_hash TEXT,
90
- healed_at TEXT NOT NULL
91
- )`],$n="CREATE VIRTUAL TABLE IF NOT EXISTS aspects_fts USING fts5(id, description, enforcement, tags)";function H(t,e,r){let n=t.prepare(e);r&&r.length>0&&n.bind(r);let s=[];for(;n.step();)s.push(n.getAsObject());return n.free(),s}function Mn(t,e,r){let n=t.prepare(e);r&&r.length>0&&n.bind(r);let s=null;return n.step()&&(s=n.getAsObject()),n.free(),s}async function kt(t){let e=await On(),r=x.join(t,".paradigm"),n=x.join(r,"aspect-graph.db"),s;if(h.existsSync(n)){let o=h.readFileSync(n);s=new e.Database(o);}else h.existsSync(r)||h.mkdirSync(r,{recursive:true}),s=new e.Database;for(let o of Fn)s.run(o);try{s.run($n);}catch{}for(let o of Nn)try{s.run(o);}catch{}return s}function Rt(t,e){if(e){let r=x.join(e,".paradigm");h.existsSync(r)||h.mkdirSync(r,{recursive:true});let n=x.join(r,"aspect-graph.db"),s=t.export();h.writeFileSync(n,Buffer.from(s));}t.close();}function It(t,e,r){let n=e.filter(i=>i.type==="aspect"),s=new Date().toISOString(),o=null;try{o=execSync("git rev-parse HEAD",{cwd:r,encoding:"utf8"}).trim();}catch{}t.run("DELETE FROM anchors"),t.run("DELETE FROM edges"),t.run("DELETE FROM aspects");try{t.run("DELETE FROM aspects_fts");}catch{}for(let i of n){let c=i.data??{},a=zn(c,i),l=Wn(c,i),u=c.value!=null?String(c.value):null,d=i.enforcement??(c.enforcement!=null?String(c.enforcement):null),f=i.tags?JSON.stringify(i.tags):null;if(t.run(`INSERT INTO aspects (id, description, category, severity, value, enforcement, defined_in, tags, created_at, updated_at)
92
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.symbol,i.description??"",a,l,u,d,i.filePath,f,i.created??s,i.modified??s]),i.anchors)for(let p of i.anchors){let{startLine:m,endLine:y}=Pt(p),w=Hn();t.run(`INSERT INTO anchors (aspect_id, file_path, start_line, end_line, content_hash, normalized_hash, materialized_at_commit, last_verified, original_content)
93
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[i.symbol,p.path,m,y,w.exact,w.normalized,o,s,w.normalizedContent]);}let g=c.edges;if(Array.isArray(g))for(let p of g)t.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
94
- VALUES (?, ?, ?, ?, ?, ?)`,[p.source??i.symbol,p.target??"",p.relation??"related-to",p.weight??1,p.origin??"explicit",s]);if(i.appliesTo)for(let p of i.appliesTo)t.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
95
- VALUES (?, ?, ?, ?, ?, ?)`,[i.symbol,p,"related-to",.5,"inferred",s]);try{t.run(`INSERT INTO aspects_fts (id, description, enforcement, tags)
96
- VALUES (?, ?, ?, ?)`,[i.symbol,i.description??"",d??"",f??""]);}catch{}}}function fr(t,e){return Mn(t,"SELECT * FROM aspects WHERE id = ?",[e])}function pr(t,e){return H(t,"SELECT * FROM anchors WHERE aspect_id = ?",[e])}function mr(t,e){return H(t,"SELECT * FROM edges WHERE source = ?",[e])}function gr(t,e){return H(t,"SELECT * FROM edges WHERE target = ?",[e])}function hr(t,e){return H(t,"SELECT * FROM edges WHERE source = ? OR target = ?",[e,e])}function yr(t,e,r){let n=new Date().toISOString();t.run(`INSERT INTO heatmap (aspect_id, access_type, count, last_accessed)
97
- VALUES (?, ?, 1, ?)
98
- ON CONFLICT(aspect_id, access_type)
99
- DO UPDATE SET count = count + 1, last_accessed = ?`,[e,r,n,n]);}function Sr(t,e=20,r){return r?H(t,"SELECT * FROM heatmap WHERE access_type = ? ORDER BY count DESC LIMIT ?",[r,e]):H(t,"SELECT * FROM heatmap ORDER BY count DESC LIMIT ?",[e])}function wr(t,e,r$1,n=true,s=.7,o=.85){let i=r$1?H(t,"SELECT * FROM anchors WHERE aspect_id = ?",[r$1]):H(t,"SELECT * FROM anchors"),c=[];for(let a of i){let u=H(t,"SELECT defined_in FROM aspects WHERE id = ?",[a.aspect_id])[0]?.defined_in,d$1=u?x.dirname(x.isAbsolute(u)?u:x.resolve(e,u)):e,f=r(a.file_path,d$1,e),g=f.resolvedPath;if(!f.exists){c.push({aspectId:a.aspect_id,path:a.file_path,startLine:a.start_line,endLine:a.end_line,status:"missing",resolvedBy:"none",exists:false,drifted:true});continue}try{let m=h.readFileSync(g,"utf8").split(`
100
- `),y=Math.max(0,a.start_line-1),w=Math.min(m.length,a.end_line),P=m.slice(y,w).join(`
101
- `),$=te.createHash("sha256").update(P).digest("hex");if(a.content_hash!=null&&$===a.content_hash){c.push({aspectId:a.aspect_id,path:a.file_path,startLine:a.start_line,endLine:a.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1}),a.drifted===1&&t.run("UPDATE anchors SET drifted = 0 WHERE id = ?",[a.id]);continue}let J=te.createHash("sha256").update($e(P)).digest("hex");if(a.normalized_hash!=null&&J===a.normalized_hash){t.run("UPDATE anchors SET content_hash = ?, drifted = 0 WHERE id = ?",[$,a.id]),c.push({aspectId:a.aspect_id,path:a.file_path,startLine:a.start_line,endLine:a.end_line,status:"cosmetic",resolvedBy:"normalized-hash",exists:!0,drifted:!1});continue}if(a.content_hash==null&&a.normalized_hash==null){t.run("UPDATE anchors SET content_hash = ?, normalized_hash = ?, drifted = 0 WHERE id = ?",[$,J,a.id]),c.push({aspectId:a.aspect_id,path:a.file_path,startLine:a.start_line,endLine:a.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1});continue}let se=!1;if(a.materialized_at_commit){let _=Un(e,a.file_path,a.materialized_at_commit,a.start_line,a.end_line);if(_){let E=Math.max(0,_.currentStart-1),S=Math.min(m.length,_.currentEnd),I=m.slice(E,S).join(`
102
- `),K=te.createHash("sha256").update(I).digest("hex");if(a.content_hash!=null&&K===a.content_hash){let Q=n;if(Q){t.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[_.currentStart,_.currentEnd,a.id]);let ae=H(t,"SELECT defined_in FROM aspects WHERE id = ?",[a.aspect_id]);ae.length>0&&Ne(e,ae[0].defined_in,a.file_path,a.start_line,a.end_line,_.currentStart,_.currentEnd);}c.push({aspectId:a.aspect_id,path:a.file_path,startLine:Q?_.currentStart:a.start_line,endLine:Q?_.currentEnd:a.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:_.currentStart,suggestedEnd:_.currentEnd,autoHealed:Q}),se=!0;}else {let Q=te.createHash("sha256").update($e(I)).digest("hex");if(a.normalized_hash!=null&&Q===a.normalized_hash){if(n){let ae=te.createHash("sha256").update(I).digest("hex");t.run("UPDATE anchors SET start_line = ?, end_line = ?, content_hash = ?, drifted = 0 WHERE id = ?",[_.currentStart,_.currentEnd,ae,a.id]);let he=H(t,"SELECT defined_in FROM aspects WHERE id = ?",[a.aspect_id]);he.length>0&&Ne(e,he[0].defined_in,a.file_path,a.start_line,a.end_line,_.currentStart,_.currentEnd);}c.push({aspectId:a.aspect_id,path:a.file_path,startLine:n?_.currentStart:a.start_line,endLine:n?_.currentEnd:a.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:_.currentStart,suggestedEnd:_.currentEnd,autoHealed:n}),se=!0;}}}}if(se)continue;if(a.original_content){let{contentSearch:_}=(_t(),d(Tt)),E=_(e,a.file_path,a.original_content,n);if(E.found&&E.score>=s){if(n&&E.score>=o&&!E.suggestedPath&&E.suggestedStart&&E.suggestedEnd){t.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[E.suggestedStart,E.suggestedEnd,a.id]);try{t.run(`INSERT INTO anchor_history (anchor_id, action, old_start, old_end, new_start, new_end, confidence, healed_at)
103
- VALUES (?, 'relocated', ?, ?, ?, ?, ?, ?)`,[a.id,a.start_line,a.end_line,E.suggestedStart,E.suggestedEnd,E.score,new Date().toISOString()]);}catch{}let I=H(t,"SELECT defined_in FROM aspects WHERE id = ?",[a.aspect_id]);I.length>0&&Ne(e,I[0].defined_in,a.file_path,a.start_line,a.end_line,E.suggestedStart,E.suggestedEnd),c.push({aspectId:a.aspect_id,path:a.file_path,startLine:E.suggestedStart,endLine:E.suggestedEnd,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:E.similarity,suggestedStart:E.suggestedStart,suggestedEnd:E.suggestedEnd,autoHealed:!0,drifted:!1});continue}c.push({aspectId:a.aspect_id,path:E.suggestedPath||a.file_path,startLine:a.start_line,endLine:a.end_line,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:E.similarity,suggestedStart:E.suggestedStart,suggestedEnd:E.suggestedEnd,autoHealed:!1,drifted:!0});continue}}t.run("UPDATE anchors SET drifted = 1 WHERE id = ?",[a.id]),c.push({aspectId:a.aspect_id,path:a.file_path,startLine:a.start_line,endLine:a.end_line,status:"modified",resolvedBy:"none",exists:!0,currentContent:P,drifted:!0});}catch{c.push({aspectId:a.aspect_id,path:a.file_path,startLine:a.start_line,endLine:a.end_line,status:"modified",resolvedBy:"none",exists:true,drifted:true});}}return c}function Pt(t){let{lines:e}=t;return typeof e=="number"?{startLine:e,endLine:e}:Array.isArray(e)?e.length===2?{startLine:e[0],endLine:e[1]}:{startLine:Math.min(...e),endLine:Math.max(...e)}:{startLine:1,endLine:1}}function Dn(t){let e=[],r=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm,n;for(;(n=r.exec(t))!==null;)e.push({oldStart:parseInt(n[1],10),oldCount:n[2]!==void 0?parseInt(n[2],10):1,newStart:parseInt(n[3],10),newCount:n[4]!==void 0?parseInt(n[4],10):1});return e}function Un(t,e,r,n,s){let o;try{o=execSync(`git diff ${r}..HEAD --unified=0 -- "${e}"`,{cwd:t,encoding:"utf8",timeout:5e3});}catch{return null}if(!o.trim())return {originalStart:n,originalEnd:s,currentStart:n,currentEnd:s};let i=Dn(o),c=0;for(let a of i){if(a.oldStart+a.oldCount<=n){c+=a.newCount-a.oldCount;continue}if(a.oldStart<s)return null;break}return c===0?null:{originalStart:n,originalEnd:s,currentStart:n+c,currentEnd:s+c}}function Ne(t,e,r,n,s,o,i){let c=x.isAbsolute(e)?e:x.join(t,e);if(!h.existsSync(c))return false;try{let a=h.readFileSync(c,"utf8"),l=n===s?`${r}:${n}`:`${r}:${n}-${s}`,u=o===i?`${r}:${o}`:`${r}:${o}-${i}`;if(!a.includes(l))return !1;let d=a.replace(l,u);return h.writeFileSync(c,d,"utf8"),!0}catch{return false}}function $e(t){return t.split(`
104
- `).map(e=>e.trimEnd()).filter(e=>e.trim()!=="").map(e=>e.replace(/\s+/g," ")).join(`
105
- `)}function Hn(t,e,r$1){return {exact:null,normalized:null,normalizedContent:null};}function zn(t,e){if(typeof t.category=="string")return t.category;let r=(e.description??"").toLowerCase();return /\b(must|require|always)\b/.test(r)?"rule":/\b(decided|chose)\b/.test(r)?"decision":/\b(limit|cannot)\b/.test(r)?"constraint":/\b(set to|configured|value)\b/.test(r)?"configuration":"rule"}function Wn(t,e){if(typeof t.severity=="string")return t.severity;let r=e.tags??[];return r.includes("critical")?"critical":r.includes("security")||r.includes("compliance")?"high":"medium"}j$1();var Gn=/L-\d{4}-\d{2}-\d{2}-\d{3}/g;async function Ct(t,e){t.run("DELETE FROM lore_links");let r=await a$4(e);if(r.length===0)return 0;let n=Xn(r),s=new Map;for(let l of r)s.set(l.id,l);let o=new Set,i=t.exec("SELECT id, enforcement FROM aspects");if(i.length>0){let{columns:l,values:u}=i[0],d=l.indexOf("id"),f=l.indexOf("enforcement");for(let g of u){let p=String(g[d]),m=g[f];if(m&&typeof m=="string"){let y=m.match(Gn);if(y)for(let w of y)s.has(w)&&o.add(`${p}\0${w}`);}}}let c=t.exec("SELECT source, target FROM edges");if(c.length>0&&i.length>0){let l=Bn(t,c);for(let[u,d]of l)for(let f of d){let g=n.get(f);if(g)for(let p of g)o.add(`${u}\0${p}`);}}if(o.size===0)return 0;let a=t.prepare("INSERT OR IGNORE INTO lore_links (aspect_id, lore_id) VALUES (?, ?)");try{for(let l of o){let[u,d]=l.split("\0");a.bind([u,d]),a.step(),a.reset();}}finally{a.free();}return o.size}async function Er(t,e,r){let n=t.exec("SELECT lore_id FROM lore_links WHERE aspect_id = ?",[r]);if(n.length===0||n[0].values.length===0)return [];let s=n[0].values.map(o=>String(o[0]));return qn(e,s)}async function At(t,e){let r=await a$4(e);if(r.length===0)return 0;let n=t.exec("SELECT id FROM aspects"),s=new Set;if(n.length>0)for(let a of n[0].values)s.add(String(a[0]));if(s.size<2)return 0;let o=new Date().toISOString(),i=0,c=t.prepare(`INSERT OR IGNORE INTO edges (source, target, relation, weight, origin, created_at)
106
- VALUES (?, ?, 'related-to', 0.3, 'learned', ?)`);try{for(let a of r){if(!a.symbols_touched||a.symbols_touched.length<2)continue;let l=[];for(let u of a.symbols_touched){let d=u.startsWith("~")?u.slice(1):u;s.has(d)&&l.push(d);}for(let u=0;u<l.length;u++)for(let d=u+1;d<l.length;d++){let[f,g]=l[u]<l[d]?[l[u],l[d]]:[l[d],l[u]];c.bind([f,g,o]),c.step(),c.reset(),i++;}}}finally{c.free();}return i}function Xn(t){let e=new Map;for(let r of t)if(r.symbols_touched)for(let n of r.symbols_touched){let s=e.get(n);s||(s=new Set,e.set(n,s)),s.add(r.id);}return e}function Bn(t,e){let r=t.exec("SELECT id FROM aspects"),n=new Set;if(r.length>0)for(let l of r[0].values)n.add(String(l[0]));let s=new Map;if(e.length===0)return s;let{columns:o,values:i}=e[0],c=o.indexOf("source"),a=o.indexOf("target");for(let l of i){let u=String(l[c]),d=String(l[a]);if(n.has(u)){let f=s.get(u);f||(f=new Set,s.set(u,f)),f.add(d),f.add(`~${u}`);}if(n.has(d)){let f=s.get(d);f||(f=new Set,s.set(d,f)),f.add(u),f.add(`~${d}`);}}return s}async function qn(t,e){let r=new Set,n=[];for(let s of e){if(r.has(s))continue;r.add(s);let o=await b$3(t,s);o&&n.push(Vn(o));}return n}function Vn(t){return {id:t.id,title:t.title,summary:t.summary,timestamp:t.timestamp,symbolsTouched:t.symbols_touched}}var le=".paradigm/personas",Yn="index.yaml";async function pe(t,e){let r=x.join(t,le);if(!h.existsSync(r))return [];let n=h.readdirSync(r).filter(o=>o.endsWith(".persona")),s=[];for(let o of n)try{let i=h.readFileSync(x.join(r,o),"utf8"),c=N.load(i);c&&c.id&&s.push(c);}catch{}return Jn(s,e)}async function me(t,e){let r=x.join(t,le,`${e}.persona`);if(!h.existsSync(r))return null;try{return N.load(h.readFileSync(r,"utf8"))}catch{return null}}function Jn(t,e){if(!e)return t;let r=t;return e.tag&&(r=r.filter(n=>n.tags?.includes(e.tag))),e.trigger_type&&(r=r.filter(n=>n.trigger.type===e.trigger_type)),e.gate&&(r=r.filter(n=>n.journey.some(s=>s.gates.includes(e.gate)))),e.flow&&(r=r.filter(n=>n.journey.some(s=>s.flow===e.flow))),e.limit&&(r=r.slice(0,e.limit)),r}async function _r(t,e){let r=x.join(t,le);h.mkdirSync(r,{recursive:true});let n=x.join(r,`${e.id}.persona`);if(h.existsSync(n))throw new Error(`Persona ${e.id} already exists`);let s=new Date().toISOString(),o={version:"1.0",id:e.id,name:e.name,description:e.description,traits:e.traits,trigger:e.trigger,fixtures:e.fixtures,tags:e.tags||[],journey:e.journey||[],created:s,updated:s};return h.writeFileSync(n,N.dump(o,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await ge(t),e.id}async function Lt(t,e,r){let n=await me(t,e);if(!n)return false;let s=x.join(t,le,`${e}.persona`),o={...n,...r,id:n.id,version:n.version,created:n.created,updated:new Date().toISOString()};return h.writeFileSync(s,N.dump(o,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await ge(t),true}async function vr(t,e){let r=x.join(t,le,`${e}.persona`);if(!h.existsSync(r))return {deleted:false,warnings:[]};let n=[],s=await pe(t);for(let o of s)if(o.id!==e){o.trigger.spawned_by?.startsWith(e+".")&&n.push(`Persona ${o.id} is spawned by ${e} \u2014 it will become orphaned`);for(let i of o.journey)i.spawns?.some(c=>c.persona===e)&&n.push(`Persona ${o.id} step ${i.id} spawns ${e} \u2014 spawn will break`);}return h.unlinkSync(r),await ge(t),{deleted:true,warnings:n}}async function kr(t,e,r,n){let s=await me(t,e);if(!s)return false;if(s.journey.some(o=>o.id===r.id))throw new Error(`Step ${r.id} already exists in persona ${e}`);if(n){let o=s.journey.findIndex(i=>i.id===n);if(o===-1)throw new Error(`Step ${n} not found in persona ${e}`);s.journey.splice(o+1,0,r);}else s.journey.push(r);return Lt(t,e,{journey:s.journey})}async function Rr(t,e,r){let n=await me(t,e);if(!n)return {removed:false,warnings:[]};let s=n.journey.findIndex(c=>c.id===r);if(s===-1)return {removed:false,warnings:[]};let o=n.journey[s],i=[];if(o.produces)for(let c of Object.keys(o.produces)){let a=`{{produces.${c}}}`;for(let l=s+1;l<n.journey.length;l++){let u=n.journey[l];JSON.stringify(u).includes(a)&&i.push(`Step ${u.id} consumes {{produces.${c}}} from this step`);}}if(o.spawns&&o.spawns.length>0)for(let c of o.spawns)i.push(`Step spawns persona ${c.persona} \u2014 spawn chain will break`);return n.journey.splice(s,1),await Lt(t,e,{journey:n.journey}),{removed:true,warnings:i}}var Kn=/^[a-z][a-z0-9-]*$/,Qn=/^[a-z][a-z0-9-]*$/,Zn=/^(GET|POST|PUT|PATCH|DELETE)\s+\//;async function Ir(t,e,r=false){let n=[],s=[];Kn.test(e.id)||n.push({type:"invalid-id",detail:`ID "${e.id}" must match /^[a-z][a-z0-9-]*$/`}),(!e.name||e.name.trim()==="")&&n.push({type:"missing-name",detail:"Name is required"}),(!e.trigger||!e.trigger.type)&&n.push({type:"missing-trigger",detail:"Trigger with type is required"}),e.trigger.type!=="root"&&!e.trigger.spawned_by&&n.push({type:"missing-spawned-by",detail:`Non-root trigger type "${e.trigger.type}" requires spawned_by`}),(!e.journey||e.journey.length===0)&&n.push({type:"empty-journey",detail:"Journey must have at least one step"});let o=new Set,i=new Set;for(let c of e.journey){Qn.test(c.id)||n.push({type:"invalid-step-id",step:c.id,detail:"Step ID must match /^[a-z][a-z0-9-]*$/"}),o.has(c.id)&&n.push({type:"duplicate-step-id",step:c.id,detail:`Duplicate step ID "${c.id}"`}),o.add(c.id),Zn.test(c.route)||n.push({type:"invalid-route",step:c.id,route:c.route,detail:'Route must match "METHOD /path" (e.g., "POST /api/auth/signup")'}),(!c.gates||c.gates.length===0)&&n.push({type:"missing-gates",step:c.id,detail:"Step must have at least one gate"}),(!c.expect||c.expect.status===void 0)&&n.push({type:"missing-expect",step:c.id,detail:"Step must have expect with status"});let l=JSON.stringify(c).match(/\{\{produces\.([^}]+)\}\}/g)||[];for(let u of l){let d=u.replace("{{produces.","").replace("}}","");i.has(d)||n.push({type:"unresolved-produces",step:c.id,key:d,detail:`{{produces.${d}}} used but not produced by a prior step`});}if(c.produces)for(let u of Object.keys(c.produces))i.add(u);}if(r){let c=x.join(t,"portal.yaml"),a=[],l=[];if(h.existsSync(c))try{let d=N.load(h.readFileSync(c,"utf8"));d.gates&&typeof d.gates=="object"&&(a=Object.keys(d.gates)),d.routes&&typeof d.routes=="object"&&(l=Object.keys(d.routes));}catch{}for(let d of e.journey)for(let f of d.gates)a.length>0&&!a.includes(f)&&n.push({type:"gate-not-found",step:d.id,gate:f,detail:`Gate ${f} not defined in portal.yaml`});for(let d of e.journey)if(l.length>0){let f=d.route;l.some(p=>Me(p,f))||s.push({type:"route-not-in-portal",detail:`Route "${f}" (step ${d.id}) not found in portal.yaml`});}for(let d of e.journey)if(d.spawns)for(let f of d.spawns)await me(t,f.persona)||n.push({type:"spawn-target-missing",step:d.id,detail:`Spawn target persona "${f.persona}" does not exist`});let u=await es(t,e.id);if(u&&n.push({type:"spawn-cycle",detail:`Circular spawn dependency: ${u.join(" \u2192 ")}`}),l.length>0||a.length>0){let d=await pe(t),f=new Set,g=new Set;for(let w of d)for(let P of w.journey){for(let $ of P.gates)f.add($);g.add(P.route);}let p=[],m=x.join(t,".paradigm","flow-index.json");if(h.existsSync(m))try{let w=JSON.parse(h.readFileSync(m,"utf8"));p=Object.keys(w.flows||{});}catch{}let y=new Set;for(let w of d)for(let P of w.journey)P.flow&&y.add(P.flow);return {persona:e.id,valid:n.length===0,errors:n,warnings:s,coverage:{routes:{covered:g.size,total:l.length,uncovered:l.filter(w=>!g.has(w))},gates:{covered:f.size,total:a.length,uncovered:a.filter(w=>!f.has(w))},flows:{covered:y.size,total:p.length,uncovered:p.filter(w=>!y.has(w))}}}}}return {persona:e.id,valid:n.length===0,errors:n,warnings:s}}function Me(t,e){let r=n=>n.replace(/:[a-zA-Z_]+/g,":param").replace(/\{\{[^}]+\}\}/g,":param");return r(t)===r(e)}async function es(t,e){let r=new Set,n=[];async function s(o){if(r.has(o)){let c=n.indexOf(o);return c!==-1?[...n.slice(c),o]:null}r.add(o),n.push(o);let i=await me(t,o);if(i){for(let c of i.journey)if(c.spawns)for(let a of c.spawns){let l=await s(a.persona);if(l)return l}}return n.pop(),null}return s(e)}async function ge(t){let e=x.join(t,le);h.mkdirSync(e,{recursive:true});let r=await pe(t),n={},s={},o={};for(let d of r){let f=new Set,g=new Set,p=[],m=new Set;for(let y of d.journey){for(let w of y.gates)f.add(w);if(y.flow&&g.add(y.flow),p.push(y.route),y.spawns)for(let w of y.spawns)m.add(w.persona);}n[d.id]={name:d.name,trigger:d.trigger.type,spawned_by:d.trigger.spawned_by,steps:d.journey.length,gates:[...f],flows:[...g],routes:p,spawns:[...m],tags:d.tags||[]};for(let y of f)s[y]||(s[y]=[]),s[y].push(d.id);for(let y of p)o[y]||(o[y]=[]),o[y].push(d.id);}let i=[],c=x.join(t,"portal.yaml");if(h.existsSync(c))try{let d=N.load(h.readFileSync(c,"utf8"));d.routes&&typeof d.routes=="object"&&(i=Object.keys(d.routes).filter(g=>!Object.keys(o).some(p=>Me(g,p))));}catch{}let a={},l=x.join(e,"chains");if(h.existsSync(l)){let d=h.readdirSync(l).filter(f=>f.endsWith(".yaml"));for(let f of d)try{let g=h.readFileSync(x.join(l,f),"utf8"),p=N.load(g);if(p&&p.id){let m=p.order.map(P=>P.persona),y=0,w=new Set;for(let P of m){let $=n[P];if($){y+=$.steps;for(let J of $.gates)w.add(J);}}a[p.id]={description:p.description||"",order:m,total_steps:y,total_gates:w.size};}}catch{}}let u={version:"1.0",generated:new Date().toISOString(),personas:n,chains:a,gate_coverage:s,route_coverage:o,uncovered_routes:i};return h.writeFileSync(x.join(e,Yn),N.dump(u,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),u}async function Pr(t){let e=await pe(t),r=new Set,n=new Set,s=new Set;for(let u of e)for(let d of u.journey){for(let f of d.gates)r.add(f);n.add(d.route),d.flow&&s.add(d.flow);}let o=[],i=[],c=x.join(t,"portal.yaml");if(h.existsSync(c))try{let u=N.load(h.readFileSync(c,"utf8"));u.gates&&typeof u.gates=="object"&&(o=Object.keys(u.gates)),u.routes&&typeof u.routes=="object"&&(i=Object.keys(u.routes));}catch{}let a=[],l=x.join(t,".paradigm","flow-index.json");if(h.existsSync(l))try{let u=JSON.parse(h.readFileSync(l,"utf8"));a=Object.keys(u.flows||{});}catch{}return {routes:{covered:n.size,total:i.length,uncovered:i.filter(u=>!Array.from(n).some(d=>Me(u,d)))},gates:{covered:r.size,total:o.length,uncovered:o.filter(u=>!r.has(u))},flows:{covered:s.size,total:a.length,uncovered:a.filter(u=>!s.has(u))},personas:e.length}}async function Cr(t,e){let r=await pe(t),n=[];for(let s of r){let o=[],i=[];for(let c of s.journey)if((c.gates.includes(e)||c.flow===e||c.route===e||c.signals?.includes(e))&&(o.push(c.id),c.spawns))for(let l of c.spawns)i.push(l.persona);o.length>0&&n.push({persona:s.id,steps:o,spawns_blocked:i});}return n}function ts(t,e){let r=e.split(/[.\[\]]+/).filter(Boolean),n=t;for(let s of r){if(n==null||typeof n!="object")return;n=n[s];}return n}function ns(t,e){let r=[];if(e.status!==t.expect.status&&r.push({type:"status",field:"status",expected:t.expect.status,actual:e.status,message:`Step ${t.id}: status is ${e.status}, expected ${t.expect.status}`}),t.expect.body?.has){let n=e.body;for(let s of t.expect.body.has)(!n||typeof n!="object"||!(s in n))&&r.push({type:"body.has",field:s,expected:true,actual:false,message:`Step ${t.id}: body missing key '${s}'`});}if(t.expect.body?.match){let n=e.body;for(let[s,o]of Object.entries(t.expect.body.match)){let i=n?ts(n,s):void 0;JSON.stringify(i)!==JSON.stringify(o)&&r.push({type:"body.match",field:s,expected:o,actual:i??null,message:`Step ${t.id}: '${s}' is ${JSON.stringify(i??null)}, expected ${JSON.stringify(o)}`});}}if(t.signals&&t.signals.length>0){let n=e.signals_fired||[];for(let s of t.signals)n.includes(s)||r.push({type:"signal",field:"signals_fired",expected:s,actual:n,message:`Step ${t.id}: signal '${s}' was not fired`});}if(t.gates.length>0&&e.gates_traversed)for(let n of t.gates)e.gates_traversed.includes(n)||r.push({type:"gate",field:"gates_traversed",expected:n,actual:e.gates_traversed,message:`Step ${t.id}: gate '${n}' was not traversed`});return r}async function Ar(t,e={}){let r=[];try{let{SentinelStorage:c}=await import('./dist-W3XCATBJ.js'),a=new c,u=(a.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.complete",scopeValue:t.id,limit:500})||[]).filter(p=>{let m=JSON.parse(p.data_json||"{}");return !(e.run_id&&m.run_id!==e.run_id||e.chain_id&&m.chain_id!==e.chain_id||e.environment&&m.environment!==e.environment)}),f=(a.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.fail",scopeValue:t.id,limit:500})||[]).filter(p=>{let m=JSON.parse(p.data_json||"{}");return !(e.run_id&&m.run_id!==e.run_id||e.chain_id&&m.chain_id!==e.chain_id||e.environment&&m.environment!==e.environment)}),g=new Map;for(let p of [...u,...f]){let m=JSON.parse(p.data_json||"{}");m.step_id&&g.set(m.step_id,m);}for(let p of t.journey){let m=g.get(p.id);if(!m){r.push({step_id:p.id,matched:!1,assertions:[],message:`No Sentinel event found for step '${p.id}' \u2014 step was never exercised`});continue}let y=ns(p,{status:m.status,body:m.body,gates_traversed:m.gates_traversed,signals_fired:m.signals_fired});r.push({step_id:p.id,matched:!0,passed:y.length===0,assertions:y});}}catch{for(let c of t.journey)r.push({step_id:c.id,matched:false,assertions:[],message:"Sentinel unavailable \u2014 cannot validate events"});}let n=r.filter(c=>c.matched).length,s=r.filter(c=>c.passed).length,o=r.filter(c=>c.matched&&!c.passed).length,i=r.reduce((c,a)=>c+a.assertions.length,0);return {run_id:e.run_id,environment:e.environment,steps:r,summary:{total_steps:t.journey.length,matched:n,unmatched:t.journey.length-n,passed:s,failed:o,assertion_failures:i}}}var oe=".paradigm/protocols",jt="index.yaml";async function De(t){let e=x.join(t,oe);if(!h.existsSync(e))return [];let r=h.readdirSync(e).filter(s=>s.endsWith(".protocol")).sort(),n=[];for(let s of r)try{let o=h.readFileSync(x.join(e,s),"utf8"),i=N.load(o);i?.id&&i?.name&&n.push(i);}catch{}return n}async function ss(t,e){let r=e.replace(/^P-/,""),n=x.join(t,oe,`${r}.protocol`);if(h.existsSync(n))try{let o=h.readFileSync(n,"utf8");return N.load(o)}catch{return null}return (await De(t)).find(o=>o.id===e)||null}async function jr(t){let e=x.join(t,oe,jt);if(!h.existsSync(e))return null;try{let r=h.readFileSync(e,"utf8");return N.load(r)}catch{return null}}async function Or(t,e,r=3){let n=await De(t);if(n.length===0)return [];let s=os(e);if(s.length===0)return [];let o=[];for(let i of n){let c=0;for(let u of i.trigger){let d=u.toLowerCase();for(let f of s)d.includes(f)&&(c+=3);}for(let u of i.tags){let d=u.toLowerCase();for(let f of s)(d.includes(f)||f.includes(d))&&(c+=2);}let a=i.name.toLowerCase(),l=i.description.toLowerCase();for(let u of s)a.includes(u)&&(c+=1),l.includes(u)&&(c+=1);for(let u of i.steps)if(u.notes){let d=u.notes.toLowerCase();for(let f of s)d.includes(f)&&(c+=.5);}c>0&&o.push({protocol:i,score:c});}return o.sort((i,c)=>c.score-i.score),o.slice(0,r)}async function Fr(t,e){let r=x.join(t,oe);h.existsSync(r)||h.mkdirSync(r,{recursive:true});let n=as(e.name),s=`P-${n}`,o=new Date().toISOString(),i={id:s,name:e.name,description:e.description,trigger:e.trigger,tags:e.tags,symbols:e.symbols||[],exemplar:e.exemplar,steps:e.steps,recorded_from:e.recorded_from,recorded_at:o,last_verified:o,verified_by:e.verified_by||"claude-opus-4-6",status:"current"},c=x.join(r,`${n}.protocol`);return h.writeFileSync(c,N.dump(i,{lineWidth:-1,noRefs:true}),"utf8"),s}async function Nr(t,e,r,n=false){let s=await ss(t,e);if(!s)return false;r.name!==void 0&&(s.name=r.name),r.description!==void 0&&(s.description=r.description),r.trigger!==void 0&&(s.trigger=r.trigger),r.tags!==void 0&&(s.tags=r.tags),r.symbols!==void 0&&(s.symbols=r.symbols),r.exemplar!==void 0&&(s.exemplar=r.exemplar),r.steps!==void 0&&(s.steps=r.steps),r.status!==void 0&&(s.status=r.status),r.verified_by!==void 0&&(s.verified_by=r.verified_by),n&&(s.last_verified=new Date().toISOString(),s.verified_by=r.verified_by||"claude-opus-4-6");let o=e.replace(/^P-/,""),i=x.join(t,oe,`${o}.protocol`);return h.writeFileSync(i,N.dump(s,{lineWidth:-1,noRefs:true}),"utf8"),true}function rs(t,e){let r=[],n="current";if(e.exemplar){let s=x.join(t,e.exemplar);h.existsSync(s)?h.statSync(s).mtime.toISOString()>e.last_verified&&(r.push(`Exemplar modified since last verified: ${e.exemplar}`),n!=="broken"&&(n="stale")):(r.push(`Exemplar missing: ${e.exemplar}`),n="broken");}for(let s of e.steps){if(s.template_from){let o=x.join(t,s.template_from);h.existsSync(o)||(r.push(`Template file missing: ${s.template_from}`),n="broken");}if(s.action==="modify"&&s.target){let o=x.join(t,s.target);!s.target.includes("{")&&!h.existsSync(o)&&(r.push(`Modify target missing: ${s.target}`),n="broken");}}return {status:n,issues:r}}async function Ot(t){let e=await De(t),r=[],n=0,s=0,o=0;for(let a of e){let l=rs(t,a);if(a.status!==l.status){a.status=l.status;let u=a.id.replace(/^P-/,""),d=x.join(t,oe,`${u}.protocol`);h.existsSync(d)&&h.writeFileSync(d,N.dump(a,{lineWidth:-1,noRefs:true}),"utf8");}switch(l.status){case "current":n++;break;case "stale":s++;break;case "broken":o++;break}r.push({id:a.id,name:a.name,status:l.status,last_verified:a.last_verified,trigger:a.trigger,tags:a.tags});}let i={version:"1.0",generated:new Date().toISOString(),protocols:r,health:{total:e.length,current:n,stale:s,broken:o}},c=x.join(t,oe);if(e.length>0){h.existsSync(c)||h.mkdirSync(c,{recursive:true});let a=x.join(c,jt);h.writeFileSync(a,N.dump(i,{lineWidth:-1,noRefs:true}),"utf8");}return i}function $r(t,e,r){if(!e||e.length<2)return null;let n={};for(let s of e){let o=x.dirname(s);n[o]||(n[o]=[]),n[o].push(s);}for(let[s,o]of Object.entries(n)){if(o.length<2)continue;let i=x.join(t,s);if(!h.existsSync(i))continue;let a=h.readdirSync(i).filter(l=>{let u=x.extname(l);return [".ts",".tsx",".js",".jsx",".rs",".py"].includes(u)}).filter(l=>!o.some(u=>x.basename(u)===l));if(a.length>0){let l=x.join(s,a[0]),u=[...o.map(d=>({action:"create",target:d})),...r.map(d=>({action:"modify",target:d}))];return {hint:`This session created ${o.length} new files in ${s}/ following existing patterns. Consider recording a protocol.`,draft:{name:`Add a ${x.basename(s).replace(/s$/,"")}`,exemplar:l,steps:u}}}}return null}function os(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(e=>e.length>1).filter(e=>!is.has(e))}var is=new Set(["a","an","the","is","are","was","were","be","been","to","of","in","for","on","with","at","by","from","it","this","that","and","or","but","if","then","so","as","do","does","did","will","would","can","could","should","may","might","must","shall","i","me","my","we","our","you","your","he","she","how","what","when","where","which","who","whom"]);function as(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var Y="pack.yaml";var cs="PARADIGM_STRICT";function de(){let t=process.env[cs];if(t===void 0||t==="")return false;let e=t.toLowerCase();return e==="1"||e==="true"||e==="yes"||e==="on"}function ls(t){return h$1(t)}function $t(t,e){if(!h.existsSync(t))return {status:"missing"};let r;try{r=h.readFileSync(t,"utf-8");}catch{return Ue({status:"unparseable",errorClass:"other",detail:"file read error"},e)}let n;try{n=N.load(r);}catch(s){let{errorClass:o,detail:i}=ls(s);return Ue({status:"unparseable",errorClass:o,detail:i},e)}if(e?.schema){let s=e.schema.safeParse(n);if(!s.success){let o={status:"invalid",errorClass:"schema",detail:`schema validation failed (${s.error.issues.length} issue(s))`};return Ue(o,e)}return {status:"ok",data:s.data}}return {status:"ok",data:n}}function Ue(t,e){if(!(e?.strict??de())||t.status==="ok"||t.status==="missing")return t;throw new Error(`yaml load failed under PARADIGM_STRICT=1 (${t.errorClass}: ${t.detail})`)}b$1();var Mt=/^[a-z0-9][a-z0-9-]{0,63}$/,He=["track","index","chronological","featured"],ze=64,ds=z.object({id:z.string().regex(Mt,"invalid section id"),name:z.string().min(1).max(120),order:z.number().int().min(0).max(9999),style:z.enum(He,{errorMap:()=>({message:`section.style must be one of ${He.join("|")}`})}),description:z.string().max(1e3).optional(),default:z.boolean({invalid_type_error:"section.default must be a boolean"}).optional()}).strict(),We=z.array(ds).max(ze,`sections must contain \u2264${ze} entries`);z.object({sections:We.optional()}).passthrough();z.object({section:z.string().regex(Mt).optional(),order:z.number().int().min(0).max(9999).optional()}).passthrough();var Ut="@a-company/university",Ht=".paradigm/university",zt=".paradigm/cache/packs.json",j=class extends Error{constructor(r,n){super(`pack-load failed (${r}: ${n})`);this.errorClass=r;this.detail=n;this.name="PackLoadError";}},us=["id","name","version","schema_version","tenant_kind"],fs=new Set(["first-party","project","external"]),Dt={id:"main",name:"Curriculum",order:1,style:"track",default:true};function Ge(t){if(t==null)return [{...Dt}];if(Array.isArray(t)&&t.length===0)return [{...Dt}];let e=We.safeParse(t);if(!e.success){let o=e.error.issues[0],i=o?`${o.path.join(".")||"sections"}: ${o.message}`:"sections failed schema validation";throw new j("manifest-invalid",i)}let r=e.data.map(o=>({...o})),n=new Set;for(let o of r){if(n.has(o.id))throw new j("manifest-invalid",`duplicate section id "${o.id}"`);n.add(o.id);}r.length===1&&!r[0].default&&(r[0]={...r[0],default:true});let s=r.filter(o=>o.default===true);if(s.length>1)throw new j("manifest-invalid",`at most one section may set default: true (found ${s.length})`);return r.sort((o,i)=>o.order-i.order||o.id.localeCompare(i.id)),r}function ue(t){let e=x.join(t,Y),r=$t(e);switch(r.status){case "missing":throw new j("missing-manifest",`no ${Y} at pack root`);case "unparseable":throw new j("manifest-unparseable",r.detail);case "invalid":throw new j("manifest-invalid",r.detail);case "ok":{let n=r.data;if(!n||typeof n!="object")throw new j("manifest-invalid","manifest is not an object");for(let s of us){let o=n[s];if(o==null||o==="")throw new j("missing-required-field",`required field ${String(s)} is missing or empty`)}if(!fs.has(String(n.tenant_kind)))throw new j("missing-required-field","tenant_kind must be one of first-party|project|external");return n.sections=Ge(n.sections),n}}}function Wt(t){let e=gs(t);if(e)return e;let r=[],n=x.join(t,"node_modules",Ut);if(h.existsSync(x.join(n,Y)))try{let o=ue(n);r.push({manifest:o,rootDir:n,source:"first-party"});}catch(o){a$1.component("#pack-loader").warn("first-party pack manifest invalid",{errorClass:o instanceof j?o.errorClass:"other"});}for(let o of ps(t))try{let i=ue(o);r.push({manifest:i,rootDir:o,source:"npm"});}catch(i){a$1.component("#pack-loader").warn("npm pack manifest invalid",{errorClass:i instanceof j?i.errorClass:"other"});}let s=x.join(t,Ht);if(h.existsSync(s)&&h.statSync(s).isDirectory()){let o=x.join(s,Y),i;if(h.existsSync(o))try{i=ue(s),r.push({manifest:i,rootDir:s,source:"local"});}catch(a){a$1.component("#pack-loader").warn("local pack manifest invalid",{errorClass:a instanceof j?a.errorClass:"other"});}let c=i?.id??"project";for(let a of ms(s))try{let l=ue(a);r.push({manifest:l,rootDir:a,source:"local",parentPackId:c});}catch(l){a$1.component("#pack-loader").warn("discipline sub-pack manifest invalid",{errorClass:l instanceof j?l.errorClass:"other"});}}return hs(t,r),r}function ps(t){let e=x.join(t,"package.json");if(!h.existsSync(e))return [];let r;try{r=JSON.parse(h.readFileSync(e,"utf8"));}catch{return []}let n=new Set([...Object.keys(r.dependencies||{}),...Object.keys(r.devDependencies||{}),...Object.keys(r.peerDependencies||{})]);if(n.size===0)return [];let s=x.join(t,"node_modules");if(!h.existsSync(s))return [];let o=[];for(let i of n){if(i===Ut)continue;let c=x.join(s,i,"package.json");if(!h.existsSync(c))continue;let a;try{a=JSON.parse(h.readFileSync(c,"utf8"));}catch{continue}let l=a.paradigm?.universityPack;if(typeof l!="string"||l.length===0)continue;let u=x.resolve(x.dirname(c),l);h.existsSync(x.join(u,Y))&&o.push(u);}return o}function ms(t){let e=[],r;try{r=h.readdirSync(t,{withFileTypes:!0});}catch{return e}for(let n of r){if(!n.isDirectory()||n.name.startsWith("."))continue;let s=x.join(t,n.name);h.existsSync(x.join(s,Y))&&e.push(s);}return e}function Qr(t,e){if(typeof t!="string"||t.length===0)throw new Error("resolveEntryAddress: address must be a non-empty string");let r=t.indexOf(":");if(r!==-1){let s=t.slice(0,r),o=t.slice(r+1);if(!s||!o)throw new Error("resolveEntryAddress: malformed <pack-id>:<entry-id> address");return {packId:s,entryId:o}}let n=t;if(e.candidatePacks&&e.entryExistsIn){let s=e.candidatePacks.filter(o=>e.entryExistsIn(o,n));if(s.length>1){let o=s.map(i=>`${i}:${n}`).join(", ");throw new Error(`resolveEntryAddress: bare entry id "${n}" is ambiguous across packs. Candidates: ${o}`)}if(s.length===1)return {packId:s[0],entryId:n}}return {packId:e.activePack,entryId:n}}function Gt(t){try{return h.statSync(x.join(t,"node_modules")).mtime.getTime()}catch{return}}function Xt(t){try{return h.statSync(x.join(t,Ht)).mtime.getTime()}catch{return}}function gs(t){let e=x.join(t,zt);if(!h.existsSync(e))return null;let r;try{r=JSON.parse(h.readFileSync(e,"utf8"));}catch{return null}if(r.version!==1||!Array.isArray(r.packs))return null;let n=Gt(t),s=Xt(t);return r.node_modules_mtime_ms!==n||r.local_university_mtime_ms!==s?null:r.packs.map(o=>({manifest:o.manifest,rootDir:o.rootDir,source:o.source,...o.parentPackId?{parentPackId:o.parentPackId}:{}}))}function hs(t,e){let r=x.join(t,zt);try{h.mkdirSync(x.dirname(r),{recursive:!0});let n={version:1,node_modules_mtime_ms:Gt(t),local_university_mtime_ms:Xt(t),packs:e.map(s=>({manifest:s.manifest,rootDir:s.rootDir,source:s.source,...s.parentPackId?{parentPackId:s.parentPackId}:{}}))};h.writeFileSync(r,JSON.stringify(n,null,2),"utf8");}catch{}}b$1();var ie=".paradigm/university",ne="content",Be="notes",Ee="policies",Te="quizzes",_e="paths",Bt="diplomas",qt="index.yaml",ys="config.yaml";function qe(t){let e=x.join(t,ie);if(h.existsSync(e))return e;try{let n=Wt(t).find(s=>s.manifest.tenant_kind==="first-party");if(n)return n.rootDir}catch{}return e}function Ve(t){if(!h.existsSync(t))return null;let e=x.join(t,Y);if(h.existsSync(e))try{return ue(t)}catch(n){a$1.component("#university-loader").warn("pack manifest invalid, using implicit manifest",{errorClass:n instanceof j?n.errorClass:"other"});}let r=x.basename(t)||"project";return {id:r,name:r,version:"0.0.0",schema_version:"1",tenant_kind:"project",description:"Implicit project pack (pack.yaml not present \u2014 v5 layout)",origin_hint:"authored",sections:Ge(void 0)}}function Ss(t,e,r){return e?{...t,...t.pack_id?{}:{pack_id:e.id},...t.discipline||!r?{}:{discipline:r}}:t}var Vt={name:"Project University",tagline:"Learn the codebase",institution:"Paradigm"},Yt={primary:"#6366f1",secondary:"#8b5cf6",accent:"#f59e0b",background:"#0f172a",surface:"#1e293b",text:"#f8fafc",textMuted:"#94a3b8",success:"#22c55e",error:"#ef4444",font:"Inter, system-ui, sans-serif"},Xe={branding:Vt,theme:Yt,content:{categories:[],defaultDifficulty:"beginner",requireApproval:false},diplomas:{includeGlobalPLSAT:true,customCertStyle:null}};function Ye(t){let e=x.join(t,ie,ys);if(!h.existsSync(e))return {...Xe};try{let r=h.readFileSync(e,"utf8"),n=N.load(r);return n?{branding:{...Vt,...n.branding||{}},theme:{...Yt,...n.theme||{}},content:{categories:n.content?.categories||[],defaultDifficulty:n.content?.defaultDifficulty||"beginner",requireApproval:n.content?.requireApproval??!1,defaultCategory:n.content?.defaultCategory},diplomas:{includeGlobalPLSAT:n.diplomas?.includeGlobalPLSAT??!0,customCertStyle:n.diplomas?.customCertStyle??null}}:{...Xe}}catch{return {...Xe}}}function ve(t){let e=x.join(t,ie,qt);if(!h.existsSync(e))return null;try{let r=h.readFileSync(e,"utf8");return N.load(r)}catch{return null}}function Jt(t){let e=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!e)return null;try{return {frontmatter:N.load(e[1]),body:e[2].trim()}}catch{return null}}function ws(t,e){return `---
107
- ${N.dump(t,{lineWidth:-1,noRefs:true,sortKeys:false})}---
108
-
109
- ${e}
110
- `}function so(t,e,r){let n=Ke(t,e,".md",r);if(!n)return null;try{let s=h.readFileSync(n,"utf8"),o=Jt(s);if(!o)return null;let i=o.frontmatter;return {frontmatter:_s(i),body:o.body}}catch{return null}}function ro(t,e,r,n){let s=e.type==="policy"?Ee:Be,o=n??qe(t),i=x.join(o,ne,s);h.mkdirSync(i,{recursive:true});let c=Ve(o),a=Ss(e,c),l=x.join(i,`${a.id}.md`),u=ws(a,r);return h.writeFileSync(l,u,"utf8"),l}function bs(t,e,r){let n=Ke(t,e,".yaml",r);if(!n)return null;try{let s=h.readFileSync(n,"utf8"),o=N.load(s);return !o||!o.id?null:vs(o)}catch{return null}}function oo(t,e,r){let n=r??qe(t),s=x.join(n,ne,Te);h.mkdirSync(s,{recursive:true});let o=Ve(n),i={...e,...e.pack_id||!o?{}:{pack_id:o.id}},c=x.join(s,`${i.id}.yaml`);return h.writeFileSync(c,N.dump(i,{lineWidth:-1,noRefs:true}),"utf8"),c}function Kt(t,e,r){let n=Ke(t,e,".yaml",r);if(!n)return null;try{let s=h.readFileSync(n,"utf8"),o=N.load(s);return !o||!o.id?null:o}catch{return null}}function io(t,e,r){let n=r??qe(t),s=x.join(n,ne,_e);h.mkdirSync(s,{recursive:true});let o=x.join(s,`${e.id}.yaml`);return h.writeFileSync(o,N.dump(e,{lineWidth:-1,noRefs:true}),"utf8"),o}function Qt(t,e){let r=x.join(t,ie,Bt);if(!h.existsSync(r))return [];let n=[];try{let s=h.readdirSync(r).filter(o=>o.endsWith(".yaml"));for(let o of s)try{let i=h.readFileSync(x.join(r,o),"utf8"),c=N.load(i);if(!c||!c.id||e?.student&&c.student!==e.student||e?.type&&c.type!==e.type)continue;n.push(c);}catch{}}catch{}return n.sort((s,o)=>o.earnedAt.localeCompare(s.earnedAt))}function ao(t,e){let r=ve(t);if(!r)return [];let n=[...r.entries];if(e.type&&(n=n.filter(o=>o.type===e.type)),e.tag&&(n=n.filter(o=>o.tags.some(i=>i.startsWith(e.tag)))),e.difficulty&&(n=n.filter(o=>o.difficulty===e.difficulty)),e.symbol&&(n=n.filter(o=>o.symbols.some(i=>i===e.symbol))),e.author&&(n=n.filter(o=>o.author===e.author)),e.query){let o=e.query.toLowerCase();n=n.filter(i=>i.title.toLowerCase().includes(o)||i.id.toLowerCase().includes(o)||i.tags.some(c=>c.toLowerCase().includes(o)));}if(e.category&&(n=n.filter(o=>o.category===e.category)),e.section&&(n=n.filter(o=>o.section===e.section)),e.track){let o=Ye(t),i=new Map;for(let c of o.content.categories)i.set(c.id,c.track||"core");n=n.filter(c=>(c.category&&i.get(c.category)||"core")===e.track);}let s=e.limit||20;return n.slice(0,s)}function Je(t){let e=x.join(t,ie),r=x.join(e,ne),n=[];for(let u of [Be,Ee]){let d=x.join(r,u);if(h.existsSync(d))try{for(let f of h.readdirSync(d).filter(g=>g.endsWith(".md")))try{let g=h.readFileSync(x.join(d,f),"utf8"),p=Jt(g);if(!p)continue;let m=p.frontmatter;n.push({id:m.id||f.replace(".md",""),title:m.title||f,type:m.type||(u===Ee?"policy":"note"),author:m.author||"unknown",created:m.created||"",updated:m.updated||"",tags:Array.isArray(m.tags)?m.tags:[],symbols:Array.isArray(m.symbols)?m.symbols:[],difficulty:m.difficulty||"beginner",file:`${ne}/${u}/${f}`,...m.category?{category:m.category}:{},...typeof m.section=="string"&&m.section?{section:m.section}:{},...typeof m.order=="number"&&Number.isFinite(m.order)?{order:m.order}:{}});}catch{}}catch{}}let s=x.join(r,Te);if(h.existsSync(s))try{for(let u of h.readdirSync(s).filter(d=>d.endsWith(".yaml")))try{let d=h.readFileSync(x.join(s,u),"utf8"),f=N.load(d);if(!f||!f.id)continue;n.push({id:f.id,title:f.title||u,type:"quiz",author:f.author||"unknown",created:f.created||"",updated:f.updated||"",tags:f.tags||[],symbols:f.symbols||[],difficulty:f.difficulty||"beginner",file:`${ne}/${Te}/${u}`,...f.category?{category:f.category}:{},...typeof f.section=="string"&&f.section?{section:f.section}:{},...typeof f.order=="number"&&Number.isFinite(f.order)?{order:f.order}:{}});}catch{}}catch{}let o=x.join(r,_e);if(h.existsSync(o))try{for(let u of h.readdirSync(o).filter(d=>d.endsWith(".yaml")))try{let d=h.readFileSync(x.join(o,u),"utf8"),f=N.load(d);if(!f||!f.id)continue;n.push({id:f.id,title:f.title||u,type:"path",author:f.author||"unknown",created:f.created||"",updated:f.updated||"",tags:f.tags||[],symbols:[],file:`${ne}/${_e}/${u}`,...f.category?{category:f.category}:{},...typeof f.section=="string"&&f.section?{section:f.section}:{},...typeof f.order=="number"&&Number.isFinite(f.order)?{order:f.order}:{}});}catch{}}catch{}let i=0,c=x.join(e,Bt);if(h.existsSync(c))try{i=h.readdirSync(c).filter(u=>u.endsWith(".yaml")).length;}catch{}let a={version:"1.0",generatedAt:new Date().toISOString(),totalContent:n.length,entries:n,diplomaCount:i};h.mkdirSync(e,{recursive:true});let l=x.join(e,qt);return h.writeFileSync(l,N.dump(a,{lineWidth:-1,noRefs:true}),"utf8"),a}function co(t,e){let r=ve(t)||Je(t),n=[],s=r.entries;e?.id&&(s=s.filter(l=>l.id===e.id));let o=null;e?.deep&&(o=Zt(t));let i=new Set(r.entries.map(l=>l.id));for(let l of s){if(l.title||n.push({contentId:l.id,severity:"error",check:"missing-title",message:"Content is missing a title",fix:"Add a title field to the content frontmatter"}),l.type==="quiz"&&xs(t,l.id,n),l.type==="path"&&Es(t,l.id,i,n),o&&l.symbols.length>0){Ye(t).content.categories.find(g=>g.id===l.category)?.validationStrictness==="relaxed";for(let g of l.symbols)o.has(g)||n.push({contentId:l.id,severity:"warning",check:"broken-symbol-ref",message:`Symbol "${g}" not found in scan-index`,fix:`Remove or update the symbol reference in ${l.id}`});}e?.deep&&l.symbols.length>0&&l.updated&&Rs(t,l,n);}Ts(t,r,n);let c=Qt(t);for(let l of c)if(l.total>0&&l.percentage!==Math.round(l.score/l.total*1e4)/100){let u=Math.round(l.score/l.total*1e4)/100;Math.abs(l.percentage-u)>.1&&n.push({contentId:l.id,severity:"warning",check:"diploma-score-mismatch",message:`Diploma percentage ${l.percentage} doesn't match score ${l.score}/${l.total} (expected ${u})`});}let a=ks(t,r);return {status:n.some(l=>l.severity==="error")?"errors":n.length>0?"warnings":"healthy",totalContent:r.totalContent,checked:s.length,issues:n,symbolCoverage:a}}function xs(t,e,r){let n=bs(t,e);if(!n){r.push({contentId:e,severity:"error",check:"unreadable-quiz",message:"Quiz file could not be parsed"});return}(!n.passThreshold||n.passThreshold<0||n.passThreshold>1)&&r.push({contentId:e,severity:"warning",check:"invalid-pass-threshold",message:`passThreshold should be between 0 and 1, got ${n.passThreshold}`,fix:"Set passThreshold to a value between 0.0 and 1.0"});for(let s of n.questions){if(!s.choices||typeof s.choices!="object"){r.push({contentId:e,severity:"error",check:"invalid-quiz-choices",message:`Question ${s.id} has no choices defined`});continue}(!s.correct||!(s.correct in s.choices))&&r.push({contentId:e,severity:"error",check:"invalid-quiz-answer",message:`Question ${s.id}: correct answer "${s.correct}" not found in choices [${Object.keys(s.choices).join(", ")}]`,fix:`Set correct to one of: ${Object.keys(s.choices).join(", ")}`});}}function Es(t,e,r,n){let s=Kt(t,e);if(!s){n.push({contentId:e,severity:"error",check:"unreadable-path",message:"Learning path file could not be parsed"});return}for(let o of s.steps)o.content.startsWith("plsat:")||r.has(o.content)||n.push({contentId:e,severity:"error",check:"broken-path-step",message:`Learning path step references "${o.content}" which doesn't exist`,fix:`Create content with id "${o.content}" or remove this step`});}function Ts(t,e,r){let n=x.join(t,ie),s=Ve(n);if(!s||!s.sections||s.sections.length===0)return;let o=new Set(s.sections.map(a=>a.id)),i=s.sections.find(a=>a.default===true);for(let a of e.entries)a.section&&!o.has(a.section)&&r.push({contentId:a.id,severity:"warning",check:"dangling-section-ref",message:`Entry references section "${a.section}" which is not declared in pack.yaml`,fix:`Add a section with id "${a.section}" to pack.yaml, or remove the section field`});let c=new Map;for(let a of s.sections)c.set(a.id,0);for(let a of e.entries)a.section&&o.has(a.section)?c.set(a.section,(c.get(a.section)||0)+1):!a.section&&i&&c.set(i.id,(c.get(i.id)||0)+1);for(let a of s.sections)(c.get(a.id)||0)===0&&r.push({contentId:a.id,severity:"warning",check:"empty-section",message:`Section "${a.id}" has zero entries`,fix:`Add at least one entry with section: "${a.id}", or remove the section from pack.yaml`});}function lo(t,e){let r=ve(t);if(!r)return [];let n=[];for(let s of r.entries)if(s.symbols.includes(e)){let o=en(t,s,e);n.push({id:s.id,title:s.title,type:s.type,stale:o});}return n}function uo(t,e){let r=ve(t);if(!r)return {paths:[],suggestedContent:[],extracurricular:[],diplomaCount:0,totalContent:0};let n=Ye(t),s=new Set;for(let f of n.content.categories)f.excludeFromOnboarding&&s.add(f.id);let o=r.entries.filter(f=>!f.category||!s.has(f.category)),i=r.entries.filter(f=>f.category&&s.has(f.category)),c=o.filter(f=>f.type==="path"),a=e?Qt(t,{student:e}):[],l=new Set(a.map(f=>f.source)),u=c.map(f=>{let g=Kt(t,f.id);return {id:f.id,title:f.title,steps:g?.steps.length||0,completed:l.has(f.id)}}),d=o.filter(f=>f.type!=="path"&&(f.difficulty==="beginner"||f.tags.includes("onboarding"))).slice(0,10);return {paths:u,suggestedContent:d,extracurricular:i,diplomaCount:a.length,totalContent:r.totalContent}}function Ke(t,e,r,n){let s=n??x.join(t,ie),o=x.join(s,ne);for(let i of [Be,Ee,Te,_e]){let c=x.join(o,i,`${e}${r}`);if(h.existsSync(c))return c}return null}function _s(t){return {id:t.id||"",title:t.title||"",type:t.type||"note",author:t.author||"unknown",created:t.created||"",updated:t.updated||"",tags:Array.isArray(t.tags)?t.tags:[],symbols:Array.isArray(t.symbols)?t.symbols:[],difficulty:t.difficulty||"beginner",estimatedMinutes:t.estimatedMinutes,prerequisites:Array.isArray(t.prerequisites)?t.prerequisites:[],...t.category?{category:t.category}:{},...t.origin?{origin:t.origin}:{},...t.source?{source:t.source}:{},...t.pack_id?{pack_id:t.pack_id}:{},...t.discipline?{discipline:t.discipline}:{},...t.section?{section:t.section}:{},...typeof t.order=="number"?{order:t.order}:{}}}function vs(t){return {...t,tags:t.tags||[],symbols:t.symbols||[],difficulty:t.difficulty||"beginner",passThreshold:t.passThreshold??.7,questions:t.questions||[]}}function Zt(t){let e=new Set,r=x.join(t,".paradigm","scan-index.json");if(!h.existsSync(r))return e;try{let n=h.readFileSync(r,"utf8"),s=JSON.parse(n);if(s.symbols&&Array.isArray(s.symbols))for(let o of s.symbols)o.symbol&&e.add(o.symbol);}catch{}return e}function ks(t,e){let r=Zt(t),n=new Set;for(let o of e.entries)for(let i of o.symbols)r.has(i)&&n.add(i);let s=r.size;return {totalSymbols:s,coveredByContent:n.size,percentage:s>0?Math.round(n.size/s*100):0}}function en(t,e,r){if(!e.updated)return false;let n=new Date(e.updated).getTime();if(isNaN(n))return false;let s=x.join(t,".paradigm","scan-index.json");if(!h.existsSync(s))return false;try{let o=h.readFileSync(s,"utf8"),i=JSON.parse(o);if(i.symbols&&Array.isArray(i.symbols)){for(let c of i.symbols)if(c.symbol===r&&c.filePath){let a=x.join(t,c.filePath);if(h.existsSync(a)&&h.statSync(a).mtime.getTime()>n)return !0}}}catch{}return false}function Rs(t,e,r){for(let n of e.symbols)if(en(t,e,n)){r.push({contentId:e.id,severity:"warning",check:"stale-content",message:`Content may be stale: symbol "${n}" was updated after content was last modified`,fix:`Review and update ${e.id} to reflect changes to ${n}`});break}}var tn=new Set(["duplicate-key-detected"]);function Is(t){let e=t.trim();if(e.includes("/")||e.includes("\\")){let r=e.split(/[/\\]/);e=r[r.length-1]||"unknown";}return e.length>40&&(e=e.slice(0,40)),e||"unknown"}var ke=class{transforms=new Map;record(e,r,n=1){let s=Is(r),o=`${e}::${s}`,i=this.transforms.get(o);i?i.count+=n:this.transforms.set(o,{kind:e,surface:s,count:n});}report(){let e=Array.from(this.transforms.values()).sort((n,s)=>n.kind!==s.kind?n.kind.localeCompare(s.kind):n.surface.localeCompare(s.surface)),r=e.filter(n=>tn.has(n.kind)).reduce((n,s)=>n+s.count,0);return {reindex_ts:new Date().toISOString(),transformations:e,lossy_count:r,strict_mode:de()}}hasLossy(){for(let e of this.transforms.values())if(tn.has(e.kind))return true;return false}totalCount(){let e=0;for(let r of this.transforms.values())e+=r.count;return e}};b$1();var Ps={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},Cs={features:["src/features/","features/","app/","src/app/","src/modules/","modules/"],components:["src/components/","components/","src/lib/","lib/","src/ui/","ui/"],gates:["middleware/","src/middleware/","auth/","src/auth/","guards/","src/guards/"],flows:["flows/","src/flows/","workflows/","src/workflows/","sagas/","src/sagas/"],integrations:["integrations/","src/integrations/","external/","src/external/","vendors/"],signals:["events/","src/events/","handlers/","src/handlers/"],state:["stores/","src/stores/","state/","src/state/","reducers/","src/reducers/"]},As={config:[".paradigm/config.yaml","package.json","tsconfig.json",".env.example"],entry:["src/index.ts","src/index.tsx","src/main.ts","src/main.tsx","index.ts","main.ts","src/app.ts","src/app.tsx"],types:["src/types/","types/","src/types.ts","types.ts"]},Qe={always:["node_modules/","dist/","build/",".git/",".next/",".nuxt/",".cache/","*.lock","*.log"],unless_testing:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","__tests__/","test/","tests/"],unless_docs:["docs/","*.md","README*","CHANGELOG*"]};function Co(){return [{name:"paradigm_reindex",description:"Rebuild scan-index.json, navigator.yaml, and flow-index.json from .purpose files. Call after modifying paradigm files or at the end of a work session to ensure static index files are fresh. Returns counts of indexed symbols, files processed, and any errors. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:false,destructiveHint:true},aliases:["rebuild","refresh","rescan","regenerate index","update index"]}]}async function Ao(t,e,r,n){if(t!=="paradigm_reindex")return {handled:false,text:""};try{let s=await Ls(r.rootDir,r);await n(),pt.clear(),gt();let o=(s.integrityReport?.brokenReferences?.length||0)+(s.integrityReport?.duplicateSymbols?.length||0)+(s.componentAnchorIssues||0)+(s.crossFileIssues||0),i={success:!0,symbolCount:s.symbolCount,breakdown:s.breakdown,flowCount:s.flowCount,filesWritten:s.filesWritten.length,...s.aspectGraphStats?{aspects:s.aspectGraphStats.aspects,loreLinks:s.aspectGraphStats.loreLinks}:{},...s.protocolHealth?{protocols:s.protocolHealth.total,staleProtocols:s.protocolHealth.stale}:{},...o>0?{issues:o}:{}};s.consistency&&(i.consistency=s.consistency);let c=JSON.stringify(i,null,2);return Ae(c.length,t),{handled:!0,text:c}}catch(s){let o=JSON.stringify({error:s.message},null,2);return Ae(o.length,t),{handled:true,text:o}}}async function Ls(t,e){let r=[],n=new ke,s;e?s=e.aggregation:s=await i(t);let o=e?.projectName||x.basename(t),i$1=x.join(t,".paradigm");h.existsSync(i$1)||h.mkdirSync(i$1,{recursive:true}),js(t,n),Os(s.purposeFiles,n);let c=Pe({symbols:s.symbols,purposeFiles:s.purposeFiles,portalFiles:s.portalFiles},{projectName:o}),a=x.join(i$1,"scan-index.json");h.writeFileSync(a,Ce(c),"utf8"),r.push(".paradigm/scan-index.json");let l=Fs(t,s),u=x.join(i$1,"navigator.yaml");h.writeFileSync(u,N.dump(l,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),r.push(".paradigm/navigator.yaml");let d=Hs(t,s.purposeFiles),f$1=0;if(d&&Object.keys(d.flows).length>0){let S=x.join(i$1,"flow-index.json");h.writeFileSync(S,JSON.stringify(d,null,2),"utf8"),r.push(".paradigm/flow-index.json"),f$1=Object.keys(d.flows).length;}let g;try{let S=await kt(t);It(S,s.symbols,t);let I=await Ct(S,t),K=await At(S,t),Q=S.exec("SELECT COUNT(*) FROM aspects")[0]?.values[0]?.[0]??0,ae=S.exec("SELECT COUNT(*) FROM anchors")[0]?.values[0]?.[0]??0,he=S.exec("SELECT COUNT(*) FROM edges")[0]?.values[0]?.[0]??0;Rt(S,t),r.push(".paradigm/aspect-graph.db"),g={aspects:Q,anchors:ae,edges:he,loreLinks:I};}catch{}let p=0;try{let S=await ge(t);p=Object.keys(S.personas).length,p>0&&r.push(".paradigm/personas/index.yaml");}catch{}let m;try{let S=await Ot(t);S.health.total>0&&(m=S.health,r.push(".paradigm/protocols/index.yaml"));}catch{}let y;try{let S=x.join(t,".paradigm","university");if(h.existsSync(S)){let I=Je(t);(I.totalContent>0||I.diplomaCount>0)&&(y={totalContent:I.totalContent,diplomaCount:I.diplomaCount},r.push(".paradigm/university/index.yaml"));}}catch{}let w;try{w=a$2(s,t);}catch{}let P;try{let S=b$4(s.symbols,t),I=S.missing+S.outOfBounds;I>0&&(P=I);}catch{}let $;try{$=c$2(s.purposeFiles,t);}catch{}let J;try{let S=[];for(let I of s.purposeFiles){let K=a$3(I);K.data&&S.push({filePath:I,data:K.data});}if(S.length>0){let K=f(S).issues.length;K>0&&(J=K);}}catch{}let se={};for(let S of s.symbols)se[S.type]=(se[S.type]||0)+1;let _={};for(let S of s.symbols)S.type==="component"&&S.componentType&&(_[S.componentType]=(_[S.componentType]||0)+1);let E=n.report();try{let S=x.join(i$1,"manifest.consistency.json");h.writeFileSync(S,JSON.stringify(E,null,2),"utf-8"),r.push(".paradigm/manifest.consistency.json");}catch{a$1.component("#reindex").warn("failed to write consistency manifest",{stage:"manifest-write"});}if(de()&&n.hasLossy())throw new Error(`reindex aborted: ${E.lossy_count} lossy transformation(s) detected under PARADIGM_STRICT=1. See .paradigm/manifest.consistency.json.`);return {action:"reindex",filesWritten:r,symbolCount:s.symbols.length,breakdown:se,flowCount:f$1,aspectGraphStats:g,personaCount:p,protocolHealth:m,consistency:E,...Object.keys(_).length>0?{componentTypeBreakdown:_}:{},...y?{universityStats:y}:{},...w?{integrityReport:w}:{},...P!==void 0?{componentAnchorIssues:P}:{},...$?{purposeHealth:$}:{},...J!==void 0?{crossFileIssues:J}:{}}}function js(t,e){let r=x.join(t,"portal.yaml");if(!h.existsSync(r))return;let n;try{n=h.readFileSync(r,"utf-8");}catch{return}try{N.load(n);}catch(a){(a?.reason?.toLowerCase()||"").includes("duplicate")&&e.record("duplicate-key-detected","portal.yaml");return}let s;try{s=N.load(n,{schema:N.FAILSAFE_SCHEMA});}catch{return}if(!s||typeof s!="object")return;let o=s,i=o.gates;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=0;for(let l of Object.keys(i))l.startsWith("^")&&a++;a>0&&e.record("prefix-stripped","portal.yaml",a);}else Array.isArray(i)&&i.length>0&&e.record("array-coerced","portal.yaml");let c=o.routes;Array.isArray(c)&&c.length>0&&e.record("array-coerced","portal.yaml"),o.version||e.record("default-applied","portal.yaml");}function Os(t,e){for(let r of t){let n;try{n=h.readFileSync(r,"utf-8");}catch{continue}try{N.load(n);}catch(u){(u?.reason?.toLowerCase()||"").includes("duplicate")&&e.record("duplicate-key-detected","purpose.yaml");continue}let s;try{s=N.load(n,{schema:N.FAILSAFE_SCHEMA});}catch{continue}if(!s||typeof s!="object")continue;let o=s,i=["components","features","gates","signals","aspects","states"],c=0;for(let u of i)Array.isArray(o[u])&&c++;c>0&&e.record("array-coerced","purpose.yaml",c);let a=(u,d)=>{if(!u||typeof u!="object"||Array.isArray(u))return 0;let f=0;for(let g of Object.keys(u))g.startsWith(d)&&f++;return f},l=a(o.gates,"^")+a(o.signals,"!")+a(o.aspects,"~")+a(o.components,"#")+a(o.features,"#");l>0&&e.record("prefix-stripped","purpose.yaml",l);}}function Fs(t,e){let r={};for(let n of e.symbols)if(n.type==="component"&&n.componentType){let s=n.componentType;r[s]||(r[s]=[]),r[s].push(n.symbol);}return {version:"1.0",generated:new Date().toISOString(),structure:Ns(t),key_files:$s(t),skip_patterns:Ms(t),symbols:Us(e.symbols,e.purposeFiles),...Object.keys(r).length>0?{symbolsByComponentType:r}:{}}}function Ns(t){let e={};for(let[r,n]of Object.entries(Cs)){let s=n.filter(o=>h.existsSync(x.join(t,o)));if(s.length>0){let o=Object.values(Ps).find(i=>i.category===r);e[r]={paths:s,symbol:o?.prefix||"@"};}}return e}function $s(t){let e={};for(let[r,n]of Object.entries(As)){let s=n.filter(o=>h.existsSync(x.join(t,o)));s.length>0&&(e[r]=s);}return e.config||(e.config=[]),e.entry||(e.entry=[]),e.types||(e.types=[]),e}function Ms(t){let e={always:[...Qe.always],unless_testing:[...Qe.unless_testing],unless_docs:[...Qe.unless_docs]},r=x.join(t,".gitignore");if(h.existsSync(r))try{let s=h.readFileSync(r,"utf8").split(`
111
- `).map(o=>o.trim()).filter(o=>o&&!o.startsWith("#")).filter(o=>o.endsWith("/")||o.includes("*")||["node_modules","dist","build",".cache"].some(i=>o.includes(i))).slice(0,20);for(let o of s)e.always.includes(o)||e.always.push(o);}catch{}return e}function Ds(t){switch(t){case "feature":return "@";case "component":return "#";case "gate":return "^";case "flow":return "$";case "integration":return "&";case "signal":return "!";case "state":return "%";case "idea":return "?";case "deprecated":return "~";case "aspect":return "~";default:return "@"}}function Us(t,e,r){let n={};for(let s of t){let i=`${Ds(s.type)}${s.id}`;if(s.filePath)n[i]=s.filePath;else {let c=e.find(a=>x.dirname(a).toLowerCase().includes(s.id.toLowerCase()));c&&(n[i]=x.dirname(c)+"/");}}return n}function Hs(t,e){let r={},n={};for(let s of e)try{let o=h.readFileSync(s,"utf8"),i=N.load(o);if(!i?.flows)continue;if(Array.isArray(i.flows))for(let c of i.flows){let a=c;if(!a.name)continue;let l=`$${a.name}`,u=nn(a.steps);u.length>0&&(r[l]={id:l,description:a.description||"",steps:u,definedIn:x.relative(t,s)},sn(l,u,n));}else for(let[c,a]of Object.entries(i.flows)){let l=c.startsWith("$")?c:`$${c}`,u=nn(a.steps);u.length>0&&(r[l]={id:l,description:a.description||"",trigger:a.trigger,steps:u,validation:a.validation,definedIn:x.relative(t,s)},sn(l,u,n));}}catch{}return Object.keys(r).length===0?null:{version:"1.0",generatedAt:new Date().toISOString(),flows:r,symbolToFlows:n}}function nn(t){if(!t||!Array.isArray(t))return [];let e=[];for(let r=0;r<t.length;r++){let n=t[r];if(typeof n=="object"&&n!==null){let s=n,o=s.action||s.description||s.component||"";o&&e.push({id:s.id||`step-${r+1}`,action:o,symbol:s.symbol||s.component,expect:s.expect});}}return e}function sn(t,e,r){for(let n of e)n.symbol&&(r[n.symbol]||(r[n.symbol]=[]),r[n.symbol].includes(t)||r[n.symbol].push(t));}export{Sr as $,so as A,ro as B,bs as C,oo as D,Kt as E,io as F,ao as G,Je as H,co as I,lo as J,uo as K,De as L,ss as M,jr as N,Or as O,Fr as P,Nr as Q,rs as R,$r as S,kt as T,Rt as U,fr as V,pr as W,mr as X,gr as Y,hr as Z,yr as _,Ae as a,wr as aa,Ks as b,Er as ba,Qs as c,Co as ca,Zs as d,Ao as da,er as e,Ls as ea,tr as f,mt as g,pt as h,pe as i,me as j,_r as k,Lt as l,vr as m,kr as n,Rr as o,Ir as p,Pr as q,Cr as r,Ar as s,de as t,$t as u,Wt as v,Qr as w,qe as x,Ve as y,Ye as z};
@@ -1,11 +0,0 @@
1
- #!/usr/bin/env node
2
- import {c,a as a$1}from'./chunk-YNDPSWOE.js';import {e as e$1}from'./chunk-VIG5LSGZ.js';import {a}from'./chunk-LKAT7IAK.js';import*as e from'fs';import*as r from'path';import*as w from'js-yaml';import l from'chalk';async function rs(P={}){let p=P.rootDir||process.cwd(),s=[],S=P.quiet,L=P.context;S||(console.log(l.blue(`
3
- \u{1FA7A} Paradigm Doctor
4
- `)),console.log(L?l.gray(`Running context audit checks...
5
- `):l.gray(`Checking Paradigm setup...
6
- `)));let N=a.command("doctor").start("Running health checks");if(!L){let E=function(t){let a=[];try{let n=e.readdirSync(t,{withFileTypes:!0});for(let i of n){if(i.name==="node_modules"||i.name==="dist"||i.name===".git")continue;let d=r.join(t,i.name);i.isDirectory()?a.push(...E(d)):i.name===".purpose"&&a.push(d);}}catch{}return a};let o=r.join(p,".paradigm");if(e.existsSync(o))if(e.statSync(o).isFile())s.push({name:".paradigm",status:"warn",message:"Legacy file format (should be directory)",fix:"paradigm upgrade --all"});else {s.push({name:".paradigm/",status:"ok",message:"Directory exists"});let a=r.join(o,"config.yaml");if(e.existsSync(a))try{let u=e.readFileSync(a,"utf8");e$1(u),s.push({name:".paradigm/config.yaml",status:"ok",message:"Valid YAML"});}catch(u){s.push({name:".paradigm/config.yaml",status:"error",message:`Invalid YAML: ${u.message}`,fix:"Check YAML syntax"});}else s.push({name:".paradigm/config.yaml",status:"missing",message:"Config file not found",fix:"paradigm init --force"});let n=["logger.md","probe.md","symbols.md"],i=r.join(o,"specs");if(e.existsSync(i))for(let u of n){let x=r.join(i,u);e.existsSync(x)?s.push({name:`.paradigm/specs/${u}`,status:"ok",message:"Present"}):s.push({name:`.paradigm/specs/${u}`,status:"missing",message:"Spec file not found",fix:"paradigm upgrade --all"});}else s.push({name:".paradigm/specs/",status:"missing",message:"Specs directory not found",fix:"paradigm upgrade --all"});let d=r.join(o,"docs");e.existsSync(d)?s.push({name:".paradigm/docs/",status:"ok",message:"Directory exists"}):s.push({name:".paradigm/docs/",status:"missing",message:"Docs directory not found",fix:"paradigm upgrade --all"});let h=r.join(o,"prompts");e.existsSync(h)?s.push({name:".paradigm/prompts/",status:"ok",message:"Directory exists"}):s.push({name:".paradigm/prompts/",status:"missing",message:"Prompts directory not found",fix:"paradigm upgrade --all"});let g=["specs","implementation-guides","prompts","decisions"],f=[];for(let u of g){let x=r.join(o,u);if(e.existsSync(x)&&e.statSync(x).isDirectory()){let k=r.join(x,".index.yaml");e.existsSync(k)||f.push(`.paradigm/${u}/`);}}f.length>0?s.push({name:"Docs-class indexes",status:"warn",message:`${f.length} director${f.length===1?"y":"ies"} missing .index.yaml: ${f.join(", ")}`,fix:"paradigm docs scaffold"}):s.push({name:"Docs-class indexes",status:"ok",message:"All docs-class directories have .index.yaml"});let y=r.join(o,"scan-index.json"),F=r.join(p,".paradigm-scan-index.json");if(e.existsSync(y)){let u=e.statSync(y),x=Date.now()-u.mtime.getTime(),k=Math.floor(x/(1e3*60*60));k>24?s.push({name:".paradigm/scan-index.json",status:"warn",message:`Stale (${k} hours old)`,fix:"paradigm index"}):s.push({name:".paradigm/scan-index.json",status:"ok",message:k>0?`${k} hours old`:"Fresh"});}else e.existsSync(F)?s.push({name:"scan-index",status:"warn",message:"Using legacy location",fix:"paradigm index"}):s.push({name:".paradigm/scan-index.json",status:"missing",message:"Not generated",fix:"paradigm index"});}else s.push({name:".paradigm/",status:"missing",message:"Not initialized",fix:"paradigm init"});let m=c(p);if(m.detected){let t=a$1(m.detected);if(t){let a=r.join(p,t.outputPath);e.existsSync(a)?s.push({name:t.outputPath,status:"ok",message:`Present (${m.detected})`}):s.push({name:t.outputPath,status:"missing",message:`Not generated for ${m.detected}`,fix:"paradigm sync"});}}let c$1=r.join(p,".premise");e.existsSync(c$1)?s.push({name:".premise",status:"ok",message:"Present"}):s.push({name:".premise",status:"missing",message:"Not found (optional)"});let v=r.join(p,".purpose");e.existsSync(v)?s.push({name:".purpose",status:"ok",message:"Present"}):s.push({name:".purpose",status:"warn",message:"Root .purpose not found",fix:"paradigm init"});let D=r.join(p,".paradigm","config.yaml");if(e.existsSync(D))try{let t=e.readFileSync(D,"utf8"),n=w.load(t)?.["purpose-required"];if(n&&Array.isArray(n)){let i=[];for(let d of n){if(!d.pattern)continue;let{glob:h}=await import('glob'),g=await h(d.pattern,{cwd:p,nodir:!1});for(let f of g){let y=r.join(p,f);try{e.statSync(y).isDirectory()&&!e.existsSync(r.join(y,".purpose"))&&i.push(f);}catch{}}}i.length>0?s.push({name:"Purpose-required",status:"warn",message:`${i.length} director${i.length===1?"y":"ies"} missing .purpose: ${i.join(", ")}`,fix:"Create .purpose files with paradigm_purpose_init + paradigm_purpose_add_component"}):s.push({name:"Purpose-required",status:"ok",message:"All required directories have .purpose files"});}}catch{}let q=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi,R=0,Y=E(p);for(let t of Y)try{let n=e.readFileSync(t,"utf8").match(q);n&&(R+=n.length);}catch{}R>0?s.push({name:"Clarification markers",status:"warn",message:`${R} [NEEDS CLARIFICATION] marker${R>1?"s":""} found in .purpose files`,fix:"Resolve open clarification markers before shipping"}):Y.length>0&&s.push({name:"Clarification markers",status:"ok",message:"No unresolved markers"});let I=r.join(p,"portal.yaml");if(e.existsSync(I))try{let t=e.readFileSync(I,"utf8"),a=w.load(t);if(a?.version&&a?.gates){let n=Object.keys(a.gates||{}).length,i=Object.keys(a.routes||{}).length;s.push({name:"portal.yaml",status:"ok",message:`Valid (${n} gates, ${i} routes)`});}else s.push({name:"portal.yaml",status:"warn",message:"Missing version or gates section",fix:'Add version: "1.0" and gates: {} to portal.yaml'});}catch(t){s.push({name:"portal.yaml",status:"error",message:`Invalid YAML: ${t.message}`,fix:"Check YAML syntax in portal.yaml"});}if(e.existsSync(I))try{let{checkPortalCompliance:t,getComplianceSummary:a}=await import('./portal-compliance-JONQ4SOP.js'),n=await t(p),i=a(n);s.push({name:"Portal compliance",status:i.status,message:i.message,fix:i.status!=="ok"?"paradigm portal check":void 0});}catch{}{let t=r.join(p,".paradigm","scan-index.json"),a=r.join(p,".paradigm","roster.yaml");try{if(e.existsSync(t)){let n=e.readFileSync(t,"utf8"),i=JSON.parse(n),d=Object.keys(i.components??{}).length,h=Object.keys(i.aspects??{}).length;if(d>0){let g=!1;if(e.existsSync(a))try{let y=w.load(e.readFileSync(a,"utf8"));g=Array.isArray(y?.active)&&y.active.includes("compliance");}catch{}let f=`${d}:${h} components:aspects`;g?s.push({name:"Aspect coverage",status:"ok",message:`${f} (claimant: rune)`}):h===0?s.push({name:"Aspect coverage",status:"info",message:`${f} ${l.dim("(no aspects defined)")}`}):s.push({name:"Aspect coverage",status:"info",message:`${f} ${l.dim("(no claimant active)")}`});}}}catch{}}let U=r.join(p,".paradigm","flows.yaml");if(e.existsSync(U))try{let t=e.readFileSync(U,"utf8"),a=w.load(t);if(a?.version&&a?.flows){let n=Object.keys(a.flows||{}).length,i=Object.entries(a.flows||{}).filter(([,d])=>!d?.steps||(d.steps?.length??0)===0);i.length>0?s.push({name:".paradigm/flows.yaml",status:"warn",message:`${n} flows defined, ${i.length} have no steps`,fix:"Add steps to empty flow definitions"}):s.push({name:".paradigm/flows.yaml",status:"ok",message:`Valid (${n} flows)`});}else s.push({name:".paradigm/flows.yaml",status:"warn",message:"Missing version or flows section",fix:'Ensure flows.yaml has version: "1.0" and flows: {}'});}catch(t){s.push({name:".paradigm/flows.yaml",status:"error",message:`Invalid YAML: ${t.message}`,fix:"Check YAML syntax in flows.yaml"});}let H=r.join(p,".paradigm","lore");if(e.existsSync(H))try{let t=e.readdirSync(H).filter(a=>a.endsWith(".yaml"));t.length===0?s.push({name:"Lore entries",status:"warn",message:"Lore directory exists but no entries found",fix:"Record a lore entry: paradigm lore record"}):s.push({name:"Lore entries",status:"ok",message:`${t.length} lore file${t.length>1?"s":""}`});}catch{s.push({name:"Lore entries",status:"warn",message:"Could not read lore directory"});}let G=r.join(p,".paradigm","university");if(e.existsSync(G))try{let t=r.join(G,"content"),a=0,n=0;if(e.existsSync(t))for(let i of ["notes","policies","quizzes","paths"]){let d=r.join(t,i);e.existsSync(d)&&(a+=e.readdirSync(d).filter(h=>h.endsWith(".md")||h.endsWith(".yaml")).length);}if(a===0)s.push({name:"University content",status:"warn",message:"University directory exists but no content found",fix:'Add content: paradigm university add note --title "Getting Started"'});else {let i=r.join(t,"quizzes");if(e.existsSync(i))for(let h of e.readdirSync(i).filter(g=>g.endsWith(".yaml")))try{let g=w.load(e.readFileSync(r.join(i,h),"utf8"));if(g?.questions)for(let f of g.questions)f.choices&&f.correct&&!(f.correct in f.choices)&&n++;}catch{}let d=r.join(t,"paths");if(e.existsSync(d))for(let h of e.readdirSync(d).filter(g=>g.endsWith(".yaml")))try{let g=w.load(e.readFileSync(r.join(d,h),"utf8"));if(g?.steps){for(let f of g.steps)if(f.content&&!f.content.startsWith("plsat:")){let y=!1;for(let F of ["notes","policies","quizzes","paths"]){let u=r.join(t,F);if(e.existsSync(u)&&e.readdirSync(u).some(k=>k.startsWith(f.content))){y=!0;break}}y||n++;}}}catch{}n>0?s.push({name:"University content",status:"warn",message:`${a} items, ${n} issue${n>1?"s":""}`,fix:"Run: paradigm university validate --deep"}):s.push({name:"University content",status:"ok",message:`${a} content item${a>1?"s":""}`});}}catch{s.push({name:"University content",status:"warn",message:"Could not read university directory"});}let _=r.join(p,".claude","hooks.json"),ss=r.join(p,"plugins","paradigm","hooks.json");if(e.existsSync(_)){let t=e.statSync(_),a=Date.now()-t.mtime.getTime(),n=Math.floor(a/(1e3*60*60*24));n>30?s.push({name:"Claude Code hooks",status:"warn",message:`Hooks are ${n} days old \u2014 may be outdated`,fix:"paradigm hooks install"}):s.push({name:"Claude Code hooks",status:"ok",message:n>0?`${n} days old`:"Fresh"});}else e.existsSync(ss)?s.push({name:"Claude Code hooks",status:"ok",message:"Using plugin hooks"}):s.push({name:"Claude Code hooks",status:"missing",message:"No hooks installed",fix:"paradigm hooks install"});let V=r.join(p,".paradigm","habits.yaml");if(e.existsSync(V))try{let t=e.readFileSync(V,"utf8"),a=w.load(t);if(a?.version&&Array.isArray(a?.habits)){let n=a.habits.filter(i=>i.enabled!==!1).length;s.push({name:"Habits config",status:"ok",message:`Valid (${n}/${a.habits.length} enabled)`});}else s.push({name:"Habits config",status:"warn",message:"Missing version or habits array",fix:"Regenerate habits.yaml with paradigm habits init"});}catch(t){s.push({name:"Habits config",status:"error",message:`Invalid YAML: ${t.message}`,fix:"Check YAML syntax in habits.yaml"});}let J=r.join(p,"AGENTS.md");if(e.existsSync(J)){let t=e.statSync(J),a=Date.now()-t.mtime.getTime(),n=Math.floor(a/(1e3*60*60*24));n>60?s.push({name:"AGENTS.md",status:"warn",message:`${n} days since last update \u2014 may be stale`,fix:"paradigm sync"}):s.push({name:"AGENTS.md",status:"ok",message:n>0?`Updated ${n} days ago`:"Fresh"});}}let O=0,T=0,$=0;for(let o of s){let m,c;switch(o.status){case "ok":m="\u2713",c=l.green;break;case "warn":m="\u26A0",c=l.yellow,T++;break;case "error":m="\u2717",c=l.red,O++;break;case "missing":m="\u25CB",c=l.gray,$++;break;case "info":m="\u2802",c=l.gray;break}if(!S){let v=o.name.padEnd(30);console.log(` ${c(m)} ${v} ${c(o.message)}`),o.fix&&console.log(l.gray(` \u2514\u2500 Fix: ${o.fix}`));}}let{runContextAudit:Z}=await import('./context-audit-JVCA6GSV.js'),M=await Z(p,{quiet:S}),W=0,z=0,b=0;!S&&M.length>0&&(console.log(""),console.log(l.blue(" Context Audit")),console.log(l.gray(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")));for(let o of M){let m,c;switch(o.status){case "ok":m="\u2713",c=l.green;break;case "warn":m="\u26A0",c=l.yellow,z++;break;case "error":m="\u2717",c=l.red,W++;break;case "advisory":m="\u2139",c=l.cyan,b++;break}if(!S){let v=o.check.padEnd(30);if(console.log(` ${c(m)} ${v} ${c(o.message)}`),o.details&&o.details.length>0){let D=o.details.slice(0,5);for(let q of D)console.log(l.gray(` \u2502 ${q}`));o.details.length>5&&console.log(l.gray(` \u2502 ... and ${o.details.length-5} more`));}o.fix&&console.log(l.gray(` \u2514\u2500 Fix: ${o.fix}`));}}let C=O+W,j=T+z,A=C+j+$===0;if(!S)if(console.log(""),A)console.log(l.green(`\u2728 All checks passed!
7
- `));else {let o=[];C>0&&o.push(l.red(`${C} error${C>1?"s":""}`)),j>0&&o.push(l.yellow(`${j} warning${j>1?"s":""}`)),$>0&&o.push(l.gray(`${$} missing`)),b>0&&o.push(l.cyan(`${b} advisor${b>1?"ies":"y"}`)),console.log(`${o.join(", ")} found.
8
- `),console.log(l.gray("Run the suggested commands to fix issues.")),console.log(l.gray(`Troubleshooting guide: .paradigm/docs/troubleshooting.md
9
- `));}if(!S&&P.explain&&!A)try{let{narrateAllGaps:o}=await import('./gap-narrator-NTXLUI7I.js'),m=[];for(let c of s)c.status!=="ok"&&(c.name===".purpose"||c.name.startsWith("Purpose-required")?m.push({type:"missing-purpose",target:c.name,severity:"improvement"}):c.name===".paradigm/scan-index.json"&&c.status==="warn"?m.push({type:"index-stale",target:c.name,severity:"improvement"}):c.name==="Portal compliance"?m.push({type:"portal-mismatch",target:c.name,severity:c.status==="error"?"blocking":"improvement"}):c.name==="Clarification markers"&&m.push({type:"missing-description",target:c.name,severity:"improvement"}));if(m.length>0){let c=o(m);console.log(l.blue(`
10
- Gap Narrations (--explain)
11
- `)),console.log(l.gray(c.narrative)),console.log("");}}catch{}A?N.success("All health checks passed",{total:s.length+M.length}):N.error("Health checks found issues",{errors:C,warnings:j,missing:$,advisories:b});try{let{captureSnapshot:o}=await import('./metrics-UESGUHTA.js');o(p);}catch{}return A}export{rs as a};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export{a as doctorCommand}from'./chunk-XQLO5URP.js';import'./chunk-YNDPSWOE.js';import'./chunk-VIG5LSGZ.js';import'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';
@@ -1,12 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a as a$1,j}from'./chunk-ERO4MJSH.js';import {d,b,a,c}from'./chunk-P344HV6Z.js';import'./chunk-5TAVYPOV.js';import t from'chalk';async function w(o){let s=process.cwd();if(!d(o)){let n=b(s);if(o.json){console.log(JSON.stringify({packs:n},null,2));return}if(n.length===0){console.log(t.yellow(`
3
- No content packs discovered.`)),console.log(t.gray(` Scaffold one with: paradigm university init
4
- `));return}console.log(t.blue(`
5
- Content packs (${n.length})
6
- `));for(let e of n){let r=e.tenantKind==="first-party"?t.cyan("first-party"):e.tenantKind==="project"?t.green("project"):t.yellow("external"),a$1=e.disciplines&&e.disciplines.length>0?t.gray(` [${e.disciplines.join(", ")}]`):"",d=a(e.packRoot),k=d.length>0?t.gray(` (${d.length} section${d.length===1?"":"s"})`):"";console.log(` ${t.white(e.id.padEnd(28))} ${r} ${e.entryCount} entries${k}${a$1}`),e.name&&e.name!==e.id&&console.log(t.gray(` ${e.name}`));}console.log(t.gray(`
7
- Tip: paradigm university list --project (list entries in project pack)`)),console.log("");return}let g=c(s,o),l=g.subPackId??g.packId,i=a$1(s);if(!i||i.totalContent===0){console.log(t.yellow(`
8
- No content found in pack "${l}".`)),console.log(t.gray(` Create content with: paradigm university add note --title "My Note"
9
- `));return}let c$1=j(s,{type:o.type,tag:o.tag,difficulty:o.difficulty,symbol:o.symbol,section:o.section,limit:o.limit?parseInt(o.limit,10):20});if(o.json){console.log(JSON.stringify({pack:l,results:c$1},null,2));return}console.log(t.blue(`
10
- University Content \u2014 pack: ${l} (${c$1.length} of ${i.totalContent})
11
- `));let h={note:"N",policy:"P",guide:"N",runbook:"N",quiz:"Q",path:"LP"};for(let n of c$1){let e=h[n.type]||"?",r=n.difficulty==="advanced"?t.red:n.difficulty==="intermediate"?t.yellow:t.green,a=n.tags.length>0?t.gray(` [${n.tags.join(", ")}]`):"";console.log(` ${t.cyan(e)} ${t.white(`${l}:${n.id}`)} \u2014 ${n.title}${a}`),n.difficulty&&console.log(` ${r(n.difficulty)} \xB7 ${n.author} \xB7 ${n.updated||n.created}`);}i.diplomaCount>0&&console.log(t.gray(`
12
- ${i.diplomaCount} diploma${i.diplomaCount>1?"s":""} earned`)),console.log();}export{w as universityListCommand};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import {h}from'./chunk-K7X3Z3GL.js';export{d as addNotebookEntry,c as classifyNotebookScope,f as incrementApplied,a as loadNotebookEntries,e as promoteFromLore,b as searchNotebooks}from'./chunk-K7X3Z3GL.js';import'./chunk-5TAVYPOV.js';h();
@@ -1,8 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a,b}from'./chunk-MU5YWTNE.js';import'./chunk-TYWB5IQJ.js';import'./chunk-AMLD7IYC.js';import'./chunk-FYDRENK7.js';import'./chunk-HXGYVS2N.js';import {e as e$1}from'./chunk-TQOT2LBO.js';import {d,c}from'./chunk-EKZDFEJW.js';import'./chunk-LPBCQM5Y.js';import'./chunk-4GC35IFF.js';import'./chunk-JIXHEBGK.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as S from'path';import e from'chalk';import O from'ora';async function I(o,n,t){let i=n?S.resolve(n):process.cwd();if(!o){t.json?console.log(JSON.stringify({error:"Task is required"})):(console.log(e.red(`
3
- Task is required.`)),console.log(e.gray(`Example: paradigm team orchestrate "Build @payment-system with Stripe"
4
- `)));return}if(!e$1(i)){t.json?console.log(JSON.stringify({error:"Team not configured"})):console.log(e.yellow("\nTeam not configured. Run `paradigm team init` first.\n"));return}let f="faceted";t.solo&&(f="solo"),t.faceted&&(f="faceted");let g;if(t.budget){let s=t.budget.split(",");g={};for(let l of s){let[a,r]=l.split("=");a==="tokens"&&(g.maxTokens=parseInt(r)),a==="cost"&&(g.maxCostUsd=parseFloat(r)),a==="warn"&&(g.warnAtPercent=parseInt(r));}}let c=O({text:"Initializing orchestrator...",isSilent:t.quiet||t.json}).start(),y=new a(i);try{await y.initialize();}catch(s){c.fail("Failed to initialize orchestrator"),t.json?console.log(JSON.stringify({error:s instanceof Error?s.message:String(s)})):console.log(e.red(`
5
- Error: ${s instanceof Error?s.message:s}
6
- `));return}if(t.background){c.text="Starting background orchestration...";let s=new b(i),l=t.notify?t.notify.split(",").filter(r=>["bell","desktop","file","webhook"].includes(r)):["bell"],a=await s.startBackground(o,{mode:f,orchestratorModel:t.model,budget:g,notify:true,notifyMethods:l});if(c.stop(),t.json){console.log(JSON.stringify({id:a.id,status:a.status,outputFile:a.outputFile,task:a.task},null,2));return}T(a);return}if(t.compare){c.text="Running comparison (solo vs faceted)...";let s=await y.compare(o,{orchestratorModel:t.model,budget:g,checkpoints:t.checkpoint?{beforeAgentSpawn:true,afterAgentComplete:true}:void 0,onAgentStart:(l,a,r)=>{if(!t.quiet&&!t.json){let $=`${l} (${r})`;c.text=`${$}: ${a.slice(0,50)}...`;}}});if(c.stop(),t.json){console.log(JSON.stringify(s,null,2));return}v(s);return}if(!t.quiet&&!t.json){let s=f==="solo"?"Solo":"Faceted";c.text=`Orchestrating (${s} mode)...`;}let p=await y.orchestrate(o,{mode:f,orchestratorModel:t.model,budget:g,checkpoints:t.checkpoint?{beforeAgentSpawn:true}:void 0,pmGovernance:t.pm?{enabled:true,blockOnViolations:true}:void 0,onMessage:(s,l)=>{t.json||t.quiet||t.live&&l.type==="text"&&process.stdout.write(e.gray(`[${s}] `)+l.content);},onAgentStart:(s,l,a)=>{if(t.json||t.quiet)return;let r=`${s} (${a})`;t.live?console.log(e.cyan(`
7
- \u25B6 ${r}: ${l}`)):c.text=`${r}: ${l.slice(0,50)}...`;},onAgentComplete:(s,l,a)=>{if(!(t.json||t.quiet)&&t.live){let r=l.success?e.green("\u2713"):e.red("\u2717"),$=l.relay?d(l.relay.metrics.tokens_used.total):"0",w=`${s} (${a})`;console.log(`${r} ${w} completed (${$})`);}},onCheckpoint:async s=>t.checkpoint?(c.stop(),console.log(e.yellow(`
8
- \u26A0 Checkpoint: ${s}`)),console.log(e.gray("Press Enter to continue, or Ctrl+C to abort...")),new Promise(l=>{process.stdin.once("data",()=>{c.start(),l(true);});})):true});if(c.stop(),t.json){console.log(JSON.stringify(p,null,2));return}C(p);}function C(o){if(console.log(),console.log(e.blue("\u2501".repeat(60))),console.log(e.blue(` Orchestration ${o.success?"Complete":"Failed"}`)),console.log(e.blue("\u2501".repeat(60))),console.log(),console.log(e.white(` Task: ${o.task.slice(0,50)}${o.task.length>50?"...":""}`)),console.log(e.gray(` Mode: ${o.mode}`)),console.log(e.gray(` ID: ${o.orchestrationId}`)),console.log(),o.success?console.log(e.green(" \u2713 Success")):console.log(e.red(` \u2717 Failed: ${o.error||"Unknown error"}`)),console.log(),console.log(e.cyan(" Metrics:")),console.log(e.gray(` Agents spawned: ${o.agentsSpawned}`)),console.log(e.gray(` Total tokens: ${d(o.totalTokens.total)}`)),console.log(e.gray(` Total cost: ${c(o.totalCost)}`)),console.log(e.gray(` Duration: ${(o.duration_ms/1e3).toFixed(1)}s`)),console.log(),o.agentResults.length>0){console.log(e.cyan(" Agents:"));for(let n of o.agentResults){let t=n.success?e.green("\u2713"):e.red("\u2717"),i=n.relay?d(n.relay.metrics.tokens_used.total):"0",u=n.relay?`${(n.relay.metrics.duration_ms/1e3).toFixed(1)}s`:"0s";console.log(e.gray(` ${t} ${n.relay?.agent||"unknown"}: ${i} (${u})`));}console.log();}if(o.complianceReport){console.log(e.cyan(" PM Compliance:"));let n=o.complianceReport.postflight;if(n){let t=n.status==="pass"?e.green("\u2713"):n.status==="warnings"?e.yellow("\u26A0"):e.red("\u2717");if(console.log(e.gray(` Status: ${t} ${n.status}`)),console.log(e.gray(` Checks: ${n.summary.passed}/${n.summary.totalChecks} passed`)),n.summary.errors>0&&console.log(e.red(` Errors: ${n.summary.errors}`)),n.summary.warnings>0&&console.log(e.yellow(` Warnings: ${n.summary.warnings}`)),n.violations.length>0)for(let i of n.violations.slice(0,5)){let u=i.severity==="error"?e.red("\u2717"):e.yellow("\u26A0");console.log(e.gray(` ${u} ${i.message}`));}}console.log();}o.log&&console.log(e.gray(` Log: .paradigm/orchestrations/${o.log.started.slice(0,10)}-*.yaml`)),console.log();}function v(o){console.log(),console.log(e.blue("\u2501".repeat(60))),console.log(e.blue(" A/B Comparison: Solo vs Faceted")),console.log(e.blue("\u2501".repeat(60))),console.log(),console.log(e.cyan(" Results:")),console.log(e.gray(" \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510")),console.log(e.gray(" \u2502 \u2502 Solo \u2502 Faceted \u2502")),console.log(e.gray(" \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"));let n=o.solo.success?e.green("\u2713 Success"):e.red("\u2717 Failed"),t=o.faceted.success?e.green("\u2713 Success"):e.red("\u2717 Failed");console.log(e.gray(` \u2502 Status \u2502 ${n.padEnd(21)} \u2502 ${t.padEnd(21)} \u2502`));let i=d(o.solo.totalTokens.total).padStart(10),u=d(o.faceted.totalTokens.total).padStart(10);console.log(e.gray(` \u2502 Tokens \u2502 ${i} \u2502 ${u} \u2502`));let f=c(o.solo.totalCost).padStart(10),g=c(o.faceted.totalCost).padStart(10);console.log(e.gray(` \u2502 Cost \u2502 ${f} \u2502 ${g} \u2502`));let c$1=`${(o.solo.duration_ms/1e3).toFixed(1)}s`.padStart(10),y=`${(o.faceted.duration_ms/1e3).toFixed(1)}s`.padStart(10);console.log(e.gray(` \u2502 Duration \u2502 ${c$1} \u2502 ${y} \u2502`));let p=`${o.solo.agentsSpawned}`.padStart(10),s=`${o.faceted.agentsSpawned}`.padStart(10);console.log(e.gray(` \u2502 Agents \u2502 ${p} \u2502 ${s} \u2502`)),console.log(e.gray(" \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")),console.log();let{winner:l,tokensSaved:a,costDiff:r}=o.comparison;l==="tie"?console.log(e.yellow(" \u2696 Result: Tie")):l==="faceted"?(console.log(e.green(" \u{1F3C6} Winner: Faceted")),r>0&&console.log(e.gray(` Saved ${c(r)} (${d(Math.abs(a))} tokens)`))):(console.log(e.green(" \u{1F3C6} Winner: Solo")),r<0&&console.log(e.gray(` Saved ${c(Math.abs(r))} (${d(Math.abs(a))} tokens)`))),console.log(),console.log(e.cyan(" Recommendation:")),l==="faceted"?(console.log(e.gray(" Use --faceted (default) for this type of task.")),console.log(e.gray(" Multi-agent orchestration is more cost-effective."))):l==="solo"?(console.log(e.gray(" Use --solo for this type of task.")),console.log(e.gray(" Single agent is simpler and cheaper here."))):(console.log(e.gray(" Both approaches work similarly for this task.")),console.log(e.gray(" Default to --faceted for complex tasks, --solo for simple ones."))),console.log();}function T(o){console.log(),console.log(e.blue("\u2501".repeat(60))),console.log(e.blue(" Orchestration started in background")),console.log(e.blue("\u2501".repeat(60))),console.log(),console.log(e.white(` ID: ${o.id}`)),console.log(e.gray(` Task: ${o.task.slice(0,50)}${o.task.length>50?"...":""}`)),console.log(e.gray(` Mode: ${o.mode}`)),console.log(e.gray(` Status: ${o.status}`)),console.log(),console.log(e.cyan(" Commands:")),console.log(e.gray(` Monitor: paradigm team status ${o.id}`)),console.log(e.gray(` Logs: tail -f ${o.outputFile}`)),console.log(e.gray(` Diff: paradigm team diff ${o.id}`)),console.log(e.gray(` Accept: paradigm team accept ${o.id}`)),console.log();}export{I as teamOrchestrateCommand};