@a-company/paradigm 7.2.0 → 7.5.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 (167) hide show
  1. package/dist/{accept-orchestration-XW44LF5Y.js → accept-orchestration-NFNY5A4Q.js} +1 -1
  2. package/dist/{aggregate-H7SB2UYT.js → aggregate-647KIGV6.js} +1 -1
  3. package/dist/ambient-5TA5CD7Z.js +2 -0
  4. package/dist/{ambient-TFLZFV5Y.js → ambient-N24SR3BC.js} +1 -1
  5. package/dist/ambient-W3SPKLKC.js +2 -0
  6. package/dist/{arch-loader-YVOS3QRY.js → arch-loader-6TDQOSUE.js} +1 -1
  7. package/dist/arch-loader-NAGXLWUQ.js +2 -0
  8. package/dist/{beacon-WVN264OT.js → beacon-4XQSMTNN.js} +1 -1
  9. package/dist/calibrate-SH6PRZFD.js +2 -0
  10. package/dist/calibration-aggregate-5IVXSBDP.js +2 -0
  11. package/dist/calibration-aggregate-DUEE3LL2.js +4 -0
  12. package/dist/captain-2MEKZKJS.js +2 -0
  13. package/dist/captain-V5XPN4UP.js +2 -0
  14. package/dist/chunk-43H6PB2A.js +142 -0
  15. package/dist/chunk-54C2PETP.js +12 -0
  16. package/dist/{chunk-RGSFU2YW.js → chunk-5LIE2QMS.js} +1 -1
  17. package/dist/{chunk-ACJWUOMA.js → chunk-74NGU6YN.js} +1 -1
  18. package/dist/chunk-ABHILQLA.js +42 -0
  19. package/dist/{chunk-2KK4JQ55.js → chunk-AMZ3ESAK.js} +2 -2
  20. package/dist/chunk-BTMT4K73.js +93 -0
  21. package/dist/chunk-BXKFSYIN.js +2 -0
  22. package/dist/{chunk-RZRFYGND.js → chunk-CHFY3JSF.js} +15 -15
  23. package/dist/chunk-D2T5AV5N.js +504 -0
  24. package/dist/{chunk-ASBK55FU.js → chunk-DLMDHS2X.js} +1 -1
  25. package/dist/{chunk-6VZSOQ7Y.js → chunk-DQ4MMMTP.js} +1 -1
  26. package/dist/chunk-F3OBFUOE.js +2 -0
  27. package/dist/chunk-GADXREYG.js +18 -0
  28. package/dist/{chunk-A5EEY6NO.js → chunk-HGT7RNOL.js} +1 -1
  29. package/dist/chunk-HLPYCWE5.js +6 -0
  30. package/dist/chunk-IGB2CIMK.js +93 -0
  31. package/dist/{chunk-27EK3OQZ.js → chunk-JJ3AUHQU.js} +1 -1
  32. package/dist/chunk-JOHPASZG.js +4 -0
  33. package/dist/chunk-JOWT6J4C.js +25 -0
  34. package/dist/chunk-L4MKNG56.js +42 -0
  35. package/dist/chunk-PRZZL57E.js +7 -0
  36. package/dist/chunk-QBIME67A.js +2 -0
  37. package/dist/{chunk-USYV5QYU.js → chunk-QTMJVEEW.js} +1 -1
  38. package/dist/chunk-RPGSQQTS.js +2 -0
  39. package/dist/chunk-RQHZUPLO.js +4 -0
  40. package/dist/chunk-SGLIPRIC.js +3 -0
  41. package/dist/chunk-SOVBBLFK.js +6 -0
  42. package/dist/chunk-SPU3R5GW.js +25 -0
  43. package/dist/{chunk-NRP2KJ6I.js → chunk-T577TTVG.js} +3 -3
  44. package/dist/{chunk-W3VWORQZ.js → chunk-VHVUJGZ2.js} +2 -2
  45. package/dist/chunk-WUSTIEYA.js +4 -0
  46. package/dist/{commands-4ENQMHFO.js → commands-RSHKXKXN.js} +1 -1
  47. package/dist/{compliance-3M6COUCO.js → compliance-EFNXWHDL.js} +1 -1
  48. package/dist/{constellation-TIKNCZWR.js → constellation-26225R5K.js} +1 -1
  49. package/dist/{diff-Z2YSIRC4.js → diff-G52RYZNF.js} +1 -1
  50. package/dist/dist-6TDAY6TQ-HMSTBL57.js +39 -0
  51. package/dist/dist-N4NYCS3D.js +2 -0
  52. package/dist/dist-O7KGTIYK.js +4 -0
  53. package/dist/{docs-OWJ7EPD7.js → docs-2O7HUSBX.js} +1 -1
  54. package/dist/doctor-KGQXLGOQ.js +2 -0
  55. package/dist/github-GI3HX3N5.js +4 -0
  56. package/dist/graph-slice-2WECDOEN.js +2 -0
  57. package/dist/index.js +6 -6
  58. package/dist/{init-QPMLEQWQ.js → init-JGYCABZZ.js} +1 -1
  59. package/dist/{integrity-FRGF5BFS.js → integrity-YUCXTQX3.js} +1 -1
  60. package/dist/mcp.js +2 -2
  61. package/dist/nomination-engine-3EYXJOZZ.js +2 -0
  62. package/dist/nomination-engine-BUPERVPR.js +2 -0
  63. package/dist/notebook-loader-QM4KUT4R.js +2 -0
  64. package/dist/{orchestrate-C5NM5MFN.js → orchestrate-RIKQB2DV.js} +1 -1
  65. package/dist/orchestration-GFNPCEUU.js +2 -0
  66. package/dist/orchestration-I62QXOWV.js +2 -0
  67. package/dist/platform-server-AAEDDBS3.js +25 -0
  68. package/dist/{probe-G3TKOJYW.js → probe-GD3VDWGT.js} +1 -1
  69. package/dist/reindex-FNL4QRUZ.js +2 -0
  70. package/dist/reindex-N4NTDLJY.js +2 -0
  71. package/dist/{review-WHRNLW2W.js → review-YG4LWV22.js} +1 -1
  72. package/dist/{ripple-B6U7263T.js → ripple-S6VBP5C6.js} +1 -1
  73. package/dist/{sentinel-EFPEX246.js → sentinel-RIEQWALQ.js} +1 -1
  74. package/dist/{sentinel-bridge-UR2MKARY.js → sentinel-bridge-D4LFDFCH.js} +1 -1
  75. package/dist/sentinel.js +1 -1
  76. package/dist/serve-NPRYOGQX.js +9 -0
  77. package/dist/{server-4D77LCST.js → server-K7G3IHR3.js} +1 -1
  78. package/dist/session-tracker-HYN6ZYPH.js +2 -0
  79. package/dist/{session-work-log-T2IE4Y4T.js → session-work-log-KZX4PGUL.js} +1 -1
  80. package/dist/{setup-L5OP24US.js → setup-GPOTHS3N.js} +1 -1
  81. package/dist/{shift-UDKXCIW7.js → shift-ZIJTQ5SW.js} +2 -2
  82. package/dist/{snapshot-MT5L6XE4.js → snapshot-2ARNF3U2.js} +1 -1
  83. package/dist/{spawn-I6XG57S2.js → spawn-PHA2SVQ3.js} +1 -1
  84. package/dist/{status-4QGKLOP6.js → status-NTWWESOR.js} +1 -1
  85. package/dist/{summary-6QNVQZJV.js → summary-4QXYLXAB.js} +1 -1
  86. package/dist/sync-layer-Z266WBWF.js +2 -0
  87. package/dist/task-6F527BNU.js +3 -0
  88. package/dist/task-loader-75NBBLRQ.js +2 -0
  89. package/dist/task-loader-INPLZRG5.js +2 -0
  90. package/dist/task-settlement-3ROAHAND.js +3 -0
  91. package/dist/task-settlement-F7CIKUG3.js +3 -0
  92. package/dist/team-PFJTOCPM.js +2 -0
  93. package/dist/tools-MAH6K5UL.js +142 -0
  94. package/dist/tools-Z354SXGS.js +2 -0
  95. package/dist/{workspace-4D4TQ637.js → workspace-HADUT5XT.js} +1 -1
  96. package/package.json +3 -6
  97. package/platform-ui/dist/assets/{AmbientSection-CwatqcBD.js → AmbientSection-xoxr3DQg.js} +1 -1
  98. package/platform-ui/dist/assets/{DocsSection-BZ2SFJBZ.js → DocsSection-Us2qksna.js} +1 -1
  99. package/platform-ui/dist/assets/{GitSection-MNNYU1tO.js → GitSection-DIHZyadf.js} +1 -1
  100. package/platform-ui/dist/assets/{GraphSection-COYjb4Pt.js → GraphSection-9TO0L1IO.js} +1 -1
  101. package/platform-ui/dist/assets/{LoreSection-B0hUbfsJ.js → LoreSection-DVDit8Aw.js} +1 -1
  102. package/platform-ui/dist/assets/{SentinelSection-BCxW1DCp.js → SentinelSection-a5_VNYcx.js} +1 -1
  103. package/platform-ui/dist/assets/{SymphonySection-BsucZRqy.js → SymphonySection-cRHEoJ9t.js} +1 -1
  104. package/platform-ui/dist/assets/TasksSection-44_gDO3L.css +1 -0
  105. package/platform-ui/dist/assets/TasksSection-h8x3qRIj.js +1 -0
  106. package/platform-ui/dist/assets/{TeamSection-C0QNTudW.js → TeamSection-mFoDyNic.js} +1 -1
  107. package/platform-ui/dist/assets/{UniversitySection-DN1-g9pw.js → UniversitySection-D99YRjmC.js} +1 -1
  108. package/platform-ui/dist/assets/{index-DwUT8pju.js → index-D_wB2S_2.js} +11 -11
  109. package/platform-ui/dist/index.html +1 -1
  110. package/dist/ambient-OW5M5LVN.js +0 -2
  111. package/dist/ambient-VCTUHHIG.js +0 -2
  112. package/dist/arch-loader-G3AAM4E2.js +0 -2
  113. package/dist/calibrate-PHVP7RPH.js +0 -4
  114. package/dist/captain-CAXGHC2V.js +0 -2
  115. package/dist/captain-CWCLFOXV.js +0 -2
  116. package/dist/chunk-33ERV2MW.js +0 -18
  117. package/dist/chunk-3I3TITBA.js +0 -25
  118. package/dist/chunk-3YM5ABNX.js +0 -2
  119. package/dist/chunk-6HYRS3PH.js +0 -142
  120. package/dist/chunk-727PXENG.js +0 -2
  121. package/dist/chunk-D6BSCELB.js +0 -2
  122. package/dist/chunk-FG3M6VVO.js +0 -30
  123. package/dist/chunk-HSY75GRR.js +0 -6
  124. package/dist/chunk-K7KT6FL3.js +0 -25
  125. package/dist/chunk-KAUGQMXU.js +0 -4
  126. package/dist/chunk-QPQBXRXX.js +0 -93
  127. package/dist/chunk-RVXQNS6K.js +0 -30
  128. package/dist/chunk-TMDPDIWA.js +0 -3
  129. package/dist/chunk-UNSI6DVD.js +0 -93
  130. package/dist/chunk-XBK244QR.js +0 -6
  131. package/dist/chunk-XMAV5AG6.js +0 -2
  132. package/dist/chunk-XSKIXXFW.js +0 -504
  133. package/dist/chunk-Y76OIMDO.js +0 -7
  134. package/dist/chunk-ZSWXLFN7.js +0 -12
  135. package/dist/dist-GQ42YS5N-4HIJZVBB.js +0 -39
  136. package/dist/dist-PW5YPGFF.js +0 -2
  137. package/dist/dist-RXYJK7AZ.js +0 -2
  138. package/dist/doctor-CBZYYQQH.js +0 -2
  139. package/dist/github-4X4MYINS.js +0 -4
  140. package/dist/lore-server-FC2GMDLT.js +0 -14
  141. package/dist/nomination-engine-EFXDEPZN.js +0 -2
  142. package/dist/nomination-engine-YRHZZZUN.js +0 -2
  143. package/dist/notebook-loader-TZVIMNDJ.js +0 -2
  144. package/dist/orchestration-EVWQWTOV.js +0 -2
  145. package/dist/orchestration-UP3KFUJT.js +0 -2
  146. package/dist/platform-server-FXF3XFHM.js +0 -25
  147. package/dist/reindex-QZYOD5K4.js +0 -2
  148. package/dist/reindex-W67B2LQP.js +0 -2
  149. package/dist/serve-L52ZUTU6.js +0 -10
  150. package/dist/serve-ZT2Z54NK.js +0 -8
  151. package/dist/session-tracker-BZ7FU4AT.js +0 -2
  152. package/dist/task-KFND4HLF.js +0 -3
  153. package/dist/task-loader-HBZ3KRH2.js +0 -2
  154. package/dist/task-loader-IO4UVFUD.js +0 -2
  155. package/dist/task-settlement-NF7PFSNE.js +0 -3
  156. package/dist/task-settlement-TATNPY6L.js +0 -3
  157. package/dist/team-6WNNLBAO.js +0 -2
  158. package/dist/tools-GDWT74O6.js +0 -2
  159. package/dist/tools-SDWAFQMQ.js +0 -142
  160. package/graph-ui/dist/assets/index-BlgXTl53.css +0 -1
  161. package/graph-ui/dist/assets/index-Bq5nXK8p.js +0 -63
  162. package/graph-ui/dist/index.html +0 -13
  163. package/lore-ui/dist/assets/index-C3EixkjW.css +0 -1
  164. package/lore-ui/dist/assets/index-DKhNxgtW.js +0 -56
  165. package/lore-ui/dist/index.html +0 -13
  166. package/platform-ui/dist/assets/CanvasSection-dFAthehN.js +0 -9
  167. package/platform-ui/dist/assets/CanvasSection-flMXU19z.css +0 -1
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import {f,e as e$1,g,a as a$2,c as c$2,b}from'./chunk-WR6D3SC6.js';import {O,Q}from'./chunk-JOHPASZG.js';import {c as c$1,a as a$1}from'./chunk-YNDPSWOE.js';import {e}from'./chunk-VIG5LSGZ.js';import {a}from'./chunk-LKAT7IAK.js';import*as t from'fs';import*as c from'path';import*as j from'js-yaml';import l from'chalk';async function ke(E={}){let p=E.rootDir||process.cwd(),e$2=[],$=E.quiet,q=E.context;$||(console.log(l.blue(`
3
+ \u{1FA7A} Paradigm Doctor
4
+ `)),console.log(q?l.gray(`Running context audit checks...
5
+ `):l.gray(`Checking Paradigm setup...
6
+ `)));let H=a.command("doctor").start("Running health checks");if(!q){let O=function(a){let s=[];try{let i=t.readdirSync(a,{withFileTypes:!0});for(let n of i){if(n.name==="node_modules"||n.name==="dist"||n.name===".git")continue;let g=c.join(a,n.name);n.isDirectory()?s.push(...O(g)):n.name===".purpose"&&s.push(g);}}catch{}return s};let o=c.join(p,".paradigm");if(t.existsSync(o))if(t.statSync(o).isFile())e$2.push({name:".paradigm",status:"warn",message:"Legacy file format (should be directory)",fix:"paradigm upgrade --all"});else {e$2.push({name:".paradigm/",status:"ok",message:"Directory exists"});let s=c.join(o,"config.yaml");if(t.existsSync(s))try{let u=t.readFileSync(s,"utf8");e(u),e$2.push({name:".paradigm/config.yaml",status:"ok",message:"Valid YAML"});}catch(u){e$2.push({name:".paradigm/config.yaml",status:"error",message:`Invalid YAML: ${u.message}`,fix:"Check YAML syntax"});}else e$2.push({name:".paradigm/config.yaml",status:"missing",message:"Config file not found",fix:"paradigm init --force"});let i=["logger.md","probe.md","symbols.md"],n=c.join(o,"specs");if(t.existsSync(n))for(let u of i){let b=c.join(n,u);t.existsSync(b)?e$2.push({name:`.paradigm/specs/${u}`,status:"ok",message:"Present"}):e$2.push({name:`.paradigm/specs/${u}`,status:"missing",message:"Spec file not found",fix:"paradigm upgrade --all"});}else e$2.push({name:".paradigm/specs/",status:"missing",message:"Specs directory not found",fix:"paradigm upgrade --all"});let g=c.join(o,"docs");t.existsSync(g)?e$2.push({name:".paradigm/docs/",status:"ok",message:"Directory exists"}):e$2.push({name:".paradigm/docs/",status:"missing",message:"Docs directory not found",fix:"paradigm upgrade --all"});let f=c.join(o,"prompts");t.existsSync(f)?e$2.push({name:".paradigm/prompts/",status:"ok",message:"Directory exists"}):e$2.push({name:".paradigm/prompts/",status:"missing",message:"Prompts directory not found",fix:"paradigm upgrade --all"});let h=["specs","implementation-guides","prompts","decisions"],d=[];for(let u of h){let b=c.join(o,u);if(t.existsSync(b)&&t.statSync(b).isDirectory()){let S=c.join(b,".index.yaml");t.existsSync(S)||d.push(`.paradigm/${u}/`);}}d.length>0?e$2.push({name:"Docs-class indexes",status:"warn",message:`${d.length} director${d.length===1?"y":"ies"} missing .index.yaml: ${d.join(", ")}`,fix:"paradigm docs scaffold"}):e$2.push({name:"Docs-class indexes",status:"ok",message:"All docs-class directories have .index.yaml"});let x=c.join(o,"scan-index.json"),C=c.join(p,".paradigm-scan-index.json");if(t.existsSync(x)){let u=t.statSync(x),b=Date.now()-u.mtime.getTime(),S=Math.floor(b/(1e3*60*60));S>24?e$2.push({name:".paradigm/scan-index.json",status:"warn",message:`Stale (${S} hours old)`,fix:"paradigm index"}):e$2.push({name:".paradigm/scan-index.json",status:"ok",message:S>0?`${S} hours old`:"Fresh"});}else t.existsSync(C)?e$2.push({name:"scan-index",status:"warn",message:"Using legacy location",fix:"paradigm index"}):e$2.push({name:".paradigm/scan-index.json",status:"missing",message:"Not generated",fix:"paradigm index"});}else e$2.push({name:".paradigm/",status:"missing",message:"Not initialized",fix:"paradigm init"});let m=c$1(p);if(m.detected){let a=a$1(m.detected);if(a){let s=c.join(p,a.outputPath);t.existsSync(s)?e$2.push({name:a.outputPath,status:"ok",message:`Present (${m.detected})`}):e$2.push({name:a.outputPath,status:"missing",message:`Not generated for ${m.detected}`,fix:"paradigm sync"});}}let r=c.join(p,".premise");t.existsSync(r)?e$2.push({name:".premise",status:"ok",message:"Present"}):e$2.push({name:".premise",status:"missing",message:"Not found (optional)"});let k=c.join(p,".purpose");t.existsSync(k)?e$2.push({name:".purpose",status:"ok",message:"Present"}):e$2.push({name:".purpose",status:"warn",message:"Root .purpose not found",fix:"paradigm init"});let v=c.join(p,".paradigm","config.yaml");if(t.existsSync(v))try{let a=t.readFileSync(v,"utf8"),i=j.load(a)?.["purpose-required"];if(i&&Array.isArray(i)){let n=[];for(let g of i){if(!g.pattern)continue;let{glob:f}=await import('glob'),h=await f(g.pattern,{cwd:p,nodir:!1});for(let d of h){let x=c.join(p,d);try{t.statSync(x).isDirectory()&&!t.existsSync(c.join(x,".purpose"))&&n.push(d);}catch{}}}n.length>0?e$2.push({name:"Purpose-required",status:"warn",message:`${n.length} director${n.length===1?"y":"ies"} missing .purpose: ${n.join(", ")}`,fix:"Create .purpose files with paradigm_purpose_init + paradigm_purpose_add_component"}):e$2.push({name:"Purpose-required",status:"ok",message:"All required directories have .purpose files"});}}catch{}let w=/\[NEEDS CLARIFICATION:\s*[^\]]+\]/gi,F=0,G=O(p);for(let a of G)try{let i=t.readFileSync(a,"utf8").match(w);i&&(F+=i.length);}catch{}F>0?e$2.push({name:"Clarification markers",status:"warn",message:`${F} [NEEDS CLARIFICATION] marker${F>1?"s":""} found in .purpose files`,fix:"Resolve open clarification markers before shipping"}):G.length>0&&e$2.push({name:"Clarification markers",status:"ok",message:"No unresolved markers"});let I=c.join(p,"portal.yaml");if(t.existsSync(I))try{let a=t.readFileSync(I,"utf8"),s=j.load(a);if(s?.version&&s?.gates){let i=Object.keys(s.gates||{}).length,n=Object.keys(s.routes||{}).length;e$2.push({name:"portal.yaml",status:"ok",message:`Valid (${i} gates, ${n} routes)`});}else e$2.push({name:"portal.yaml",status:"warn",message:"Missing version or gates section",fix:'Add version: "1.0" and gates: {} to portal.yaml'});}catch(a){e$2.push({name:"portal.yaml",status:"error",message:`Invalid YAML: ${a.message}`,fix:"Check YAML syntax in portal.yaml"});}if(t.existsSync(I))try{let{checkPortalCompliance:a,getComplianceSummary:s}=await import('./portal-compliance-JONQ4SOP.js'),i=await a(p),n=s(i);e$2.push({name:"Portal compliance",status:n.status,message:n.message,fix:n.status!=="ok"?"paradigm portal check":void 0});}catch{}{let a=c.join(p,".paradigm","scan-index.json"),s=c.join(p,".paradigm","roster.yaml");try{if(t.existsSync(a)){let i=t.readFileSync(a,"utf8"),n=JSON.parse(i),g=Object.keys(n.components??{}).length,f=Object.keys(n.aspects??{}).length;if(g>0){let h=!1;if(t.existsSync(s))try{let x=j.load(t.readFileSync(s,"utf8"));h=Array.isArray(x?.active)&&x.active.includes("compliance");}catch{}let d=`${g}:${f} components:aspects`;h?e$2.push({name:"Aspect coverage",status:"ok",message:`${d} (claimant: rune)`}):f===0?e$2.push({name:"Aspect coverage",status:"info",message:`${d} ${l.dim("(no aspects defined)")}`}):e$2.push({name:"Aspect coverage",status:"info",message:`${d} ${l.dim("(no claimant active)")}`});}}}catch{}}let V=c.join(p,".paradigm","flows.yaml");if(t.existsSync(V))try{let a=t.readFileSync(V,"utf8"),s=j.load(a);if(s?.version&&s?.flows){let i=Object.keys(s.flows||{}).length,n=Object.entries(s.flows||{}).filter(([,g])=>!g?.steps||(g.steps?.length??0)===0);n.length>0?e$2.push({name:".paradigm/flows.yaml",status:"warn",message:`${i} flows defined, ${n.length} have no steps`,fix:"Add steps to empty flow definitions"}):e$2.push({name:".paradigm/flows.yaml",status:"ok",message:`Valid (${i} flows)`});}else e$2.push({name:".paradigm/flows.yaml",status:"warn",message:"Missing version or flows section",fix:'Ensure flows.yaml has version: "1.0" and flows: {}'});}catch(a){e$2.push({name:".paradigm/flows.yaml",status:"error",message:`Invalid YAML: ${a.message}`,fix:"Check YAML syntax in flows.yaml"});}let J=c.join(p,".paradigm","lore");if(t.existsSync(J))try{let a=t.readdirSync(J).filter(s=>s.endsWith(".yaml"));a.length===0?e$2.push({name:"Lore entries",status:"warn",message:"Lore directory exists but no entries found",fix:"Record a lore entry: paradigm lore record"}):e$2.push({name:"Lore entries",status:"ok",message:`${a.length} lore file${a.length>1?"s":""}`});}catch{e$2.push({name:"Lore entries",status:"warn",message:"Could not read lore directory"});}let B=c.join(p,".paradigm","university");if(t.existsSync(B))try{let a=c.join(B,"content"),s=0,i=0;if(t.existsSync(a))for(let n of ["notes","policies","quizzes","paths"]){let g=c.join(a,n);t.existsSync(g)&&(s+=t.readdirSync(g).filter(f=>f.endsWith(".md")||f.endsWith(".yaml")).length);}if(s===0)e$2.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 n=c.join(a,"quizzes");if(t.existsSync(n))for(let f of t.readdirSync(n).filter(h=>h.endsWith(".yaml")))try{let h=j.load(t.readFileSync(c.join(n,f),"utf8"));if(h?.questions)for(let d of h.questions)d.choices&&d.correct&&!(d.correct in d.choices)&&i++;}catch{}let g=c.join(a,"paths");if(t.existsSync(g))for(let f of t.readdirSync(g).filter(h=>h.endsWith(".yaml")))try{let h=j.load(t.readFileSync(c.join(g,f),"utf8"));if(h?.steps){for(let d of h.steps)if(d.content&&!d.content.startsWith("plsat:")){let x=!1;for(let C of ["notes","policies","quizzes","paths"]){let u=c.join(a,C);if(t.existsSync(u)&&t.readdirSync(u).some(S=>S.startsWith(d.content))){x=!0;break}}x||i++;}}}catch{}i>0?e$2.push({name:"University content",status:"warn",message:`${s} items, ${i} issue${i>1?"s":""}`,fix:"Run: paradigm university validate --deep"}):e$2.push({name:"University content",status:"ok",message:`${s} content item${s>1?"s":""}`});}}catch{e$2.push({name:"University content",status:"warn",message:"Could not read university directory"});}let K=c.join(p,".claude","hooks.json"),le=c.join(p,"plugins","paradigm","hooks.json");if(t.existsSync(K)){let a=t.statSync(K),s=Date.now()-a.mtime.getTime(),i=Math.floor(s/(1e3*60*60*24));i>30?e$2.push({name:"Claude Code hooks",status:"warn",message:`Hooks are ${i} days old \u2014 may be outdated`,fix:"paradigm hooks install"}):e$2.push({name:"Claude Code hooks",status:"ok",message:i>0?`${i} days old`:"Fresh"});}else t.existsSync(le)?e$2.push({name:"Claude Code hooks",status:"ok",message:"Using plugin hooks"}):e$2.push({name:"Claude Code hooks",status:"missing",message:"No hooks installed",fix:"paradigm hooks install"});let Q=c.join(p,".paradigm","habits.yaml");if(t.existsSync(Q))try{let a=t.readFileSync(Q,"utf8"),s=j.load(a);if(s?.version&&Array.isArray(s?.habits)){let i=s.habits.filter(n=>n.enabled!==!1).length;e$2.push({name:"Habits config",status:"ok",message:`Valid (${i}/${s.habits.length} enabled)`});}else e$2.push({name:"Habits config",status:"warn",message:"Missing version or habits array",fix:"Regenerate habits.yaml with paradigm habits init"});}catch(a){e$2.push({name:"Habits config",status:"error",message:`Invalid YAML: ${a.message}`,fix:"Check YAML syntax in habits.yaml"});}let X=c.join(p,"AGENTS.md");if(t.existsSync(X)){let a=t.statSync(X),s=Date.now()-a.mtime.getTime(),i=Math.floor(s/(1e3*60*60*24));i>60?e$2.push({name:"AGENTS.md",status:"warn",message:`${i} days since last update \u2014 may be stale`,fix:"paradigm sync"}):e$2.push({name:"AGENTS.md",status:"ok",message:i>0?`Updated ${i} days ago`:"Fresh"});}try{let{summarizeTeamFunnel:a}=await import('./team-funnel-RAJ6EDG3.js'),s=a(p,30);if(s.orchestrated+s.soloDeclared+s.bypasses>0||s.eligible>0){let n=s.invocationRate!==null?`${Math.round(s.invocationRate*100)}%`:"n/a",g=s.legibleRate!==null?`${Math.round(s.legibleRate*100)}%`:"n/a",f=Object.entries(s.soloByReason).map(([h,d])=>`${h}:${d}`).join(" ");e$2.push({name:"Team funnel (30d)",status:s.bypasses>s.orchestrated?"warn":"info",message:`eligible ${s.eligible} \xB7 orchestrated ${s.orchestrated} \xB7 solo ${s.soloDeclared}${f?` (${f})`:""} \xB7 bypass ${s.bypasses} \xB7 invocation ${n} \xB7 legible ${g}`,...s.bypasses>s.orchestrated?{fix:"Orchestrate eligible tasks (paradigm_orchestrate_inline) or declare `paradigm solo <reason>`"}:{}});}}catch{}try{let a=c.join(p,".paradigm","events","settlement-liveness.jsonl");if(t.existsSync(a)){let i=t.readFileSync(a,"utf8").trim().split(`
7
+ `).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null);if(i.length===0)e$2.push({name:"Learning-loop liveness",status:"info",message:"No settlements recorded yet (probe writes on each task-DAG settlement)"});else {let n=i.slice(-20),g=i.slice(-5),f=n.filter(u=>u.chainLive===!1),h=g.filter(u=>u.chainLive===!1),d=f.length>0?f[f.length-1]:void 0,x=d?.stages?Object.entries(d.stages).filter(([,u])=>u==="threw").map(([u])=>u):[],C=x.length>0?` (stage: ${x.join(", ")})`:"";h.length>=3?e$2.push({name:"Learning-loop liveness",status:"error",message:`DEAD CHAIN: ${h.length}/5 recent settlements severed${C} \u2014 the learning loop is not closing`,fix:"A settlement-chain stage is throwing. Inspect .paradigm/events/settlement-liveness.jsonl and the named stage."}):f.length>0?e$2.push({name:"Learning-loop liveness",status:"warn",message:`${f.length}/${n.length} recent settlements had a severed chain${C}`,fix:"Inspect the named stage in .paradigm/events/settlement-liveness.jsonl."}):e$2.push({name:"Learning-loop liveness",status:"ok",message:`${n.length} recent settlements, chain live`});}}}catch{}}let y=(()=>{try{let o=O(p),m=Q(o),r=Object.values(m.perAgent).reduce((v,w)=>v+w.resolved,0),k=Object.values(m.perAgent).reduce((v,w)=>v+w.overturned,0);return {present:o.length>0,certCount:o.length,rollup:m,resolvedTotal:r,overturnedTotal:k}}catch{return null}})();y&&y.rollup.overall!==null&&y.resolvedTotal>=3&&y.rollup.overall>.5&&e$2.push({name:"Repeat-failure-rate",status:"warn",message:`High: ${y.rollup.overall} of resolved certs were overturned (${y.overturnedTotal}/${y.resolvedTotal})`,fix:"Learnings are breaking repeatedly \u2014 review refinements via /paradigm:class review"});let U=0,W=0,A=0;for(let o of e$2){let m,r;switch(o.status){case "ok":m="\u2713",r=l.green;break;case "warn":m="\u26A0",r=l.yellow,W++;break;case "error":m="\u2717",r=l.red,U++;break;case "missing":m="\u25CB",r=l.gray,A++;break;case "info":m="\u2802",r=l.gray;break}if(!$){let k=o.name.padEnd(30);console.log(` ${r(m)} ${k} ${r(o.message)}`),o.fix&&console.log(l.gray(` \u2514\u2500 Fix: ${o.fix}`));}}if(!$&&y)if(f("Classroom / learning health"),!y.present)e$1(" No certifications yet \u2014 the learning loop has not turned. This is normal for a fresh project.");else {let{overall:o}=y.rollup,m=o===null?"n/a (no certs resolved yet)":String(o);g("repeat-failure-rate (global)",m),g("resolved / overturned",`${y.resolvedTotal} / ${y.overturnedTotal}`);let r=Object.keys(y.rollup.perAgent).sort();if(r.length>0){a$2(" "+l.dim("per-agent:"));for(let k of r){let v=y.rollup.perAgent[k],w=v.rate===null?"n/a":String(v.rate);a$2(` ${l.dim(k+":")} rate ${w} (${v.overturned}/${v.resolved} overturned)`);}}y.overturnedTotal>0&&e$1(` ${y.overturnedTotal} learning${y.overturnedTotal>1?"s were":" was"} overturned by the field \u2014 the loop is correcting (healthy).`),o!==null&&y.resolvedTotal>=3&&o>.5?c$2(` Repeat-failure-rate is high (${o} > 0.5) \u2014 learnings are breaking repeatedly. Review refinements via /paradigm:class review.`):o!==null&&b(" Repeat-failure-rate within healthy range.");}let{runContextAudit:ce}=await import('./context-audit-JVCA6GSV.js'),T=await ce(p,{quiet:$}),z=0,Y=0,R=0;!$&&T.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 T){let m,r;switch(o.status){case "ok":m="\u2713",r=l.green;break;case "warn":m="\u26A0",r=l.yellow,Y++;break;case "error":m="\u2717",r=l.red,z++;break;case "advisory":m="\u2139",r=l.cyan,R++;break}if(!$){let k=o.check.padEnd(30);if(console.log(` ${r(m)} ${k} ${r(o.message)}`),o.details&&o.details.length>0){let v=o.details.slice(0,5);for(let w of v)console.log(l.gray(` \u2502 ${w}`));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 P=U+z,D=W+Y,L=P+D+A===0;if(!$)if(console.log(""),L)console.log(l.green(`\u2728 All checks passed!
8
+ `));else {let o=[];P>0&&o.push(l.red(`${P} error${P>1?"s":""}`)),D>0&&o.push(l.yellow(`${D} warning${D>1?"s":""}`)),A>0&&o.push(l.gray(`${A} missing`)),R>0&&o.push(l.cyan(`${R} advisor${R>1?"ies":"y"}`)),console.log(`${o.join(", ")} found.
9
+ `),console.log(l.gray("Run the suggested commands to fix issues.")),console.log(l.gray(`Troubleshooting guide: .paradigm/docs/troubleshooting.md
10
+ `));}if(!$&&E.explain&&!L)try{let{narrateAllGaps:o}=await import('./gap-narrator-NTXLUI7I.js'),m=[];for(let r of e$2)r.status!=="ok"&&(r.name===".purpose"||r.name.startsWith("Purpose-required")?m.push({type:"missing-purpose",target:r.name,severity:"improvement"}):r.name===".paradigm/scan-index.json"&&r.status==="warn"?m.push({type:"index-stale",target:r.name,severity:"improvement"}):r.name==="Portal compliance"?m.push({type:"portal-mismatch",target:r.name,severity:r.status==="error"?"blocking":"improvement"}):r.name==="Clarification markers"&&m.push({type:"missing-description",target:r.name,severity:"improvement"}));if(m.length>0){let r=o(m);console.log(l.blue(`
11
+ Gap Narrations (--explain)
12
+ `)),console.log(l.gray(r.narrative)),console.log("");}}catch{}L?H.success("All health checks passed",{total:e$2.length+T.length}):H.error("Health checks found issues",{errors:P,warnings:D,missing:A,advisories:R});try{let{captureSnapshot:o}=await import('./metrics-UESGUHTA.js');o(p);}catch{}return L}export{ke as a};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import {l}from'./chunk-TMDPDIWA.js';import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import*as i from'fs';import*as c from'path';import*as f from'js-yaml';b$1();var g=".paradigm/arch.yaml";function u(e){let n=c.join(e,g);if(!i.existsSync(n))return null;try{let t=i.readFileSync(n,"utf8");return f.load(t)}catch{return null}}function S(e,n){let t=c.join(e,g),r=c.dirname(t);i.existsSync(r)||i.mkdirSync(r,{recursive:true}),i.writeFileSync(t,f.dump(n,{lineWidth:-1,noRefs:true}),"utf8");}function b(e,n){let t=u(e);if(!t)return {unassigned:[],missing_purpose:[]};let r=new Set;for(let o of t.tiers)for(let p of o.components)r.add(p);let s=new Set;try{let o=l(n.index,"component");for(let p of o)s.add(p.symbol);}catch(o){a.component("#arch-loader").warn("Could not load symbol index for drift check",{error:String(o)});}let a$1=Array.from(s).filter(o=>!r.has(o)),h=Array.from(r).filter(o=>!s.has(o));return {unassigned:a$1,missing_purpose:h}}function k(e){let n=r=>r.replace(/[^a-zA-Z0-9_-]/g,"-"),t=["graph TD"];for(let r of e.tiers){let s=n(r.id);t.push(` ${s}["${r.label}\\n(${r.responsibility})"]`);}for(let r of e.links){let s=n(r.from),a=n(r.to);r.via?t.push(` ${s} -->|"${r.via}"| ${a}`):t.push(` ${s} --> ${a}`);}return t.join(`
2
+ import {l}from'./chunk-SGLIPRIC.js';import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import*as i from'fs';import*as c from'path';import*as f from'js-yaml';b$1();var g=".paradigm/arch.yaml";function u(e){let n=c.join(e,g);if(!i.existsSync(n))return null;try{let t=i.readFileSync(n,"utf8");return f.load(t)}catch{return null}}function S(e,n){let t=c.join(e,g),r=c.dirname(t);i.existsSync(r)||i.mkdirSync(r,{recursive:true}),i.writeFileSync(t,f.dump(n,{lineWidth:-1,noRefs:true}),"utf8");}function b(e,n){let t=u(e);if(!t)return {unassigned:[],missing_purpose:[]};let r=new Set;for(let o of t.tiers)for(let p of o.components)r.add(p);let s=new Set;try{let o=l(n.index,"component");for(let p of o)s.add(p.symbol);}catch(o){a.component("#arch-loader").warn("Could not load symbol index for drift check",{error:String(o)});}let a$1=Array.from(s).filter(o=>!r.has(o)),h=Array.from(r).filter(o=>!s.has(o));return {unassigned:a$1,missing_purpose:h}}function k(e){let n=r=>r.replace(/[^a-zA-Z0-9_-]/g,"-"),t=["graph TD"];for(let r of e.tiers){let s=n(r.id);t.push(` ${s}["${r.label}\\n(${r.responsibility})"]`);}for(let r of e.links){let s=n(r.from),a=n(r.to);r.via?t.push(` ${s} -->|"${r.via}"| ${a}`):t.push(` ${s} --> ${a}`);}return t.join(`
3
3
  `)}export{g as a,u as b,S as c,b as d,k as e};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import {s,r as r$1}from'./chunk-33ERV2MW.js';import {b as b$1,a as a$1}from'./chunk-EK4ZRIFJ.js';import {d}from'./chunk-5TAVYPOV.js';import*as r from'fs';import*as a from'path';import*as x from'os';import*as T from'crypto';import*as h from'js-yaml';function w(){let n=a.join(x.homedir(),".paradigm");return r.existsSync(n)||r.mkdirSync(n,{recursive:true}),n}function M(n){let s=a.resolve(n);return T.createHash("sha256").update(s).digest("hex").slice(0,12)}function f(n){let s=M(n),e=a.join(w(),"sessions",s);r.existsSync(e)||r.mkdirSync(e,{recursive:true});let t=a.join(e,"pending-handoffs");return r.existsSync(t)||r.mkdirSync(t,{recursive:true}),e}function S(n){let s=f(n),e=a.join(s,"_project-meta.json"),o={name:a.basename(a.resolve(n)),path:a.resolve(n),lastSeen:new Date().toISOString()};r.writeFileSync(e,JSON.stringify(o,null,2));}function E(n,s){let e=f(n),t=a.join(e,"pending-handoffs",`${s.id}.json`);r.writeFileSync(t,JSON.stringify(s,null,2));}function O(n){let s=f(n),e=a.join(s,"pending-handoffs");if(!r.existsSync(e))return [];let t=[];try{let o=r.readdirSync(e);for(let l of o)if(l.endsWith(".json"))try{let u=r.readFileSync(a.join(e,l),"utf8"),m=JSON.parse(u);m.status==="pending"&&t.push(m);}catch{}}catch{}return t.sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime()),t}function W(n,s){let e=f(n),t=a.join(e,"pending-handoffs",`${s}.json`);if(r.existsSync(t))try{let o=r.readFileSync(t,"utf8"),l=JSON.parse(o);l.status="delivered",r.writeFileSync(t,JSON.stringify(l,null,2));}catch{}}function y(){let n=a.join(w(),"wisdom");return r.existsSync(n)||r.mkdirSync(n,{recursive:true}),n}function H(){let n=a.join(y(),"antipatterns.yaml");if(!r.existsSync(n))return [];try{let s=r.readFileSync(n,"utf8");return h.load(s)?.antipatterns||[]}catch{return []}}function L(){let n=a.join(y(),"decisions");if(!r.existsSync(n))return [];let s=[];try{let e=r.readdirSync(n);for(let t of e)if(!(!t.endsWith(".yaml")&&!t.endsWith(".yml")))try{let o=r.readFileSync(a.join(n,t),"utf8"),l=h.load(o);s.push(l);}catch{}}catch{}return s.sort((e,t)=>e.id.localeCompare(t.id)),s}function _(){let n=a.join(y(),"preferences.yaml");if(!r.existsSync(n))return null;try{let s=r.readFileSync(n,"utf8");return h.load(s)}catch{return null}}function J(n){let s=a.join(y(),"antipatterns.yaml"),e={version:"1.0",antipatterns:[]};if(r.existsSync(s))try{let t=r.readFileSync(s,"utf8"),o=h.load(t);o&&typeof o=="object"&&(e={version:o.version||"1.0",antipatterns:Array.isArray(o.antipatterns)?o.antipatterns:[]});}catch{}e.antipatterns.push({...n,added:new Date().toISOString()}),r.writeFileSync(s,h.dump(e,{lineWidth:-1}));}function U(n){let s=a.join(y(),"decisions");r.existsSync(s)||r.mkdirSync(s,{recursive:true});let e=n.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),t=`${n.id}-${e}.yaml`,o=a.join(s,t);r.writeFileSync(o,h.dump(n,{lineWidth:-1}));}b$1();var k={"claude-opus-4":{input:15,output:75,name:"Claude Opus 4"},"claude-sonnet-4":{input:3,output:15,name:"Claude Sonnet 4"},"claude-haiku-3.5":{input:.8,output:4,name:"Claude Haiku 3.5"}},j=50,P=".paradigm/session-breadcrumbs.json",I=".paradigm/session-checkpoint.json",A=10080*60*1e3,C=class{session;rootDir=null;_recovered=false;lastLoreEntryId=null;constructor(){this.session=this.createNewSession();}setRootDir(s$1){this.rootDir=s$1;try{let{clearSessionWorkLog:e}=(s(),d(r$1));e(s$1);}catch{}}createNewSession(){return {sessionId:`s${Date.now().toString(36)}`,startTime:Date.now(),lastActivity:Date.now(),model:"claude-sonnet-4",resourceReads:[],toolCalls:[],breadcrumbs:[],totals:{resourceReadCount:0,toolCallCount:0,totalBytes:0,totalTokens:0,estimatedCostUsd:0}}}addBreadcrumb(s,e,t={}){this.session.breadcrumbs.push({timestamp:Date.now(),action:s,tool:t.tool,symbol:t.symbol,summary:e}),this.session.breadcrumbs.length>j&&(this.session.breadcrumbs=this.session.breadcrumbs.slice(-j)),this.persistBreadcrumbs();}getBreadcrumbs(s=20){return this.session.breadcrumbs.slice(-s)}persistBreadcrumbs(){if(!this.rootDir)return;let s={sessionId:this.session.sessionId,startTime:this.session.startTime,lastActivity:this.session.lastActivity,breadcrumbs:this.session.breadcrumbs,symbolsModified:this.extractSymbolsFromBreadcrumbs(),filesExplored:this.extractFilesFromBreadcrumbs()},e;try{e=JSON.stringify(s,null,2);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: JSON.stringify failed",{error:t.message});return}try{let t=a.join(this.rootDir,P),o=a.dirname(t);r.existsSync(o)||r.mkdirSync(o,{recursive:!0}),r.writeFileSync(t,e);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: local write failed",{error:t.message});}try{let t=f(this.rootDir);r.writeFileSync(a.join(t,"breadcrumbs.json"),e),S(this.rootDir);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: global write failed",{error:t.message});}}loadPreviousSession(){if(!this.rootDir)return null;try{let s=f(this.rootDir),e=a.join(s,"breadcrumbs.json");if(r.existsSync(e)){let t=r.readFileSync(e,"utf8");return JSON.parse(t)}}catch{}try{let s=a.join(this.rootDir,P);if(!r.existsSync(s))return null;let e=r.readFileSync(s,"utf8");return JSON.parse(e)}catch{return null}}saveCheckpoint(s){let e={phase:s.phase,context:s.context,timestamp:Date.now(),sessionId:this.session.sessionId,externalId:s.externalId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:this.session.breadcrumbs.slice(-10)},t=this.persistCheckpoint(e);return {checkpoint:e,persisted:t}}loadCheckpoint(){if(!this.rootDir)return null;let s=null;try{let e=f(this.rootDir),t=a.join(e,"checkpoint.json");if(r.existsSync(t)){let o=r.readFileSync(t,"utf8");s=JSON.parse(o);}}catch{}if(!s)try{let e=a.join(this.rootDir,I);if(r.existsSync(e)){let t=r.readFileSync(e,"utf8");s=JSON.parse(t);}}catch{}if(s&&Date.now()-s.timestamp>A)return null;if(s)for(let e of ["modifiedFiles","symbolsTouched","decisions"]){let t=s[e];if(typeof t=="string")try{s[e]=JSON.parse(t);}catch{s[e]=[];}}return s}persistCheckpoint(s){let e={local:false,global:false};if(!this.rootDir)return a$1.component("#session-tracker").warn("persistCheckpoint: rootDir not set, skipping write"),e;let t;try{t=JSON.stringify(s,null,2);}catch(o){return a$1.component("#session-tracker").error("persistCheckpoint: JSON.stringify failed",{error:o.message}),e}try{let o=a.join(this.rootDir,I),l=a.dirname(o);r.existsSync(l)||r.mkdirSync(l,{recursive:!0}),r.writeFileSync(o,t),e.local=!0;}catch(o){a$1.component("#session-tracker").error("persistCheckpoint: local write failed",{error:o.message});}try{let o=f(this.rootDir);r.writeFileSync(a.join(o,"checkpoint.json"),t),S(this.rootDir),e.global=!0;}catch(o){a$1.component("#session-tracker").error("persistCheckpoint: global write failed",{error:o.message});}return e}setLastLoreEntryId(s){this.lastLoreEntryId=s;}getLastLoreEntryId(){return this.lastLoreEntryId}hasRecoveredThisSession(){return this._recovered}markRecovered(){this._recovered=true;}extractSymbolsFromBreadcrumbs(){let s=new Set;for(let e of this.session.breadcrumbs)e.symbol&&s.add(e.symbol);return Array.from(s)}extractFilesFromBreadcrumbs(){let s=new Set;for(let e of this.session.breadcrumbs){let t=e.summary.match(/\b[\w./]+\.(ts|js|tsx|jsx|py|go|rs|yaml|json|md)\b/g);if(t)for(let o of t)s.add(o);}return Array.from(s)}estimateTokens(s){let e=typeof s=="number"?s:s.length;return Math.ceil(e/3.5)}calculateCost(s,e=true){let t=k[this.session.model],o=e?t.output:t.input;return s/1e6*o}setModel(s){this.session.model=s,this.recalculateTotals();}getModel(){return this.session.model}trackResourceRead(s,e){let t=this.extractResourceType(s),o=this.estimateTokens(e);this.session.resourceReads.push({timestamp:Date.now(),resourceType:t,uri:s,bytes:e,tokens:o}),this.session.lastActivity=Date.now(),this.updateTotals(e,o);}trackToolCall(s,e){let t=this.estimateTokens(e);this.session.toolCalls.push({timestamp:Date.now(),toolName:s,responseBytes:e,responseTokens:t}),this.session.lastActivity=Date.now(),this.updateTotals(e,t);}updateTotals(s,e){this.session.totals.resourceReadCount=this.session.resourceReads.length,this.session.totals.toolCallCount=this.session.toolCalls.length,this.session.totals.totalBytes+=s,this.session.totals.totalTokens+=e,this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}recalculateTotals(){this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}extractResourceType(s){return s.replace("paradigm://","").split("/")[0]||"unknown"}getStats(){return {...this.session}}getCostBreakdown(){let s={},e=0,t=0;for(let i of this.session.resourceReads)s[i.resourceType]||(s[i.resourceType]={count:0,bytes:0,tokens:0}),s[i.resourceType].count++,s[i.resourceType].bytes+=i.bytes,s[i.resourceType].tokens+=i.tokens,e+=i.bytes,t+=i.tokens;let o={},l=0,u=0;for(let i of this.session.toolCalls)o[i.toolName]||(o[i.toolName]={count:0,bytes:0,tokens:0}),o[i.toolName].count++,o[i.toolName].bytes+=i.responseBytes,o[i.toolName].tokens+=i.responseTokens,l+=i.responseBytes,u+=i.responseTokens;let m=t+u,g=this.calculateCost(m);return {model:k[this.session.model].name,modelId:this.session.model,pricing:k[this.session.model],resources:{count:this.session.resourceReads.length,bytes:e,tokens:t,costUsd:this.calculateCost(t),byType:s},tools:{count:this.session.toolCalls.length,bytes:l,tokens:u,costUsd:this.calculateCost(u),byName:o},total:{tokens:m,costUsd:g}}}getHandoffRecommendation(s=2e5,e){let t=this.session.totals.totalTokens,o=t*4,l=e||t+o,u=Math.round(l/s*100),m,g;u>=85?(m="handoff-urgent",g="Context is nearly full. Initiate handoff immediately to preserve session continuity."):u>=70?(m="handoff-recommended",g="Context usage is high. Consider initiating handoff soon to ensure smooth transition."):u>=50?(m="consider-handoff",g="Context usage is moderate. Plan a good stopping point for potential handoff."):(m="continue",g="Context usage is healthy. Continue working.");let i=[],v=Math.round((Date.now()-this.session.startTime)/6e4),D=this.session.toolCalls.length+this.session.resourceReads.length;return D>50&&i.push(`High number of MCP interactions (${D})`),v>30&&i.push(`Session duration >30 min (${v} min)`),this.session.totals.totalBytes>5e5&&i.push(`Large data volume (${Math.round(this.session.totals.totalBytes/1024)}KB)`),{recommendation:m,message:g,usagePercent:u,signals:i}}getDurationMinutes(){return Math.round((Date.now()-this.session.startTime)/6e4)}reset(){this.session=this.createNewSession(),this._recovered=false,this.lastLoreEntryId=null;}},b=null;function X(){return b||(b=new C),b}function q(){b&&b.reset();}
2
+ import {s,r as r$1}from'./chunk-GADXREYG.js';import {b as b$1,a as a$1}from'./chunk-EK4ZRIFJ.js';import {d}from'./chunk-5TAVYPOV.js';import*as r from'fs';import*as a from'path';import*as x from'os';import*as T from'crypto';import*as h from'js-yaml';function w(){let n=a.join(x.homedir(),".paradigm");return r.existsSync(n)||r.mkdirSync(n,{recursive:true}),n}function M(n){let s=a.resolve(n);return T.createHash("sha256").update(s).digest("hex").slice(0,12)}function f(n){let s=M(n),e=a.join(w(),"sessions",s);r.existsSync(e)||r.mkdirSync(e,{recursive:true});let t=a.join(e,"pending-handoffs");return r.existsSync(t)||r.mkdirSync(t,{recursive:true}),e}function S(n){let s=f(n),e=a.join(s,"_project-meta.json"),o={name:a.basename(a.resolve(n)),path:a.resolve(n),lastSeen:new Date().toISOString()};r.writeFileSync(e,JSON.stringify(o,null,2));}function E(n,s){let e=f(n),t=a.join(e,"pending-handoffs",`${s.id}.json`);r.writeFileSync(t,JSON.stringify(s,null,2));}function O(n){let s=f(n),e=a.join(s,"pending-handoffs");if(!r.existsSync(e))return [];let t=[];try{let o=r.readdirSync(e);for(let l of o)if(l.endsWith(".json"))try{let u=r.readFileSync(a.join(e,l),"utf8"),m=JSON.parse(u);m.status==="pending"&&t.push(m);}catch{}}catch{}return t.sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime()),t}function W(n,s){let e=f(n),t=a.join(e,"pending-handoffs",`${s}.json`);if(r.existsSync(t))try{let o=r.readFileSync(t,"utf8"),l=JSON.parse(o);l.status="delivered",r.writeFileSync(t,JSON.stringify(l,null,2));}catch{}}function y(){let n=a.join(w(),"wisdom");return r.existsSync(n)||r.mkdirSync(n,{recursive:true}),n}function H(){let n=a.join(y(),"antipatterns.yaml");if(!r.existsSync(n))return [];try{let s=r.readFileSync(n,"utf8");return h.load(s)?.antipatterns||[]}catch{return []}}function L(){let n=a.join(y(),"decisions");if(!r.existsSync(n))return [];let s=[];try{let e=r.readdirSync(n);for(let t of e)if(!(!t.endsWith(".yaml")&&!t.endsWith(".yml")))try{let o=r.readFileSync(a.join(n,t),"utf8"),l=h.load(o);s.push(l);}catch{}}catch{}return s.sort((e,t)=>e.id.localeCompare(t.id)),s}function _(){let n=a.join(y(),"preferences.yaml");if(!r.existsSync(n))return null;try{let s=r.readFileSync(n,"utf8");return h.load(s)}catch{return null}}function J(n){let s=a.join(y(),"antipatterns.yaml"),e={version:"1.0",antipatterns:[]};if(r.existsSync(s))try{let t=r.readFileSync(s,"utf8"),o=h.load(t);o&&typeof o=="object"&&(e={version:o.version||"1.0",antipatterns:Array.isArray(o.antipatterns)?o.antipatterns:[]});}catch{}e.antipatterns.push({...n,added:new Date().toISOString()}),r.writeFileSync(s,h.dump(e,{lineWidth:-1}));}function U(n){let s=a.join(y(),"decisions");r.existsSync(s)||r.mkdirSync(s,{recursive:true});let e=n.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),t=`${n.id}-${e}.yaml`,o=a.join(s,t);r.writeFileSync(o,h.dump(n,{lineWidth:-1}));}b$1();var k={"claude-opus-4":{input:15,output:75,name:"Claude Opus 4"},"claude-sonnet-4":{input:3,output:15,name:"Claude Sonnet 4"},"claude-haiku-3.5":{input:.8,output:4,name:"Claude Haiku 3.5"}},j=50,P=".paradigm/session-breadcrumbs.json",I=".paradigm/session-checkpoint.json",A=10080*60*1e3,C=class{session;rootDir=null;_recovered=false;lastLoreEntryId=null;constructor(){this.session=this.createNewSession();}setRootDir(s$1){this.rootDir=s$1;try{let{clearSessionWorkLog:e}=(s(),d(r$1));e(s$1);}catch{}}createNewSession(){return {sessionId:`s${Date.now().toString(36)}`,startTime:Date.now(),lastActivity:Date.now(),model:"claude-sonnet-4",resourceReads:[],toolCalls:[],breadcrumbs:[],totals:{resourceReadCount:0,toolCallCount:0,totalBytes:0,totalTokens:0,estimatedCostUsd:0}}}addBreadcrumb(s,e,t={}){this.session.breadcrumbs.push({timestamp:Date.now(),action:s,tool:t.tool,symbol:t.symbol,summary:e}),this.session.breadcrumbs.length>j&&(this.session.breadcrumbs=this.session.breadcrumbs.slice(-j)),this.persistBreadcrumbs();}getBreadcrumbs(s=20){return this.session.breadcrumbs.slice(-s)}persistBreadcrumbs(){if(!this.rootDir)return;let s={sessionId:this.session.sessionId,startTime:this.session.startTime,lastActivity:this.session.lastActivity,breadcrumbs:this.session.breadcrumbs,symbolsModified:this.extractSymbolsFromBreadcrumbs(),filesExplored:this.extractFilesFromBreadcrumbs()},e;try{e=JSON.stringify(s,null,2);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: JSON.stringify failed",{error:t.message});return}try{let t=a.join(this.rootDir,P),o=a.dirname(t);r.existsSync(o)||r.mkdirSync(o,{recursive:!0}),r.writeFileSync(t,e);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: local write failed",{error:t.message});}try{let t=f(this.rootDir);r.writeFileSync(a.join(t,"breadcrumbs.json"),e),S(this.rootDir);}catch(t){a$1.component("#session-tracker").error("persistBreadcrumbs: global write failed",{error:t.message});}}loadPreviousSession(){if(!this.rootDir)return null;try{let s=f(this.rootDir),e=a.join(s,"breadcrumbs.json");if(r.existsSync(e)){let t=r.readFileSync(e,"utf8");return JSON.parse(t)}}catch{}try{let s=a.join(this.rootDir,P);if(!r.existsSync(s))return null;let e=r.readFileSync(s,"utf8");return JSON.parse(e)}catch{return null}}saveCheckpoint(s){let e={phase:s.phase,context:s.context,timestamp:Date.now(),sessionId:this.session.sessionId,externalId:s.externalId,plan:s.plan,modifiedFiles:s.modifiedFiles,symbolsTouched:s.symbolsTouched,decisions:s.decisions,recentBreadcrumbs:this.session.breadcrumbs.slice(-10)},t=this.persistCheckpoint(e);return {checkpoint:e,persisted:t}}loadCheckpoint(){if(!this.rootDir)return null;let s=null;try{let e=f(this.rootDir),t=a.join(e,"checkpoint.json");if(r.existsSync(t)){let o=r.readFileSync(t,"utf8");s=JSON.parse(o);}}catch{}if(!s)try{let e=a.join(this.rootDir,I);if(r.existsSync(e)){let t=r.readFileSync(e,"utf8");s=JSON.parse(t);}}catch{}if(s&&Date.now()-s.timestamp>A)return null;if(s)for(let e of ["modifiedFiles","symbolsTouched","decisions"]){let t=s[e];if(typeof t=="string")try{s[e]=JSON.parse(t);}catch{s[e]=[];}}return s}persistCheckpoint(s){let e={local:false,global:false};if(!this.rootDir)return a$1.component("#session-tracker").warn("persistCheckpoint: rootDir not set, skipping write"),e;let t;try{t=JSON.stringify(s,null,2);}catch(o){return a$1.component("#session-tracker").error("persistCheckpoint: JSON.stringify failed",{error:o.message}),e}try{let o=a.join(this.rootDir,I),l=a.dirname(o);r.existsSync(l)||r.mkdirSync(l,{recursive:!0}),r.writeFileSync(o,t),e.local=!0;}catch(o){a$1.component("#session-tracker").error("persistCheckpoint: local write failed",{error:o.message});}try{let o=f(this.rootDir);r.writeFileSync(a.join(o,"checkpoint.json"),t),S(this.rootDir),e.global=!0;}catch(o){a$1.component("#session-tracker").error("persistCheckpoint: global write failed",{error:o.message});}return e}setLastLoreEntryId(s){this.lastLoreEntryId=s;}getLastLoreEntryId(){return this.lastLoreEntryId}hasRecoveredThisSession(){return this._recovered}markRecovered(){this._recovered=true;}extractSymbolsFromBreadcrumbs(){let s=new Set;for(let e of this.session.breadcrumbs)e.symbol&&s.add(e.symbol);return Array.from(s)}extractFilesFromBreadcrumbs(){let s=new Set;for(let e of this.session.breadcrumbs){let t=e.summary.match(/\b[\w./]+\.(ts|js|tsx|jsx|py|go|rs|yaml|json|md)\b/g);if(t)for(let o of t)s.add(o);}return Array.from(s)}estimateTokens(s){let e=typeof s=="number"?s:s.length;return Math.ceil(e/3.5)}calculateCost(s,e=true){let t=k[this.session.model],o=e?t.output:t.input;return s/1e6*o}setModel(s){this.session.model=s,this.recalculateTotals();}getModel(){return this.session.model}trackResourceRead(s,e){let t=this.extractResourceType(s),o=this.estimateTokens(e);this.session.resourceReads.push({timestamp:Date.now(),resourceType:t,uri:s,bytes:e,tokens:o}),this.session.lastActivity=Date.now(),this.updateTotals(e,o);}trackToolCall(s,e){let t=this.estimateTokens(e);this.session.toolCalls.push({timestamp:Date.now(),toolName:s,responseBytes:e,responseTokens:t}),this.session.lastActivity=Date.now(),this.updateTotals(e,t);}updateTotals(s,e){this.session.totals.resourceReadCount=this.session.resourceReads.length,this.session.totals.toolCallCount=this.session.toolCalls.length,this.session.totals.totalBytes+=s,this.session.totals.totalTokens+=e,this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}recalculateTotals(){this.session.totals.estimatedCostUsd=this.calculateCost(this.session.totals.totalTokens);}extractResourceType(s){return s.replace("paradigm://","").split("/")[0]||"unknown"}getStats(){return {...this.session}}getCostBreakdown(){let s={},e=0,t=0;for(let i of this.session.resourceReads)s[i.resourceType]||(s[i.resourceType]={count:0,bytes:0,tokens:0}),s[i.resourceType].count++,s[i.resourceType].bytes+=i.bytes,s[i.resourceType].tokens+=i.tokens,e+=i.bytes,t+=i.tokens;let o={},l=0,u=0;for(let i of this.session.toolCalls)o[i.toolName]||(o[i.toolName]={count:0,bytes:0,tokens:0}),o[i.toolName].count++,o[i.toolName].bytes+=i.responseBytes,o[i.toolName].tokens+=i.responseTokens,l+=i.responseBytes,u+=i.responseTokens;let m=t+u,g=this.calculateCost(m);return {model:k[this.session.model].name,modelId:this.session.model,pricing:k[this.session.model],resources:{count:this.session.resourceReads.length,bytes:e,tokens:t,costUsd:this.calculateCost(t),byType:s},tools:{count:this.session.toolCalls.length,bytes:l,tokens:u,costUsd:this.calculateCost(u),byName:o},total:{tokens:m,costUsd:g}}}getHandoffRecommendation(s=2e5,e){let t=this.session.totals.totalTokens,o=t*4,l=e||t+o,u=Math.round(l/s*100),m,g;u>=85?(m="handoff-urgent",g="Context is nearly full. Initiate handoff immediately to preserve session continuity."):u>=70?(m="handoff-recommended",g="Context usage is high. Consider initiating handoff soon to ensure smooth transition."):u>=50?(m="consider-handoff",g="Context usage is moderate. Plan a good stopping point for potential handoff."):(m="continue",g="Context usage is healthy. Continue working.");let i=[],v=Math.round((Date.now()-this.session.startTime)/6e4),D=this.session.toolCalls.length+this.session.resourceReads.length;return D>50&&i.push(`High number of MCP interactions (${D})`),v>30&&i.push(`Session duration >30 min (${v} min)`),this.session.totals.totalBytes>5e5&&i.push(`Large data volume (${Math.round(this.session.totals.totalBytes/1024)}KB)`),{recommendation:m,message:g,usagePercent:u,signals:i}}getDurationMinutes(){return Math.round((Date.now()-this.session.startTime)/6e4)}reset(){this.session=this.createNewSession(),this._recovered=false,this.lastLoreEntryId=null;}},b=null;function X(){return b||(b=new C),b}function q(){b&&b.reset();}
3
3
  export{E as a,O as b,W as c,H as d,L as e,_ as f,J as g,U as h,k as i,X as j,q as k};
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ import {c,b as b$2}from'./chunk-3KVVC4WV.js';import {m,a as a$2,d,g as g$1}from'./chunk-WUSTIEYA.js';import {z,i,c as c$1,f as f$2,j as j$1}from'./chunk-KAFQA7HV.js';import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import {f as f$1,b as b$3}from'./chunk-ECO3LHCE.js';import {b,a as a$1}from'./chunk-5TAVYPOV.js';import*as f from'fs';import*as g from'path';import*as at from'js-yaml';import*as O from'os';function rt(e){return g.join(e,nt,Et)}function Nt(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${e}-${t}`}function x(e,t){let n={id:Nt(),timestamp:new Date().toISOString(),...t};N.push(n),N.length>R&&(N=N.slice(-R));try{let r=g.join(e,nt);f.mkdirSync(r,{recursive:!0});let o=rt(e);f.appendFileSync(o,JSON.stringify(n)+`
3
+ `,"utf8"),xt(o);}catch{}return n}function xt(e){try{if(f.statSync(e).size>512*1024){let r=f.readFileSync(e,"utf8").trim().split(`
4
+ `);if(r.length>R){let o=r.slice(-R);f.writeFileSync(e,o.join(`
5
+ `)+`
6
+ `,"utf8");}}}catch{}}function Wt(e,t){let n=jt(e);return t?.type&&(n=n.filter(r=>r.type===t.type)),t?.source&&(n=n.filter(r=>r.source===t.source)),t?.symbol&&(n=n.filter(r=>r.symbols?.includes(t.symbol))),t?.agent&&(n=n.filter(r=>r.agent===t.agent)),t?.since&&(n=n.filter(r=>r.timestamp>=t.since)),n.sort((r,o)=>o.timestamp.localeCompare(r.timestamp)),t?.limit&&(n=n.slice(0,t.limit)),n}function jt(e){let t=rt(e);if(!f.existsSync(t))return [...N];try{return f.readFileSync(t,"utf8").trim().split(`
7
+ `).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return [...N]}}function ot(e,t,n){let r=0,o=0,i=0,s=0;if(n.symbols?.length&&e.symbols?.length)for(let l of n.symbols)for(let a of e.symbols)et(l,a)&&(r=Math.max(r,1));if(n.paths?.length&&e.path){for(let l of n.paths)if(et(l,e.path)){o=1;break}}if(n.concepts?.length){let l=[e.context||"",...e.keywords||[],e.type||""].join(" ").toLowerCase(),a=0;for(let m of n.concepts)m&&l.includes(m.toLowerCase())&&a++;n.concepts.length>0&&(i=a/n.concepts.length);}if(n.signals?.length){for(let l of n.signals)if(l.type===e.type){s=1;break}}let c=[r,o,i,s].sort((l,a)=>a-l),u=c[0]*.5+c[1]*.2+c[2]*.15+c[3]*.15,d=n.threshold??.6;return {agentId:t,score:u,breakdown:{symbolMatch:r,pathMatch:o,conceptMatch:i,signalMatch:s},shouldNominate:u>=d,quietReason:u<d?"below-threshold":void 0}}function et(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var nt,Et,R,N,it=b(()=>{nt=".paradigm/events",Et="stream.jsonl",R=1e3,N=[];});function U(e){let t=g.join(e,Ft);if(!f.existsSync(t))return {...b$2};try{let n=f.readFileSync(t,"utf8"),r=at.load(n);return kt(b$2,r)}catch{return {...b$2}}}function kt(e,t){let n={...e};if(t.version&&(n.version=t.version),t.default_ring&&(n.default_ring=t.default_ring),t.observation&&(n.observation={allow:t.observation.allow||e.observation?.allow,deny:[...e.observation?.deny||[],...t.observation.deny||[]].filter((r,o,i)=>i.indexOf(r)===o)}),t.streams){n.streams={...e.streams};for(let r of ["work_log","learning_journal","team_decisions"])t.streams[r]&&(n.streams[r]={...e.streams?.[r],...t.streams[r],deny_content:[...e.streams?.[r]?.deny_content||[],...t.streams[r]?.deny_content||[]].filter((o,i,s)=>s.indexOf(o)===i)});}return t.upstream&&(n.upstream={...e.upstream,...t.upstream}),t.network&&(n.network={...e.network,...t.network}),t.agent_overrides&&(n.agent_overrides={...e.agent_overrides,...t.agent_overrides}),t.deployment&&(n.deployment={...e.deployment,...t.deployment}),n}function B(e,t,n){return n&&e.agent_overrides?.[n]?.observation&&e.agent_overrides[n].observation.deny?.some(o=>L(o,t))||e.observation?.deny?.some(r=>L(r,t))?false:e.observation?.allow?.length?e.observation.allow.some(r=>L(r,t)):true}function Zt(e,t,n){let r=t.streams?.[n];if(!r)return {filtered:e,redacted:[]};let o=[],i=e;if(r.redaction)for(let s of r.redaction)try{let c=new RegExp(s.pattern,"gi"),u=i.match(c);u&&(o.push(...u),i=i.replace(c,s.replacement||"[REDACTED]"));}catch{}return {filtered:i,redacted:o}}function L(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var Ft,ct=b(()=>{c();Ft=".paradigm/data-policy.yaml";});function ut(e,t){try{let r=f.readFileSync(e,"utf8").trim().split(`
8
+ `).filter(o=>o.trim());r.length>t&&f.writeFileSync(e,r.slice(-t).join(`
9
+ `)+`
10
+ `,"utf8");}catch{}}function dt(e){try{return f.existsSync(e)?f.readFileSync(e,"utf8").trim().split(`
11
+ `).filter(t=>t.trim()).map(t=>{try{return JSON.parse(t)}catch{return null}}).filter(t=>t!==null):[]}catch{return []}}function ne(e,t){try{let n=g.join(e,j);f.mkdirSync(n,{recursive:!0});let r=g.join(n,lt);f.appendFileSync(r,JSON.stringify(t)+`
12
+ `,"utf8"),ut(r,ft);}catch(n){a.component("#field-failures").warn("failed to record field failure",{agent:t.agent,orchestrationId:t.orchestrationId,error:n instanceof Error?n.message:String(n)});}}function re(e){return dt(g.join(e,j,lt))}function oe(e,t){return `ff-${e}-${t}`}function mt(e,t){try{let n=g.join(e,j);f.mkdirSync(n,{recursive:!0});let r=g.join(n,P);f.appendFileSync(r,JSON.stringify(t)+`
13
+ `,"utf8"),ut(r,ft);}catch(n){a.component("#classroom-certifications").warn("failed to record certification",{agent:t.agent,entryId:t.entryId,error:n instanceof Error?n.message:String(n)});}}function ie(e){return dt(g.join(e,j,P))}function se(e,t,n){try{let r=g.join(e,j,P);if(!f.existsSync(r))return !1;let o=f.readFileSync(r,"utf8").trim().split(`
14
+ `).filter(c=>c.trim()),i=!1,s=o.map(c=>{if(i)return c;try{let u=JSON.parse(c);return u.entryId===t&&u.outcome==="pending"?(i=!0,JSON.stringify({...u,outcome:"overturned",overturnedByFailureId:n,boundAt:new Date().toISOString()})):c}catch{return c}});return i&&f.writeFileSync(r,s.join(`
15
+ `)+`
16
+ `,"utf8"),i}catch(r){return a.component("#classroom-certifications").warn("failed to overturn certification",{entryId:t,error:r instanceof Error?r.message:String(r)}),false}}function ae(e,t){try{let n=g.join(e,j,P);if(!f.existsSync(n))return !1;let r=f.readFileSync(n,"utf8").trim().split(`
17
+ `).filter(s=>s.trim()),o=!1,i=r.map(s=>{if(o)return s;try{let c=JSON.parse(s);return c.entryId===t&&c.outcome==="pending"?(o=!0,JSON.stringify({...c,outcome:"survived",survivedAt:new Date().toISOString()})):s}catch{return s}});return o&&f.writeFileSync(n,i.join(`
18
+ `)+`
19
+ `,"utf8"),o}catch(n){return a.component("#classroom-certifications").warn("failed to survive certification",{entryId:t,error:n instanceof Error?n.message:String(n)}),false}}var j,lt,P,ft,gt=b(()=>{b$1();j=".paradigm/events",lt="field-failures.jsonl",P="classroom-certifications.jsonl",ft=500;});function $t(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${e}-${t}`}function It(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${e}-${t}`}function yt(e,t){let n=i(e),r=U(e),o=[];for(let d of n){if(!d.attention||!c$1(d.id,e)||t.path&&!B(r,t.path,d.id))continue;let l=ot(t,d.id,d.attention);l.shouldNominate&&o.push({profile:d,score:l});}if(o.length===0)return {nominations:[],debates:[]};let i$1=$(e,{since:new Date(Date.now()-3e4).toISOString()}),s=o.filter(({profile:d})=>!i$1.find(a=>a.agent===d.id&&a.brief===pt(d,t,{...o.find(m=>m.profile.id===d.id).score})));if(s.length===0)return {nominations:[],debates:[]};let c=s.map(({profile:d,score:l})=>{let a=Mt(t,l),m=Jt(d,t);return {id:$t(),agent:d.id,relevance:l.score,urgency:a,type:m,brief:pt(d,t,l),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});Ut(e,c);let u=Lt(e,c);return u.length>0&&Bt(e,u),{nominations:c,debates:u}}function Mt(e,t){return e.severity==="critical"?"critical":e.severity==="error"||e.type==="compliance-violation"||e.type==="error-encountered"?"high":e.type==="gate-added"||e.type==="route-created"||t.score>=.9?"medium":"low"}function Jt(e,t){let n=e.collaboration?.stance;return t.type==="compliance-violation"||t.type==="error-encountered"?"warning":t.type==="gate-added"||t.type==="route-created"?"observation":n==="advisory"||n==="lead"?"suggestion":"observation"}function pt(e,t,n){let r=e.role||e.id;switch(t.type){case "gate-checked":return `${r}: Gate check on ${t.symbols?.join(", ")||"route"} \u2014 verify gate coverage is complete`;case "file-modified":return `${r}: ${t.path||"File"} modified \u2014 review for ${e.id==="security"?"security implications":e.id==="tester"?"test coverage":e.id==="reviewer"?"code quality":"consistency"}`;case "compliance-violation":return `${r}: Compliance violation detected \u2014 ${t.context||"check .purpose and portal.yaml coverage"}`;case "route-created":return `${r}: New route ${t.symbols?.join(", ")||""} \u2014 ${e.id==="security"?"needs gate assignment in portal.yaml":"review route structure"}`;case "gate-added":return `${r}: Gate ${t.symbols?.join(", ")||""} added \u2014 ${e.id==="security"?"verify enforcement points":"check downstream impact"}`;case "decision-made":return `${r}: Decision recorded \u2014 ${t.context?.slice(0,80)||"review for alignment with project patterns"}`;case "work-completed":return `${r}: Work completed on ${t.symbols?.join(", ")||t.context?.slice(0,40)||"task"} \u2014 review outcome`;case "error-encountered":return `${r}: Error detected \u2014 ${t.context?.slice(0,80)||"investigate root cause"}`;default:{let o=n.breakdown.symbolMatch>0?`symbol match on ${t.symbols?.join(", ")||"unknown"}`:n.breakdown.pathMatch>0?`path ${t.path||"unknown"}`:t.context?.slice(0,60)||t.type;return `${r}: ${o}`}}}function Lt(e,t){if(t.length<2)return [];let n=[],r=new Map;for(let o of t)for(let i of o.triggered_by){let s=r.get(i)||[];s.push(o),r.set(i,s);}for(let[o,i]of r){if(i.length<2||new Set(i.map(d=>d.agent)).size<2)continue;let c=new Set(i.map(d=>d.type)),u=c.size>1&&c.has("warning")&&c.has("suggestion");n.push({id:It(),topic:`Multiple agents responded to event ${o}`,nominations:i.map(d=>d.id),type:u?"conflicting":"complementary",overlap_events:[o]});}return n}function q(e){return g.join(e,_,Tt)}function G(e){return g.join(e,_,Rt)}function Ut(e,t){try{let n=g.join(e,_);f.mkdirSync(n,{recursive:!0});let r=q(e),o=t.map(s=>JSON.stringify(s)).join(`
20
+ `)+`
21
+ `;f.appendFileSync(r,o,"utf8"),H(r,ht);let{nominationTtlDays:i}=D(e);St(r,i*24*60*60*1e3);}catch{}}function Bt(e,t){try{let n=g.join(e,_);f.mkdirSync(n,{recursive:!0});let r=G(e),o=t.map(s=>JSON.stringify(s)).join(`
22
+ `)+`
23
+ `;f.appendFileSync(r,o,"utf8"),H(r,Ct);let{debateTtlDays:i}=D(e);St(r,i*24*60*60*1e3);}catch{}}function qt(e,t){try{let n=g.join(e,_);f.mkdirSync(n,{recursive:!0});let r=g.join(n,At);f.appendFileSync(r,JSON.stringify(t)+`
24
+ `,"utf8"),H(r,ht);}catch(n){a.component("#promotion-decisions").warn("failed to record promotion decision",{agent:t.agent,error:n instanceof Error?n.message:String(n)});}}function H(e,t){try{let r=f.readFileSync(e,"utf8").trim().split(`
25
+ `).filter(o=>o.trim());if(r.length>t){let o=r.slice(-t);f.writeFileSync(e,o.join(`
26
+ `)+`
27
+ `,"utf8");}}catch{}}function D(e){let t={nominationTtlDays:Pt,debateTtlDays:Ot};try{let n=g.join(e,".paradigm","config.yaml");if(!f.existsSync(n))return t;let r=a$1("js-yaml"),o=f.readFileSync(n,"utf8"),s=r.load(o)?.ambient;return s?{nominationTtlDays:typeof s["nomination-ttl-days"]=="number"?s["nomination-ttl-days"]:t.nominationTtlDays,debateTtlDays:typeof s["debate-ttl-days"]=="number"?s["debate-ttl-days"]:t.debateTtlDays}:t}catch{return t}}function St(e,t){try{if(!f.existsSync(e))return;let r=f.readFileSync(e,"utf8").trim().split(`
28
+ `).filter(s=>s.trim());if(r.length<=Dt)return;let o=Date.now()-t,i=r.filter(s=>{try{let c=JSON.parse(s);return (c.timestamp?new Date(c.timestamp).getTime():Date.now())>=o}catch{return !0}});i.length<r.length&&f.writeFileSync(e,i.join(`
29
+ `)+`
30
+ `,"utf8");}catch{}}function $(e,t){let n=q(e);if(!f.existsSync(n))return [];try{let o=f.readFileSync(n,"utf8").trim().split(`
31
+ `).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null);return t?.agent&&(o=o.filter(i=>i.agent===t.agent)),t?.urgency&&(o=o.filter(i=>i.urgency===t.urgency)),t?.surfaced!==void 0&&(o=o.filter(i=>i.surfaced===t.surfaced)),t?.pending_only&&(o=o.filter(i=>!i.engaged)),t?.since&&(o=o.filter(i=>i.timestamp>=t.since)),o.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),t?.limit&&(o=o.slice(0,t.limit)),o}catch{return []}}function he(e){let t=G(e);if(!f.existsSync(t))return [];try{return f.readFileSync(t,"utf8").trim().split(`
32
+ `).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function ye(e,t,n,r){let o=q(e);if(!f.existsSync(o))return false;try{let s=f.readFileSync(o,"utf8").trim().split(`
33
+ `),c=!1,u=s.map(d=>{try{let l=JSON.parse(d);return l.id===t?(l.engaged=!0,l.response=n,r&&(l.reason=r),c=!0,JSON.stringify(l)):d}catch{return d}});if(c&&(f.writeFileSync(o,u.join(`
34
+ `)+`
35
+ `,"utf8"),n==="accepted"||n==="dismissed")){let d=JSON.parse(s.find(a=>{try{return JSON.parse(a).id===t}catch{return !1}}));i(e).find(a=>a.id===d.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&x(e,{type:"work-completed",source:"agent-action",agent:d.agent,context:`Nomination ${t} ${n} \u2014 feedback for learning`,data:{nomination_id:t,response:n}});}return c}catch{return false}}function Se(e,t,n,r){let o=G(e);if(!f.existsSync(o))return false;try{let s=f.readFileSync(o,"utf8").trim().split(`
36
+ `),c=!1,u=s.map(d=>{try{let l=JSON.parse(d);if(l.id===t){l.resolution={chosen:n,reason:r,resolved_by:"human",resolved_at:new Date().toISOString()},c=!0;let a=l.nominations.filter(m=>m!==n);for(let m of a){let h=$(e).find(b=>b.id===m);h&&x(e,{type:"work-completed",source:"agent-action",agent:h.agent,context:`Debate ${t} resolved \u2014 nomination ${m} not chosen`,data:{debate_id:t,chosen:n,reason:r}});}return JSON.stringify(l)}return d}catch{return d}});return c&&f.writeFileSync(o,u.join(`
37
+ `)+`
38
+ `,"utf8"),c}catch{return false}}function be(e){let t=g.join(e,_,".last-processed"),n="";try{f.existsSync(t)&&(n=f.readFileSync(t,"utf8").trim());}catch{}let r=g.join(e,_,"stream.jsonl");if(!f.existsSync(r))return {processed:0,nominations:[]};let o=[];try{o=f.readFileSync(r,"utf8").trim().split(`
39
+ `).filter(a=>a.trim()).map(a=>{try{return JSON.parse(a)}catch{return null}}).filter(a=>a!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(n){let l=o.findIndex(a=>a.id===n);l>=0&&(i=l+1);}let s=o.slice(i);if(s.length===0)return {processed:0,nominations:[]};let c=[],u=s.slice(0,50);for(let l of u){let{nominations:a}=yt(e,l);c.push(...a);}let d=u[u.length-1];try{f.mkdirSync(g.join(e,_),{recursive:!0}),f.writeFileSync(t,d.id,"utf8");}catch{}return {processed:u.length,nominations:c}}function we(e,t,n){let r=U(e);if(t.path&&!B(r,t.path))return {event:x(e,t),nominations:[],debates:[]};let o=x(e,t);if(n?.skipNominations)return {event:o,nominations:[],debates:[]};let{nominations:i,debates:s}=yt(e,o);return i.length>0&&Ht(e,i),{event:o,nominations:i,debates:s}}function _e(e,t){let n=f$2(e,t);if(!n?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let r=n.attention.threshold??.6,{nominationTtlDays:o}=D(e),i=o*24*60*60*1e3,u=$(e,{agent:t}).filter(y=>y.engaged||Date.now()-new Date(y.timestamp).getTime()<i).filter(y=>y.engaged);if(u.length<5)return {adjusted:false,oldThreshold:r,newThreshold:r,reason:`Insufficient data (${u.length}/5 engaged nominations)`};let d=u.filter(y=>y.response==="accepted").length,l=u.filter(y=>y.response==="dismissed").length,a=d/u.length,m=l/u.length,h=r,b="No adjustment needed";if(m>.6?(h=Math.min(.95,r+.05),b=`High dismiss rate (${(m*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):a>.8&&(h=Math.max(.2,r-.05),b=`High accept rate (${(a*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),h===r)return {adjusted:false,oldThreshold:r,newThreshold:h,reason:b};n.attention.threshold=h;let v=g.join(e,".paradigm/agents",`${t}.agent`),F=f.existsSync(v)?"project":"global";return j$1(t,n,F,e),x(e,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${r.toFixed(2)} \u2192 ${h.toFixed(2)} (${b})`,data:{old_threshold:r,new_threshold:h,accept_rate:a,dismiss_rate:m}}),{adjusted:true,oldThreshold:r,newThreshold:h,reason:b}}function Gt(e,t){let{nominationTtlDays:n}=D(e),r=n*24*60*60*1e3,i=$(e,{agent:t}).filter(a=>a.engaged||Date.now()-new Date(a.timestamp).getTime()<r),s=i.filter(a=>a.response==="accepted").length,c=i.filter(a=>a.response==="dismissed").length,u=i.filter(a=>a.response==="deferred").length,d=i.filter(a=>!a.engaged).length,l=s+c+u;return {total:i.length,accepted:s,dismissed:c,deferred:u,pending:d,acceptRate:l>0?s/l:0}}function ve(e){let n=i(e).filter(a=>c$1(a.id,e)).map(a=>{let m=Gt(e,a.id),h=0;try{let b=g.join(O.homedir(),".paradigm","notebooks",a.id);f.existsSync(b)&&(h=f.readdirSync(b).filter(v=>v.endsWith(".yaml")).length);}catch{}return {id:a.id,acceptRate:m.acceptRate,threshold:a.attention?.threshold??.5,expertiseCount:(a.expertise||[]).length,notebookCount:h,transferableCount:(a.transferable||[]).length,totalNominations:m.total}}),r=n.length||1,o=n.reduce((a,m)=>a+m.acceptRate,0)/r,i$1=n.reduce((a,m)=>a+m.threshold,0)/r,s=n.reduce((a,m)=>a+m.expertiseCount,0),c=n.reduce((a,m)=>a+m.notebookCount,0),u=n.reduce((a,m)=>a+m.transferableCount,0),d=n.reduce((a,m)=>a+m.totalNominations,0),l;return d<10?l="cold-start":o<.5?l="accumulating":o<.7?l="calibrating":l="mature",{agents:n,aggregate:{avgAcceptRate:o,avgThreshold:i$1,totalExpertise:s,totalNotebooks:c,totalTransferable:u},healthStatus:l}}function Ht(e,t){if(t.length===0)return;let n=g.join(O.homedir(),".paradigm","score","outbox");if(f.existsSync(n))try{let r=g.join(n,`nom-${Date.now()}.json`),o={type:"nomination_forward",nominations:t.map(i=>({...i})),origin:Yt(e),timestamp:new Date().toISOString()};f.writeFileSync(r,JSON.stringify(o),"utf8");}catch{}}function Yt(e){try{let t=g.join(e,".paradigm","config.yaml");if(f.existsSync(t)){let r=f.readFileSync(t,"utf8").match(/project:\s*(.+)/);if(r)return r[1].trim()}}catch{}return g.basename(e)}function Ee(e,t){let n=b$3(t,{trigger:"pattern_discovered",limit:100}),r=b$3(t,{trigger:"human_feedback",limit:100}),o=[...n,...r],i=[];for(let s of o){if(s.promoted_to_notebook)continue;let c=(s.tags||[s.pattern?.id||"learned-pattern"]).map(a$2).filter(Boolean),u=s.confidence_after??0,d$1=u>=.8,l=.5,a=false;try{let m=d(t,c,e);l=m.value,a=m.found;}catch{}if(qt(e,{ts:new Date().toISOString(),agent:t,concepts:c,before:l,after:u,delta:u-l,promoted:d$1,priorFound:a,gate:"absolute-0.8"}),!((s.confidence_after??0)<.8))try{let{entry:m}=g$1(t,{context:s.pattern?.applies_when||s.insight.slice(0,80),snippet:s.pattern?.correct_approach||s.insight,confidence:s.confidence_after??.5,concepts:c,tags:s.tags??[],provenance:{source:"lore",loreEntryId:s.id,createdBy:t}},"global",e);i.push({journalId:s.id,notebookId:m.id});try{mt(e,{ts:new Date().toISOString(),agent:t,entryId:m.id,concepts:c,confidenceAtCert:s.confidence_after??.5,certifiedBy:"gate",outcome:"pending"});}catch{}try{let h=g.join(O.homedir(),".paradigm","agents",t,"journal");if(f.existsSync(h)){let b=f.readdirSync(h).filter(v=>v.endsWith(".yaml"));for(let v of b){let F=g.join(h,v),y=f.readFileSync(F,"utf8");if(y.includes(s.id)){let Y=y.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${m.id}"`);if(Y===y){let z=y.trimEnd().split(`
40
+ `);z.push(`promoted_to_notebook: "${m.id}"`),f.writeFileSync(F,z.join(`
41
+ `)+`
42
+ `,"utf8");}else f.writeFileSync(F,Y,"utf8");break}}}}catch{}}catch(m){console.error("PROMOTE_THREW",m.message);}}return {promoted:i.length,entries:i}}function Ne(e){let t=g.join(e,zt),n={default_min_urgency:"low",enable_debates:true};if(!f.existsSync(t))return n;try{let r=a$1("js-yaml"),o=f.readFileSync(t,"utf8"),i=r.load(o);return {...n,...i}}catch{return n}}function xe(e,t){let n={critical:0,high:1,medium:2,low:3},r=n[t.default_min_urgency||"low"]??3;return e.filter(o=>{let i=n[o.urgency]??3;if(t.preferences){let s=t.preferences.find(c=>c.agent===o.agent);if(s){if(s.always_show)return true;if(s.mute_unless?.length&&!s.mute_unless.some(u=>o.urgency===u||o.type===u))return false;if(s.min_urgency){let c=n[s.min_urgency]??3;return i<=c}}}return i<=r})}var _,Tt,At,Rt,ht,Ct,Pt,Ot,Dt,zt,Vt=b(()=>{it();ct();z();f$1();m();gt();b$1();_=".paradigm/events",Tt="nominations.jsonl",At="promotion-decisions.jsonl",Rt="debates.jsonl",ht=500,Ct=200,Pt=7,Ot=14,Dt=100;zt=".paradigm/surfacing.yaml";});export{Ne as A,xe as B,Vt as C,Wt as a,it as b,U as c,Zt as d,ct as e,ne as f,re as g,oe as h,ie as i,se as j,ae as k,gt as l,yt as m,Lt as n,Ut as o,$ as p,he as q,ye as r,Se as s,be as t,we as u,_e as v,Gt as w,ve as x,Ht as y,Ee as z};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {j,a,c,b as b$1,k as k$1}from'./chunk-ACJWUOMA.js';import*as m from'fs';import*as b from'path';import*as k from'js-yaml';function re(o,e="unknown"){j().trackToolCall(e,o);}function W(){k$1();}function J(o,e){switch(o){case "paradigm_search":return {summary:`Searched for "${e.query}"${e.type?` (type: ${e.type})`:""}`,symbol:e.query};case "paradigm_ripple":return {summary:`Ripple analysis on ${e.symbol}${e.depth?` (depth: ${e.depth})`:""}`,symbol:e.symbol};case "paradigm_related":return {summary:`Checked relations for ${e.symbol}`,symbol:e.symbol};case "paradigm_status":return {summary:"Checked project status"};case "paradigm_navigate":{let n=e.intent,t=e.target,s=e.task;return n==="context"&&s?{summary:`Navigate context: "${s}"`}:t?{summary:`Navigate ${n||"find"}: ${t}`,symbol:t}:{summary:`Navigate (${n||"unknown"})`}}case "paradigm_gates_for_route":return {summary:`Gate suggestions for ${e.method||"GET"} ${e.route}`};case "paradigm_wisdom_context":return {summary:`Checked wisdom for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_context":return {summary:`Checked history for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_record":return {summary:`Recorded ${e.type}: ${(e.description||"").slice(0,60)}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_fragility":return {summary:`Checked fragility for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_flows_affected":return {summary:`Checked flows affected by ${e.symbol}`,symbol:e.symbol};case "paradigm_reindex":return {summary:"Rebuilt static index files"};case "paradigm_session_checkpoint":return {summary:`Checkpoint: phase=${e.phase}, ${(e.context||"").slice(0,60)}`};case "paradigm_task_create":return {summary:`Created task: "${(e.blurb||"").slice(0,60)}"`};case "paradigm_task_done":return {summary:`Completed task ${e.id}`};case "paradigm_task_shelve":return {summary:`Shelved task ${e.id}`};case "paradigm_task_list":return {summary:`Listed tasks (status: ${e.status||"open"})`};case "paradigm_task_update":return {summary:`Updated task ${e.id}`};case "paradigm_assessment_record":return {summary:`Assessment: ${(e.title||"").slice(0,60)} \u2192 ${e.arc_id}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_assessment_list":return {summary:e.arc_id?`Listed entries in ${e.arc_id}`:"Listed assessment arcs"};case "paradigm_assessment_search":return {summary:`Searched assessments${e.symbol?` for ${e.symbol}`:""}`,symbol:e.symbol};case "paradigm_assessment_arc_create":return {summary:`Created arc: ${e.id}`};case "paradigm_assessment_arc_close":return {summary:`Closed arc: ${e.arc_id}`};default:{let n=o.replace(/^paradigm_/,""),t=Object.values(e).find(s=>typeof s=="string"&&s.length>0);return {summary:t?`${n}: ${t.slice(0,60)}`:n,symbol:e.symbol||void 0}}}}function ae(o,e){let n=j(),{summary:t,symbol:s}=J(o,e);n.addBreadcrumb("tool-call",t,{tool:o,symbol:s});}function ce(){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 de(o,e,n){let t=j();if(o==="paradigm_session_health"||o==="paradigm_context_check"){let s=e.contextWindowSize||2e5,i=e.estimatedTotalTokens,a=t.getStats(),{recommendation:r,message:u,usagePercent:l,signals:d}=t.getHandoffRecommendation(s,i),c=t.getDurationMinutes();return {handled:true,text:JSON.stringify({recommendation:r,message:u,stats:{sessionDurationMinutes:c,mcpToolCalls:a.totals.toolCallCount,mcpResourceReads:a.totals.resourceReadCount,estimatedMcpTokens:a.totals.totalTokens,estimatedTotalTokens:i||Math.round(a.totals.totalTokens*5),contextWindowSize:s,usagePercent:l},signals:d,action:r==="continue"?null:"Call paradigm_handoff_prepare to create handoff file"},null,2)}}if(o==="paradigm_handoff_prepare"){let s=e.summary,i=e.nextSteps||[],a$1=e.agent||"builder",r=e.modifiedFiles||[],u=e.symbolsTouched||[],l=e.openQuestions||[],d=t.getStats(),c=t.getCostBreakdown(),f=`h${Date.now().toString(36)}`,g=new Date().toISOString(),p={id:f,timestamp:g,from:"current-session",to:a$1,summary:s,nextSteps:i,modifiedFiles:r,symbolsTouched:u,openQuestions:l,sessionStats:{duration:t.getDurationMinutes(),mcpCalls:d.totals.toolCallCount+d.totals.resourceReadCount,estimatedTokens:d.totals.totalTokens,estimatedCostUsd:c.total.costUsd,model:c.model},status:"pending"},y=false;try{a(n.rootDir,p),y=!0;}catch{}let w=`# Handoff: ${g}
2
+ import {j,a,c,b as b$1,k as k$1}from'./chunk-74NGU6YN.js';import*as m from'fs';import*as b from'path';import*as k from'js-yaml';function re(o,e="unknown"){j().trackToolCall(e,o);}function W(){k$1();}function J(o,e){switch(o){case "paradigm_search":return {summary:`Searched for "${e.query}"${e.type?` (type: ${e.type})`:""}`,symbol:e.query};case "paradigm_ripple":return {summary:`Ripple analysis on ${e.symbol}${e.depth?` (depth: ${e.depth})`:""}`,symbol:e.symbol};case "paradigm_related":return {summary:`Checked relations for ${e.symbol}`,symbol:e.symbol};case "paradigm_status":return {summary:"Checked project status"};case "paradigm_navigate":{let n=e.intent,t=e.target,s=e.task;return n==="context"&&s?{summary:`Navigate context: "${s}"`}:t?{summary:`Navigate ${n||"find"}: ${t}`,symbol:t}:{summary:`Navigate (${n||"unknown"})`}}case "paradigm_gates_for_route":return {summary:`Gate suggestions for ${e.method||"GET"} ${e.route}`};case "paradigm_wisdom_context":return {summary:`Checked wisdom for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_context":return {summary:`Checked history for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_record":return {summary:`Recorded ${e.type}: ${(e.description||"").slice(0,60)}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_history_fragility":return {summary:`Checked fragility for ${Array.isArray(e.symbols)?e.symbols.join(", "):"symbols"}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_flows_affected":return {summary:`Checked flows affected by ${e.symbol}`,symbol:e.symbol};case "paradigm_reindex":return {summary:"Rebuilt static index files"};case "paradigm_session_checkpoint":return {summary:`Checkpoint: phase=${e.phase}, ${(e.context||"").slice(0,60)}`};case "paradigm_task_create":return {summary:`Created task: "${(e.blurb||"").slice(0,60)}"`};case "paradigm_task_done":return {summary:`Completed task ${e.id}`};case "paradigm_task_shelve":return {summary:`Shelved task ${e.id}`};case "paradigm_task_list":return {summary:`Listed tasks (status: ${e.status||"open"})`};case "paradigm_task_update":return {summary:`Updated task ${e.id}`};case "paradigm_assessment_record":return {summary:`Assessment: ${(e.title||"").slice(0,60)} \u2192 ${e.arc_id}`,symbol:Array.isArray(e.symbols)?e.symbols[0]:void 0};case "paradigm_assessment_list":return {summary:e.arc_id?`Listed entries in ${e.arc_id}`:"Listed assessment arcs"};case "paradigm_assessment_search":return {summary:`Searched assessments${e.symbol?` for ${e.symbol}`:""}`,symbol:e.symbol};case "paradigm_assessment_arc_create":return {summary:`Created arc: ${e.id}`};case "paradigm_assessment_arc_close":return {summary:`Closed arc: ${e.arc_id}`};default:{let n=o.replace(/^paradigm_/,""),t=Object.values(e).find(s=>typeof s=="string"&&s.length>0);return {summary:t?`${n}: ${t.slice(0,60)}`:n,symbol:e.symbol||void 0}}}}function ae(o,e){let n=j(),{summary:t,symbol:s}=J(o,e);n.addBreadcrumb("tool-call",t,{tool:o,symbol:s});}function ce(){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 de(o,e,n){let t=j();if(o==="paradigm_session_health"||o==="paradigm_context_check"){let s=e.contextWindowSize||2e5,i=e.estimatedTotalTokens,a=t.getStats(),{recommendation:r,message:u,usagePercent:l,signals:d}=t.getHandoffRecommendation(s,i),c=t.getDurationMinutes();return {handled:true,text:JSON.stringify({recommendation:r,message:u,stats:{sessionDurationMinutes:c,mcpToolCalls:a.totals.toolCallCount,mcpResourceReads:a.totals.resourceReadCount,estimatedMcpTokens:a.totals.totalTokens,estimatedTotalTokens:i||Math.round(a.totals.totalTokens*5),contextWindowSize:s,usagePercent:l},signals:d,action:r==="continue"?null:"Call paradigm_handoff_prepare to create handoff file"},null,2)}}if(o==="paradigm_handoff_prepare"){let s=e.summary,i=e.nextSteps||[],a$1=e.agent||"builder",r=e.modifiedFiles||[],u=e.symbolsTouched||[],l=e.openQuestions||[],d=t.getStats(),c=t.getCostBreakdown(),f=`h${Date.now().toString(36)}`,g=new Date().toISOString(),p={id:f,timestamp:g,from:"current-session",to:a$1,summary:s,nextSteps:i,modifiedFiles:r,symbolsTouched:u,openQuestions:l,sessionStats:{duration:t.getDurationMinutes(),mcpCalls:d.totals.toolCallCount+d.totals.resourceReadCount,estimatedTokens:d.totals.totalTokens,estimatedCostUsd:c.total.costUsd,model:c.model},status:"pending"},y=false;try{a(n.rootDir,p),y=!0;}catch{}let w=`# Handoff: ${g}
3
3
 
4
4
  ## Session Summary
5
5
  ${s}
@@ -12,6 +12,6 @@ ${i.map((S,v)=>`${v+1}. ${S}`).join(`
12
12
  - Modified files: ${r.length>0?r.join(", "):"(not specified)"}
13
13
  - Symbols touched: ${u.length>0?u.join(", "):"(not specified)"}
14
14
  - Open questions: ${l.length>0?l.join(", "):"(none)"}
15
- `;return W(),{handled:true,text:JSON.stringify({handoff:p,markdownSummary:w,persisted:y,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(o==="paradigm_session_stats"){let s=t.getStats(),i=t.getCostBreakdown(),a=t.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(s.startTime).toISOString(),durationMinutes:a,lastActivity:new Date(s.lastActivity).toISOString()},model:{name:i.model,id:i.modelId,pricing:{inputPerMillion:`$${i.pricing.input.toFixed(2)}`,outputPerMillion:`$${i.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:i.resources.tokens,tools:i.tools.tokens}},cost:{totalUsd:`$${i.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${i.resources.costUsd.toFixed(4)}`,tools:`$${i.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:i.resources.byType,toolsByName:i.tools.byName}},null,2)}}if(o==="paradigm_session_recover"){let{checkpoint:s,pendingHandoffs:i,previousSession:a}=z(n.rootDir);if(!a&&i.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 r={found:true};if(s){let l=Date.now()-s.timestamp,d=Math.round(l/6e4),c=Math.round(l/36e5);r.checkpoint={phase:s.phase,context:s.context,age:c>1?`${c} hours ago`:`${d} 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(a){let l=Date.now()-a.lastActivity,d=Math.round(l/6e4),c=Math.round(l/36e5),g=a.breadcrumbs.slice(-10).map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}));r.previousSession={sessionId:a.sessionId,startTime:new Date(a.startTime).toISOString(),lastActivity:new Date(a.lastActivity).toISOString(),age:c>1?`${c} hours ago`:`${d} minutes ago`},r.context={symbolsModified:a.symbolsModified,filesExplored:a.filesExplored},r.recentActions=g;}if(i.length>0){r.pendingHandoffs=i.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 i)try{c(n.rootDir,l.id);}catch{}}let u="Continue where the previous session left off.";if(s)u=`Previous session was in "${s.phase}" phase: ${s.context}`,s.decisions?.length&&(u+=` Key decisions: ${s.decisions.slice(0,2).join("; ")}`);else if(i.length>0){let l=i[i.length-1];u=`Handoff received: "${l.summary}". `,l.nextSteps.length>0&&(u+=`Start with: ${l.nextSteps[0]}`);}else if(a){let l=a.breadcrumbs.slice(-10);if(l.length>0){let d=l[l.length-1];d.symbol&&(u=`Last work involved ${d.symbol}. Consider checking its current state with paradigm_ripple.`);}}return r.suggestion=u,r.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.",t.markRecovered(),{handled:true,text:JSON.stringify(r,null,2)}}if(o==="paradigm_session_checkpoint"){t.setRootDir(n.rootDir);let s=e.phase,i=e.context,a=e.externalId,r=e.plan,u=e.modifiedFiles,l=e.symbolsTouched,d=e.decisions,{checkpoint:c,persisted:f}=t.saveCheckpoint({phase:s,context:i,externalId:a,plan:r,modifiedFiles:u,symbolsTouched:l,decisions:d}),g=f.local||f.global;return {handled:true,text:JSON.stringify({saved:g,persisted:f,checkpoint:{phase:c.phase,context:c.context,sessionId:c.sessionId,...c.externalId?{externalId:c.externalId}:{},timestamp:new Date(c.timestamp).toISOString(),modifiedFiles:c.modifiedFiles?.length||0,symbolsTouched:c.symbolsTouched?.length||0,decisions:c.decisions?.length||0,recentBreadcrumbs:c.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 z(o){let e=j();e.setRootDir(o);let n=e.loadCheckpoint(),t=e.loadPreviousSession(),s=[];try{s=b$1(o);}catch{}return {checkpoint:n,pendingHandoffs:s,previousSession:t}}async function le(o){let{checkpoint:e,pendingHandoffs:n}=z(o);if(!e&&n.length===0)return null;let t=[];if(t.push("--- SESSION RECOVERY ---"),e){let s=Date.now()-e.timestamp,i=Math.round(s/6e4),a=Math.round(s/36e5),r=a>1?`${a}h ago`:`${i}m ago`;t.push(`Previous session was in "${e.phase}" phase (${r}): ${e.context}`),e.modifiedFiles?.length&&t.push(`Modified files: ${e.modifiedFiles.join(", ")}`),e.symbolsTouched?.length&&t.push(`Symbols: ${e.symbolsTouched.join(", ")}`),e.decisions?.length&&t.push(`Decisions: ${e.decisions.join("; ")}`),e.plan&&t.push(`Plan: ${e.plan.slice(0,200)}`);}if(n.length>0){let s=n[n.length-1];t.push(`Pending handoff: "${s.summary}"`),s.nextSteps.length>0&&t.push(`Next steps: ${s.nextSteps.slice(0,3).join(", ")}`);}try{try{let{reapStaleInProgress:u}=await import('./task-settlement-TATNPY6L.js');await u(o);}catch{}let{assembleCaptainBoard:s,proposeClaimantFor:i}=await import('./captain-CWCLFOXV.js'),a=await s(o,{proposeClaimants:!0}),r=a.unclaimed.slice(0,5);if(a.summary.open>0||a.summary.inFlight>0||a.summary.runs>0){t.push(""),t.push(`Cid (captain): ${a.summary.open} open, ${a.summary.inFlight} in-flight`+(a.summary.runs>0?`, ${a.summary.runs} active run(s)`:"")+`, ${a.summary.unclaimed} unclaimed`);let{updateTask:u,loadTask:l}=await import('./task-loader-HBZ3KRH2.js');for(let d of r){let c=d.tags.length>0?` [${d.tags.join(", ")}]`:"",f=d.proposedClaimant;if(!f){let g=await l(o,d.taskId);g&&(f=await i(g,o));}if(f){try{let g=await l(o,d.taskId);g&&!g.claimant&&g.status==="open"&&await u(o,d.taskId,{claimant:f});}catch{}t.push(` [${d.priority}] ${d.taskId}: ${d.blurb}${c} \u2192 proposed ${f.ref}`);}else t.push(` [${d.priority}] ${d.taskId}: ${d.blurb}${c}`);}}}catch{try{let{loadTasks:s}=await import('./task-loader-HBZ3KRH2.js'),i=await s(o,{status:"open",limit:5});if(i.length>0){t.push(""),t.push("Open tasks:");for(let a of i){let r=a.tags.length>0?` [${a.tags.join(", ")}]`:"";t.push(` [${a.priority}] ${a.id}: ${a.blurb}${r}`);}}}catch{}}try{let{loadLoreEntries:s}=await import('./lore-loader-PXFKMKAN.js'),a=(await s(o,{limit:10})).filter(r=>r.tags?.some(u=>u.startsWith("arc:")));if(a.length>0){let r=new Map;for(let d of a){let c=d.tags?.find(f=>f.startsWith("arc:"))||"";r.set(c,(r.get(c)||0)+1);}let u=e?.symbolsTouched||[];if((u.length>0?a.filter(d=>d.symbols_touched?.some(c=>u.includes(c))):a.slice(0,3)).length>0||r.size>0){t.push(""),t.push("Active lore arcs:");for(let[d,c]of r)t.push(` ${d} (${c} entries)`);}}}catch{}try{let{loadNominations:s}=await import('./nomination-engine-EFXDEPZN.js'),i=s(o,{pending_only:!0}).filter(a=>a.urgency==="critical"||a.urgency==="high");if(i.length>0){t.push(""),t.push("Ambient nominations (urgent):");for(let a of i.slice(0,5))t.push(` [${a.urgency}] ${a.brief}`);i.length>5&&t.push(` ... and ${i.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return t.push(""),t.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."),t.push("---"),t.join(`
15
+ `;return W(),{handled:true,text:JSON.stringify({handoff:p,markdownSummary:w,persisted:y,recovery:"The next session will automatically receive this handoff via paradigm_session_recover."},null,2)}}if(o==="paradigm_session_stats"){let s=t.getStats(),i=t.getCostBreakdown(),a=t.getDurationMinutes();return {handled:true,text:JSON.stringify({session:{startTime:new Date(s.startTime).toISOString(),durationMinutes:a,lastActivity:new Date(s.lastActivity).toISOString()},model:{name:i.model,id:i.modelId,pricing:{inputPerMillion:`$${i.pricing.input.toFixed(2)}`,outputPerMillion:`$${i.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:i.resources.tokens,tools:i.tools.tokens}},cost:{totalUsd:`$${i.total.costUsd.toFixed(4)}`,breakdown:{resources:`$${i.resources.costUsd.toFixed(4)}`,tools:`$${i.tools.costUsd.toFixed(4)}`},note:"Cost is for MCP output tokens only (responses sent to model)"},details:{resourcesByType:i.resources.byType,toolsByName:i.tools.byName}},null,2)}}if(o==="paradigm_session_recover"){let{checkpoint:s,pendingHandoffs:i,previousSession:a}=z(n.rootDir);if(!a&&i.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 r={found:true};if(s){let l=Date.now()-s.timestamp,d=Math.round(l/6e4),c=Math.round(l/36e5);r.checkpoint={phase:s.phase,context:s.context,age:c>1?`${c} hours ago`:`${d} 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(a){let l=Date.now()-a.lastActivity,d=Math.round(l/6e4),c=Math.round(l/36e5),g=a.breadcrumbs.slice(-10).map(p=>({time:new Date(p.timestamp).toISOString(),action:p.action,tool:p.tool,symbol:p.symbol,summary:p.summary}));r.previousSession={sessionId:a.sessionId,startTime:new Date(a.startTime).toISOString(),lastActivity:new Date(a.lastActivity).toISOString(),age:c>1?`${c} hours ago`:`${d} minutes ago`},r.context={symbolsModified:a.symbolsModified,filesExplored:a.filesExplored},r.recentActions=g;}if(i.length>0){r.pendingHandoffs=i.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 i)try{c(n.rootDir,l.id);}catch{}}let u="Continue where the previous session left off.";if(s)u=`Previous session was in "${s.phase}" phase: ${s.context}`,s.decisions?.length&&(u+=` Key decisions: ${s.decisions.slice(0,2).join("; ")}`);else if(i.length>0){let l=i[i.length-1];u=`Handoff received: "${l.summary}". `,l.nextSteps.length>0&&(u+=`Start with: ${l.nextSteps[0]}`);}else if(a){let l=a.breadcrumbs.slice(-10);if(l.length>0){let d=l[l.length-1];d.symbol&&(u=`Last work involved ${d.symbol}. Consider checking its current state with paradigm_ripple.`);}}return r.suggestion=u,r.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.",t.markRecovered(),{handled:true,text:JSON.stringify(r,null,2)}}if(o==="paradigm_session_checkpoint"){t.setRootDir(n.rootDir);let s=e.phase,i=e.context,a=e.externalId,r=e.plan,u=e.modifiedFiles,l=e.symbolsTouched,d=e.decisions,{checkpoint:c,persisted:f}=t.saveCheckpoint({phase:s,context:i,externalId:a,plan:r,modifiedFiles:u,symbolsTouched:l,decisions:d}),g=f.local||f.global;return {handled:true,text:JSON.stringify({saved:g,persisted:f,checkpoint:{phase:c.phase,context:c.context,sessionId:c.sessionId,...c.externalId?{externalId:c.externalId}:{},timestamp:new Date(c.timestamp).toISOString(),modifiedFiles:c.modifiedFiles?.length||0,symbolsTouched:c.symbolsTouched?.length||0,decisions:c.decisions?.length||0,recentBreadcrumbs:c.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 z(o){let e=j();e.setRootDir(o);let n=e.loadCheckpoint(),t=e.loadPreviousSession(),s=[];try{s=b$1(o);}catch{}return {checkpoint:n,pendingHandoffs:s,previousSession:t}}async function le(o){let{checkpoint:e,pendingHandoffs:n}=z(o);if(!e&&n.length===0)return null;let t=[];if(t.push("--- SESSION RECOVERY ---"),e){let s=Date.now()-e.timestamp,i=Math.round(s/6e4),a=Math.round(s/36e5),r=a>1?`${a}h ago`:`${i}m ago`;t.push(`Previous session was in "${e.phase}" phase (${r}): ${e.context}`),e.modifiedFiles?.length&&t.push(`Modified files: ${e.modifiedFiles.join(", ")}`),e.symbolsTouched?.length&&t.push(`Symbols: ${e.symbolsTouched.join(", ")}`),e.decisions?.length&&t.push(`Decisions: ${e.decisions.join("; ")}`),e.plan&&t.push(`Plan: ${e.plan.slice(0,200)}`);}if(n.length>0){let s=n[n.length-1];t.push(`Pending handoff: "${s.summary}"`),s.nextSteps.length>0&&t.push(`Next steps: ${s.nextSteps.slice(0,3).join(", ")}`);}try{try{let{reapStaleInProgress:u}=await import('./task-settlement-3ROAHAND.js');await u(o);}catch{}let{assembleCaptainBoard:s,proposeClaimantFor:i}=await import('./captain-V5XPN4UP.js'),a=await s(o,{proposeClaimants:!0}),r=a.unclaimed.slice(0,5);if(a.summary.open>0||a.summary.inFlight>0||a.summary.runs>0){t.push(""),t.push(`Cid (captain): ${a.summary.open} open, ${a.summary.inFlight} in-flight`+(a.summary.runs>0?`, ${a.summary.runs} active run(s)`:"")+`, ${a.summary.unclaimed} unclaimed`);let{updateTask:u,loadTask:l}=await import('./task-loader-75NBBLRQ.js');for(let d of r){let c=d.tags.length>0?` [${d.tags.join(", ")}]`:"",f=d.proposedClaimant;if(!f){let g=await l(o,d.taskId);g&&(f=await i(g,o));}if(f){try{let g=await l(o,d.taskId);g&&!g.claimant&&g.status==="open"&&await u(o,d.taskId,{claimant:f});}catch{}t.push(` [${d.priority}] ${d.taskId}: ${d.blurb}${c} \u2192 proposed ${f.ref}`);}else t.push(` [${d.priority}] ${d.taskId}: ${d.blurb}${c}`);}}}catch{try{let{loadTasks:s}=await import('./task-loader-75NBBLRQ.js'),i=await s(o,{status:"open",limit:5});if(i.length>0){t.push(""),t.push("Open tasks:");for(let a of i){let r=a.tags.length>0?` [${a.tags.join(", ")}]`:"";t.push(` [${a.priority}] ${a.id}: ${a.blurb}${r}`);}}}catch{}}try{let{loadLoreEntries:s}=await import('./lore-loader-PXFKMKAN.js'),a=(await s(o,{limit:10})).filter(r=>r.tags?.some(u=>u.startsWith("arc:")));if(a.length>0){let r=new Map;for(let d of a){let c=d.tags?.find(f=>f.startsWith("arc:"))||"";r.set(c,(r.get(c)||0)+1);}let u=e?.symbolsTouched||[];if((u.length>0?a.filter(d=>d.symbols_touched?.some(c=>u.includes(c))):a.slice(0,3)).length>0||r.size>0){t.push(""),t.push("Active lore arcs:");for(let[d,c]of r)t.push(` ${d} (${c} entries)`);}}}catch{}try{let{loadNominations:s}=await import('./nomination-engine-3EYXJOZZ.js'),i=s(o,{pending_only:!0}).filter(a=>a.urgency==="critical"||a.urgency==="high");if(i.length>0){t.push(""),t.push("Ambient nominations (urgent):");for(let a of i.slice(0,5))t.push(` [${a.urgency}] ${a.brief}`);i.length>5&&t.push(` ... and ${i.length-5} more. Use paradigm_ambient_nominations to see all.`);}}catch{}return t.push(""),t.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."),t.push("---"),t.join(`
16
16
  `)}var T=class{cache=new Map;ttlMs;constructor(e=3e4){this.ttlMs=e;}async getOrCompute(e,n){let t=this.cache.get(e);if(t&&Date.now()-t.createdAt<this.ttlMs)return t.data;let s=await n();return this.cache.set(e,{data:s,createdAt:Date.now()}),s}invalidate(e){this.cache.delete(e);}invalidatePrefix(e){for(let n of this.cache.keys())n.startsWith(e)&&this.cache.delete(n);}clear(){this.cache.clear();}stats(){return {size:this.cache.size,ttlMs:this.ttlMs}}},fe=new T(3e4);var $=".paradigm/personas",B="index.yaml";async function O(o,e){let n=b.join(o,$);if(!m.existsSync(n))return [];let t=m.readdirSync(n).filter(i=>i.endsWith(".persona")),s=[];for(let i of t)try{let a=m.readFileSync(b.join(n,i),"utf8"),r=k.load(a);r&&r.id&&s.push(r);}catch{}return G(s,e)}async function R(o,e){let n=b.join(o,$,`${e}.persona`);if(!m.existsSync(n))return null;try{return k.load(m.readFileSync(n,"utf8"))}catch{return null}}function G(o,e){if(!e)return o;let n=o;return e.tag&&(n=n.filter(t=>t.tags?.includes(e.tag))),e.trigger_type&&(n=n.filter(t=>t.trigger.type===e.trigger_type)),e.gate&&(n=n.filter(t=>t.journey.some(s=>s.gates.includes(e.gate)))),e.flow&&(n=n.filter(t=>t.journey.some(s=>s.flow===e.flow))),e.limit&&(n=n.slice(0,e.limit)),n}async function me(o,e){let n=b.join(o,$);m.mkdirSync(n,{recursive:true});let t=b.join(n,`${e.id}.persona`);if(m.existsSync(t))throw new Error(`Persona ${e.id} already exists`);let s=new Date().toISOString(),i={version:"1.0",id:e.id,name:e.name,description:e.description,traits:e.traits,trigger:e.trigger,fixtures:e.fixtures,tags:e.tags||[],journey:e.journey||[],created:s,updated:s};return m.writeFileSync(t,k.dump(i,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await A(o),e.id}async function H(o,e,n){let t=await R(o,e);if(!t)return false;let s=b.join(o,$,`${e}.persona`),i={...t,...n,id:t.id,version:t.version,created:t.created,updated:new Date().toISOString()};return m.writeFileSync(s,k.dump(i,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),await A(o),true}async function ge(o,e){let n=b.join(o,$,`${e}.persona`);if(!m.existsSync(n))return {deleted:false,warnings:[]};let t=[],s=await O(o);for(let i of s)if(i.id!==e){i.trigger.spawned_by?.startsWith(e+".")&&t.push(`Persona ${i.id} is spawned by ${e} \u2014 it will become orphaned`);for(let a of i.journey)a.spawns?.some(r=>r.persona===e)&&t.push(`Persona ${i.id} step ${a.id} spawns ${e} \u2014 spawn will break`);}return m.unlinkSync(n),await A(o),{deleted:true,warnings:t}}async function ye(o,e,n,t){let s=await R(o,e);if(!s)return false;if(s.journey.some(i=>i.id===n.id))throw new Error(`Step ${n.id} already exists in persona ${e}`);if(t){let i=s.journey.findIndex(a=>a.id===t);if(i===-1)throw new Error(`Step ${t} not found in persona ${e}`);s.journey.splice(i+1,0,n);}else s.journey.push(n);return H(o,e,{journey:s.journey})}async function he(o,e,n){let t=await R(o,e);if(!t)return {removed:false,warnings:[]};let s=t.journey.findIndex(r=>r.id===n);if(s===-1)return {removed:false,warnings:[]};let i=t.journey[s],a=[];if(i.produces)for(let r of Object.keys(i.produces)){let u=`{{produces.${r}}}`;for(let l=s+1;l<t.journey.length;l++){let d=t.journey[l];JSON.stringify(d).includes(u)&&a.push(`Step ${d.id} consumes {{produces.${r}}} from this step`);}}if(i.spawns&&i.spawns.length>0)for(let r of i.spawns)a.push(`Step spawns persona ${r.persona} \u2014 spawn chain will break`);return t.journey.splice(s,1),await H(o,e,{journey:t.journey}),{removed:true,warnings:a}}var q=/^[a-z][a-z0-9-]*$/,V=/^[a-z][a-z0-9-]*$/,Q=/^(GET|POST|PUT|PATCH|DELETE)\s+\//;async function we(o,e,n=false){let t=[],s=[];q.test(e.id)||t.push({type:"invalid-id",detail:`ID "${e.id}" must match /^[a-z][a-z0-9-]*$/`}),(!e.name||e.name.trim()==="")&&t.push({type:"missing-name",detail:"Name is required"}),(!e.trigger||!e.trigger.type)&&t.push({type:"missing-trigger",detail:"Trigger with type is required"}),e.trigger.type!=="root"&&!e.trigger.spawned_by&&t.push({type:"missing-spawned-by",detail:`Non-root trigger type "${e.trigger.type}" requires spawned_by`}),(!e.journey||e.journey.length===0)&&t.push({type:"empty-journey",detail:"Journey must have at least one step"});let i=new Set,a=new Set;for(let r of e.journey){V.test(r.id)||t.push({type:"invalid-step-id",step:r.id,detail:"Step ID must match /^[a-z][a-z0-9-]*$/"}),i.has(r.id)&&t.push({type:"duplicate-step-id",step:r.id,detail:`Duplicate step ID "${r.id}"`}),i.add(r.id),Q.test(r.route)||t.push({type:"invalid-route",step:r.id,route:r.route,detail:'Route must match "METHOD /path" (e.g., "POST /api/auth/signup")'}),(!r.gates||r.gates.length===0)&&t.push({type:"missing-gates",step:r.id,detail:"Step must have at least one gate"}),(!r.expect||r.expect.status===void 0)&&t.push({type:"missing-expect",step:r.id,detail:"Step must have expect with status"});let l=JSON.stringify(r).match(/\{\{produces\.([^}]+)\}\}/g)||[];for(let d of l){let c=d.replace("{{produces.","").replace("}}","");a.has(c)||t.push({type:"unresolved-produces",step:r.id,key:c,detail:`{{produces.${c}}} used but not produced by a prior step`});}if(r.produces)for(let d of Object.keys(r.produces))a.add(d);}if(n){let r=b.join(o,"portal.yaml"),u=[],l=[];if(m.existsSync(r))try{let c=k.load(m.readFileSync(r,"utf8"));c.gates&&typeof c.gates=="object"&&(u=Object.keys(c.gates)),c.routes&&typeof c.routes=="object"&&(l=Object.keys(c.routes));}catch{}for(let c of e.journey)for(let f of c.gates)u.length>0&&!u.includes(f)&&t.push({type:"gate-not-found",step:c.id,gate:f,detail:`Gate ${f} not defined in portal.yaml`});for(let c of e.journey)if(l.length>0){let f=c.route;l.some(p=>I(p,f))||s.push({type:"route-not-in-portal",detail:`Route "${f}" (step ${c.id}) not found in portal.yaml`});}for(let c of e.journey)if(c.spawns)for(let f of c.spawns)await R(o,f.persona)||t.push({type:"spawn-target-missing",step:c.id,detail:`Spawn target persona "${f.persona}" does not exist`});let d=await K(o,e.id);if(d&&t.push({type:"spawn-cycle",detail:`Circular spawn dependency: ${d.join(" \u2192 ")}`}),l.length>0||u.length>0){let c=await O(o),f=new Set,g=new Set;for(let S of c)for(let v of S.journey){for(let j of v.gates)f.add(j);g.add(v.route);}let p=[],y=b.join(o,".paradigm","flow-index.json");if(m.existsSync(y))try{let S=JSON.parse(m.readFileSync(y,"utf8"));p=Object.keys(S.flows||{});}catch{}let w=new Set;for(let S of c)for(let v of S.journey)v.flow&&w.add(v.flow);return {persona:e.id,valid:t.length===0,errors:t,warnings:s,coverage:{routes:{covered:g.size,total:l.length,uncovered:l.filter(S=>!g.has(S))},gates:{covered:f.size,total:u.length,uncovered:u.filter(S=>!f.has(S))},flows:{covered:w.size,total:p.length,uncovered:p.filter(S=>!w.has(S))}}}}}return {persona:e.id,valid:t.length===0,errors:t,warnings:s}}function I(o,e){let n=t=>t.replace(/:[a-zA-Z_]+/g,":param").replace(/\{\{[^}]+\}\}/g,":param");return n(o)===n(e)}async function K(o,e){let n=new Set,t=[];async function s(i){if(n.has(i)){let r=t.indexOf(i);return r!==-1?[...t.slice(r),i]:null}n.add(i),t.push(i);let a=await R(o,i);if(a){for(let r of a.journey)if(r.spawns)for(let u of r.spawns){let l=await s(u.persona);if(l)return l}}return t.pop(),null}return s(e)}async function A(o){let e=b.join(o,$);m.mkdirSync(e,{recursive:true});let n=await O(o),t={},s={},i={};for(let c of n){let f=new Set,g=new Set,p=[],y=new Set;for(let w of c.journey){for(let S of w.gates)f.add(S);if(w.flow&&g.add(w.flow),p.push(w.route),w.spawns)for(let S of w.spawns)y.add(S.persona);}t[c.id]={name:c.name,trigger:c.trigger.type,spawned_by:c.trigger.spawned_by,steps:c.journey.length,gates:[...f],flows:[...g],routes:p,spawns:[...y],tags:c.tags||[]};for(let w of f)s[w]||(s[w]=[]),s[w].push(c.id);for(let w of p)i[w]||(i[w]=[]),i[w].push(c.id);}let a=[],r=b.join(o,"portal.yaml");if(m.existsSync(r))try{let c=k.load(m.readFileSync(r,"utf8"));c.routes&&typeof c.routes=="object"&&(a=Object.keys(c.routes).filter(g=>!Object.keys(i).some(p=>I(g,p))));}catch{}let u={},l=b.join(e,"chains");if(m.existsSync(l)){let c=m.readdirSync(l).filter(f=>f.endsWith(".yaml"));for(let f of c)try{let g=m.readFileSync(b.join(l,f),"utf8"),p=k.load(g);if(p&&p.id){let y=p.order.map(v=>v.persona),w=0,S=new Set;for(let v of y){let j=t[v];if(j){w+=j.steps;for(let U of j.gates)S.add(U);}}u[p.id]={description:p.description||"",order:y,total_steps:w,total_gates:S.size};}}catch{}}let d={version:"1.0",generated:new Date().toISOString(),personas:t,chains:u,gate_coverage:s,route_coverage:i,uncovered_routes:a};return m.writeFileSync(b.join(e,B),k.dump(d,{indent:2,lineWidth:120,noRefs:true,sortKeys:false})),d}async function be(o){let e=await O(o),n=new Set,t=new Set,s=new Set;for(let d of e)for(let c of d.journey){for(let f of c.gates)n.add(f);t.add(c.route),c.flow&&s.add(c.flow);}let i=[],a=[],r=b.join(o,"portal.yaml");if(m.existsSync(r))try{let d=k.load(m.readFileSync(r,"utf8"));d.gates&&typeof d.gates=="object"&&(i=Object.keys(d.gates)),d.routes&&typeof d.routes=="object"&&(a=Object.keys(d.routes));}catch{}let u=[],l=b.join(o,".paradigm","flow-index.json");if(m.existsSync(l))try{let d=JSON.parse(m.readFileSync(l,"utf8"));u=Object.keys(d.flows||{});}catch{}return {routes:{covered:t.size,total:a.length,uncovered:a.filter(d=>!Array.from(t).some(c=>I(d,c)))},gates:{covered:n.size,total:i.length,uncovered:i.filter(d=>!n.has(d))},flows:{covered:s.size,total:u.length,uncovered:u.filter(d=>!s.has(d))},personas:e.length}}async function Se(o,e){let n=await O(o),t=[];for(let s of n){let i=[],a=[];for(let r of s.journey)if((r.gates.includes(e)||r.flow===e||r.route===e||r.signals?.includes(e))&&(i.push(r.id),r.spawns))for(let l of r.spawns)a.push(l.persona);i.length>0&&t.push({persona:s.id,steps:i,spawns_blocked:a});}return t}function X(o,e){let n=e.split(/[.\[\]]+/).filter(Boolean),t=o;for(let s of n){if(t==null||typeof t!="object")return;t=t[s];}return t}function Y(o,e){let n=[];if(e.status!==o.expect.status&&n.push({type:"status",field:"status",expected:o.expect.status,actual:e.status,message:`Step ${o.id}: status is ${e.status}, expected ${o.expect.status}`}),o.expect.body?.has){let t=e.body;for(let s of o.expect.body.has)(!t||typeof t!="object"||!(s in t))&&n.push({type:"body.has",field:s,expected:true,actual:false,message:`Step ${o.id}: body missing key '${s}'`});}if(o.expect.body?.match){let t=e.body;for(let[s,i]of Object.entries(o.expect.body.match)){let a=t?X(t,s):void 0;JSON.stringify(a)!==JSON.stringify(i)&&n.push({type:"body.match",field:s,expected:i,actual:a??null,message:`Step ${o.id}: '${s}' is ${JSON.stringify(a??null)}, expected ${JSON.stringify(i)}`});}}if(o.signals&&o.signals.length>0){let t=e.signals_fired||[];for(let s of o.signals)t.includes(s)||n.push({type:"signal",field:"signals_fired",expected:s,actual:t,message:`Step ${o.id}: signal '${s}' was not fired`});}if(o.gates.length>0&&e.gates_traversed)for(let t of o.gates)e.gates_traversed.includes(t)||n.push({type:"gate",field:"gates_traversed",expected:t,actual:e.gates_traversed,message:`Step ${o.id}: gate '${t}' was not traversed`});return n}async function xe(o,e={}){let n=[];try{let{SentinelStorage:r}=await import('./dist-VGFSP3XM.js'),u=new r,d=(u.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.complete",scopeValue:o.id,limit:500})||[]).filter(p=>{let y=JSON.parse(p.data_json||"{}");return !(e.run_id&&y.run_id!==e.run_id||e.chain_id&&y.chain_id!==e.chain_id||e.environment&&y.environment!==e.environment)}),f=(u.queryEvents?.({schemaId:"paradigm-personas",eventType:"persona.step.fail",scopeValue:o.id,limit:500})||[]).filter(p=>{let y=JSON.parse(p.data_json||"{}");return !(e.run_id&&y.run_id!==e.run_id||e.chain_id&&y.chain_id!==e.chain_id||e.environment&&y.environment!==e.environment)}),g=new Map;for(let p of [...d,...f]){let y=JSON.parse(p.data_json||"{}");y.step_id&&g.set(y.step_id,y);}for(let p of o.journey){let y=g.get(p.id);if(!y){n.push({step_id:p.id,matched:!1,assertions:[],message:`No Sentinel event found for step '${p.id}' \u2014 step was never exercised`});continue}let w=Y(p,{status:y.status,body:y.body,gates_traversed:y.gates_traversed,signals_fired:y.signals_fired});n.push({step_id:p.id,matched:!0,passed:w.length===0,assertions:w});}}catch{for(let r of o.journey)n.push({step_id:r.id,matched:false,assertions:[],message:"Sentinel unavailable \u2014 cannot validate events"});}let t=n.filter(r=>r.matched).length,s=n.filter(r=>r.passed).length,i=n.filter(r=>r.matched&&!r.passed).length,a=n.reduce((r,u)=>r+u.assertions.length,0);return {run_id:e.run_id,environment:e.environment,steps:n,summary:{total_steps:o.journey.length,matched:t,unmatched:o.journey.length-t,passed:s,failed:i,assertion_failures:a}}}var _=".paradigm/protocols",L="index.yaml";async function E(o){let e=b.join(o,_);if(!m.existsSync(e))return [];let n=m.readdirSync(e).filter(s=>s.endsWith(".protocol")).sort(),t=[];for(let s of n)try{let i=m.readFileSync(b.join(e,s),"utf8"),a=k.load(i);a?.id&&a?.name&&t.push(a);}catch{}return t}async function Z(o,e){let n=e.replace(/^P-/,""),t=b.join(o,_,`${n}.protocol`);if(m.existsSync(t))try{let i=m.readFileSync(t,"utf8");return k.load(i)}catch{return null}return (await E(o)).find(i=>i.id===e)||null}async function Qe(o){let e=b.join(o,_,L);if(!m.existsSync(e))return null;try{let n=m.readFileSync(e,"utf8");return k.load(n)}catch{return null}}async function Ke(o,e,n=3){let t=await E(o);if(t.length===0)return [];let s=te(e);if(s.length===0)return [];let i=[];for(let a of t){let r=0;for(let d of a.trigger){let c=d.toLowerCase();for(let f of s)c.includes(f)&&(r+=3);}for(let d of a.tags){let c=d.toLowerCase();for(let f of s)(c.includes(f)||f.includes(c))&&(r+=2);}let u=a.name.toLowerCase(),l=a.description.toLowerCase();for(let d of s)u.includes(d)&&(r+=1),l.includes(d)&&(r+=1);for(let d of a.steps)if(d.notes){let c=d.notes.toLowerCase();for(let f of s)c.includes(f)&&(r+=.5);}r>0&&i.push({protocol:a,score:r});}return i.sort((a,r)=>r.score-a.score),i.slice(0,n)}async function Xe(o,e){let n=b.join(o,_);m.existsSync(n)||m.mkdirSync(n,{recursive:true});let t=ne(e.name),s=`P-${t}`,i=new Date().toISOString(),a={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:i,last_verified:i,verified_by:e.verified_by||"claude-opus-4-6",status:"current"},r=b.join(n,`${t}.protocol`);return m.writeFileSync(r,k.dump(a,{lineWidth:-1,noRefs:true}),"utf8"),s}async function Ye(o,e,n,t=false){let s=await Z(o,e);if(!s)return false;n.name!==void 0&&(s.name=n.name),n.description!==void 0&&(s.description=n.description),n.trigger!==void 0&&(s.trigger=n.trigger),n.tags!==void 0&&(s.tags=n.tags),n.symbols!==void 0&&(s.symbols=n.symbols),n.exemplar!==void 0&&(s.exemplar=n.exemplar),n.steps!==void 0&&(s.steps=n.steps),n.status!==void 0&&(s.status=n.status),n.verified_by!==void 0&&(s.verified_by=n.verified_by),t&&(s.last_verified=new Date().toISOString(),s.verified_by=n.verified_by||"claude-opus-4-6");let i=e.replace(/^P-/,""),a=b.join(o,_,`${i}.protocol`);return m.writeFileSync(a,k.dump(s,{lineWidth:-1,noRefs:true}),"utf8"),true}function ee(o,e){let n=[],t="current";if(e.exemplar){let s=b.join(o,e.exemplar);m.existsSync(s)?m.statSync(s).mtime.toISOString()>e.last_verified&&(n.push(`Exemplar modified since last verified: ${e.exemplar}`),t!=="broken"&&(t="stale")):(n.push(`Exemplar missing: ${e.exemplar}`),t="broken");}for(let s of e.steps){if(s.template_from){let i=b.join(o,s.template_from);m.existsSync(i)||(n.push(`Template file missing: ${s.template_from}`),t="broken");}if(s.action==="modify"&&s.target){let i=b.join(o,s.target);!s.target.includes("{")&&!m.existsSync(i)&&(n.push(`Modify target missing: ${s.target}`),t="broken");}}return {status:t,issues:n}}async function Ze(o){let e=await E(o),n=[],t=0,s=0,i=0;for(let u of e){let l=ee(o,u);if(u.status!==l.status){u.status=l.status;let d=u.id.replace(/^P-/,""),c=b.join(o,_,`${d}.protocol`);m.existsSync(c)&&m.writeFileSync(c,k.dump(u,{lineWidth:-1,noRefs:true}),"utf8");}switch(l.status){case "current":t++;break;case "stale":s++;break;case "broken":i++;break}n.push({id:u.id,name:u.name,status:l.status,last_verified:u.last_verified,trigger:u.trigger,tags:u.tags});}let a={version:"1.0",generated:new Date().toISOString(),protocols:n,health:{total:e.length,current:t,stale:s,broken:i}},r=b.join(o,_);if(e.length>0){m.existsSync(r)||m.mkdirSync(r,{recursive:true});let u=b.join(r,L);m.writeFileSync(u,k.dump(a,{lineWidth:-1,noRefs:true}),"utf8");}return a}function et(o,e,n){if(!e||e.length<2)return null;let t={};for(let s of e){let i=b.dirname(s);t[i]||(t[i]=[]),t[i].push(s);}for(let[s,i]of Object.entries(t)){if(i.length<2)continue;let a=b.join(o,s);if(!m.existsSync(a))continue;let u=m.readdirSync(a).filter(l=>{let d=b.extname(l);return [".ts",".tsx",".js",".jsx",".rs",".py"].includes(d)}).filter(l=>!i.some(d=>b.basename(d)===l));if(u.length>0){let l=b.join(s,u[0]),d=[...i.map(c=>({action:"create",target:c})),...n.map(c=>({action:"modify",target:c}))];return {hint:`This session created ${i.length} new files in ${s}/ following existing patterns. Consider recording a protocol.`,draft:{name:`Add a ${b.basename(s).replace(/s$/,"")}`,exemplar:l,steps:d}}}}return null}function te(o){return o.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(e=>e.length>1).filter(e=>!se.has(e))}var se=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 ne(o){return o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}
17
17
  export{et as A,re as a,ae as b,ce as c,de as d,le as e,fe as f,O as g,R as h,me as i,H as j,ge as k,ye as l,he as m,we as n,A as o,be as p,Se as q,xe as r,E as s,Z as t,Qe as u,Ke as v,Xe as w,Ye as x,ee as y,Ze as z};
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ import {f,a,o,z}from'./chunk-AMZ3ESAK.js';import {t}from'./chunk-M7JHVVDW.js';import {a as a$2,b as b$5,c as c$1}from'./chunk-M4UMM6DC.js';import {d as d$1}from'./chunk-F3OBFUOE.js';import {m,b as b$3}from'./chunk-WUSTIEYA.js';import {j,b as b$2,a as a$5}from'./chunk-GRZQIKST.js';import {b as b$1,a as a$4}from'./chunk-EK4ZRIFJ.js';import {a as a$1,b as b$4}from'./chunk-4TXOVRWD.js';import {H as H$1,m as m$1}from'./chunk-JOHPASZG.js';import {a as a$3,q}from'./chunk-K6TLYNRQ.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as y from'fs';import*as T from'path';import*as D from'crypto';import {execSync}from'child_process';import*as O from'js-yaml';import*as V from'os';import ue from'sql.js';var kt={};c(kt,{contentSearch:()=>de,detectFileRename:()=>Ot,generateFingerprint:()=>Ct,levenshteinDistance:()=>vt,levenshteinSimilarity:()=>rt,searchSiblingFiles:()=>Ft,slidingWindowSearch:()=>Q});function Ct(e){let t=e.split(`
3
+ `).filter(s=>s.trim()!=="");return {firstLine:J(t[0]||""),lastLine:J(t[t.length-1]||""),lineCount:t.length,structuralHash:Nt(t)}}function Nt(e){let t=e.map(s=>s.trim()).filter(s=>It.test(s)).map(s=>{let r=s.match(It);return r?r[1].trim():""}).join("|");return D.createHash("sha256").update(t).digest("hex").slice(0,16)}function J(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function vt(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;e.length>t.length&&([e,t]=[t,e]);let s=e.length,r=t.length;if(s>5e3||r>5e3)return Math.abs(s-r);let n=new Array(s+1),o=new Array(s+1);for(let a=0;a<=s;a++)n[a]=a;for(let a=1;a<=r;a++){o[0]=a;for(let c=1;c<=s;c++){let i=e[c-1]===t[a-1]?0:1;o[c]=Math.min(n[c]+1,o[c-1]+1,n[c-1]+i);}[n,o]=[o,n];}return n[s]}function rt(e,t){if(e.length===0&&t.length===0)return 1;let s=Math.max(e.length,t.length);return 1-vt(e,t)/s}function Q(e,t,s,r=3){let{lineCount:n}=t,o=Math.max(1,Math.floor(n*.8)),a=Math.ceil(n*1.2),c=[],i=st(s);for(let d of [n,o,a])if(!(d>e.length))for(let u=0;u<=e.length-d;u++){let f=e.slice(u,u+d),E=le(f,t,i);if(E>=.5){let h=f.join(`
4
+ `);c.push({windowStart:u+1,windowEnd:u+d,similarity:rt(st(h),i),score:E});}}let l=new Map;for(let d of c){let u=l.get(d.windowStart);(!u||d.score>u.score)&&l.set(d.windowStart,d);}return Array.from(l.values()).sort((d,u)=>u.score-d.score).slice(0,r)}function le(e,t,s){let r=e.filter(f=>f.trim()!=="");if(r.length===0)return 0;let n=0,o=J(r[0]),a=J(r[r.length-1]),c=0;o===t.firstLine&&(c+=.5),a===t.lastLine&&(c+=.5),n+=c*ie,Nt(r)===t.structuralHash&&(n+=oe);let l=r.join(`
5
+ `),d=rt(st(l),s);d>=.8&&(n+=(d-.8)/.2*ae);let u=r.length/t.lineCount;if(u>=.8&&u<=1.2){let f=1-Math.abs(1-u)/.2;n+=f*ce;}return n}function st(e){return e.split(`
6
+ `).map(t=>t.trim()).filter(t=>t!=="").join(`
7
+ `)}function Ot(e,t){try{let s=execSync(`git log --follow --diff-filter=R --name-status --format="" -- "${t}"`,{cwd:e,encoding:"utf8",timeout:5e3}).trim();if(!s)return null;let r=s.split(`
8
+ `);for(let n of r){let o=n.split(" ");if(o.length>=3&&o[0].startsWith("R"))return o[2]}return null}catch{return null}}function Ft(e,t,s,r,n=10){let o=T.isAbsolute(t)?t:T.join(e,t);if(!y.existsSync(o))return [];let a=[];try{let c=y.readdirSync(o).filter(i=>!i.startsWith(".")&&y.statSync(T.join(o,i)).isFile()).slice(0,n);for(let i of c)try{let d=y.readFileSync(T.join(o,i),"utf8").split(`
9
+ `),u=Q(d,s,r,1);if(u.length>0&&u[0].score>=.7){let f=T.relative(e,T.join(o,i));a.push({file:f,score:u[0].score,start:u[0].windowStart,end:u[0].windowEnd});}}catch{}}catch{return []}return a.sort((c,i)=>i.score-c.score)}function de(e,t,s,r=true){let n=Ct(s),o=T.isAbsolute(t)?t:T.join(e,t);if(y.existsSync(o)){let d=y.readFileSync(o,"utf8").split(`
10
+ `),u=Q(d,n,s);if(u.length>0){let f=u[0];return {found:f.score>=.7,score:f.score,suggestedStart:f.windowStart,suggestedEnd:f.windowEnd,similarity:f.similarity}}}let a=Ot(e,t);if(a){let l=T.join(e,a);if(y.existsSync(l)){let u=y.readFileSync(l,"utf8").split(`
11
+ `),f=Q(u,n,s);if(f.length>0&&f[0].score>=.7)return {found:true,score:f[0].score,suggestedStart:f[0].windowStart,suggestedEnd:f[0].windowEnd,suggestedPath:a,similarity:f[0].similarity}}}let c=T.dirname(t),i=Ft(e,c,n,s);if(i.length>0&&i[0].score>=.7){let l=i[0];return {found:true,score:l.score,suggestedStart:l.start,suggestedEnd:l.end,suggestedPath:l.file!==t?l.file:void 0,similarity:l.score}}return {found:false,score:0}}var It,ie,oe,ae,ce,Mt=b(()=>{It=/^\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 )/;ie=.4,oe=.3,ae=.2,ce=.1;});var ee=300*1e3,B=null;function Lt(){B=null;}function M(e,t){return y.existsSync(T.join(e,t))}function H(e,t){return y.existsSync(T.join(e,t))}function ne(e,t,s){let r=e;try{if(!y.existsSync(r))return !1;let n=y.readdirSync(r,{withFileTypes:!0});for(let o of n){if(o.isFile()&&o.name.endsWith(t))return !0;if(o.isDirectory())try{if(y.readdirSync(T.join(r,o.name)).some(c=>c.endsWith(t)))return !0}catch{}}}catch{}return false}var se={wisdom:e=>M(e,".paradigm/wisdom"),history:e=>M(e,".paradigm/history"),lore:e=>M(e,".paradigm/lore"),habits:e=>H(e,".paradigm/habits.yaml"),sentinel:e=>{try{let t=T.join(e,".paradigm","config.yaml");return y.existsSync(t)?y.readFileSync(t,"utf-8").includes("sentinel"):!1}catch{return false}},flows:e=>H(e,".paradigm/flow-index.json")||H(e,".paradigm/flows.yaml"),fixtures:e=>H(e,".paradigm/fixtures.yaml"),orchestration:e=>H(e,".paradigm/agents.yaml"),tasks:e=>M(e,".paradigm/tasks"),assessment:e=>M(e,".paradigm/lore"),personas:e=>ne(e,".persona"),protocols:e=>M(e,".paradigm/protocols"),symphony:()=>{let e=T.join(V.homedir(),".paradigm","score");return y.existsSync(e)},university:e=>M(e,".paradigm/university"),agents:e=>{let t=T.join(V.homedir(),".paradigm","agents");return M(e,".paradigm/agents")||y.existsSync(t)},"aspect-graph":e=>H(e,".paradigm/aspect-graph.db"),pan:e=>H(e,".pan")||H(e,"nevr.yaml"),notebooks:e=>{let t=T.join(V.homedir(),".paradigm","notebooks");return M(e,".paradigm/notebooks")||y.existsSync(t)}},Rt=class{modules=new Map;activatedAdvanced=new Set;rootDir;constructor(t){this.rootDir=t;}register(t){this.modules.set(t.key,t);}registerAll(t){for(let s of t)this.register(s);}detectActiveFeatures(){if(B&&Date.now()-B.timestamp<ee)return B.features;let t=new Set;for(let[s,r]of this.modules){if(r.tier==="core"){t.add(s);continue}if(r.tier==="advanced"){this.activatedAdvanced.has(s)&&t.add(s);continue}let n=r.detect||se[s];if(n)try{n(this.rootDir)&&t.add(s);}catch{}else t.add(s);}return B={features:t,timestamp:Date.now()},t}getActiveTools(){let t=this.detectActiveFeatures(),s=[];for(let[r,n]of this.modules)t.has(r)&&s.push(...n.getToolsList());return s}activateAdvanced(t){let s=this.modules.get(t);return !s||s.tier!=="advanced"?null:(this.activatedAdvanced.add(t),s.getToolsList())}getAvailableAdvanced(){let t=[];for(let[s,r]of this.modules)r.tier==="advanced"&&!this.activatedAdvanced.has(s)&&t.push({key:s,toolCount:r.getToolsList().length});return t}async dispatch(t,s,r,n){let o=this.detectActiveFeatures();for(let[a,c]of this.modules)if(o.has(a))try{let i=await c.handleTool(t,s,r,n);if(i.handled)return i}catch(i){return {handled:true,text:JSON.stringify({error:`Tool handler error in module "${a}"`,message:i.message},null,2)}}return null}get size(){return this.modules.size}getRegistryInfo(){let t=this.detectActiveFeatures(),s={core:0,feature:0,advanced:0};for(let r of this.modules.values())s[r.tier]++;return {total:this.modules.size,byTier:s,activeFeatures:[...t],availableAdvanced:[...this.modules.entries()].filter(([r,n])=>n.tier==="advanced"&&!this.activatedAdvanced.has(r)).map(([r])=>r)}}};var it=null;async function fe(){return it||(it=await ue()),it}var pe=[`CREATE TABLE IF NOT EXISTS aspects (
12
+ id TEXT PRIMARY KEY,
13
+ description TEXT NOT NULL,
14
+ category TEXT DEFAULT 'rule',
15
+ severity TEXT DEFAULT 'medium',
16
+ value TEXT,
17
+ enforcement TEXT,
18
+ defined_in TEXT NOT NULL,
19
+ tags TEXT,
20
+ created_at TEXT NOT NULL,
21
+ updated_at TEXT NOT NULL
22
+ )`,`CREATE TABLE IF NOT EXISTS anchors (
23
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
24
+ aspect_id TEXT NOT NULL REFERENCES aspects(id) ON DELETE CASCADE,
25
+ file_path TEXT NOT NULL,
26
+ start_line INTEGER NOT NULL,
27
+ end_line INTEGER NOT NULL,
28
+ content_hash TEXT,
29
+ normalized_hash TEXT,
30
+ materialized_at_commit TEXT,
31
+ last_verified TEXT,
32
+ drifted INTEGER DEFAULT 0
33
+ )`,"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 (
34
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
35
+ source TEXT NOT NULL,
36
+ target TEXT NOT NULL,
37
+ relation TEXT NOT NULL,
38
+ weight REAL DEFAULT 1.0,
39
+ origin TEXT DEFAULT 'explicit',
40
+ created_at TEXT NOT NULL
41
+ )`,"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 (
42
+ aspect_id TEXT NOT NULL,
43
+ lore_id TEXT NOT NULL,
44
+ PRIMARY KEY (aspect_id, lore_id)
45
+ )`,`CREATE TABLE IF NOT EXISTS search_log (
46
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
47
+ query TEXT NOT NULL,
48
+ results_returned TEXT NOT NULL,
49
+ selected_result TEXT,
50
+ timestamp TEXT NOT NULL
51
+ )`,"CREATE INDEX IF NOT EXISTS idx_search_query ON search_log(query)",`CREATE TABLE IF NOT EXISTS search_weights (
52
+ query_normalized TEXT NOT NULL,
53
+ aspect_id TEXT NOT NULL,
54
+ weight REAL DEFAULT 1.0,
55
+ hit_count INTEGER DEFAULT 1,
56
+ last_hit TEXT NOT NULL,
57
+ PRIMARY KEY (query_normalized, aspect_id)
58
+ )`,`CREATE TABLE IF NOT EXISTS heatmap (
59
+ aspect_id TEXT NOT NULL,
60
+ access_type TEXT NOT NULL,
61
+ count INTEGER DEFAULT 0,
62
+ last_accessed TEXT NOT NULL,
63
+ PRIMARY KEY (aspect_id, access_type)
64
+ )`],ge=["ALTER TABLE anchors ADD COLUMN original_content TEXT",`CREATE TABLE IF NOT EXISTS anchor_history (
65
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
66
+ anchor_id INTEGER NOT NULL,
67
+ action TEXT NOT NULL,
68
+ old_start INTEGER,
69
+ old_end INTEGER,
70
+ new_start INTEGER,
71
+ new_end INTEGER,
72
+ old_path TEXT,
73
+ new_path TEXT,
74
+ confidence REAL,
75
+ commit_hash TEXT,
76
+ healed_at TEXT NOT NULL
77
+ )`],me="CREATE VIRTUAL TABLE IF NOT EXISTS aspects_fts USING fts5(id, description, enforcement, tags)";function C(e,t,s){let r=e.prepare(t);s&&s.length>0&&r.bind(s);let n=[];for(;r.step();)n.push(r.getAsObject());return r.free(),n}function he(e,t,s){let r=e.prepare(t);s&&s.length>0&&r.bind(s);let n=null;return r.step()&&(n=r.getAsObject()),r.free(),n}async function Pt(e){let t=await fe(),s=T.join(e,".paradigm"),r=T.join(s,"aspect-graph.db"),n;if(y.existsSync(r)){let o=y.readFileSync(r);n=new t.Database(o);}else y.existsSync(s)||y.mkdirSync(s,{recursive:true}),n=new t.Database;for(let o of pe)n.run(o);try{n.run(me);}catch{}for(let o of ge)try{n.run(o);}catch{}return n}function Ht(e,t){if(t){let s=T.join(t,".paradigm");y.existsSync(s)||y.mkdirSync(s,{recursive:true});let r=T.join(s,"aspect-graph.db"),n=e.export();y.writeFileSync(r,Buffer.from(n));}e.close();}function Dt(e,t,s){let r=t.filter(a=>a.type==="aspect"),n=new Date().toISOString(),o=null;try{o=execSync("git rev-parse HEAD",{cwd:s,encoding:"utf8"}).trim();}catch{}e.run("DELETE FROM anchors"),e.run("DELETE FROM edges"),e.run("DELETE FROM aspects");try{e.run("DELETE FROM aspects_fts");}catch{}for(let a of r){let c=a.data??{},i=Te(c,a),l=be(c,a),d=c.value!=null?String(c.value):null,u=a.enforcement??(c.enforcement!=null?String(c.enforcement):null),f=a.tags?JSON.stringify(a.tags):null;if(e.run(`INSERT INTO aspects (id, description, category, severity, value, enforcement, defined_in, tags, created_at, updated_at)
78
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a.symbol,a.description??"",i,l,d,u,a.filePath,f,a.created??n,a.modified??n]),a.anchors)for(let h of a.anchors){let{startLine:w,endLine:F}=Ut(h),I=Se();e.run(`INSERT INTO anchors (aspect_id, file_path, start_line, end_line, content_hash, normalized_hash, materialized_at_commit, last_verified, original_content)
79
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a.symbol,h.path,w,F,I.exact,I.normalized,o,n,I.normalizedContent]);}let E=c.edges;if(Array.isArray(E))for(let h of E)e.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
80
+ VALUES (?, ?, ?, ?, ?, ?)`,[h.source??a.symbol,h.target??"",h.relation??"related-to",h.weight??1,h.origin??"explicit",n]);if(a.appliesTo)for(let h of a.appliesTo)e.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
81
+ VALUES (?, ?, ?, ?, ?, ?)`,[a.symbol,h,"related-to",.5,"inferred",n]);try{e.run(`INSERT INTO aspects_fts (id, description, enforcement, tags)
82
+ VALUES (?, ?, ?, ?)`,[a.symbol,a.description??"",u??"",f??""]);}catch{}}}function Ze(e,t){return he(e,"SELECT * FROM aspects WHERE id = ?",[t])}function tn(e,t){return C(e,"SELECT * FROM anchors WHERE aspect_id = ?",[t])}function en(e,t){return C(e,"SELECT * FROM edges WHERE source = ?",[t])}function nn(e,t){return C(e,"SELECT * FROM edges WHERE target = ?",[t])}function sn(e,t){return C(e,"SELECT * FROM edges WHERE source = ? OR target = ?",[t,t])}function rn(e,t,s){let r=new Date().toISOString();e.run(`INSERT INTO heatmap (aspect_id, access_type, count, last_accessed)
83
+ VALUES (?, ?, 1, ?)
84
+ ON CONFLICT(aspect_id, access_type)
85
+ DO UPDATE SET count = count + 1, last_accessed = ?`,[t,s,r,r]);}function on(e,t=20,s){return s?C(e,"SELECT * FROM heatmap WHERE access_type = ? ORDER BY count DESC LIMIT ?",[s,t]):C(e,"SELECT * FROM heatmap ORDER BY count DESC LIMIT ?",[t])}function an(e,t,s,r=true,n=.7,o=.85){let a=s?C(e,"SELECT * FROM anchors WHERE aspect_id = ?",[s]):C(e,"SELECT * FROM anchors"),c=[];for(let i of a){let d$1=C(e,"SELECT defined_in FROM aspects WHERE id = ?",[i.aspect_id])[0]?.defined_in,u=d$1?T.dirname(T.isAbsolute(d$1)?d$1:T.resolve(t,d$1)):t,f=H$1(i.file_path,u,t),E=f.resolvedPath;if(!f.exists){c.push({aspectId:i.aspect_id,path:i.file_path,startLine:i.start_line,endLine:i.end_line,status:"missing",resolvedBy:"none",exists:false,drifted:true});continue}try{let w=y.readFileSync(E,"utf8").split(`
86
+ `),F=Math.max(0,i.start_line-1),I=Math.min(w.length,i.end_line),U=w.slice(F,I).join(`
87
+ `),X=D.createHash("sha256").update(U).digest("hex");if(i.content_hash!=null&&X===i.content_hash){c.push({aspectId:i.aspect_id,path:i.file_path,startLine:i.start_line,endLine:i.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1}),i.drifted===1&&e.run("UPDATE anchors SET drifted = 0 WHERE id = ?",[i.id]);continue}let $=D.createHash("sha256").update(at(U)).digest("hex");if(i.normalized_hash!=null&&$===i.normalized_hash){e.run("UPDATE anchors SET content_hash = ?, drifted = 0 WHERE id = ?",[X,i.id]),c.push({aspectId:i.aspect_id,path:i.file_path,startLine:i.start_line,endLine:i.end_line,status:"cosmetic",resolvedBy:"normalized-hash",exists:!0,drifted:!1});continue}if(i.content_hash==null&&i.normalized_hash==null){e.run("UPDATE anchors SET content_hash = ?, normalized_hash = ?, drifted = 0 WHERE id = ?",[X,$,i.id]),c.push({aspectId:i.aspect_id,path:i.file_path,startLine:i.start_line,endLine:i.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1});continue}let W=!1;if(i.materialized_at_commit){let m=Ee(t,i.file_path,i.materialized_at_commit,i.start_line,i.end_line);if(m){let g=Math.max(0,m.currentStart-1),z=Math.min(w.length,m.currentEnd),k=w.slice(g,z).join(`
88
+ `),p=D.createHash("sha256").update(k).digest("hex");if(i.content_hash!=null&&p===i.content_hash){let S=r;if(S){e.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[m.currentStart,m.currentEnd,i.id]);let N=C(e,"SELECT defined_in FROM aspects WHERE id = ?",[i.aspect_id]);N.length>0&&ot(t,N[0].defined_in,i.file_path,i.start_line,i.end_line,m.currentStart,m.currentEnd);}c.push({aspectId:i.aspect_id,path:i.file_path,startLine:S?m.currentStart:i.start_line,endLine:S?m.currentEnd:i.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:m.currentStart,suggestedEnd:m.currentEnd,autoHealed:S}),W=!0;}else {let S=D.createHash("sha256").update(at(k)).digest("hex");if(i.normalized_hash!=null&&S===i.normalized_hash){if(r){let N=D.createHash("sha256").update(k).digest("hex");e.run("UPDATE anchors SET start_line = ?, end_line = ?, content_hash = ?, drifted = 0 WHERE id = ?",[m.currentStart,m.currentEnd,N,i.id]);let Y=C(e,"SELECT defined_in FROM aspects WHERE id = ?",[i.aspect_id]);Y.length>0&&ot(t,Y[0].defined_in,i.file_path,i.start_line,i.end_line,m.currentStart,m.currentEnd);}c.push({aspectId:i.aspect_id,path:i.file_path,startLine:r?m.currentStart:i.start_line,endLine:r?m.currentEnd:i.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:m.currentStart,suggestedEnd:m.currentEnd,autoHealed:r}),W=!0;}}}}if(W)continue;if(i.original_content){let{contentSearch:m}=(Mt(),d(kt)),g=m(t,i.file_path,i.original_content,r);if(g.found&&g.score>=n){if(r&&g.score>=o&&!g.suggestedPath&&g.suggestedStart&&g.suggestedEnd){e.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[g.suggestedStart,g.suggestedEnd,i.id]);try{e.run(`INSERT INTO anchor_history (anchor_id, action, old_start, old_end, new_start, new_end, confidence, healed_at)
89
+ VALUES (?, 'relocated', ?, ?, ?, ?, ?, ?)`,[i.id,i.start_line,i.end_line,g.suggestedStart,g.suggestedEnd,g.score,new Date().toISOString()]);}catch{}let k=C(e,"SELECT defined_in FROM aspects WHERE id = ?",[i.aspect_id]);k.length>0&&ot(t,k[0].defined_in,i.file_path,i.start_line,i.end_line,g.suggestedStart,g.suggestedEnd),c.push({aspectId:i.aspect_id,path:i.file_path,startLine:g.suggestedStart,endLine:g.suggestedEnd,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:g.similarity,suggestedStart:g.suggestedStart,suggestedEnd:g.suggestedEnd,autoHealed:!0,drifted:!1});continue}c.push({aspectId:i.aspect_id,path:g.suggestedPath||i.file_path,startLine:i.start_line,endLine:i.end_line,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:g.similarity,suggestedStart:g.suggestedStart,suggestedEnd:g.suggestedEnd,autoHealed:!1,drifted:!0});continue}}e.run("UPDATE anchors SET drifted = 1 WHERE id = ?",[i.id]),c.push({aspectId:i.aspect_id,path:i.file_path,startLine:i.start_line,endLine:i.end_line,status:"modified",resolvedBy:"none",exists:!0,currentContent:U,drifted:!0});}catch{c.push({aspectId:i.aspect_id,path:i.file_path,startLine:i.start_line,endLine:i.end_line,status:"modified",resolvedBy:"none",exists:true,drifted:true});}}return c}function Ut(e){let{lines:t}=e;return typeof t=="number"?{startLine:t,endLine:t}:Array.isArray(t)?t.length===2?{startLine:t[0],endLine:t[1]}:{startLine:Math.min(...t),endLine:Math.max(...t)}:{startLine:1,endLine:1}}function ye(e){let t=[],s=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm,r;for(;(r=s.exec(e))!==null;)t.push({oldStart:parseInt(r[1],10),oldCount:r[2]!==void 0?parseInt(r[2],10):1,newStart:parseInt(r[3],10),newCount:r[4]!==void 0?parseInt(r[4],10):1});return t}function Ee(e,t,s,r,n){let o;try{o=execSync(`git diff ${s}..HEAD --unified=0 -- "${t}"`,{cwd:e,encoding:"utf8",timeout:5e3});}catch{return null}if(!o.trim())return {originalStart:r,originalEnd:n,currentStart:r,currentEnd:n};let a=ye(o),c=0;for(let i of a){if(i.oldStart+i.oldCount<=r){c+=i.newCount-i.oldCount;continue}if(i.oldStart<n)return null;break}return c===0?null:{originalStart:r,originalEnd:n,currentStart:r+c,currentEnd:n+c}}function ot(e,t,s,r,n,o,a){let c=T.isAbsolute(t)?t:T.join(e,t);if(!y.existsSync(c))return false;try{let i=y.readFileSync(c,"utf8"),l=r===n?`${s}:${r}`:`${s}:${r}-${n}`,d=o===a?`${s}:${o}`:`${s}:${o}-${a}`;if(!i.includes(l))return !1;let u=i.replace(l,d);return y.writeFileSync(c,u,"utf8"),!0}catch{return false}}function at(e){return e.split(`
90
+ `).map(t=>t.trimEnd()).filter(t=>t.trim()!=="").map(t=>t.replace(/\s+/g," ")).join(`
91
+ `)}function Se(e,t,s){return {exact:null,normalized:null,normalizedContent:null};}function Te(e,t){if(typeof e.category=="string")return e.category;let s=(t.description??"").toLowerCase();return /\b(must|require|always)\b/.test(s)?"rule":/\b(decided|chose)\b/.test(s)?"decision":/\b(limit|cannot)\b/.test(s)?"constraint":/\b(set to|configured|value)\b/.test(s)?"configuration":"rule"}function be(e,t){if(typeof e.severity=="string")return e.severity;let s=t.tags??[];return s.includes("critical")?"critical":s.includes("security")||s.includes("compliance")?"high":"medium"}j();var _e=/L-\d{4}-\d{2}-\d{2}-\d{3}/g;async function Xt(e,t){e.run("DELETE FROM lore_links");let s=await a$5(t);if(s.length===0)return 0;let r=xe(s),n=new Map;for(let l of s)n.set(l.id,l);let o=new Set,a=e.exec("SELECT id, enforcement FROM aspects");if(a.length>0){let{columns:l,values:d}=a[0],u=l.indexOf("id"),f=l.indexOf("enforcement");for(let E of d){let h=String(E[u]),w=E[f];if(w&&typeof w=="string"){let F=w.match(_e);if(F)for(let I of F)n.has(I)&&o.add(`${h}\0${I}`);}}}let c=e.exec("SELECT source, target FROM edges");if(c.length>0&&a.length>0){let l=we(e,c);for(let[d,u]of l)for(let f of u){let E=r.get(f);if(E)for(let h of E)o.add(`${d}\0${h}`);}}if(o.size===0)return 0;let i=e.prepare("INSERT OR IGNORE INTO lore_links (aspect_id, lore_id) VALUES (?, ?)");try{for(let l of o){let[d,u]=l.split("\0");i.bind([d,u]),i.step(),i.reset();}}finally{i.free();}return o.size}async function dn(e,t,s){let r=e.exec("SELECT lore_id FROM lore_links WHERE aspect_id = ?",[s]);if(r.length===0||r[0].values.length===0)return [];let n=r[0].values.map(o=>String(o[0]));return Re(t,n)}async function Wt(e,t){let s=await a$5(t);if(s.length===0)return 0;let r=e.exec("SELECT id FROM aspects"),n=new Set;if(r.length>0)for(let i of r[0].values)n.add(String(i[0]));if(n.size<2)return 0;let o=new Date().toISOString(),a=0,c=e.prepare(`INSERT OR IGNORE INTO edges (source, target, relation, weight, origin, created_at)
92
+ VALUES (?, ?, 'related-to', 0.3, 'learned', ?)`);try{for(let i of s){if(!i.symbols_touched||i.symbols_touched.length<2)continue;let l=[];for(let d of i.symbols_touched){let u=d.startsWith("~")?d.slice(1):d;n.has(u)&&l.push(u);}for(let d=0;d<l.length;d++)for(let u=d+1;u<l.length;u++){let[f,E]=l[d]<l[u]?[l[d],l[u]]:[l[u],l[d]];c.bind([f,E,o]),c.step(),c.reset(),a++;}}}finally{c.free();}return a}function xe(e){let t=new Map;for(let s of e)if(s.symbols_touched)for(let r of s.symbols_touched){let n=t.get(r);n||(n=new Set,t.set(r,n)),n.add(s.id);}return t}function we(e,t){let s=e.exec("SELECT id FROM aspects"),r=new Set;if(s.length>0)for(let l of s[0].values)r.add(String(l[0]));let n=new Map;if(t.length===0)return n;let{columns:o,values:a}=t[0],c=o.indexOf("source"),i=o.indexOf("target");for(let l of a){let d=String(l[c]),u=String(l[i]);if(r.has(d)){let f=n.get(d);f||(f=new Set,n.set(d,f)),f.add(u),f.add(`~${d}`);}if(r.has(u)){let f=n.get(u);f||(f=new Set,n.set(u,f)),f.add(d),f.add(`~${u}`);}}return n}async function Re(e,t){let s=new Set,r=[];for(let n of t){if(s.has(n))continue;s.add(n);let o=await b$2(e,n);o&&r.push(Le(o));}return r}function Le(e){return {id:e.id,title:e.title,summary:e.summary,timestamp:e.timestamp,symbolsTouched:e.symbols_touched}}b$1();m();var G=".paradigm/curriculum",Ie="index.yaml";async function zt(e){let t=T.join(e,G);if(!y.existsSync(t))return [];let s=y.readdirSync(t).filter(n=>n.endsWith(".syllabus")).sort(),r=[];for(let n of s)try{let o=y.readFileSync(T.join(t,n),"utf8"),a=O.load(o);a?.id&&a?.agent&&r.push(a);}catch{}return r}async function gn(e,t){let s=T.join(e,G,`${t}.syllabus`);if(y.existsSync(s))try{let o=y.readFileSync(s,"utf8"),a=O.load(o);if(a?.id)return a}catch{}let n=(await zt(e)).filter(o=>o.agent===t);return n.length===0?null:n.reduce((o,a)=>a.version>o.version?a:o)}async function mn(e,t){let s=T.join(e,G);y.existsSync(s)||y.mkdirSync(s,{recursive:true});let r=new Date().toISOString(),n=T.join(s,`${t.agent}.syllabus`),o=1;if(y.existsSync(n))try{let i=O.load(y.readFileSync(n,"utf8"));i?.version&&(o=i.version+1);}catch{}let a=`SY-${t.agent}`,c={id:a,agent:t.agent,version:o,sources:t.sources||[],scope:t.scope,success_criteria:t.success_criteria||[],notebook_target:t.notebook_target,approved_by:t.approved_by,approved_at:t.approved_at||r,term_ttl_days:t.term_ttl_days,status:"current",last_ratified:t.last_ratified||r,recorded_from:t.recorded_from};return y.writeFileSync(n,O.dump(c,{lineWidth:-1,noRefs:true}),"utf8"),a}function Ae(e,t){let s=[],r="current",n=Date.parse(t.last_ratified),o=!Number.isNaN(n),a=b$3(t.agent,e),c=new Map(a.map(i=>[i.id,i]));for(let i of t.sources)if(i.kind==="notebook"){let l=c.get(i.ref);if(!l){s.push(`Notebook source missing: ${i.ref}`),r="broken";continue}if(o&&l.updated){let d=Date.parse(l.updated);!Number.isNaN(d)&&d>n&&(s.push(`Notebook source updated since ratification: ${i.ref}`),r!=="broken"&&(r="stale"));}}else i.kind==="scenario"&&(Ce(e).has(i.ref)||(s.push(`Scenario source missing: ${i.ref}`),r="broken"));if(o&&typeof t.term_ttl_days=="number"){let i=n+t.term_ttl_days*24*60*60*1e3;Date.now()>i&&r==="current"?(s.push(`Term expired: ratified ${t.last_ratified}, ttl ${t.term_ttl_days}d`),r="expired"):Date.now()>i&&r==="stale"&&(s.push(`Term expired: ratified ${t.last_ratified}, ttl ${t.term_ttl_days}d`),r="expired");}return {status:r,issues:s}}function Ce(e){try{let t=T.join(e,".paradigm/curriculum/scenarios");if(!y.existsSync(t))return new Set;let s=new Set;for(let r of y.readdirSync(t))if(r.endsWith(".scenario"))try{let n=O.load(y.readFileSync(T.join(t,r),"utf8"));n?.id&&s.add(n.id);}catch{}return s}catch{return new Set}}async function $t(e){let t=await zt(e),s=[],r=0,n=0,o=0,a=0;for(let l of t){let d=Ae(e,l);if(l.status!==d.status){l.status=d.status;let u=T.join(e,G,`${l.agent}.syllabus`);y.existsSync(u)&&y.writeFileSync(u,O.dump(l,{lineWidth:-1,noRefs:true}),"utf8");}switch(d.status){case "current":r++;break;case "stale":n++;break;case "broken":o++;break;case "expired":a++;break}s.push({id:l.id,agent:l.agent,version:l.version,status:d.status,last_ratified:l.last_ratified,scope:l.scope});}let c={version:"1.0",generated:new Date().toISOString(),syllabi:s,health:{total:t.length,current:r,stale:n,broken:o,expired:a}},i=T.join(e,G);return t.length>0&&(y.existsSync(i)||y.mkdirSync(i,{recursive:true}),y.writeFileSync(T.join(i,Ie),O.dump(c,{lineWidth:-1,noRefs:true}),"utf8")),(o>0||a>0)&&a$4.component("#syllabus-loader").warn("syllabi require re-ratification",{broken:o,expired:a,stale:n}),c}var Ne="PARADIGM_STRICT";function Z(){let e=process.env[Ne];if(e===void 0||e==="")return false;let t=e.toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}var Bt=new Set(["duplicate-key-detected"]);function ve(e){let t=e.trim();if(t.includes("/")||t.includes("\\")){let s=t.split(/[/\\]/);t=s[s.length-1]||"unknown";}return t.length>40&&(t=t.slice(0,40)),t||"unknown"}var tt=class{transforms=new Map;record(t,s,r=1){let n=ve(s),o=`${t}::${n}`,a=this.transforms.get(o);a?a.count+=r:this.transforms.set(o,{kind:t,surface:n,count:r});}report(){let t=Array.from(this.transforms.values()).sort((r,n)=>r.kind!==n.kind?r.kind.localeCompare(n.kind):r.surface.localeCompare(n.surface)),s=t.filter(r=>Bt.has(r.kind)).reduce((r,n)=>r+n.count,0);return {reindex_ts:new Date().toISOString(),transformations:t,lossy_count:s,strict_mode:Z()}}hasLossy(){for(let t of this.transforms.values())if(Bt.has(t.kind))return true;return false}totalCount(){let t=0;for(let s of this.transforms.values())t+=s.count;return t}};b$1();var Oe={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},Fe={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/"]},ke={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"]},ct={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 Pn(){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 Hn(e,t,s,r){if(e!=="paradigm_reindex")return {handled:false,text:""};try{let n=await Me(s.rootDir,s);await r(),f.clear(),Lt();let o=(n.integrityReport?.brokenReferences?.length||0)+(n.integrityReport?.duplicateSymbols?.length||0)+(n.componentAnchorIssues||0)+(n.crossFileIssues||0),a$1={success:!0,symbolCount:n.symbolCount,breakdown:n.breakdown,flowCount:n.flowCount,filesWritten:n.filesWritten.length,...n.aspectGraphStats?{aspects:n.aspectGraphStats.aspects,loreLinks:n.aspectGraphStats.loreLinks}:{},...n.protocolHealth?{protocols:n.protocolHealth.total,staleProtocols:n.protocolHealth.stale}:{},...n.syllabusHealth?{syllabi:n.syllabusHealth.total,syllabiNeedingRatification:n.syllabusHealth.stale+n.syllabusHealth.broken+n.syllabusHealth.expired}:{},...n.scenarioHealth?{scenarios:n.scenarioHealth.total}:{},...o>0?{issues:o}:{}};n.consistency&&(a$1.consistency=n.consistency);let c=JSON.stringify(a$1,null,2);return a(c.length,e),{handled:!0,text:c}}catch(n){let o=JSON.stringify({error:n.message},null,2);return a(o.length,e),{handled:true,text:o}}}async function Me(e,t$1){let s=[],r=new tt,n;t$1?n=t$1.aggregation:n=await m$1(e);let o$1=t$1?.projectName||T.basename(e),a=T.join(e,".paradigm");y.existsSync(a)||y.mkdirSync(a,{recursive:true}),je(e,r),Pe(n.purposeFiles,r);let c=a$1({symbols:n.symbols,purposeFiles:n.purposeFiles,portalFiles:n.portalFiles},{projectName:o$1}),i=T.join(a,"scan-index.json");y.writeFileSync(i,b$4(c),"utf8"),s.push(".paradigm/scan-index.json");let l=He(e,n),d=T.join(a,"navigator.yaml");y.writeFileSync(d,O.dump(l,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),s.push(".paradigm/navigator.yaml");let u=$e(e,n.purposeFiles),f=0;if(u&&Object.keys(u.flows).length>0){let p=T.join(a,"flow-index.json");y.writeFileSync(p,JSON.stringify(u,null,2),"utf8"),s.push(".paradigm/flow-index.json"),f=Object.keys(u.flows).length;}let E;try{let p=await Pt(e);Dt(p,n.symbols,e);let S=await Xt(p,e),N=await Wt(p,e),Y=p.exec("SELECT COUNT(*) FROM aspects")[0]?.values[0]?.[0]??0,Kt=p.exec("SELECT COUNT(*) FROM anchors")[0]?.values[0]?.[0]??0,qt=p.exec("SELECT COUNT(*) FROM edges")[0]?.values[0]?.[0]??0;Ht(p,e),s.push(".paradigm/aspect-graph.db"),E={aspects:Y,anchors:Kt,edges:qt,loreLinks:S};}catch{}let h=0;try{let p=await o(e);h=Object.keys(p.personas).length,h>0&&s.push(".paradigm/personas/index.yaml");}catch{}let w;try{let p=await z(e);p.health.total>0&&(w=p.health,s.push(".paradigm/protocols/index.yaml"));}catch{}let F;try{let p=await $t(e);p.health.total>0&&(F=p.health,s.push(".paradigm/curriculum/index.yaml"));}catch{}let I;try{let p=await d$1(e);p.health.total>0&&(I={total:p.health.total,active:p.health.active,retired:p.health.retired},s.push(".paradigm/curriculum/scenarios/index.yaml"));}catch{}let U;try{let p=T.join(e,".paradigm","university");if(y.existsSync(p)){let S=t(e);(S.totalContent>0||S.diplomaCount>0)&&(U={totalContent:S.totalContent,diplomaCount:S.diplomaCount},s.push(".paradigm/university/index.yaml"));}}catch{}let X;try{X=a$2(n,e);}catch{}let $;try{let p=b$5(n.symbols,e),S=p.missing+p.outOfBounds;S>0&&($=S);}catch{}let W;try{W=c$1(n.purposeFiles,e);}catch{}let m;try{let p=[];for(let S of n.purposeFiles){let N=a$3(S);N.data&&p.push({filePath:S,data:N.data});}if(p.length>0){let N=q(p).issues.length;N>0&&(m=N);}}catch{}let g={};for(let p of n.symbols)g[p.type]=(g[p.type]||0)+1;let z$1={};for(let p of n.symbols)p.type==="component"&&p.componentType&&(z$1[p.componentType]=(z$1[p.componentType]||0)+1);let k=r.report();try{let p=T.join(a,"manifest.consistency.json");y.writeFileSync(p,JSON.stringify(k,null,2),"utf-8"),s.push(".paradigm/manifest.consistency.json");}catch{a$4.component("#reindex").warn("failed to write consistency manifest",{stage:"manifest-write"});}if(Z()&&r.hasLossy())throw new Error(`reindex aborted: ${k.lossy_count} lossy transformation(s) detected under PARADIGM_STRICT=1. See .paradigm/manifest.consistency.json.`);return {action:"reindex",filesWritten:s,symbolCount:n.symbols.length,breakdown:g,flowCount:f,aspectGraphStats:E,personaCount:h,protocolHealth:w,...F?{syllabusHealth:F}:{},...I?{scenarioHealth:I}:{},consistency:k,...Object.keys(z$1).length>0?{componentTypeBreakdown:z$1}:{},...U?{universityStats:U}:{},...X?{integrityReport:X}:{},...$!==void 0?{componentAnchorIssues:$}:{},...W?{purposeHealth:W}:{},...m!==void 0?{crossFileIssues:m}:{}}}function je(e,t){let s=T.join(e,"portal.yaml");if(!y.existsSync(s))return;let r;try{r=y.readFileSync(s,"utf-8");}catch{return}try{O.load(r);}catch(i){(i?.reason?.toLowerCase()||"").includes("duplicate")&&t.record("duplicate-key-detected","portal.yaml");return}let n;try{n=O.load(r,{schema:O.FAILSAFE_SCHEMA});}catch{return}if(!n||typeof n!="object")return;let o=n,a=o.gates;if(a&&typeof a=="object"&&!Array.isArray(a)){let i=0;for(let l of Object.keys(a))l.startsWith("^")&&i++;i>0&&t.record("prefix-stripped","portal.yaml",i);}else Array.isArray(a)&&a.length>0&&t.record("array-coerced","portal.yaml");let c=o.routes;Array.isArray(c)&&c.length>0&&t.record("array-coerced","portal.yaml"),o.version||t.record("default-applied","portal.yaml");}function Pe(e,t){for(let s of e){let r;try{r=y.readFileSync(s,"utf-8");}catch{continue}try{O.load(r);}catch(d){(d?.reason?.toLowerCase()||"").includes("duplicate")&&t.record("duplicate-key-detected","purpose.yaml");continue}let n;try{n=O.load(r,{schema:O.FAILSAFE_SCHEMA});}catch{continue}if(!n||typeof n!="object")continue;let o=n,a=["components","features","gates","signals","aspects","states"],c=0;for(let d of a)Array.isArray(o[d])&&c++;c>0&&t.record("array-coerced","purpose.yaml",c);let i=(d,u)=>{if(!d||typeof d!="object"||Array.isArray(d))return 0;let f=0;for(let E of Object.keys(d))E.startsWith(u)&&f++;return f},l=i(o.gates,"^")+i(o.signals,"!")+i(o.aspects,"~")+i(o.components,"#")+i(o.features,"#");l>0&&t.record("prefix-stripped","purpose.yaml",l);}}function He(e,t){let s={};for(let r of t.symbols)if(r.type==="component"&&r.componentType){let n=r.componentType;s[n]||(s[n]=[]),s[n].push(r.symbol);}return {version:"1.0",generated:new Date().toISOString(),structure:De(e),key_files:Ue(e),skip_patterns:Xe(e),symbols:ze(t.symbols,t.purposeFiles),...Object.keys(s).length>0?{symbolsByComponentType:s}:{}}}function De(e){let t={};for(let[s,r]of Object.entries(Fe)){let n=r.filter(o=>y.existsSync(T.join(e,o)));if(n.length>0){let o=Object.values(Oe).find(a=>a.category===s);t[s]={paths:n,symbol:o?.prefix||"@"};}}return t}function Ue(e){let t={};for(let[s,r]of Object.entries(ke)){let n=r.filter(o=>y.existsSync(T.join(e,o)));n.length>0&&(t[s]=n);}return t.config||(t.config=[]),t.entry||(t.entry=[]),t.types||(t.types=[]),t}function Xe(e){let t={always:[...ct.always],unless_testing:[...ct.unless_testing],unless_docs:[...ct.unless_docs]},s=T.join(e,".gitignore");if(y.existsSync(s))try{let n=y.readFileSync(s,"utf8").split(`
93
+ `).map(o=>o.trim()).filter(o=>o&&!o.startsWith("#")).filter(o=>o.endsWith("/")||o.includes("*")||["node_modules","dist","build",".cache"].some(a=>o.includes(a))).slice(0,20);for(let o of n)t.always.includes(o)||t.always.push(o);}catch{}return t}function We(e){switch(e){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 ze(e,t,s){let r={};for(let n of e){let a=`${We(n.type)}${n.id}`;if(n.filePath)r[a]=n.filePath;else {let c=t.find(i=>T.dirname(i).toLowerCase().includes(n.id.toLowerCase()));c&&(r[a]=T.dirname(c)+"/");}}return r}function $e(e,t){let s={},r={};for(let n of t)try{let o=y.readFileSync(n,"utf8"),a=O.load(o);if(!a?.flows)continue;if(Array.isArray(a.flows))for(let c of a.flows){let i=c;if(!i.name)continue;let l=`$${i.name}`,d=Gt(i.steps);d.length>0&&(s[l]={id:l,description:i.description||"",steps:d,definedIn:T.relative(e,n)},Yt(l,d,r));}else for(let[c,i]of Object.entries(a.flows)){let l=c.startsWith("$")?c:`$${c}`,d=Gt(i.steps);d.length>0&&(s[l]={id:l,description:i.description||"",trigger:i.trigger,steps:d,validation:i.validation,definedIn:T.relative(e,n)},Yt(l,d,r));}}catch{}return Object.keys(s).length===0?null:{version:"1.0",generatedAt:new Date().toISOString(),flows:s,symbolToFlows:r}}function Gt(e){if(!e||!Array.isArray(e))return [];let t=[];for(let s=0;s<e.length;s++){let r=e[s];if(typeof r=="object"&&r!==null){let n=r,o=n.action||n.description||n.component||"";o&&t.push({id:n.id||`step-${s+1}`,action:o,symbol:n.symbol||n.component,expect:n.expect});}}return t}function Yt(e,t,s){for(let r of t)r.symbol&&(s[r.symbol]||(s[r.symbol]=[]),s[r.symbol].includes(e)||s[r.symbol].push(e));}export{Rt as a,Z as b,Pt as c,Ht as d,Ze as e,tn as f,en as g,nn as h,sn as i,rn as j,on as k,an as l,dn as m,zt as n,gn as o,mn as p,Ae as q,Pn as r,Hn as s,Me as t};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import*as d from'fs';import*as g from'path';import*as h from'js-yaml';b$1();var T=".paradigm/tasks",y="entries",C="index.yaml";function I(e){if(e&&e.session_link&&!e.external_ref){let n=e.session_link,i=n.toLowerCase(),r;i.includes("github")?r="github":i.includes("session")?r="session":r="url",e.external_ref={provider:r,ref:n},delete e.session_link;}let t=e?.external_ref;return t&&t.kind!==void 0&&t.provider===void 0&&(t.provider=t.kind,delete t.kind),e}function D(e,t){let n=g.join(e,T,y,t);if(!d.existsSync(n))return `T-${t}-001`;let i=d.readdirSync(n).filter(o=>o.startsWith("T-")&&o.endsWith(".yaml")).map(o=>{let c=o.match(/T-\d{4}-\d{2}-\d{2}-(\d+)\.yaml/);return c?parseInt(c[1],10):0}),r=i.length>0?Math.max(...i)+1:1;return `T-${t}-${String(r).padStart(3,"0")}`}function A(e,t){return e===t?true:({open:["in-progress","done","shelved"],"in-progress":["done","open","shelved"],shelved:["open"],done:["open"]}[e]??[]).includes(t)}var O={high:0,medium:1,low:2},N=["open","in-progress"];function $(e,t){return t==="all"?true:t==="active"?N.includes(e.status):e.status===t}function R(e){let t=e.created?new Date(e.created).getTime():NaN;if(!Number.isNaN(t))return t;let n=e.id?.match(/^T-(\d{4}-\d{2}-\d{2})-/);if(n){let i=new Date(n[1]).getTime();if(!Number.isNaN(i))return i}return 0}function W(e,t){let n=e;if(t.status&&t.status!=="all"&&(n=n.filter(i=>$(i,t.status))),t.priority&&(n=n.filter(i=>i.priority===t.priority)),t.tag&&(n=n.filter(i=>i.tags.includes(t.tag))),t.claimant){let{kind:i,ref:r}=t.claimant;n=n.filter(o=>o.claimant!=null&&o.claimant.ref===r&&(i===void 0||o.claimant.kind===i));}return n.sort((i,r)=>{let o=(O[i.priority]??1)-(O[r.priority]??1);return o!==0?o:R(r)-R(i)}),t.limit&&(n=n.slice(0,t.limit)),n}async function b(e,t){let n=g.join(e,T,y);if(!d.existsSync(n))return [];let i={status:"open",limit:20,...t},r=[],o=d.readdirSync(n).filter(c=>/^\d{4}-\d{2}-\d{2}$/.test(c)).sort().reverse();for(let c of o){let k=g.join(n,c),u=d.readdirSync(k).filter(s=>s.endsWith(".yaml")).sort();for(let s of u)try{let a=d.readFileSync(g.join(k,s),"utf8"),f=I(h.load(a));r.push(f);}catch{}}return W(r,i)}async function V(e,t,n){return b(e,{claimant:t,status:n?.status??"active",limit:n?.limit??200})}async function K(e,t){let n=t.match(/^T-(\d{4}-\d{2}-\d{2})-/);if(n){let r=g.join(e,T,y,n[1],`${t}.yaml`);if(d.existsSync(r))try{return I(h.load(d.readFileSync(r,"utf8")))}catch{return null}}return (await b(e,{status:"all",limit:9999})).find(r=>r.id===t)||null}function L(e){let t=[],n=new Map;for(let s of e)s.id&&n.set(s.id,s);for(let s of e)if(s.id){s.parentTaskId===s.id?t.push({kind:"self-parent",taskId:s.id,detail:s.id}):s.parentTaskId&&!n.has(s.parentTaskId)&&t.push({kind:"dangling-parent",taskId:s.id,detail:s.parentTaskId});for(let a of s.dependsOn??[])a===s.id?t.push({kind:"self-parent",taskId:s.id,detail:`dependsOn:${a}`}):n.has(a)||t.push({kind:"dangling-dependency",taskId:s.id,detail:a});}let i=0,r=1,o=2,c=new Map;for(let s of n.keys())c.set(s,i);let k=s=>{let a=[];s.parentTaskId&&s.parentTaskId!==s.id&&n.has(s.parentTaskId)&&a.push(s.parentTaskId);for(let f of s.dependsOn??[])f!==s.id&&n.has(f)&&a.push(f);return a},u=new Set;for(let s of n.keys()){if(c.get(s)!==i)continue;let a=[{id:s,path:[s]}],f=new Set;for(;a.length;){let l=a[a.length-1];c.get(l.id)===i&&(c.set(l.id,r),f.add(l.id));let S=false;for(let p of k(n.get(l.id)))if(c.get(p)===r){let m=l.path.indexOf(p),w=m>=0?l.path.slice(m).concat(p):[l.id,p],P=[...w].sort().join("|");u.has(P)||(u.add(P),t.push({kind:"cycle",taskId:p,detail:w.join(" \u2192 ")}));}else if(c.get(p)===i){a.push({id:p,path:[...l.path,p]}),S=true;break}S||(c.set(l.id,o),f.delete(l.id),a.pop());}}return t}async function B(e,t){let n=new Date,i=n.toISOString().slice(0,10),r=g.join(e,T,y,i);d.mkdirSync(r,{recursive:true});let o=D(e,i),c={id:o,blurb:t.blurb,priority:t.priority||"medium",status:"open",tags:t.tags||[],created:n.toISOString(),related_lore:t.related_lore,claimant:t.claimant,parentTaskId:t.parentTaskId,dependsOn:t.dependsOn,stage:t.stage,external_ref:t.external_ref,session_link:t.session_link};return I(c),d.writeFileSync(g.join(r,`${o}.yaml`),h.dump(j(c),{lineWidth:-1,noRefs:true})),await F(e),o}async function v(e,t,n){let i=await K(e,t);if(!i)return false;let r=i.created.slice(0,10),o=g.join(e,T,y,r,`${t}.yaml`);if(!d.existsSync(o))return false;let{id:c,created:k,...u}=n;if(u.status!==void 0&&u.status!==i.status){if(!A(i.status,u.status))return a.component("#task-loader").warn("Illegal task status transition rejected",{taskId:t,from:i.status,to:u.status}),false;u.status==="in-progress"&&!i.started_at&&u.started_at===void 0&&(u.started_at=new Date().toISOString()),i.status==="done"&&u.status==="open"&&(u.completed=void 0,u.settledAt=void 0,u.crashed_at=void 0,u.crash_reason=void 0);}let s={...i,...u};if(d.writeFileSync(o,h.dump(j(s),{lineWidth:-1,noRefs:true})),await F(e),_(s.status)&&s.parentTaskId)try{let{settleParentIfComplete:a}=await import('./task-settlement-F7CIKUG3.js');await a(e,s.parentTaskId,s.id);}catch(a$1){a.component("#task-loader").warn("Settlement after updateTask failed (non-fatal)",{taskId:t,parentTaskId:s.parentTaskId,error:a$1 instanceof Error?a$1.message:String(a$1)});}if(_(s.status))try{let a$1=await b(e,{status:"all",limit:9999}),f=new Map(a$1.map(l=>[l.id,l]));for(let l of a$1){if(!l.blocked_on||!l.dependsOn?.includes(s.id))continue;(l.dependsOn??[]).every(p=>{let m=f.get(p);return m!=null&&_(m.status)})&&(await v(e,l.id,{blocked_on:void 0}),a.component("#task-loader").info("Auto-cleared blocked_on (all deps terminal)",{taskId:l.id,resolvedBy:s.id}));}}catch(a$1){a.component("#task-loader").warn("blocked_on auto-clear failed (non-fatal)",{taskId:t,error:a$1 instanceof Error?a$1.message:String(a$1)});}return true}function _(e){return e==="done"||e==="shelved"}async function U(e,t){return v(e,t,{status:"done",completed:new Date().toISOString()})}async function Y(e,t){return v(e,t,{status:"shelved",shelved:new Date().toISOString()})}async function F(e){let t=g.join(e,T,y),n=g.join(e,T),i=0,r=0,o=0,c=0,k=0,u=[];if(d.existsSync(t)){let a=d.readdirSync(t).filter(f=>/^\d{4}-\d{2}-\d{2}$/.test(f));for(let f of a){let l=g.join(t,f),S=d.readdirSync(l).filter(p=>p.endsWith(".yaml"));for(let p of S)try{let m=I(h.load(d.readFileSync(g.join(l,p),"utf8")));i++,m.status==="open"?r++:m.status==="in-progress"?o++:m.status==="done"?c++:m.status==="shelved"&&k++,!m.parentTaskId&&m.id&&u.push(m.id);}catch{}}}let s={version:"1.1",total:i,open:r,in_progress:o,done:c,shelved:k,roots:u,last_updated:new Date().toISOString()};return d.mkdirSync(n,{recursive:true}),d.writeFileSync(g.join(n,C),h.dump(s,{lineWidth:-1,noRefs:true})),s}function j(e){let t={};for(let[n,i]of Object.entries(e))i!==void 0&&(t[n]=i);return t}export{I as a,D as b,A as c,b as d,V as e,K as f,L as g,B as h,v as i,U as j,Y as k,F as l};