@a-company/paradigm 7.1.0 → 7.2.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 (131) hide show
  1. package/dist/{accept-orchestration-WMGFGYDK.js → accept-orchestration-XW44LF5Y.js} +1 -1
  2. package/dist/add-CBDU23S2.js +12 -0
  3. package/dist/{aggregate-KZICPVT3.js → aggregate-H7SB2UYT.js} +1 -1
  4. package/dist/{ambient-HAXPDIWK.js → ambient-TFLZFV5Y.js} +1 -1
  5. package/dist/ambient-VCTUHHIG.js +2 -0
  6. package/dist/arch-loader-YVOS3QRY.js +2 -0
  7. package/dist/{beacon-52EWNZPK.js → beacon-WVN264OT.js} +1 -1
  8. package/dist/captain-CAXGHC2V.js +2 -0
  9. package/dist/captain-CWCLFOXV.js +2 -0
  10. package/dist/{chunk-QDP4G53M.js → chunk-27EK3OQZ.js} +4 -4
  11. package/dist/chunk-2KK4JQ55.js +17 -0
  12. package/dist/chunk-3I3TITBA.js +25 -0
  13. package/dist/chunk-3YM5ABNX.js +2 -0
  14. package/dist/{chunk-RDWWSQGH.js → chunk-6HYRS3PH.js} +14 -14
  15. package/dist/{chunk-S3UVQ5RV.js → chunk-6VZSOQ7Y.js} +1 -1
  16. package/dist/chunk-727PXENG.js +2 -0
  17. package/dist/chunk-A5EEY6NO.js +3 -0
  18. package/dist/{chunk-DLMDHS2X.js → chunk-ASBK55FU.js} +1 -1
  19. package/dist/{chunk-4GC35IFF.js → chunk-D6BSCELB.js} +1 -1
  20. package/dist/{chunk-G6DK3ND3.js → chunk-DH7QVZDI.js} +9 -0
  21. package/dist/chunk-FG3M6VVO.js +30 -0
  22. package/dist/chunk-FNYYQNJY.js +2 -0
  23. package/dist/chunk-K6TLYNRQ.js +7 -0
  24. package/dist/chunk-K7KT6FL3.js +25 -0
  25. package/dist/chunk-M7JHVVDW.js +6 -0
  26. package/dist/chunk-NFN5UUJB.js +2 -0
  27. package/dist/{chunk-EG22HDXI.js → chunk-NRP2KJ6I.js} +12 -12
  28. package/dist/{chunk-VPNJL4LS.js → chunk-QPQBXRXX.js} +1 -1
  29. package/dist/chunk-RZRFYGND.js +504 -0
  30. package/dist/chunk-UNSI6DVD.js +93 -0
  31. package/dist/{chunk-W4BW7GXA.js → chunk-USYV5QYU.js} +1 -1
  32. package/dist/chunk-VOPJ47QY.js +2 -0
  33. package/dist/{chunk-KP5VOYAH.js → chunk-W3VWORQZ.js} +1 -1
  34. package/dist/chunk-WMTES556.js +2 -0
  35. package/dist/chunk-XBK244QR.js +6 -0
  36. package/dist/{chunk-YQK3XU63.js → chunk-XSKIXXFW.js} +12 -12
  37. package/dist/{chunk-MBSY57RN.js → chunk-Y76OIMDO.js} +1 -1
  38. package/dist/chunk-YYRP7FLC.js +2 -0
  39. package/dist/{compliance-4P3EE5OA.js → compliance-3M6COUCO.js} +3 -3
  40. package/dist/{constellation-RHZAEFV7.js → constellation-TIKNCZWR.js} +1 -1
  41. package/dist/{cost-24UZSS2P.js → cost-VTHZQKO4.js} +2 -2
  42. package/dist/{diff-VBVIUNL5.js → diff-Z2YSIRC4.js} +1 -1
  43. package/dist/{dist-TNE4GFT7.js → dist-PW5YPGFF.js} +1 -1
  44. package/dist/{docs-NTP6UENF.js → docs-OWJ7EPD7.js} +1 -1
  45. package/dist/github-4X4MYINS.js +4 -0
  46. package/dist/{habits-BX2IRSUI.js → habits-UA7YT3CG.js} +3 -3
  47. package/dist/{hooks-AXBWYJ5V.js → hooks-XXJ7CSGJ.js} +1 -1
  48. package/dist/index.js +9 -9
  49. package/dist/{init-F4MSKZIW.js → init-QPMLEQWQ.js} +1 -1
  50. package/dist/{integrity-7TKX3DZ4.js → integrity-FRGF5BFS.js} +1 -1
  51. package/dist/lint-Y4P3MHBV.js +26 -0
  52. package/dist/list-5XRLWD7K.js +12 -0
  53. package/dist/mcp.js +1 -1
  54. package/dist/{migrate-5M4KUQ2L.js → migrate-LIVXILOO.js} +1 -1
  55. package/dist/nomination-engine-EFXDEPZN.js +2 -0
  56. package/dist/{orchestrate-MLUGQOEJ.js → orchestrate-C5NM5MFN.js} +1 -1
  57. package/dist/orchestration-EVWQWTOV.js +2 -0
  58. package/dist/orchestration-UP3KFUJT.js +2 -0
  59. package/dist/{platform-server-Y6TLEXR2.js → platform-server-FXF3XFHM.js} +1 -1
  60. package/dist/{probe-27ARJKRO.js → probe-G3TKOJYW.js} +1 -1
  61. package/dist/quiz-QKIKAVL7.js +10 -0
  62. package/dist/registry-NEW4OJ44.js +2 -0
  63. package/dist/reindex-QZYOD5K4.js +2 -0
  64. package/dist/{reindex-ZLDQBFUR.js → reindex-W67B2LQP.js} +1 -1
  65. package/dist/remember-KZYAY77S.js +14 -0
  66. package/dist/{review-BRO2UP4M.js → review-WHRNLW2W.js} +1 -1
  67. package/dist/{ripple-KCVDS3WE.js → ripple-B6U7263T.js} +1 -1
  68. package/dist/{serve-2PKJP65E.js → serve-6RNZYK2I.js} +2 -2
  69. package/dist/{serve-XZ6GBUS3.js → serve-ZT2Z54NK.js} +1 -1
  70. package/dist/{setup-5V2AGLQ6.js → setup-L5OP24US.js} +3 -3
  71. package/dist/{shift-PM4GI736.js → shift-UDKXCIW7.js} +3 -3
  72. package/dist/{show-N5LGB5B2.js → show-VXNGIJE4.js} +3 -3
  73. package/dist/{snapshot-YMX5QRBM.js → snapshot-MT5L6XE4.js} +1 -1
  74. package/dist/{spawn-PHA2SVQ3.js → spawn-I6XG57S2.js} +1 -1
  75. package/dist/status-45KIG32R.js +6 -0
  76. package/dist/{status-3GJXI4IK.js → status-4QGKLOP6.js} +4 -4
  77. package/dist/{summary-RPU2BS3Q.js → summary-6QNVQZJV.js} +1 -1
  78. package/dist/symphony-KQJ6HIXB.js +53 -0
  79. package/dist/symphony-VDNDFK7H.js +2 -0
  80. package/dist/symphony-relay-ASMKPDEE.js +3 -0
  81. package/dist/task-KFND4HLF.js +3 -0
  82. package/dist/task-loader-HBZ3KRH2.js +2 -0
  83. package/dist/task-loader-IO4UVFUD.js +2 -0
  84. package/dist/task-settlement-NF7PFSNE.js +3 -0
  85. package/dist/task-settlement-TATNPY6L.js +3 -0
  86. package/dist/team-6WNNLBAO.js +2 -0
  87. package/dist/thread-2A7QKU72.js +41 -0
  88. package/dist/tools-GDWT74O6.js +2 -0
  89. package/dist/tools-SDWAFQMQ.js +142 -0
  90. package/dist/validate-OZTX3FYX.js +13 -0
  91. package/dist/validate-RIMSY3RP.js +9 -0
  92. package/dist/{workspace-6POCBPDY.js → workspace-4D4TQ637.js} +1 -1
  93. package/package.json +1 -1
  94. package/dist/add-V6XR7DU5.js +0 -12
  95. package/dist/agent-loader-Z753DQWH.js +0 -2
  96. package/dist/ambient-QB7V4TBR.js +0 -6
  97. package/dist/captain-3COP6YTD.js +0 -2
  98. package/dist/chunk-4CGPLLWQ.js +0 -30
  99. package/dist/chunk-7SWEOPWF.js +0 -2
  100. package/dist/chunk-CHSU6LTR.js +0 -2
  101. package/dist/chunk-EKNLG73M.js +0 -6
  102. package/dist/chunk-H55W26AR.js +0 -3
  103. package/dist/chunk-HE2NA5QF.js +0 -8
  104. package/dist/chunk-JIXHEBGK.js +0 -7
  105. package/dist/chunk-MBPLJKE5.js +0 -3
  106. package/dist/chunk-OIYJUU6T.js +0 -25
  107. package/dist/chunk-QO7YPQXC.js +0 -2
  108. package/dist/chunk-XPPFILCM.js +0 -2
  109. package/dist/chunk-YCDOA5IQ.js +0 -18
  110. package/dist/lint-IGKE6UPS.js +0 -26
  111. package/dist/list-NC3QGT75.js +0 -12
  112. package/dist/lore-loader-HAZ5FRLP.js +0 -2
  113. package/dist/nomination-engine-ORHH4L2W.js +0 -2
  114. package/dist/orchestration-O2OVPTIZ.js +0 -2
  115. package/dist/quiz-TNV6APBM.js +0 -10
  116. package/dist/remember-MJRNTXYS.js +0 -14
  117. package/dist/session-work-log-FF7CKMWP.js +0 -2
  118. package/dist/status-ENAI35NL.js +0 -6
  119. package/dist/symphony-CFAYJGLF.js +0 -2
  120. package/dist/symphony-L56O5ZG3.js +0 -53
  121. package/dist/symphony-relay-Y2UR3YNR.js +0 -3
  122. package/dist/task-loader-H7HQAYGL.js +0 -2
  123. package/dist/task-loader-YZME4RKE.js +0 -2
  124. package/dist/task-settlement-HINBVZBE.js +0 -3
  125. package/dist/task-settlement-XC6E6JNT.js +0 -3
  126. package/dist/team-25LK6CWM.js +0 -2
  127. package/dist/thread-HFXK65D4.js +0 -41
  128. package/dist/tools-GAU5WOEI.js +0 -2
  129. package/dist/validate-IQG7DBFC.js +0 -9
  130. package/dist/validate-LSCDOLBO.js +0 -13
  131. package/dist/work-log-loader-CRVTOMVB.js +0 -2
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b}from'./chunk-EG22HDXI.js';import'./chunk-DLMDHS2X.js';import'./chunk-FYDRENK7.js';import'./chunk-ECLUYHAR.js';import'./chunk-TYWB5IQJ.js';import'./chunk-YXLGVOZO.js';import'./chunk-XPPFILCM.js';import'./chunk-MBPLJKE5.js';import'./chunk-EKZDFEJW.js';import'./chunk-LPBCQM5Y.js';import'./chunk-4GC35IFF.js';import'./chunk-JIXHEBGK.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as g from'path';import e from'chalk';async function u(n,s,r){let a=s?g.resolve(s):process.cwd();if(!n){r.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(e.red(`
2
+ import {b}from'./chunk-NRP2KJ6I.js';import'./chunk-TYWB5IQJ.js';import'./chunk-ASBK55FU.js';import'./chunk-ECLUYHAR.js';import'./chunk-YXLGVOZO.js';import'./chunk-FYDRENK7.js';import'./chunk-3YM5ABNX.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-EKZDFEJW.js';import'./chunk-LPBCQM5Y.js';import'./chunk-D6BSCELB.js';import'./chunk-K6TLYNRQ.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as g from'path';import e from'chalk';async function u(n,s,r){let a=s?g.resolve(s):process.cwd();if(!n){r.json?console.log(JSON.stringify({error:"Orchestration ID required"})):(console.log(e.red(`
3
3
  Orchestration ID required.`)),console.log(e.gray(`Usage: paradigm team accept <orchestration-id>
4
4
  `)));return}let l=new b(a),o=l.getOrchestration(n);if(!o){r.json?console.log(JSON.stringify({error:"Orchestration not found",id:n})):console.log(e.red(`
5
5
  Orchestration not found: ${n}
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import {c as c$1,a,h,g}from'./chunk-YYRP7FLC.js';import {t}from'./chunk-M7JHVVDW.js';import'./chunk-5TAVYPOV.js';import r from'chalk';import*as c from'path';import {execSync}from'child_process';import*as P from'os';var N=".paradigm/university";function O(){try{return execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").slice(0,20)||"unknown"}catch{try{return P.userInfo().username}catch{return "unknown"}}}async function F(o,e){let i=process.cwd(),f=!!(e.pack||e.project||e.discipline),S=f?e:{...e,project:true},n=c$1(i,S),m=n.subPackRoot??n.packRoot,g$1=f?m:void 0,R=c.join(i,N),y=c.resolve(m)===c.resolve(R);if(e.title||(console.error(r.red(`
3
+ Error: --title is required
4
+ `)),process.exit(1)),e.section){let t=a(n.subPackRoot??n.packRoot);if(t.length>0&&!new Set(t.map(l=>l.id)).has(e.section)){let l=t.map(q=>q.id).join(", "),j=n.subPackId??n.packId;console.error(r.red(`
5
+ Error: section "${e.section}" not declared in pack "${j}". Available: ${l}
6
+ `)),process.exit(1);}}let s=e.order!==void 0?parseInt(e.order,10):void 0;e.order!==void 0&&(s===void 0||Number.isNaN(s))&&(console.error(r.red(`
7
+ Error: --order must be an integer (got "${e.order}")
8
+ `)),process.exit(1));let p=O(),a$1=new Date().toISOString().slice(0,10),v=e.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40),b=e.tags?e.tags.split(",").map(t=>t.trim()):[],k=e.symbols?e.symbols.split(",").map(t=>t.trim()):[];if(o==="quiz"){let t$1=`Q-${v}`,h$1={id:t$1,title:e.title,description:e.body||"",author:p,created:a$1,updated:a$1,tags:b,symbols:k,difficulty:e.difficulty||"beginner",passThreshold:.7,questions:[],...e.section?{section:e.section}:{},...s!==void 0?{order:s}:{}};h(i,h$1,g$1),y&&t(i),console.log(r.green(`
9
+ Created quiz: ${t$1}`)),console.log(r.gray(` Add questions by editing the YAML file
10
+ `));return}let d=`${o==="policy"?"P":"N"}-${v}`,z={id:d,title:e.title,type:o,author:p,created:a$1,updated:a$1,tags:b,symbols:k,difficulty:e.difficulty||"beginner",estimatedMinutes:e.minutes?parseInt(e.minutes,10):void 0,prerequisites:[],...e.section?{section:e.section}:{},...s!==void 0?{order:s}:{}};g(i,z,e.body||"",g$1),y&&t(i),console.log(r.green(`
11
+ Created ${o}: ${d}`)),console.log(r.gray(` Edit at .paradigm/university/content/${o==="policy"?"policies":"notes"}/${d}.md
12
+ `));}export{F as universityAddCommand};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {c,l as l$1,m,o as o$1,B}from'./chunk-4GC35IFF.js';import'./chunk-JIXHEBGK.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as u from'fs';import*as l from'path';import o from'chalk';import S from'ora';async function A(d){let h=process.cwd(),a=l.resolve(h,d);console.log(o.blue(`
2
+ import {c,l as l$1,m,o as o$1,B}from'./chunk-D6BSCELB.js';import'./chunk-K6TLYNRQ.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';import*as u from'fs';import*as l from'path';import o from'chalk';import S from'ora';async function A(d){let h=process.cwd(),a=l.resolve(h,d);console.log(o.blue(`
3
3
  \u{1F52E} Aggregating Premise...
4
4
  `));let c$1=S("Loading sources...").start();try{let e,g=l.join(a,".premise");if(u.existsSync(g)){let{data:r,errors:s}=c(g);if(s.length>0){c$1.warn("Warnings parsing .premise file");for(let n of s)console.log(o.yellow(` \u26A0 ${n}`));console.log(o.gray(` Falling back to directory aggregation...
5
5
  `));}if(r&&!s.some(n=>n.includes("Required")))try{e=await l$1(r,a);}catch(n){console.log(o.yellow(` \u26A0 Error using .premise file: ${n.message}`)),console.log(o.gray(` Falling back to directory aggregation...
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import'./chunk-5TAVYPOV.js';import*as s from'path';import t from'chalk';async function g(n){let e=n.project?s.resolve(n.project):process.cwd(),r=n.dryRun===true,{readPendingVerdicts:a}=await import('./session-work-log-FF7CKMWP.js'),i=a(e);if(i.length===0){console.log(t.dim("[paradigm] No pending verdicts \u2014 postflight skipped."));return}console.log(t.cyan(`[paradigm] Running postflight \u2014 ${i.length} pending verdict(s)${r?" (dry run)":""}...`));let{runPostflightLearning:l}=await import('./ambient-QB7V4TBR.js'),o=await l(e,{dry_run:r});if(o.journalsWritten===0&&o.promoted===0){console.log(t.dim("[paradigm] Postflight complete \u2014 no new journals written."));return}console.log(t.green("[paradigm] Postflight complete:")),o.journalsWritten>0&&console.log(` ${t.bold(o.journalsWritten)} journal entries written across ${o.agentsProcessed.length} agent(s)`),o.promoted>0&&console.log(` ${t.bold(o.promoted)} entries auto-promoted to notebooks`);}export{g as ambientPostflightCommand};
2
+ import'./chunk-5TAVYPOV.js';import*as s from'path';import t from'chalk';async function g(n){let e=n.project?s.resolve(n.project):process.cwd(),r=n.dryRun===true,{readPendingVerdicts:a}=await import('./session-work-log-T2IE4Y4T.js'),i=a(e);if(i.length===0){console.log(t.dim("[paradigm] No pending verdicts \u2014 postflight skipped."));return}console.log(t.cyan(`[paradigm] Running postflight \u2014 ${i.length} pending verdict(s)${r?" (dry run)":""}...`));let{runPostflightLearning:l}=await import('./ambient-VCTUHHIG.js'),o=await l(e,{dry_run:r});if(o.journalsWritten===0&&o.promoted===0){console.log(t.dim("[paradigm] Postflight complete \u2014 no new journals written."));return}console.log(t.green("[paradigm] Postflight complete:")),o.journalsWritten>0&&console.log(` ${t.bold(o.journalsWritten)} journal entries written across ${o.agentsProcessed.length} agent(s)`),o.promoted>0&&console.log(` ${t.bold(o.promoted)} entries auto-promoted to notebooks`);}export{g as ambientPostflightCommand};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export{a as getAmbientToolsList,b as handleAmbientTool,c as runPostflightLearning}from'./chunk-XBK244QR.js';import'./chunk-FG3M6VVO.js';import'./chunk-3KVVC4WV.js';import'./chunk-KAUGQMXU.js';import'./chunk-Q527BPUF.js';import'./chunk-33ERV2MW.js';import'./chunk-KAFQA7HV.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-ECO3LHCE.js';import'./chunk-5TAVYPOV.js';
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export{a as ARCH_FILE,e as generateMermaid,d as getArchDrift,b as loadArchMap,c as saveArchMap}from'./chunk-A5EEY6NO.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-D6BSCELB.js';import'./chunk-K6TLYNRQ.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {m,o,C,B}from'./chunk-4GC35IFF.js';import'./chunk-JIXHEBGK.js';import'./chunk-ZJQY5PPP.js';import {a}from'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';import*as i from'fs';import*as c from'path';import n from'chalk';import O from'ora';function G(u){let o=[],g=[{pattern:"portal.yaml",desc:"Authorization topology"},{pattern:"src/lib/api.ts",desc:"API utilities"},{pattern:"src/lib/api.js",desc:"API utilities"},{pattern:"src/utils/api.ts",desc:"API utilities"},{pattern:"src/hooks/useAuth.ts",desc:"Auth hook"},{pattern:"src/hooks/useAuth.tsx",desc:"Auth hook"},{pattern:"src/context/AuthContext.tsx",desc:"Auth context"},{pattern:"src/store/index.ts",desc:"State store"},{pattern:"src/types/index.ts",desc:"Type definitions"},{pattern:"src/types.ts",desc:"Type definitions"},{pattern:".paradigm/config.yaml",desc:"Paradigm config"},{pattern:"tsconfig.json",desc:"TypeScript config"},{pattern:"package.json",desc:"Package manifest"}];for(let{pattern:r,desc:l}of g){let t=c.join(u,r);i.existsSync(t)&&o.push({path:r,description:l});}return o.slice(0,8)}function E(u){let o=c.join(u,".paradigm","prompts"),g=[];if(i.existsSync(o)){let r=i.readdirSync(o).filter(l=>l.endsWith(".md"));for(let l of r){let t=l.replace(".md","").replace(/-/g," ");g.push({name:t.charAt(0).toUpperCase()+t.slice(1),path:`.paradigm/prompts/${l}`});}}return g.slice(0,6)}function I(u,o,g,r,l){let t=[];t.push(`# Beacon - ${u}`),t.push(""),t.push("> Quick-start orientation for AI agents. Generated by Paradigm."),t.push(""),t.push("## Constellation (Symbol Map)"),t.push(""),t.push("```");let a=o.filter(e=>e.type==="component"),m=o.filter(e=>e.type==="gate");for(let e of a.slice(0,15)){let p=e.references.filter(d=>d.startsWith("^")),b=`${e.symbol.padEnd(20)} \u2192 ${c.dirname(e.filePath).padEnd(25)}`;p.length>0&&(b+=` \u2192 ${p.join(", ")}`),t.push(b);}if(a.length>15&&t.push(`... and ${a.length-15} more components`),t.push("```"),t.push(""),m.length>0){t.push("## Gates (Authorization)"),t.push("");for(let e of m.slice(0,6)){let p=e.description?` - ${e.description}`:"";t.push(`- \`${e.symbol}\`${p}`);}m.length>6&&t.push(`- ... and ${m.length-6} more gates`),t.push("");}if(g.length>0){t.push("## Landmarks (Key Files)"),t.push("");for(let e of g)t.push(`- \`${e.path}\` - ${e.description}`);t.push("");}if(r.length>0){t.push("## Pathways (Common Tasks)"),t.push("");for(let e of r)t.push(`- "${e.name}" \u2192 \`${e.path}\``);t.push("");}return t.push("## Symbol Quick Reference"),t.push(""),t.push("| Symbol | Type | Meaning |"),t.push("|--------|------|---------|"),t.push("| `#` | Component | Any documented code unit |"),t.push("| `$` | Flow | Multi-step process |"),t.push("| `^` | Gate | Authorization checkpoint |"),t.push("| `!` | Signal | Event for side effects |"),t.push("| `~` | Aspect | Rule with code anchor |"),t.push(""),t.push("## For More Context"),t.push(""),t.push("- Full symbol graph: `.paradigm/constellation.json`"),t.push("- Detailed context: `.paradigm/specs/` for detailed specifications"),t.push("- Session history: `.paradigm/thread.md` (if available)"),t.push("- Error mapping: `.paradigm/echoes.yaml` (if available)"),t.push(""),t.push("---"),t.push(`*Generated: ${new Date().toISOString().split("T")[0]}*`),t.push("*Run `paradigm beacon --refresh` to update*"),t.join(`
2
+ import {m,o,C,B}from'./chunk-D6BSCELB.js';import'./chunk-K6TLYNRQ.js';import'./chunk-ZJQY5PPP.js';import {a}from'./chunk-LKAT7IAK.js';import'./chunk-5TAVYPOV.js';import*as i from'fs';import*as c from'path';import n from'chalk';import O from'ora';function G(u){let o=[],g=[{pattern:"portal.yaml",desc:"Authorization topology"},{pattern:"src/lib/api.ts",desc:"API utilities"},{pattern:"src/lib/api.js",desc:"API utilities"},{pattern:"src/utils/api.ts",desc:"API utilities"},{pattern:"src/hooks/useAuth.ts",desc:"Auth hook"},{pattern:"src/hooks/useAuth.tsx",desc:"Auth hook"},{pattern:"src/context/AuthContext.tsx",desc:"Auth context"},{pattern:"src/store/index.ts",desc:"State store"},{pattern:"src/types/index.ts",desc:"Type definitions"},{pattern:"src/types.ts",desc:"Type definitions"},{pattern:".paradigm/config.yaml",desc:"Paradigm config"},{pattern:"tsconfig.json",desc:"TypeScript config"},{pattern:"package.json",desc:"Package manifest"}];for(let{pattern:r,desc:l}of g){let t=c.join(u,r);i.existsSync(t)&&o.push({path:r,description:l});}return o.slice(0,8)}function E(u){let o=c.join(u,".paradigm","prompts"),g=[];if(i.existsSync(o)){let r=i.readdirSync(o).filter(l=>l.endsWith(".md"));for(let l of r){let t=l.replace(".md","").replace(/-/g," ");g.push({name:t.charAt(0).toUpperCase()+t.slice(1),path:`.paradigm/prompts/${l}`});}}return g.slice(0,6)}function I(u,o,g,r,l){let t=[];t.push(`# Beacon - ${u}`),t.push(""),t.push("> Quick-start orientation for AI agents. Generated by Paradigm."),t.push(""),t.push("## Constellation (Symbol Map)"),t.push(""),t.push("```");let a=o.filter(e=>e.type==="component"),m=o.filter(e=>e.type==="gate");for(let e of a.slice(0,15)){let p=e.references.filter(d=>d.startsWith("^")),b=`${e.symbol.padEnd(20)} \u2192 ${c.dirname(e.filePath).padEnd(25)}`;p.length>0&&(b+=` \u2192 ${p.join(", ")}`),t.push(b);}if(a.length>15&&t.push(`... and ${a.length-15} more components`),t.push("```"),t.push(""),m.length>0){t.push("## Gates (Authorization)"),t.push("");for(let e of m.slice(0,6)){let p=e.description?` - ${e.description}`:"";t.push(`- \`${e.symbol}\`${p}`);}m.length>6&&t.push(`- ... and ${m.length-6} more gates`),t.push("");}if(g.length>0){t.push("## Landmarks (Key Files)"),t.push("");for(let e of g)t.push(`- \`${e.path}\` - ${e.description}`);t.push("");}if(r.length>0){t.push("## Pathways (Common Tasks)"),t.push("");for(let e of r)t.push(`- "${e.name}" \u2192 \`${e.path}\``);t.push("");}return t.push("## Symbol Quick Reference"),t.push(""),t.push("| Symbol | Type | Meaning |"),t.push("|--------|------|---------|"),t.push("| `#` | Component | Any documented code unit |"),t.push("| `$` | Flow | Multi-step process |"),t.push("| `^` | Gate | Authorization checkpoint |"),t.push("| `!` | Signal | Event for side effects |"),t.push("| `~` | Aspect | Rule with code anchor |"),t.push(""),t.push("## For More Context"),t.push(""),t.push("- Full symbol graph: `.paradigm/constellation.json`"),t.push("- Detailed context: `.paradigm/specs/` for detailed specifications"),t.push("- Session history: `.paradigm/thread.md` (if available)"),t.push("- Error mapping: `.paradigm/echoes.yaml` (if available)"),t.push(""),t.push("---"),t.push(`*Generated: ${new Date().toISOString().split("T")[0]}*`),t.push("*Run `paradigm beacon --refresh` to update*"),t.join(`
3
3
  `)}async function q(u,o$1={}){let g=process.cwd(),r=u?c.resolve(g,u):g,l=c.basename(r),t=!o$1.json&&!o$1.quiet;t&&console.log(n.blue(`
4
4
  \u{1F526} Generating Beacon...
5
5
  `));let a$1=o$1.json?null:O("Scanning project...").start(),m$1=a.command("beacon").start("Generating beacon",{project:l});try{let e=c.join(r,".paradigm"),p=o$1.output||c.join(e,"beacon.md");if(!o$1.json&&i.existsSync(p)&&!o$1.refresh){if(a$1?.info("Beacon already exists"),t){console.log(n.gray(` Use --refresh to regenerate
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export{E as assembleCaptainBoard,C as getCaptainToolsList,D as handleCaptainTool,F as proposeClaimantFor}from'./chunk-K7KT6FL3.js';import'./chunk-W3VWORQZ.js';import'./chunk-Q527BPUF.js';import'./chunk-VOPJ47QY.js';import'./chunk-RGSFU2YW.js';import'./chunk-TMDPDIWA.js';import'./chunk-KLBH26PA.js';import'./chunk-GRZQIKST.js';import'./chunk-ACJWUOMA.js';import'./chunk-33ERV2MW.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-5TAVYPOV.js';
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export{z as assembleCaptainBoard,x as getCaptainToolsList,y as handleCaptainTool,A as proposeClaimantFor}from'./chunk-3I3TITBA.js';import'./chunk-4QADCWPU.js';import'./chunk-NKYNHSA5.js';import'./chunk-2KK4JQ55.js';import'./chunk-M7JHVVDW.js';import'./chunk-A5EEY6NO.js';import'./chunk-ACJWUOMA.js';import'./chunk-Q527BPUF.js';import'./chunk-33ERV2MW.js';import'./chunk-VOPJ47QY.js';import'./chunk-GRZQIKST.js';import'./chunk-EK4ZRIFJ.js';import'./chunk-D6BSCELB.js';import'./chunk-K6TLYNRQ.js';import'./chunk-ZJQY5PPP.js';import'./chunk-5TAVYPOV.js';
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b as b$1}from'./chunk-MBSY57RN.js';import {a as a$2,g as g$1,h,d as d$1,f}from'./chunk-UIKLE3WD.js';import {g}from'./chunk-4GC35IFF.js';import {c}from'./chunk-JIXHEBGK.js';import {c as c$1,d,e}from'./chunk-YNDPSWOE.js';import {a as a$1}from'./chunk-LKAT7IAK.js';import*as i from'fs';import*as a from'path';import {fileURLToPath}from'url';import t from'chalk';import q from'ora';function b(s){try{return i.readFileSync(s,"utf8").split(`
2
+ import {b as b$1}from'./chunk-Y76OIMDO.js';import {a as a$2,g as g$1,h,d as d$2,f}from'./chunk-UIKLE3WD.js';import {g}from'./chunk-D6BSCELB.js';import {d}from'./chunk-K6TLYNRQ.js';import {c,d as d$1,e}from'./chunk-YNDPSWOE.js';import {a as a$1}from'./chunk-LKAT7IAK.js';import*as i from'fs';import*as a from'path';import {fileURLToPath}from'url';import t from'chalk';import q from'ora';function b(s){try{return i.readFileSync(s,"utf8").split(`
3
3
  `).length}catch{return 0}}function _(s){let o=g$1(s);if(o&&f[o])return f[o].name;let e=a$2(s);if(e!=="backend")return e.charAt(0).toUpperCase()+e.slice(1)}function U(s){let o=[],e=0,n={name:"cursor",displayName:"Cursor"},g=a.join(s,".cursorrules"),r=a.join(s,".cursor","rules");if(i.existsSync(g)){let l=b(g);n.legacy={path:".cursorrules",lines:l,type:"legacy"},e+=l;}if(i.existsSync(r)){let l=i.readdirSync(r).filter(m=>m.endsWith(".mdc"));l.length>0&&(n.modern=l.map(m=>{let x=a.join(r,m),j=b(x);return e+=j,{path:`.cursor/rules/${m}`,lines:j,type:"modern"}}));}(n.legacy||n.modern)&&o.push(n);let u={name:"copilot",displayName:"GitHub Copilot"},c=a.join(s,".github","copilot-instructions.md"),f=a.join(s,".github","instructions");if(i.existsSync(c)){let l=b(c);u.legacy={path:".github/copilot-instructions.md",lines:l,type:"legacy"},e+=l;}if(i.existsSync(f)){let l=i.readdirSync(f).filter(m=>m.endsWith(".md"));l.length>0&&(u.modern=l.map(m=>{let x=a.join(f,m),j=b(x);return e+=j,{path:`.github/instructions/${m}`,lines:j,type:"modern"}}));}(u.legacy||u.modern)&&o.push(u);let h=a.join(s,".windsurfrules");if(i.existsSync(h)){let l=b(h);o.push({name:"windsurf",displayName:"Windsurf",legacy:{path:".windsurfrules",lines:l,type:"legacy"}}),e+=l;}let w=a.join(s,"CLAUDE.md");if(i.existsSync(w)){let l=b(w);o.push({name:"claude",displayName:"Claude",legacy:{path:"CLAUDE.md",lines:l,type:"legacy"}}),e+=l;}let p=a.join(s,"AGENTS.md");if(i.existsSync(p)){let l=b(p);o.push({name:"agents",displayName:"AGENTS.md",legacy:{path:"AGENTS.md",lines:l,type:"legacy"}}),e+=l;}let y=a$2(s),d=g$1(s);return {ides:o,hasExisting:o.length>0,totalLines:e,projectType:_(s),discipline:y!=="backend"?y:void 0,stack:d||void 0}}function O(s,o){let e=[];e.push("# Migrate IDE Instructions to Paradigm Format"),e.push(""),e.push("## Overview"),e.push(""),e.push(`Migrate existing IDE instruction files for **${o}** to Paradigm's managed, scoped format.`),e.push(""),e.push("## Source Files Found"),e.push("");for(let n of s.ides)if(n.legacy&&e.push(`- \`${n.legacy.path}\` (${n.legacy.lines} lines) - ${n.displayName} ${n.legacy.type} format`),n.modern)for(let g of n.modern)e.push(`- \`${g.path}\` (${g.lines} lines) - ${n.displayName} modern format`);return e.push(""),s.ides.some(n=>n.name==="cursor")&&(e.push("## Cursor Migration \u2192 `.cursor/rules/*.mdc`"),e.push(""),e.push("Split the existing `.cursorrules` into scoped `.mdc` files with YAML frontmatter:"),e.push(""),e.push("### File Structure"),e.push(""),e.push("```"),e.push(".cursor/rules/"),e.push("\u251C\u2500\u2500 project-core.mdc # Always applies - project overview, architecture"),e.push("\u251C\u2500\u2500 code-style.mdc # globs: **/*.{ts,tsx,js,jsx} - naming, formatting"),e.push("\u251C\u2500\u2500 components.mdc # globs: **/components/**/* - component patterns"),e.push("\u251C\u2500\u2500 api-patterns.mdc # globs: **/api/**/* - API conventions"),e.push("\u251C\u2500\u2500 testing.mdc # globs: **/*.test.* - testing guidelines"),e.push("\u2514\u2500\u2500 custom.mdc # Any project-specific rules"),e.push("```"),e.push(""),e.push("### Frontmatter Format"),e.push(""),e.push("```yaml"),e.push("---"),e.push("description: Brief description of what these rules cover"),e.push('globs: "**/*.ts" # File pattern (OR use alwaysApply)'),e.push("alwaysApply: true # Apply to all files (OR use globs)"),e.push("---"),e.push("```"),e.push("")),s.ides.some(n=>n.name==="copilot")&&(e.push("## Copilot Migration \u2192 `.github/instructions/*.instructions.md`"),e.push(""),e.push("Split into scoped instruction files with `applyTo` frontmatter:"),e.push(""),e.push("### File Structure"),e.push(""),e.push("```"),e.push(".github/"),e.push("\u251C\u2500\u2500 copilot-instructions.md # Always applies - core rules"),e.push("\u2514\u2500\u2500 instructions/"),e.push(" \u251C\u2500\u2500 typescript.instructions.md # applyTo: **/*.ts"),e.push(" \u251C\u2500\u2500 react.instructions.md # applyTo: **/*.tsx"),e.push(" \u251C\u2500\u2500 api.instructions.md # applyTo: **/api/**"),e.push(" \u2514\u2500\u2500 testing.instructions.md # applyTo: **/*.test.*"),e.push("```"),e.push(""),e.push("### Frontmatter Format"),e.push(""),e.push("```yaml"),e.push("---"),e.push('applyTo: "**/*.ts"'),e.push("---"),e.push("```"),e.push("")),e.push("## Migration Steps"),e.push(""),e.push("1. **Read each source file** and identify logical sections:"),e.push(" - Project overview / architecture"),e.push(" - Code style / naming conventions"),e.push(" - Language-specific patterns"),e.push(" - Framework-specific rules"),e.push(" - Testing guidelines"),e.push(" - API patterns"),e.push(""),e.push("2. **Create scoped target files** with appropriate frontmatter"),e.push(""),e.push("3. **Backup originals** by renaming to `.bak`:"),e.push(" - `.cursorrules` \u2192 `.cursorrules.bak`"),e.push(" - `.github/copilot-instructions.md` \u2192 `.github/copilot-instructions.md.bak`"),e.push(""),e.push("4. **Verify** the migration by checking that rules apply correctly"),e.push(""),e.push("## Tips"),e.push(""),e.push("- **Prefer specific globs** over `alwaysApply` when possible"),e.push("- **Keep files focused** - one concern per file"),e.push("- **Use descriptive names** that indicate the scope"),e.push("- **Paradigm will generate its own rules** - keep custom rules separate"),e.push("- After migration, run `paradigm sync` to add Paradigm-managed rules"),e.push(""),e.push("---"),e.push(""),e.push("*Generated by `paradigm init --migrate`*"),e.join(`
4
4
  `)}function G(){let s=fileURLToPath(import.meta.url),o=a.dirname(s),e=[a.join(o,"..","..","templates","paradigm"),a.join(o,"..","templates","paradigm"),a.join(o,"..","..","src","templates","paradigm")];for(let n of e)if(i.existsSync(n))return n;return a.join(o,"..","templates","paradigm")}var A={directories:["prompts"],files:["echoes.yaml","docs/commands.md","docs/queries.md","specs/disciplines.md","specs/context-tracking.md"]};function z(s){for(let o of A.directories)if(s===o||s.startsWith(o+"/"))return true;return !!A.files.includes(s)}function N(s,o,e,n=""){i.existsSync(o)||i.mkdirSync(o,{recursive:true});let g=i.readdirSync(s,{withFileTypes:true});for(let r of g){let u=a.join(s,r.name),c=a.join(o,r.name),f=n?`${n}/${r.name}`:r.name;if(!z(f))if(r.isDirectory())N(u,c,e,f);else {let h=i.readFileSync(u,"utf8");h=h.replace(/\{\{PROJECT_NAME\}\}/g,e),i.writeFileSync(c,h,"utf8");}}}function M(s,o){if(console.log(t.blue(`
5
5
  \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510`)),console.log(t.blue("\u2502")+t.white.bold(" Welcome to Paradigm ")+t.blue("\u2502")),console.log(t.blue("\u2502")+t.gray(" Let's set up your project ")+t.blue("\u2502")),console.log(t.blue(`\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
@@ -59,15 +59,15 @@ What you get: agents with accurate context, ripple analysis, and drift detection
59
59
  `)),console.log(t.cyan(" paradigm init --migrate")),console.log(t.gray(` Get an AI-ready prompt to convert your existing rules
60
60
  `)),console.log(t.cyan(" paradigm init --force")),console.log(t.gray(` Create .paradigm/ alongside existing files
61
61
  `)),console.log(t.cyan(" paradigm init --dry-run")),console.log(t.gray(` Preview what would be created
62
- `))));let u=G(),c$2=a.join(o,".paradigm");if(i.existsSync(c$2)){let d=i.statSync(c$2);if(d.isFile()){if(!s.force){console.log(t.yellow(" \u26A0 Legacy .paradigm file found.")),console.log(t.gray(" Run `paradigm upgrade --all` to migrate.\n"));return}i.unlinkSync(c$2);}else if(d.isDirectory()&&!s.force){console.log(t.yellow(` \u26A0 .paradigm/ already exists (use --force to overwrite)
63
- `));return}}n.start("Creating .paradigm/ directory...");try{i.existsSync(c$2)||i.mkdirSync(c$2,{recursive:!0}),i.existsSync(u)?(N(u,c$2,e$1),i.existsSync(a.join(c$2,"fixtures.yaml"))||L(c$2),Y(c$2,o,s.stack),n.succeed(t.green(".paradigm/ created"))):(n.warn(t.yellow("Templates not found, creating minimal structure")),H(c$2,e$1));}catch(d){n.fail(t.red(`Failed: ${d.message}`));return}let f=a.join(o,".premise");(!i.existsSync(f)||s.force)&&(n.start("Creating .premise..."),i.writeFileSync(f,g(e$1)),n.succeed(t.green(".premise created")));let h=a.join(o,".purpose");(!i.existsSync(h)||s.force)&&(n.start("Creating .purpose..."),i.writeFileSync(h,c()),n.succeed(t.green(".purpose created")));let w=a.join(o,"portal.yaml");i.existsSync(w)||(console.log(t.gray(" \u25CB No portal.yaml (optional - create manually if you need gate/auth definitions)")),console.log(t.gray(" See: https://github.com/a-company/paradigm/blob/main/docs/guides/portals.md")));let p;s.ide?p=["cursor","copilot","windsurf","claude"].includes(s.ide.toLowerCase())?s.ide.toLowerCase():"cursor":(n.start("Detecting IDE..."),p=c$1(o).detected||"cursor",n.succeed(`Using ${t.cyan(p)}`));let y=d(o);if(y){n.start("Generating IDE instructions...");let d=e(o,p,y,true);d.success?n.succeed(t.green(d.message||"IDE instructions generated")):n.warn(t.yellow(d.message));}if(!s.quick){n.start("Creating scan index for MCP tools...");try{await b$1(o,{quiet:!0}),n.succeed(t.green("Scan index created"));}catch(d){n.warn(t.yellow("Could not create scan index: "+d.message)),console.log(t.gray(" Run `paradigm scan` manually after adding .purpose files"));}}B(p,r),V(o,e$1,p,r),g$1.success("Paradigm initialized",{project:e$1,ide:p});}function Y(s,o,e){let n=a.join(s,"config.yaml");if(!i.existsSync(n))return;let g=a$2(o);if(g==="auto")return;let r=i.readFileSync(n,"utf8");r=r.replace(/^discipline:\s*auto\b.*$/m,`discipline: ${g}`);let u=e||g$1(o),c=u?h(u):d$1(g);if(!c){let y=function(){let d=Object.entries(p.symbolMapping).map(([m,x])=>` "${m}": "${x}"`).join(`
62
+ `))));let u=G(),c$1=a.join(o,".paradigm");if(i.existsSync(c$1)){let d=i.statSync(c$1);if(d.isFile()){if(!s.force){console.log(t.yellow(" \u26A0 Legacy .paradigm file found.")),console.log(t.gray(" Run `paradigm upgrade --all` to migrate.\n"));return}i.unlinkSync(c$1);}else if(d.isDirectory()&&!s.force){console.log(t.yellow(` \u26A0 .paradigm/ already exists (use --force to overwrite)
63
+ `));return}}n.start("Creating .paradigm/ directory...");try{i.existsSync(c$1)||i.mkdirSync(c$1,{recursive:!0}),i.existsSync(u)?(N(u,c$1,e$1),i.existsSync(a.join(c$1,"fixtures.yaml"))||L(c$1),Y(c$1,o,s.stack),n.succeed(t.green(".paradigm/ created"))):(n.warn(t.yellow("Templates not found, creating minimal structure")),H(c$1,e$1));}catch(d){n.fail(t.red(`Failed: ${d.message}`));return}let f=a.join(o,".premise");(!i.existsSync(f)||s.force)&&(n.start("Creating .premise..."),i.writeFileSync(f,g(e$1)),n.succeed(t.green(".premise created")));let h=a.join(o,".purpose");(!i.existsSync(h)||s.force)&&(n.start("Creating .purpose..."),i.writeFileSync(h,d()),n.succeed(t.green(".purpose created")));let w=a.join(o,"portal.yaml");i.existsSync(w)||(console.log(t.gray(" \u25CB No portal.yaml (optional - create manually if you need gate/auth definitions)")),console.log(t.gray(" See: https://github.com/a-company/paradigm/blob/main/docs/guides/portals.md")));let p;s.ide?p=["cursor","copilot","windsurf","claude"].includes(s.ide.toLowerCase())?s.ide.toLowerCase():"cursor":(n.start("Detecting IDE..."),p=c(o).detected||"cursor",n.succeed(`Using ${t.cyan(p)}`));let y=d$1(o);if(y){n.start("Generating IDE instructions...");let d=e(o,p,y,true);d.success?n.succeed(t.green(d.message||"IDE instructions generated")):n.warn(t.yellow(d.message));}if(!s.quick){n.start("Creating scan index for MCP tools...");try{await b$1(o,{quiet:!0}),n.succeed(t.green("Scan index created"));}catch(d){n.warn(t.yellow("Could not create scan index: "+d.message)),console.log(t.gray(" Run `paradigm scan` manually after adding .purpose files"));}}B(p,r),V(o,e$1,p,r),g$1.success("Paradigm initialized",{project:e$1,ide:p});}function Y(s,o,e){let n=a.join(s,"config.yaml");if(!i.existsSync(n))return;let g=a$2(o);if(g==="auto")return;let r=i.readFileSync(n,"utf8");r=r.replace(/^discipline:\s*auto\b.*$/m,`discipline: ${g}`);let u=e||g$1(o),c=u?h(u):d$2(g);if(!c){let y=function(){let d=Object.entries(p.symbolMapping).map(([m,x])=>` "${m}": "${x}"`).join(`
64
64
  `);r=r.replace(/ symbol-mapping:\n(?:(?: .*| *)\n)*/,` symbol-mapping:
65
65
  ${d}
66
66
  `);let l=p.purposeRequired.map(m=>` - pattern: "${m.pattern}"
67
67
  depth: ${m.depth}`).join(`
68
68
  `);r=r.replace(/purpose-required:\n(?: - pattern:.*\n depth:.*\n)*/,`purpose-required:
69
69
  ${l}
70
- `),i.writeFileSync(n,r,"utf8");};let p=d$1(g);y();return}u&&(r=r.replace(/^(discipline:\s*.+)$/m,`$1
70
+ `),i.writeFileSync(n,r,"utf8");};let p=d$2(g);y();return}u&&(r=r.replace(/^(discipline:\s*.+)$/m,`$1
71
71
  stack: ${u}`));let f=Object.entries(c.symbolMapping).map(([p,y])=>` "${p}": "${y}"`).join(`
72
72
  `);r=r.replace(/ symbol-mapping:\n(?:(?: .*| *)\n)*/,` symbol-mapping:
73
73
  ${f}
@@ -0,0 +1,17 @@
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}
3
+
4
+ ## Session Summary
5
+ ${s}
6
+
7
+ ## Next Steps
8
+ ${i.map((S,v)=>`${v+1}. ${S}`).join(`
9
+ `)||"(none specified)"}
10
+
11
+ ## Key Context
12
+ - Modified files: ${r.length>0?r.join(", "):"(not specified)"}
13
+ - Symbols touched: ${u.length>0?u.join(", "):"(not specified)"}
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(`
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
+ 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,25 @@
1
+ #!/usr/bin/env node
2
+ import {a as a$5}from'./chunk-NKYNHSA5.js';import {f,a as a$1,q as q$1,t as t$1,y as y$1,s,x as x$1,w as w$1,v,A as A$1}from'./chunk-2KK4JQ55.js';import {w}from'./chunk-M7JHVVDW.js';import {b as b$2}from'./chunk-A5EEY6NO.js';import {d,g,e,h,j as j$1,f as f$1}from'./chunk-ACJWUOMA.js';import {a as a$2,d as d$1}from'./chunk-Q527BPUF.js';import {a as a$4}from'./chunk-VOPJ47QY.js';import {j,a as a$3,i,b as b$1,h as h$1,g as g$1,c,d as d$2}from'./chunk-GRZQIKST.js';import {b,a}from'./chunk-EK4ZRIFJ.js';import {t,C,p,x,y,r}from'./chunk-D6BSCELB.js';import*as D from'fs';import*as A from'path';import*as J from'js-yaml';import {execSync}from'child_process';import*as _t from'os';b();b();var Dt=".paradigm/navigator.yaml";async function Qe(n){let e=A.join(n,Dt);if(!D.existsSync(e))return {config:null,configPath:null};try{let o=D.readFileSync(e,"utf8");return {config:J.load(o),configPath:e}}catch(o){return a.component("#navigator-loader").error("Error parsing navigator.yaml",{error:o}),{config:null,configPath:e}}}function Ye(n,e,o){switch(e.intent){case "find":return Rt(n,e.target||"");case "explore":return Ft(n,e.target||"");case "context":return It(n,e.task||"");default:return {paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[],explanation:"Unknown intent"}}}function Rt(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]};if(e.match(/^[@#^$&!%?~]/)){let r=n.symbols[e];if(r)t.paths.push(r),t.symbols.push(e),t.explanation=`Found symbol ${e} at ${r}`;else {let s=Object.entries(n.symbols).filter(([i])=>i.includes(e.slice(1))).slice(0,5);s.length>0?(t.paths=s.map(([,i])=>i),t.symbols=s.map(([i])=>i),t.explanation=`Found ${s.length} symbols matching "${e}"`):t.explanation=`Symbol ${e} not found in navigator`;}}else {let r=Object.entries(n.symbols).filter(([s])=>s.toLowerCase().includes(e.toLowerCase())).slice(0,5);if(r.length>0)t.paths=r.map(([,s])=>s),t.symbols=r.map(([s])=>s),t.explanation=`Found ${r.length} symbols matching "${e}"`;else {let s=At(n,e);s?(t.paths=s.paths,t.explanation=`Found ${e} in structure: ${s.paths.join(", ")}`):t.explanation=`No matches found for "${e}"`;}}return t.suggested_order=ue(t.paths,n),t}function Ft(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase();for(let[s,i]of Object.entries(n.structure))if(i&&(s.toLowerCase().includes(r)||r.includes(s.toLowerCase()))){t.paths.push(...i.paths);let a=Object.entries(n.symbols).filter(([c])=>c.startsWith(i.symbol)).slice(0,10);t.symbols.push(...a.map(([c])=>c));}for(let[s,i]of Object.entries(n.key_files))s.toLowerCase().includes(r)&&t.paths.push(...i);if(t.paths.length===0){let s=Object.entries(n.symbols).filter(([i,a])=>i.toLowerCase().includes(r)||a.toLowerCase().includes(r)).slice(0,10);t.paths=[...new Set(s.map(([,i])=>i))],t.symbols=s.map(([i])=>i);}return t.explanation=`Exploration paths for "${e}": ${t.paths.length} locations, ${t.symbols.length} symbols`,t.suggested_order=ue(t.paths,n),t}function It(n,e,o){let t={paths:[],symbols:[],skip:n.skip_patterns.always,suggested_order:[]},r=e.toLowerCase(),s=Ot(r);for(let[i,a]of Object.entries(n.structure))a&&s.some(c=>i.toLowerCase().includes(c))&&t.paths.push(...a.paths);for(let[i,a]of Object.entries(n.symbols)){let c=i.slice(1).toLowerCase();s.some(l=>c.includes(l)||l.includes(c))&&(t.paths.push(a),t.symbols.push(i));}return t.paths.push(...n.key_files.config),t.paths=[...new Set(t.paths)],t.symbols=[...new Set(t.symbols)],r.includes("test")?t.skip=n.skip_patterns.always:t.skip=[...n.skip_patterns.always,...n.skip_patterns.unless_testing],!r.includes("doc")&&!r.includes("readme")&&t.skip.push(...n.skip_patterns.unless_docs),t.explanation=`Context for "${e}": ${t.paths.length} relevant files, ${t.symbols.length} symbols`,t.suggested_order=ue(t.paths,n),t}function At(n,e){let o=e.toLowerCase();for(let[t,r]of Object.entries(n.structure))if(r&&(t.toLowerCase().includes(o)||o.includes(t.toLowerCase())))return r;return null}function Ot(n){let e=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","add","create","make","update","change","fix","implement","new","this","that","it","i","we","you","they"]);return n.split(/\s+/).map(o=>o.replace(/[^a-z0-9]/g,"")).filter(o=>o.length>2&&!e.has(o))}function ue(n,e){let o={};for(let t of n){let r=0;e.key_files.config.some(s=>t.includes(s))&&(r+=100),e.key_files.entry.some(s=>t.includes(s))&&(r+=80),e.key_files.types.some(s=>t.includes(s))&&(r+=60),r-=t.split("/").length*2,o[t]=r;}return [...n].sort((t,r)=>(o[r]||0)-(o[t]||0))}b();function ge(n,e){let o=[];for(let[t$1,r]of n.siblingIndices){let s=t(r.index,e);for(let i of s)o.push({project:t$1,symbol:`${t$1}/${i.symbol}`,type:i.type,description:i.description,filePath:i.filePath});}return o}function Xe(n,e){let o=[],t=e.includes("/")?e.split("/").pop():e;for(let[r,s]of n.siblingIndices){let i=[],a=C(s.index);for(let c of a){let l=c.references||[],d=c.description||"",u=l.some(y=>y===t||y===e||y.endsWith(`/${t}`)),m=d.includes(t);(u||m)&&i.push({symbol:c.symbol,type:c.type,description:c.description});}i.length>0&&o.push({project:r,references:i});}return o}var Et={name:"paradigm_navigate",description:'Navigate the codebase efficiently. Use "find" to locate a symbol, "explore" to browse an area, or "context" to get relevant files for a task. Returns file paths, symbol locations, and context summaries. ~200 tokens.',inputSchema:{type:"object",properties:{intent:{type:"string",enum:["find","explore","context"],description:'Navigation intent: "find" for symbol lookup, "explore" for area browsing, "context" for task-based discovery'},target:{type:"string",description:'For "find": symbol (e.g., @checkout) or path. For "explore": category or area name (e.g., authentication, components)'},task:{type:"string",description:'For "context" intent: describe the task (e.g., "add Apple Pay to checkout")'},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields (default: "detailed")'}},required:["intent"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["go to","open","show me","find file","explore","browse","locate code"]};function Mn(){return [Et]}async function tt(n,e,o){if(n!=="paradigm_navigate")return {handled:false,text:""};let t={intent:e.intent||"find",target:e.target,task:e.task},r=await Qe(o.rootDir);if(r.config||(r={config:Tt(o),configPath:null}),false);if(t.intent==="context"&&!t.task)return {handled:true,text:JSON.stringify({error:"Missing task for context intent",example:'paradigm_navigate({ intent: "context", task: "add Apple Pay to checkout" })'},null,2)};if((t.intent==="find"||t.intent==="explore")&&!t.target)return {handled:true,text:JSON.stringify({error:`Missing target for ${t.intent} intent`,example:t.intent==="find"?'paradigm_navigate({ intent: "find", target: "@checkout" })':'paradigm_navigate({ intent: "explore", target: "components" })'},null,2)};let s=`navigate:${t.intent}:${t.target||""}:${t.task||""}`,i=await f.getOrCompute(s,()=>{let c=Ye(r.config,t,o.rootDir),l={intent:t.intent,...t.target&&{target:t.target},...t.task&&{task:t.task},paths:c.paths,symbols:c.symbols,skip:c.skip.slice(0,10),suggested_order:c.suggested_order,...c.explanation&&{explanation:c.explanation}};if(r.config?.auto_generated&&(l.auto_generated=true,l.tip="Using auto-generated navigator from .purpose files. Run `paradigm scan` for more accurate results."),c.paths.length===0?(l.note="No paths found.",l.recovery=["Try a different search term","Use `paradigm_search` to find symbols by name","Check `.purpose` files exist in your project","Run `paradigm scan` to build the full navigator index"]):c.paths.length>5&&(l.tip=l.tip||"Many paths returned. Start with suggested_order for efficient exploration."),o.workspace){if(t.intent==="find"&&t.target&&c.paths.length===0){let d=ge(o.workspace,t.target);d.length>0&&(l.workspaceResults=d.slice(0,5).map(u=>({symbol:u.symbol,type:u.type,description:u.description,project:u.project})),l.note="Not found locally. Found in workspace siblings.",l.recovery=void 0);}else if(t.intent==="context"&&t.task){let d=ge(o.workspace,t.task);d.length>0&&(l.workspaceContext=d.slice(0,5).map(u=>({symbol:u.symbol,type:u.type,description:u.description,project:u.project})));}}return JSON.stringify(l,null,2)}),a=i;if(e.response_format==="concise")try{let c=JSON.parse(i);delete c.skip,delete c.tip,delete c.note,delete c.recovery,delete c.workspaceResults,delete c.workspaceContext,delete c.auto_generated,a=JSON.stringify(c,null,2);}catch{}try{let c=A.join(o.rootDir,".paradigm",".nav-called");D.writeFileSync(c,new Date().toISOString(),"utf8");}catch{}return {handled:true,text:a}}function Tt(n){let e={},o={features:{paths:[],symbol:"@"},components:{paths:[],symbol:"#"},gates:{paths:[],symbol:"^"},flows:{paths:[],symbol:"$"}},t=C(n.index),r=new Set;for(let a of t)if(a.filePath){e[a.symbol]=a.filePath,r.add(a.filePath);let c=a.filePath.replace(/\/[^/]+$/,"");switch(a.type){case "feature":o.features.paths.includes(c)||o.features.paths.push(c);break;case "component":o.components.paths.includes(c)||o.components.paths.push(c);break;case "gate":o.gates.paths.includes(c)||o.gates.paths.push(c);break;case "flow":o.flows.paths.includes(c)||o.flows.paths.push(c);break}}let s=[],i=[];for(let a of n.aggregation.purposeFiles)s.push(a.filePath);return s.push(".paradigm/config.yaml"),n.gateConfig&&s.push("portal.yaml"),{version:"1.0",generated:new Date().toISOString(),auto_generated:true,structure:o,key_files:{config:s.slice(0,10),entry:i,types:[]},skip_patterns:{always:["node_modules/","dist/",".git/","build/","coverage/"],unless_testing:["__tests__/","*.test.*","*.spec.*"],unless_docs:["*.md","docs/"]},symbols:e}}function ot(n,e,o={}){let{maxResults:t=20}=o,r=[],s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=[`rg -n --no-heading "${s}" "${n}" --glob "!node_modules" --glob "!.git" --glob "!dist" --glob "!build" --glob "!coverage" --max-count 50 2>/dev/null`,`grep -rn "${s}" "${n}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build --exclude-dir=coverage 2>/dev/null | head -50`],a="";for(let l of i)try{if(a=execSync(l,{encoding:"utf8",maxBuffer:1024*1024}),a.trim())break}catch{continue}if(!a.trim())return r;let c=a.trim().split(`
3
+ `);for(let l of c.slice(0,t)){let d=l.match(/^(.+?):(\d+):(.*)$/);if(d){let[,u,m,y]=d,x=A.relative(n,u),f="unknown";x.includes(".purpose")||x.includes("portal.yaml")?f="purpose":y.includes("//")||y.includes("#")||y.includes("*")?f="comment":f="code",r.push({filePath:x,line:parseInt(m,10),content:y.trim().slice(0,200),context:f});}}return r}b();var Lt=30*1e3,st=new Map;async function rt(n){let e=A.resolve(n),o=st.get(e);if(o&&Date.now()-o.loadedAt<Lt)return o.index;let t=await Ht(e);return t&&st.set(e,{index:t,loadedAt:Date.now()}),t}async function Ht(n){let e=A.join(n,".paradigm","flow-index.json");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return JSON.parse(o)}catch(o){return a.component("#flow-loader").error("Error parsing flow-index.json",{error:o}),null}}function Bt(n,e){let o=n.symbolToFlows[e]||[],t=[];for(let r of o){let s=n.flows[r];if(!s)continue;let i=s.steps.map((a,c)=>({step:a,index:c})).filter(({step:a})=>a.symbol===e);for(let{step:a,index:c}of i){let l=s.steps.slice(c+1).map(d=>d.id);t.push({flowId:s.id,definedIn:s.definedIn,description:s.description,trigger:s.trigger,stepAffected:{id:a.id,action:a.action,position:c+1},downstreamSteps:l,validation:s.validation});}}return t}function it(n,e){let o=Bt(n,e),t=new Set;for(let i of o)i.validation?.command&&t.add(i.validation.command);let r="low",s=o.reduce((i,a)=>i+a.downstreamSteps.length,0);return o.length>3||s>10?r="high":(o.length>1||s>3)&&(r="medium"),{symbol:e,totalFlows:o.length,impactLevel:r,affectedFlows:o,validationCommands:Array.from(t),suggestion:o.length>0?`Changes to ${e} may affect ${o.length} flow(s). ${t.size>0?"Run validation commands to verify.":"Test manually."}`:`No flows reference ${e} directly.`}}function to(){return [{name:"paradigm_ripple",description:"IMPORTANT: Call BEFORE modifying any symbol to understand impact. Shows what depends on it directly and indirectly, helping you avoid breaking changes. Returns direct and indirect dependents with file paths and dependency depth. ~300 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to analyze (e.g., "#checkout", "$payment-flow", "^authenticated")'},depth:{type:"number",description:"How many hops to traverse (default: 3, max: 5)"},includeWorkspace:{type:"boolean",description:"Also check sibling workspace projects for cross-project impact (default: false). Requires workspace configured in config.yaml."},response_format:{type:"string",enum:["concise","detailed"],description:'Response detail level. "concise" returns minimal fields to save tokens (default: "detailed")'}},required:["symbol"]},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["dependencies","impact","blast radius","what would break","dependents","affects"]}]}async function se(n,e,o){if(n!=="paradigm_ripple")return {handled:false,text:""};let{symbol:t,depth:r$1=3,includeWorkspace:s=false,response_format:i}=e,a=p(o.index,t);if(!a){let h=Mt(o.rootDir,t);return a$1(h.length,n),{handled:true,text:h}}let c=Math.min(Math.max(r$1||3,1),5),l=x(o.index,t),d=new Set([t]),u=new Map;function m(h,C){if(C>=c)return;let v=[];for(let w of h){if(d.has(w))continue;d.add(w);let P=x(o.index,w);for(let T of P)d.has(T.symbol)||v.push(T.symbol);}v.length>0&&(u.set(C+1,v),m(v,C+1));}m(l.map(h=>h.symbol),1);let y$1=new Set;for(let[,h]of u)for(let C of h)C!==t&&!l.find(v=>v.symbol===C)&&y$1.add(C);let x$1=y(o.index,t),f=l.length+y$1.size,j="low";f>10?j="high":f>3&&(j="medium");let N=await rt(o.rootDir),R=null;if(N){let h=it(N,t);h.totalFlows>0&&(h.impactLevel==="high"&&j==="low"?j="medium":h.impactLevel==="high"&&(j="high"),R={totalFlows:h.totalFlows,affectedFlows:h.affectedFlows.map(C=>({flowId:C.flowId,impactLevel:C.downstreamSteps.length>2?"high":"medium",reason:`Symbol is in step ${C.stepAffected.position}, affects ${C.downstreamSteps.length} downstream steps`})),validationSuggestion:h.validationCommands.length>0?`Run: ${h.validationCommands[0]}`:void 0});}let $=new Set([t,...l.map(h=>h.symbol),...y$1]),I=[];try{let h=r(o.index,"gate");for(let C of h)$.has(C.symbol)&&I.push({gate:C.symbol,description:C.description});for(let C of l)C.type==="gate"&&!I.find(v=>v.gate===C.symbol)&&I.push({gate:C.symbol,description:C.description});}catch{}let _={symbol:a.symbol,type:a.type,description:a.description,depth:c,impact:j,analysis:{directlyAffected:l.map(h=>({symbol:h.symbol,type:h.type,description:h.description})),indirectlyAffected:Array.from(y$1),indirectByLevel:Object.fromEntries(u),dependsOn:x$1.map(h=>({symbol:h.symbol,type:h.type}))},summary:{directCount:l.length,indirectCount:y$1.size,totalAffected:f,dependsOnCount:x$1.length,levelsAnalyzed:c},recommendation:Jt(j)};R&&(_.affectedFlows=R),I.length>0&&(_.affectedGates=I),_.suggestedReviewScope=Gt(j,l.length,y$1.size,I.length,R?.totalFlows??0);try{let h=await q$1(o.rootDir,t);h.length>0&&(_.personas_affected=h,h.length>2&&j==="low"&&(_.impact="medium"));}catch{}try{let h=w(o.rootDir,t);h.length>0&&(_.university_content_affected=h.map(C=>({id:C.id,title:C.title,type:C.type,stale:C.stale})));}catch{}if(s&&o.workspace){let h=Xe(o.workspace,t);if(h.length>0){_.workspaceImpact={siblings:h.map(v=>({project:v.project,references:v.references.map(w=>({symbol:w.symbol,type:w.type,description:w.description}))}))};let C=h.reduce((v,w)=>v+w.references.length,0);C>0&&j==="low"&&(_.impact="medium"),C>5&&(_.impact="high");}}let O=i==="concise"?{symbol:_.symbol,impact:_.impact,summary:_.summary}:_,E=JSON.stringify(O,null,2);return a$1(E.length,n),{handled:true,text:E}}function Mt(n,e){let o=ot(n,e,{maxResults:20});if(o.length===0)return JSON.stringify({error:"Symbol not found in index",symbol:e,fallback:"searched",referencesFound:0,suggestion:"Run `paradigm scan` to build the index, or check that .purpose files contain this symbol"},null,2);let t=[...new Set(o.map(i=>i.filePath))],r={};for(let i of o)r[i.context]=(r[i.context]||0)+1;let s="low";return t.length>10||o.length>20?s="high":(t.length>3||o.length>5)&&(s="medium"),JSON.stringify({symbol:e,status:"not-indexed",fallback:"grep-search",estimatedImpact:s,analysis:{filesAffected:t.slice(0,10),totalFilesAffected:t.length,totalReferences:o.length,contextBreakdown:r,sampleReferences:o.slice(0,5).map(i=>({file:i.filePath,line:i.line,preview:i.content.slice(0,100)}))},note:"This is a fallback grep search. For accurate dependency analysis, run `paradigm scan` to index your project.",suggestion:"Run `paradigm scan` to enable full ripple analysis with dependency tracking"},null,2)}function Jt(n){switch(n){case "high":return "High impact change - review all affected symbols carefully before modifying";case "medium":return "Moderate impact - check direct dependencies for breaking changes";case "low":return "Low impact - safe to modify with standard review"}}function Gt(n,e,o,t,r){let s=[];return e>0&&s.push(`Review ${e} direct dependent(s) for breaking changes`),o>0&&s.push(`Scan ${o} indirect dependent(s) for cascading effects`),t>0&&s.push(`Verify ${t} affected gate(s) still enforce correct auth/access`),r>0&&s.push(`Validate ${r} affected flow(s) end-to-end`),n==="high"?s.push("Consider running full test suite before merging"):n==="medium"&&s.push("Run targeted tests for affected components"),s.length===0&&s.push("No downstream dependents detected - safe to proceed"),s}b();b();var qt=30*1e3,ye=new Map,ct=".paradigm/wisdom";async function lt(n){let e=A.resolve(n),o=ye.get(e);if(o&&Date.now()-o.loadedAt<qt)return o.context;let t=await Ut(e);return ye.set(e,{context:t,loadedAt:Date.now()}),t}async function Ut(n){let e$1=A.join(n,ct),o=D.existsSync(e$1),[t,r,s,i]=o?await Promise.all([zt(e$1),Vt(e$1),Kt(e$1),Qt(e$1)]):[null,[],null,[]],a=[],c=[],l=null;try{a=d(),c=e(),l=f$1();}catch{}let d$1=new Set(r.map(f=>f.id)),u=r.map(f=>({...f,scope:"project"}));for(let f of a)d$1.has(f.id)||u.push({...f,scope:"global"});let m=new Set(i.map(f=>f.id)),y=i.map(f=>({...f,scope:"project"}));for(let f of c)m.has(f.id)||y.push({...f,scope:"global"});let x=t;if(l&&!t)x=l;else if(l&&t){let f={...t.by_symbol};if(l.by_symbol)for(let[j,N]of Object.entries(l.by_symbol))f[j]||(f[j]=N);x={...t,by_symbol:f,global:{...l.global,...t.global}};}return {preferences:x,antipatterns:u,decisions:y,expertise:s}}function q(n){let e=A.resolve(n);ye.delete(e);}async function zt(n){let e=A.join(n,"preferences.yaml");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return J.load(o)}catch(o){return a.component("#wisdom-loader").error("Error parsing preferences.yaml",{error:o}),null}}async function Vt(n){let e=A.join(n,"antipatterns.yaml");if(!D.existsSync(e))return [];try{let o=D.readFileSync(e,"utf8");return J.load(o).antipatterns||[]}catch(o){return a.component("#wisdom-loader").error("Error parsing antipatterns.yaml",{error:o}),[]}}async function Kt(n){let e=A.join(n,"expertise.yaml");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return J.load(o)}catch(o){return a.component("#wisdom-loader").error("Error parsing expertise.yaml",{error:o}),null}}var at=new Set;async function Qt(n){let e=A.join(n,"decisions");if(!D.existsSync(e))return [];let o=[];try{let t=D.readdirSync(e);t.some(s=>s.endsWith(".yaml")||s.endsWith(".yml"))&&!at.has(e)&&(at.add(e),a.component("#wisdom-loader").warn("wisdom-decisions found; run `paradigm migrate decisions` in v6.0. In v5.39.0 wisdom-decisions are still read but will be migrated to TD-streams in v6.0."));for(let s of t){if(!s.endsWith(".yaml")&&!s.endsWith(".yml"))continue;let i=A.join(e,s);try{let a=D.readFileSync(i,"utf8"),c=J.load(a);o.push(c);}catch(a$1){a.component("#wisdom-loader").error(`Error parsing ${s}`,{error:a$1});}}}catch(t){a.component("#wisdom-loader").error("Error reading decisions directory",{error:t});}return o.sort((t,r)=>t.id.localeCompare(r.id)),o}function dt(n,e){return e.map(o=>Yt(n,o))}function Yt(n,e){let o=n.preferences?.by_symbol?.[e]||null,t=n.antipatterns.filter(i=>i.symbols.some(a=>a===e||re(e,a))),r=n.decisions.filter(i=>i.symbols.some(a=>a===e||re(e,a))),s=n.expertise?.experts.filter(i=>i.symbols?.some(a=>a===e||re(e,a)))||[];return {symbol:e,preferences:o,antipatterns:t,decisions:r,experts:s}}function pt(n,e){return n.expertise?n.expertise.experts.filter(o=>!!(e.symbol&&o.symbols&&o.symbols.some(t=>t===e.symbol||re(e.symbol,t))||e.area&&o.areas&&o.areas.some(t=>t.toLowerCase().includes(e.area.toLowerCase())))):[]}function re(n,e){if(e.endsWith("*")){let o=e.slice(0,-1);return n.startsWith(o)}return n===e}async function ft(n,e){let o=A.join(n,ct),t=A.join(o,"antipatterns.yaml");D.existsSync(o)||D.mkdirSync(o,{recursive:true});let r={version:"1.0",antipatterns:[]};if(D.existsSync(t))try{let s=D.readFileSync(t,"utf8"),i=J.load(s);i&&typeof i=="object"&&(r={version:i.version||"1.0",antipatterns:Array.isArray(i.antipatterns)?i.antipatterns:[]});}catch{}r.antipatterns.push({...e,added:new Date().toISOString()}),D.writeFileSync(t,J.dump(r,{lineWidth:-1})),q(n);}b();var mt=".paradigm/history";async function ut(n){let e=A.join(n,mt);if(!D.existsSync(e))return {index:null,validation:null};let[o,t]=await Promise.all([Xt(e),Zt(e)]);return {index:o,validation:t}}async function Xt(n){let e=A.join(n,"index.yaml");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return J.load(o)}catch(o){return a.component("#history-loader").error("Error parsing index.yaml",{error:o.message}),null}}async function Zt(n){let e=A.join(n,"validation.yaml");if(!D.existsSync(e))return null;try{let o=D.readFileSync(e,"utf8");return J.load(o)}catch(o){return a.component("#history-loader").error("Error parsing validation.yaml",{error:o.message}),null}}function ao(n,e){return e.map(o=>en(n,o))}function en(n,e){let o=n.index?.by_symbol?.[e]||null,t=[];if(n.index?.co_changes){for(let s of n.index.co_changes)if(s.symbols.includes(e))for(let i of s.symbols)i!==e&&!t.includes(i)&&t.push(i);}let r=n.validation?.by_symbol?.[e]||null;return {symbol:e,summary:o,recent:o?.recent||[],co_changes:t,validation:r}}function co(n,e){let o=[],t=[];if(!n.index)return {symbols:e,fragile:[],warnings:["No history index available - cannot assess fragility"],safe_to_modify:true,recommendations:[]};for(let i of e){let a=n.index.by_symbol?.[i];a&&(a.fragility==="high"||a.fragility==="critical")&&o.push({symbol:i,fragility:a.fragility,reason:`Stability score: ${a.stability_score.toFixed(2)}`});let c=n.index.fragile_symbols?.find(l=>l.symbol===i);c&&!o.find(l=>l.symbol===i)&&o.push(c);}for(let i of e){let a=n.index.co_changes?.filter(c=>c.symbols.includes(i));if(a?.length)for(let c of a){let l=c.symbols.filter(d=>d!==i&&!e.includes(d));l.length>0&&c.correlation>.7&&t.push(`${i} often changes with ${l.join(", ")} (${Math.round(c.correlation*100)}% correlation)`);}}let r=o.filter(i=>i.fragility==="critical").length===0,s=[];return o.length>0&&(s.push("Consider adding extra test coverage before modifying fragile symbols"),s.push("Review recent rollbacks and failures for these symbols")),t.length>0&&s.push("Check if co-changing symbols also need updates"),{symbols:e,fragile:o,warnings:t,safe_to_modify:r,recommendations:s}}async function tn(n,e){let o=A.join(n,mt),t=A.join(o,"log.jsonl");D.existsSync(o)||D.mkdirSync(o,{recursive:true});let r=nn(t),s=new Date().toISOString(),i={id:r,ts:s,...e},a=JSON.stringify(i)+`
4
+ `;return D.appendFileSync(t,a),r}async function lo(n,e,o,t){return tn(n,{type:"validate",symbols:[],author:{type:"agent",id:"system"},ref:e,result:o,tests:t})}function nn(n){let e=1;return D.existsSync(n)&&(e=D.readFileSync(n,"utf8").split(`
5
+ `).filter(t=>t.trim()).length+1),`h${String(e).padStart(4,"0")}`}async function ae(n){return n.wisdom||(n.wisdom=await lt(n.rootDir)),n.wisdom}async function vo(n){return n.history||(n.history=await ut(n.rootDir)),n.history}j();b();var gt=false;function Ao(){return [{name:"paradigm_wisdom_context",description:"Get team wisdom (preferences, antipatterns, decisions) for symbols before implementing. Call this before making changes to understand team patterns. Returns preferences, antipatterns, and decisions relevant to the specified symbols. ~200 tokens.",inputSchema:{type:"object",properties:{symbols:{type:"array",items:{type:"string"},description:'Symbols to get wisdom for (e.g., ["@checkout", "#payment-form"])'},include_global:{type:"boolean",description:"Include global preferences (default: true)"}},required:["symbols"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_wisdom_record",description:"Record a new team learning: antipattern (what not to do) or decision (architectural choice). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to record"},id:{type:"string",description:'Unique ID (for antipattern: e.g., "api-001", for decision: e.g., "001")'},symbols:{type:"array",items:{type:"string"},description:"Related symbols"},description:{type:"string",description:"What not to do (antipattern) or the decision made (decision)"},reason:{type:"string",description:"Why this is an antipattern / context for decision"},alternative:{type:"string",description:"What to do instead (for antipatterns)"},title:{type:"string",description:"Decision title (for decisions)"},status:{type:"string",enum:["proposed","accepted","deprecated","superseded"],description:"Decision status (for decisions)"},rationale:{type:"object",properties:{factors:{type:"array",items:{type:"string"}},conclusion:{type:"string"}},description:"Decision rationale (for decisions)"},consequences:{type:"object",properties:{positive:{type:"array",items:{type:"string"}},negative:{type:"array",items:{type:"string"}},mitigations:{type:"array",items:{type:"string"}}},description:"Expected consequences (for decisions)"},scope:{type:"string",enum:["project","global"],description:'Where to store: "project" (default) writes to .paradigm/wisdom/, "global" writes to ~/.paradigm/wisdom/'}},required:["type","id","symbols"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_wisdom_promote",description:"Promote a project-local antipattern or decision to global scope (~/.paradigm/wisdom/). Makes it available across all projects. ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["antipattern","decision"],description:"Type of wisdom to promote"},id:{type:"string",description:"ID of the antipattern or decision to promote"}},required:["type","id"]}},{name:"paradigm_wisdom_expert",description:"Find human experts who know about specific symbols or areas. Returns names and contact info for relevant experts. ~100 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Symbol to find experts for (e.g., "@checkout")'},area:{type:"string",description:'General area to find experts for (e.g., "payments", "auth")'}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function ht(n,e$1,o){switch(n){case "paradigm_wisdom_context":{let{symbols:t,include_global:r=true}=e$1,s=await ae(o),i=dt(s,t),a={symbols:t,wisdom:i.map(d=>({symbol:d.symbol,preferences:d.preferences,antipatterns:d.antipatterns.map(u=>({id:u.id,description:u.description,reason:u.reason,alternative:u.alternative,scope:u.scope||"project"})),decisions:d.decisions.map(u=>({id:u.id,title:u.title,status:u.status,decision:u.decision,scope:u.scope||"project"})),experts:d.experts.map(u=>u.name)}))};r&&s.preferences?.global&&(a.global_preferences=s.preferences.global);let c=i.reduce((d,u)=>d+u.antipatterns.length,0),l=i.reduce((d,u)=>d+u.decisions.length,0);a.summary={symbols_with_preferences:i.filter(d=>d.preferences).length,total_antipatterns:c,total_decisions:l,has_experts:i.some(d=>d.experts.length>0)},c>0&&(a.warning="There are antipatterns for these symbols - review before implementing");try{let d={},u=[];for(let m of t){let y=await a$3(o.rootDir,{symbol:m,hasAssessment:!0,limit:100});if(y.length===0)continue;let x={correct:0,partial:0,incorrect:0},f=0,j=0;for(let R of y){let $=R.assessment.verdict;x[$]++,R.confidence!=null&&(f+=R.confidence,j++);}d[m]={total:y.length,...x,avgConfidence:j>0?Math.round(f/j*1e3)/1e3:null};let N=(x.correct+x.partial*.5)/y.length;N<.6&&y.length>=3&&u.push(`Low historical accuracy for ${m}: ${Math.round(N*100)}% across ${y.length} entries. Proceed with extra caution.`);}Object.keys(d).length>0&&(a.calibration=d),u.length>0&&(a.calibration_warnings=u);}catch{}return {handled:true,text:JSON.stringify(a,null,2)}}case "paradigm_wisdom_record":{let{type:t,id:r,symbols:s,description:i,reason:a$1,alternative:c,title:l,status:d,rationale:u,consequences:m,scope:y="project"}=e$1;if(t==="antipattern"){if(!i||!a$1||!c)return {handled:true,text:JSON.stringify({error:"Antipattern requires description, reason, and alternative"})};let x={id:r,symbols:s,description:i,reason:a$1,alternative:c};return y==="global"?g(x):await ft(o.rootDir,x),q(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,scope:y,message:`Antipattern recorded to ${y} scope`})}}if(t==="decision"){if(!l||!i||!u||!m)return {handled:true,text:JSON.stringify({error:"Decision requires title, description (as the decision), rationale, and consequences"})};if(gt||(gt=true,a.component("#wisdom").warn('paradigm_wisdom_record({type:"decision"}) is deprecated. Use paradigm_decision_record instead.',{deprecation:"v6.0",canonical_tool:"paradigm_decision_record"})),y==="global"){let j={id:r,title:l,status:d||"proposed",date:new Date().toISOString().split("T")[0],symbols:s,context:a$1||"",decision:i,rationale:u,consequences:m};return h(j),q(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,scope:"global",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record for project-scoped decisions.',message:"Decision recorded to global scope"})}}let x=a$2(o.rootDir,{title:l,decision:i,rationale:{factors:u.factors,conclusion:u.conclusion},participants:[{id:"wisdom-record",role:"agent",stance:"proposed"}],symbols_affected:s,status:d==="accepted"?"active":d==="proposed"?"proposed":"active",context:a$1||void 0,consequences:m,date:new Date().toISOString().split("T")[0],migrated_from:"wisdom-decision"}),f=d$1(o.rootDir,x.id);return q(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:x.id,legacy_id:r,scope:"project",deprecation:'paradigm_wisdom_record({type:"decision"}) is deprecated; use paradigm_decision_record going forward.',message:`Decision recorded (routed to decisions stream as ${x.id})`,...f?{companion_lore_id:f}:{}})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_promote":{let{type:t,id:r}=e$1,s=await ae(o),i=A.basename(o.rootDir);if(t==="antipattern"){let a=s.antipatterns.find(l=>l.id===r);return a?d().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Antipattern "${r}" already exists in global scope`})}:(g({...a,learned_from:`promoted from ${i}`}),q(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"antipattern",id:r,promoted_from:i,message:`Antipattern "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Antipattern "${r}" not found in project`})}}if(t==="decision"){let a=s.decisions.find(l=>l.id===r);return a?e().some(l=>l.id===r)?{handled:true,text:JSON.stringify({error:`Decision "${r}" already exists in global scope`})}:(h(a),q(o.rootDir),{handled:true,text:JSON.stringify({success:true,type:"decision",id:r,promoted_from:i,message:`Decision "${r}" promoted to global scope`})}):{handled:true,text:JSON.stringify({error:`Decision "${r}" not found in project`})}}return {handled:true,text:JSON.stringify({error:`Unknown type: ${t}`})}}case "paradigm_wisdom_expert":{let{symbol:t,area:r}=e$1;if(!t&&!r)return {handled:true,text:JSON.stringify({error:"Either symbol or area is required"})};let s=await ae(o),i=pt(s,{symbol:t,area:r});return {handled:true,text:JSON.stringify({query:{symbol:t,area:r},count:i.length,experts:i.map(a=>({name:a.name,symbols:a.symbols,areas:a.areas,contact:a.contact,notes:a.notes})),suggestion:i.length>0?"Consider reaching out to these experts before making significant changes":"No experts found - consider documenting expertise when this area is worked on"})}}default:return {handled:false,text:""}}}function $o(){return [{name:"paradigm_protocol_search",description:"Search for protocols matching a task description. Call BEFORE exploring the codebase \u2014 if a matching protocol exists, follow its steps instead of discovering the pattern from scratch. Returns top matches with steps, exemplar, and freshness info. ~200 tokens.",inputSchema:{type:"object",properties:{task:{type:"string",description:'Task description to search for (e.g., "add a new page", "add API route")'},limit:{type:"number",description:"Maximum results (default: 3)"}},required:["task"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_get",description:"Get a specific protocol by ID with full details and freshness check. ~300 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID (e.g., "P-add-view")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_protocol_record",description:"Record a new protocol after completing repeatable work. Captures the steps you followed so future agents can skip exploration. ~100 tokens.",inputSchema:{type:"object",properties:{name:{type:"string",description:'Protocol name (e.g., "Add a new view")'},description:{type:"string",description:"What this protocol accomplishes"},trigger:{type:"array",items:{type:"string"},description:'Phrases that should match this protocol (e.g., ["add view", "new page"])'},tags:{type:"array",items:{type:"string"},description:'Classification tags (e.g., ["ui", "frontend"])'},symbols:{type:"array",items:{type:"string"},description:'Paradigm symbols involved (e.g., ["#logs-view"])'},exemplar:{type:"string",description:'Canonical file to study for this pattern (e.g., "ui/src/views/LogsView.tsx")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"],description:"Step action type"},target:{type:"string",description:"File path (supports {Name}/{name} placeholders)"},template_from:{type:"string",description:"File to use as template (for create actions)"},reference:{type:"string",description:"Where in the file to make changes (for modify actions)"},command:{type:"string",description:"Command to execute (for run actions)"},notes:{type:"string",description:"Additional guidance for this step"}},required:["action"]},description:"Ordered steps to follow"},recorded_from:{type:"string",description:'Lore entry ID this protocol was learned from (e.g., "L-2026-03-01-001")'}},required:["name","description","trigger","tags","steps"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_update",description:"Update an existing protocol. Use refresh:true after successfully following a protocol to bump last_verified. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Protocol ID to update (e.g., "P-add-view")'},refresh:{type:"boolean",description:"Set true to bump last_verified to now (use after successfully following the protocol)"},name:{type:"string",description:"Updated name"},description:{type:"string",description:"Updated description"},trigger:{type:"array",items:{type:"string"},description:"Updated trigger phrases"},tags:{type:"array",items:{type:"string"},description:"Updated tags"},symbols:{type:"array",items:{type:"string"},description:"Updated symbols"},exemplar:{type:"string",description:"Updated exemplar path"},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",enum:["create","modify","run","verify"]},target:{type:"string"},template_from:{type:"string"},reference:{type:"string"},command:{type:"string"},notes:{type:"string"}},required:["action"]},description:"Updated steps"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_protocol_validate",description:"Validate protocol references \u2014 check that referenced files exist, exemplars haven't drifted. Validates all protocols if no ID given. ~200 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Protocol ID to validate (omit to validate all)"}}},annotations:{readOnlyHint:true,destructiveHint:false}}]}async function bt(n,e,o){switch(n){case "paradigm_protocol_search":{let t=e.task,r=e.limit||3,s=await v(o.rootDir,t,r);return s.length===0?{handled:true,text:JSON.stringify({count:0,task:t,message:"No matching protocol found. Consider recording one after completing this task."})}:{handled:true,text:JSON.stringify({count:s.length,task:t,matches:s.map(i=>({id:i.protocol.id,name:i.protocol.name,description:i.protocol.description,score:i.score,status:i.protocol.status,exemplar:i.protocol.exemplar,last_verified:i.protocol.last_verified,steps:i.protocol.steps.map(sn)}))},null,2)}}case "paradigm_protocol_get":{let t=e.id,r=await t$1(o.rootDir,t);if(!r)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let s=y$1(o.rootDir,r);return {handled:true,text:JSON.stringify({...r,freshness:{status:s.status,issues:s.issues}},null,2)}}case "paradigm_protocol_record":{let t=e.steps||[],r=await w$1(o.rootDir,{name:e.name,description:e.description,trigger:e.trigger||[],tags:e.tags||[],symbols:e.symbols||[],exemplar:e.exemplar,steps:t,recorded_from:e.recorded_from,verified_by:"claude-opus-4-6"});return {handled:true,text:JSON.stringify({success:true,id:r,name:e.name,message:"Protocol recorded successfully"})}}case "paradigm_protocol_update":{let t=e.id,r=e.refresh,s={};e.name!==void 0&&(s.name=e.name),e.description!==void 0&&(s.description=e.description),e.trigger!==void 0&&(s.trigger=e.trigger),e.tags!==void 0&&(s.tags=e.tags),e.symbols!==void 0&&(s.symbols=e.symbols),e.exemplar!==void 0&&(s.exemplar=e.exemplar),e.steps!==void 0&&(s.steps=e.steps);let i=await x$1(o.rootDir,t,s,r===true);return {handled:true,text:JSON.stringify({success:i,id:t,refreshed:r===true,message:i?r?"Protocol updated and verified":"Protocol updated":`Protocol not found: ${t}`})}}case "paradigm_protocol_validate":{let t=e.id;if(t){let a=await t$1(o.rootDir,t);if(!a)return {handled:true,text:JSON.stringify({error:`Protocol not found: ${t}`})};let c=y$1(o.rootDir,a);return {handled:true,text:JSON.stringify({id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified},null,2)}}let s$1=(await s(o.rootDir)).map(a=>{let c=y$1(o.rootDir,a);return {id:a.id,name:a.name,status:c.status,issues:c.issues,last_verified:a.last_verified}}),i={total:s$1.length,current:s$1.filter(a=>a.status==="current").length,stale:s$1.filter(a=>a.status==="stale").length,broken:s$1.filter(a=>a.status==="broken").length};return {handled:true,text:JSON.stringify({protocols:s$1,health:i},null,2)}}default:return {handled:false,text:""}}}function sn(n){let e={action:n.action};return n.target&&(e.target=n.target),n.template_from&&(e.template_from=n.template_from),n.reference&&(e.reference=n.reference),n.command&&(e.command=n.command),n.notes&&(e.notes=n.notes),e}j();var V=null,he=false;async function be(n){if(V)he||(await V.ensureReady(),he=true);else {let e=A.join(n,".paradigm","sentinel","sentinel.db");V=new a$5(e),await V.ensureReady(),he=true;}return V}async function rn(n,e){return (await be(n)).recordPracticeEvent(e)}async function Wo(n,e){return (await be(n)).getPracticeEvents(e)}async function we(n,e){return (await be(n)).getComplianceRate(e)}async function St(n,e){let o=["discovery","verification","testing","documentation","collaboration","security"],t=[];for(let r of o){let s=await we(n,{...e,habitCategory:r});s.total>0&&t.push({category:r,...s});}return t}async function Lo(n,e,o){let t=[];for(let r of e){let s=await rn(n,{habitId:r.habitId,habitCategory:r.habitCategory,result:r.result,engineer:o.engineer,sessionId:o.sessionId,loreEntryId:o.loreEntryId,taskDescription:o.taskDescription,symbolsTouched:o.symbolsTouched,filesModified:o.filesModified,notes:r.notes});t.push(s);}return t}b();function xt(n){return {handled:true,text:JSON.stringify({error:n},null,2)}}var ce={code:"lore_type_decision_removed",message:"lore type 'decision' was removed in v6.0. Use paradigm_decision_record instead. The decision will be stored in .paradigm/decisions/ and a companion lore insight entry (type:'insight' with references.decision_id) will be written automatically so the timeline stays complete. For narrative-only references, use paradigm_lore_record({type:'insight', references:{decision_id}}).",successor_tool:"paradigm_decision_record",doc:"docs/private/plans/v6.0-decisions-locked.md",removed_in:"6.0.0"};function vt(){let n=process.env.PARADIGM_AUTHOR;if(n)return Se(n);try{let e=execSync("git config user.name",{encoding:"utf-8",timeout:3e3}).trim();if(e)return Se(e)}catch{}try{let e=_t.userInfo().username;if(e)return Se(e)}catch{}return "unknown"}function Se(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,20)||"unknown"}function Ko(){return [{name:"paradigm_lore_search",description:"Search lore entries by symbol, author, date range, type, or tags. Returns project history records. Returns matching entries with titles, dates, and symbol references. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#sentinel-sdk", "^authenticated")'},author:{type:"string",description:'Filter by author (human user name, e.g., "ascend")'},hasAgent:{type:"boolean",description:"Filter by AI assistance: true = AI-assisted entries, false = human-only"},authorType:{type:"string",enum:["human","agent"],description:"(Deprecated, use hasAgent) Filter by old author type"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Filter by entry type"},tag:{type:"string",description:'Filter by tag prefix (e.g., "arc:lore-evolution" for arc entries)'},hasBody:{type:"boolean",description:"Filter for entries with/without long-form body content"},dateFrom:{type:"string",description:'Filter from date (ISO 8601, e.g., "2026-02-20")'},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},tags:{type:"array",items:{type:"string"},description:"Filter by tags (OR logic)"},hasReview:{type:"boolean",description:"Filter for entries with/without reviews"},hasConfidence:{type:"boolean",description:"Filter for entries with/without confidence scores"},hasAssessment:{type:"boolean",description:"Filter for entries with/without assessment verdicts"},limit:{type:"number",description:"Maximum results (default: 20)"},offset:{type:"number",description:"Offset for pagination"}}},annotations:{readOnlyHint:true,destructiveHint:false},aliases:["history","what happened","past work","project history","previous sessions","lore"]},{name:"paradigm_lore_record",description:"Record a new lore entry (agent session, milestone, retro, insight, etc.). Call after completing significant work. Returns the created entry ID and file path. For decisions, use paradigm_decision_record (a companion lore insight is auto-written). ~100 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"Entry type"},title:{type:"string",description:'Short title (e.g., "Built Sentinel Phase 1")'},summary:{type:"string",description:"2-3 sentence narrative summary"},symbols_touched:{type:"array",items:{type:"string"},description:'Symbols affected (e.g., ["#sentinel-sdk", "^authenticated"])'},symbols_created:{type:"array",items:{type:"string"},description:"New symbols introduced"},files_created:{type:"array",items:{type:"string"},description:"Files created"},files_modified:{type:"array",items:{type:"string"},description:"Files modified"},lines_added:{type:"number",description:"Lines of code added"},lines_removed:{type:"number",description:"Lines of code removed"},commit:{type:"string",description:"Git commit hash"},duration_minutes:{type:"number",description:"Duration in minutes"},decisions:{type:"array",items:{type:"object",properties:{id:{type:"string"},decision:{type:"string"},rationale:{type:"string"}},required:["id","decision","rationale"]},description:"Decisions made during this work"},errors_encountered:{type:"array",items:{type:"object",properties:{description:{type:"string"},resolution:{type:"string"},time_to_fix:{type:"string"}},required:["description","resolution"]}},learnings:{type:"array",items:{type:"string"},description:"Key learnings from this work"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object",description:'Per-check results (e.g., { "build": "pass", "tests": "fail" })'}}},tags:{type:"array",items:{type:"string"},description:"Tags for categorization"},meta:{type:"object",description:'Project-defined metadata (open-ended key-value pairs, e.g., { meeting_type: "design-review", sprint: 12 })'},body:{type:"string",description:"Long-form content (detailed retrospective notes, decision rationale, etc.)"},linked_lore:{type:"array",items:{type:"string"},description:"Cross-references to other lore entry IDs"},linked_tasks:{type:"array",items:{type:"string"},description:"References to paradigm task IDs"},linked_commits:{type:"array",items:{type:"string"},description:"Git commit SHAs related to this entry"},confidence:{type:"number",description:"Agent confidence in correctness of this work (0.0 to 1.0)"},stream:{type:"string",enum:["work-log","journal","decision","auto"],description:'Knowledge stream classification. "auto" classifies based on content. Default: stores in lore (backward compatible).'}},required:["title","summary","symbols_touched"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_timeline",description:"Get lore timeline overview: recent entries, active authors, hot symbols. Call for project history orientation. ~200 tokens.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Number of recent entries to include (default: 10)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_get",description:"Fetch a single lore entry by ID. Returns the full entry with all fields. ~150 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:'Lore entry ID (e.g., "L-2026-02-23-001" or "L-2026-03-02-ascend-143025-001")'}},required:["id"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_update",description:"Update an existing lore entry. Merges provided fields into the existing entry. Returns updated entry confirmation. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to update"},title:{type:"string",description:"New title"},summary:{type:"string",description:"New summary"},type:{type:"string",enum:["agent-session","human-note","review","incident","milestone","retro","insight"],description:"New entry type"},symbols_touched:{type:"array",items:{type:"string"},description:"Updated symbols list"},symbols_created:{type:"array",items:{type:"string"},description:"Updated created symbols"},files_created:{type:"array",items:{type:"string"}},files_modified:{type:"array",items:{type:"string"}},lines_added:{type:"number"},lines_removed:{type:"number"},commit:{type:"string"},duration_minutes:{type:"number"},learnings:{type:"array",items:{type:"string"},description:"Updated learnings"},verification:{type:"object",properties:{status:{type:"string",enum:["pass","fail","partial","untested"]},details:{type:"object"}}},tags:{type:"array",items:{type:"string"}},confidence:{type:"number",description:"Agent confidence in correctness (0.0 to 1.0)"}},required:["id"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_assess",description:"Record a human assessment verdict on a lore entry (correct/partial/incorrect). Computes calibration delta if confidence was recorded. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to assess"},verdict:{type:"string",enum:["correct","partial","incorrect"],description:"Assessment verdict on the decisions/changes made"},notes:{type:"string",description:"Optional assessment notes"}},required:["id","verdict"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_lore_calibration",description:"Query calibration statistics across assessed lore entries. Returns accuracy rate, average confidence, calibration score, and verdict breakdown. Supports groupBy for domain-specific reliability maps. ~200 tokens.",inputSchema:{type:"object",properties:{symbol:{type:"string",description:'Filter by symbol (e.g., "#auth-middleware")'},tag:{type:"string",description:"Filter by tag prefix"},author:{type:"string",description:"Filter by author"},dateFrom:{type:"string",description:"Filter from date (ISO 8601)"},dateTo:{type:"string",description:"Filter to date (ISO 8601)"},groupBy:{type:"string",enum:["symbol","tag","type"],description:"Group calibration stats by dimension"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_lore_delete",description:"Delete a lore entry. Requires explicit confirmation to prevent accidental deletion. ~100 tokens.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Lore entry ID to delete"},confirm:{type:"boolean",description:"Must be true to proceed with deletion"}},required:["id","confirm"]},annotations:{readOnlyHint:false,destructiveHint:true}}]}async function xe(n,e,o){switch(n){case "paradigm_lore_search":{let t={author:e.author,hasAgent:e.hasAgent,authorType:e.authorType,symbol:e.symbol,dateFrom:e.dateFrom,dateTo:e.dateTo,type:e.type,tag:e.tag,hasBody:e.hasBody,tags:e.tags,hasReview:e.hasReview,hasConfidence:e.hasConfidence,hasAssessment:e.hasAssessment,limit:e.limit||20,offset:e.offset},r=await a$3(o.rootDir,t);return {handled:true,text:JSON.stringify({count:r.length,filter:Object.fromEntries(Object.entries(t).filter(([,s])=>s!==void 0)),entries:r.map(kt)},null,2)}}case "paradigm_lore_record":{let{type:t,title:r,summary:s,symbols_touched:i,symbols_created:a$1,files_created:c,files_modified:l,lines_added:d,lines_removed:u,commit:m,duration_minutes:y,decisions:x,errors_encountered:f,learnings:j,verification:N,tags:R,meta:$,body:I,linked_lore:_,linked_tasks:O,linked_commits:E,confidence:h}=e;if(t==="decision")return a.component("#lore").warn("rejected paradigm_lore_record({type:'decision'}) \u2014 removed in v6.0",{removed_in:ce.removed_in,successor_tool:ce.successor_tool}),xt(ce);let C;try{let S=new Date(Date.now()-2592e6).toISOString(),b=await we(o.rootDir,{dateFrom:S});if(b.total>0){let p=(await St(o.rootDir,{dateFrom:S})).filter(k=>k.rate<60).map(k=>k.category);C={rate:b.rate,followed:b.followed,skipped:b.skipped,partial:b.partial,weakAreas:p.length>0?p:void 0};}}catch{}let v={id:"",type:t||"agent-session",timestamp:new Date().toISOString(),duration_minutes:y,author:vt(),agent:{provider:"anthropic",model:"claude-opus-4-6"},title:r,summary:s,symbols_touched:i,symbols_created:a$1,files_created:c,files_modified:l,lines_added:d,lines_removed:u,commit:m,decisions:x,errors_encountered:f,learnings:j,verification:N,tags:R,meta:$||void 0,habit_compliance:C,body:I,linked_lore:_,linked_tasks:O,linked_commits:E,confidence:h!=null&&h>=0&&h<=1?h:void 0},w=await d$2(o.rootDir,v);j$1().setLastLoreEntryId(w);try{let S=process.env.PARADIGM_AGENT_ID;if(S&&i&&i.length>0){let{updateExpertiseFromLore:b}=await import('./agent-loader-W3RQJVW7.js');b(o.rootDir,S,{symbols_touched:i,confidence:h!=null&&h>=0&&h<=1?h:void 0});}}catch{}let P=null;try{c&&c.length>=2&&(P=A$1(o.rootDir,c,l||[]));}catch{}let T;if(e.stream){let S=e.stream,b=S==="auto"?cn(e):S;try{if(b==="work-log"){let{recordWorkLog:g}=await import('./work-log-loader-DL5GZ2BQ.js');g(o.rootDir,{agent:v.agent?.model||"unknown",summary:v.summary,outcome:v.verification?.status==="pass"?"pass":v.verification?.status==="fail"?"fail":"partial",files_modified:v.files_modified,symbols_touched:v.symbols_touched,commit:v.commit,linked_lore:v.id||w}),T="work-log";}else if(b==="journal"&&v.learnings?.length){let{recordJournalEntry:g}=await import('./journal-loader-CNNA4EAU.js');for(let p of v.learnings)g(v.agent?.model||"unknown",{trigger:"self_reflection",insight:p,project:o.projectName||"unknown",transferable:!1,linked_work_log:v.id||w});T="journal";}else if(b==="decision"&&v.decisions?.length){let{recordDecision:g}=await import('./decision-loader-HELL2AMX.js');for(let p of v.decisions)g(o.rootDir,{title:p.decision.slice(0,100),decision:p.decision,rationale:p.rationale,participants:[{id:`agent/${v.agent?.model||"unknown"}`,role:"agent",stance:"proposed"}],symbols_affected:v.symbols_touched,status:"active",linked_lore:v.id||w});T="decision";}}catch{}}return {handled:true,text:JSON.stringify({success:true,id:w,type:t,title:r,message:"Lore entry recorded successfully",...T?{stream:T}:{},...P?{protocol_suggestion:P}:{}})}}case "paradigm_lore_timeline":{let t=e.limit||10,r=await c(o.rootDir),s=await a$3(o.rootDir,{limit:t}),i={};for(let l of s)for(let d of l.symbols_touched)i[d]=(i[d]||0)+1;let a=Object.entries(i).sort(([,l],[,d])=>d-l).slice(0,10).map(([l,d])=>({symbol:l,count:d})),c$1={};for(let l of s){let d=l.author;c$1[d]||(c$1[d]={count:0,lastActive:l.timestamp,hasAgent:l.agent!=null}),c$1[d].count++,l.agent&&(c$1[d].hasAgent=true),l.timestamp>c$1[d].lastActive&&(c$1[d].lastActive=l.timestamp);}return {handled:true,text:JSON.stringify({timeline:r||{version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]},recentEntries:s.map(kt),hotSymbols:a,authors:Object.entries(c$1).map(([l,d])=>({id:l,hasAgent:d.hasAgent,entries:d.count,lastActive:d.lastActive}))},null,2)}}case "paradigm_lore_get":{let t=e.id,r=await b$1(o.rootDir,t);return r?{handled:true,text:JSON.stringify(r,null,2)}:{handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})}}case "paradigm_lore_update":{let t=e.id,{id:r,...s}=e,i={};for(let[c,l]of Object.entries(s))l!==void 0&&(i[c]=l);let a=await g$1(o.rootDir,t,i);return {handled:true,text:JSON.stringify({success:a,id:t,message:a?"Lore entry updated":`Lore entry not found: ${t}`})}}case "paradigm_lore_assess":{let t=e.id,r=e.verdict,s=e.notes,i=await b$1(o.rootDir,t);if(!i)return {handled:true,text:JSON.stringify({error:`Lore entry not found: ${t}`})};let a={verdict:r,assessed_by:vt(),assessed_at:new Date().toISOString(),notes:s},c=await h$1(o.rootDir,t,a);try{let m=process.env.PARADIGM_AGENT_ID;if(m&&c&&i.symbols_touched?.length){let{updateExpertiseFromAssessment:y}=await import('./agent-loader-W3RQJVW7.js');y(o.rootDir,m,{symbols_touched:i.symbols_touched,verdict:r});}}catch{}let l=r==="correct"?1:r==="partial"?.5:0,d=i.confidence!=null?l-i.confidence:null,u=d!=null?d>.1?"Under-confident (actual outcome better than predicted)":d<-0.1?"Over-confident (actual outcome worse than predicted)":"Well-calibrated":"No confidence recorded \u2014 delta not computed";return {handled:true,text:JSON.stringify({success:c,id:t,verdict:r,confidence:i.confidence??null,delta:d,deltaDescription:u,message:c?`Assessment recorded: ${r}${d!=null?` (delta: ${d>0?"+":""}${d.toFixed(2)})`:""}`:`Failed to assess: ${t}`})}}case "paradigm_lore_calibration":{let t={symbol:e.symbol,tag:e.tag,author:e.author,dateFrom:e.dateFrom,dateTo:e.dateTo,hasAssessment:true},r=await a$3(o.rootDir,t),s=r.filter(I=>I.confidence!=null),i=r.length,a=s.length,c={correct:0,partial:0,incorrect:0},l=0,d=0,u=0;for(let I of r){let _=I.assessment.verdict;c[_]++;let O=_==="correct"?1:_==="partial"?.5:0;l+=O,I.confidence!=null&&(d+=I.confidence,u+=Math.abs(O-I.confidence));}let m=i>0?l/i:0,y=a>0?d/a:null,x=a>0?l/i-d/a:null,f=a>0?1-u/a:null,j=e.groupBy,N;if(j&&i>0){let I=new Map;for(let _ of r){let O=[];j==="symbol"?O=_.symbols_touched||[]:j==="tag"?O=_.tags||[]:j==="type"&&(O=[_.type||"agent-session"]);for(let E of O)I.has(E)||I.set(E,[]),I.get(E).push(_);}N=Array.from(I.entries()).map(([_,O])=>{let E=O.filter(P=>P.confidence!=null),h={correct:0,partial:0,incorrect:0},C=0,v=0,w=0;for(let P of O){let T=P.assessment.verdict;h[T]++;let S=T==="correct"?1:T==="partial"?.5:0;C+=S,P.confidence!=null&&(v+=P.confidence,w+=Math.abs(S-P.confidence));}return {key:_,total:O.length,accuracyRate:C/O.length,avgConfidence:E.length>0?v/E.length:null,calibrationScore:E.length>0?1-w/E.length:null,verdictBreakdown:h}}).sort((_,O)=>O.total-_.total);}let R=[],$=i<5?`Low sample size (N=${i}). Stats may not be representative.`:i<15?`Moderate sample (N=${i}). Trends are directional, not conclusive.`:null;return $&&R.push($),f!=null&&(f>=.9?R.push("Excellent calibration \u2014 confidence predictions closely match outcomes."):f>=.7?R.push("Good calibration \u2014 some room for improvement in confidence estimates."):f>=.5?R.push("Fair calibration \u2014 significant gap between predicted confidence and outcomes."):R.push("Poor calibration \u2014 confidence predictions diverge substantially from outcomes.")),x!=null&&(x>.15?R.push("Tendency toward under-confidence \u2014 outcomes are better than predicted."):x<-0.15&&R.push("Tendency toward over-confidence \u2014 outcomes are worse than predicted.")),c.incorrect>i*.3&&i>=5&&R.push(`High error rate: ${c.incorrect}/${i} entries assessed as incorrect.`),{handled:true,text:JSON.stringify({totalAssessed:i,totalWithConfidence:a,accuracyRate:Math.round(m*1e3)/1e3,avgConfidence:y!=null?Math.round(y*1e3)/1e3:null,avgDelta:x!=null?Math.round(x*1e3)/1e3:null,calibrationScore:f!=null?Math.round(f*1e3)/1e3:null,verdictBreakdown:c,...N?{groups:N}:{},insights:R},null,2)}}case "paradigm_lore_delete":{let t=e.id;if(!e.confirm)return {handled:true,text:JSON.stringify({success:false,message:"Deletion requires confirm: true"})};let s=await i(o.rootDir,t);return {handled:true,text:JSON.stringify({success:s,id:t,message:s?"Lore entry deleted":`Lore entry not found: ${t}`})}}default:return {handled:false,text:""}}}function cn(n){return n.task_ref||n.files_modified||n.commit?"work-log":n.learnings||n.confidence!==void 0?"journal":n.decisions?.some(o=>o.rationale)?"decision":"work-log"}function kt(n){return {id:n.id,type:n.type,title:n.title,summary:n.summary,author:n.author,agent:n.agent,timestamp:n.timestamp,duration_minutes:n.duration_minutes,symbols_touched:n.symbols_touched,verification:n.verification?.status,review:n.review?{completeness:n.review.completeness,quality:n.review.quality}:null,confidence:n.confidence??null,assessment:n.assessment?n.assessment.verdict:null,assessment_delta:n.assessment_delta??null,tags:n.tags}}function ls(){return [{name:"paradigm_captain_brief",description:"Cid's pre-task context discovery pipeline. Searches symbols, maps blast radius, checks gates, finds protocols, surfaces warnings, and produces a Context Brief injected into every subsequent agent. Call before starting any multi-file task. ~400 tokens.",inputSchema:{type:"object",properties:{taskDescription:{type:"string",description:"The task to produce a context brief for"},symbols:{type:"array",items:{type:"string"},description:'Optional pre-known symbols to anchor the search (e.g., ["#auth", "^authenticated"])'},depth:{type:"string",enum:["quick","standard","deep"],description:"Brief depth. quick=search+navigate only (<800 tokens). standard=+ripple top 3+wisdom. deep=+ripple top 5+full lore scan. Default: standard"}},required:["taskDescription"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_captain_debrief",description:"Cid's post-task maintenance pass. Audits .purpose coverage for touched directories, creates stubs for gaps, queues rich doc areas to Documentor, records lore, and writes the .cid-briefed marker that clears the stop hook. Call after all agents complete. ~200 tokens.",inputSchema:{type:"object",properties:{orchestrationId:{type:"string",description:"The orchestration run ID (from paradigm_orchestrate_inline)"},sessionSummary:{type:"string",description:"What was accomplished in this session"},touchedFiles:{type:"array",items:{type:"string"},description:"Files modified during this session"},newSymbols:{type:"array",items:{type:"string"},description:"New symbols registered during this session"},notes:{type:"string",description:"Optional additional notes from the orchestrating session"}},required:["orchestrationId","sessionSummary","touchedFiles"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_captain_board",description:"Cid's owned run-DAG board (#captain-board). action='read' (default, read-only) assembles the live orchestration DAG \u2014 each run's epic + ordered stage-children with status/claimant/dependsOn, plus ripple-ranked unclaimed open tasks and a summary. action='claim' writes a task's claimant (status stays open; human/peer claims override an archetype proposal). action='advance' records a blocked_on reason without changing status (orchestration owns in-progress/done). ~300 tokens.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["read","claim","advance"],description:"Board action. Default 'read'."},taskId:{type:"string",description:"Target task id (required for claim/advance)."},claimant:{type:"object",description:"For claim: the new owner { kind: 'archetype'|'human'|'peer', ref }.",properties:{kind:{type:"string",enum:["archetype","human","peer"]},ref:{type:"string"}}},blockedOn:{type:"string",description:"For advance: the blocking reason recorded on the task."}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}async function ds(n,e,o){return n==="paradigm_captain_brief"?ln(e,o):n==="paradigm_captain_debrief"?dn(e,o):n==="paradigm_captain_board"?un(e,o):{handled:false,text:""}}async function ln(n,e){let o=n.taskDescription,t$1=n.symbols||[],r=n.depth||"standard",s=A.join(e.rootDir,".paradigm"),i=A.join(s,".cid-session"),a=A.join(s,".cid-briefed");try{D.existsSync(a)&&D.unlinkSync(a);let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r};D.mkdirSync(s,{recursive:!0}),D.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let c=_n(o),l=[],d=new Set;for(let S of t$1)if(!d.has(S)){d.add(S);let b=Pt(S);l.push({id:S,type:b,description:"Provided as anchor symbol"});}let u=[];try{for(let S of c.slice(0,3)){let g=t(e.index,S).slice(0,5);for(let p of g)if(!d.has(p.symbol)){d.add(p.symbol);let k=Pn(p.type);l.push({id:p.symbol,type:k,description:p.description||"",file:p.file}),u.push(p.symbol);}}}catch{}let m={directories:[],files:[]};try{let S=await tt("paradigm_navigate",{intent:"context",task:o,response_format:"concise"},e);if(S.handled){let b=JSON.parse(S.text);if(b.files)for(let g of b.files){let p=typeof g=="string"?g:g.path||g.file||"";p&&m.files.push(p);}if(b.directories)for(let g of b.directories){let p=typeof g=="string"?g:g.path||g.directory||"";p&&m.directories.push(p);}if(b.symbols)for(let g of b.symbols){let p=typeof g=="string"?g:g.id;p&&!d.has(p)&&(d.add(p),l.push({id:p,type:Pt(p),description:typeof g=="object"&&g.description||""}));}}}catch{}let y=new Set(m.directories);for(let S of m.files){let b=A.dirname(S);b&&b!=="."&&y.add(b);}let x=l.slice(0,r==="deep"?5:3),f={affectedFiles:[],affectedSymbols:[],affectedFlows:[],affectedGates:[],fragileSymbols:[]};if(r!=="quick"&&x.length>0)for(let S of x)try{let b=await se("paradigm_ripple",{symbol:S.id,depth:2,response_format:"concise"},e);if(b.handled){let g=JSON.parse(b.text);if(g.analysis){for(let p of g.analysis.directlyAffected||[]){let k=p.symbol||p;k&&!f.affectedSymbols.includes(k)&&f.affectedSymbols.push(k);}for(let p of g.analysis.indirectlyAffected||[])p&&!f.affectedSymbols.includes(p)&&f.affectedSymbols.push(p);}if(g.affectedFlows?.affectedFlows)for(let p of g.affectedFlows.affectedFlows){let k=p.flowId||p;k&&!f.affectedFlows.includes(k)&&f.affectedFlows.push(k);}if(g.affectedGates)for(let p of g.affectedGates){let k=p.gate||p;k&&!f.affectedGates.includes(k)&&f.affectedGates.push(k);}g.impact==="high"&&(f.fragileSymbols.includes(S.id)||f.fragileSymbols.push(S.id));}}catch{}let j=[],N=Cn(o);if(N.length>0)try{let{handleGatesForRoute:S}=await import('./tools-SDWAFQMQ.js').catch(()=>({handleGatesForRoute:null})),b=A.join(e.rootDir,"portal.yaml");if(D.existsSync(b)){let g=D.readFileSync(b,"utf8");for(let p of N){let k=g.includes(p);j.push({route:p,gate:"^authenticated",declared:k});}}else for(let g of N)j.push({route:g,gate:"(unknown \u2014 no portal.yaml)",declared:!1});}catch{}let R=[];if(r!=="quick"&&l.length>0)try{let S=l.slice(0,5).map(g=>g.id),b=await ht("paradigm_wisdom_context",{symbols:S,include_global:!0},e);if(b.handled){let g=JSON.parse(b.text);if(g.antipatterns)for(let p of g.antipatterns.slice(0,3)){let k=p.pattern||p.description||p.text||String(p);k&&!R.includes(k)&&R.push(k);}if(g.wisdom?.antipatterns)for(let p of g.wisdom.antipatterns.slice(0,3)){let k=p.pattern||p.description||String(p);k&&!R.includes(k)&&R.push(k);}}}catch{}let $={matched:false};try{let S=await bt("paradigm_protocol_search",{task:o,limit:1},e);if(S.handled){let b=JSON.parse(S.text),g=b.matches||b.protocols||b.results||[];if(g.length>0){let p=g[0];$={matched:!0,id:p.id,name:p.name||p.title,steps:(p.steps||[]).slice(0,5).map(k=>typeof k=="string"?k:k.description||String(k))};}}}catch{}let I=[];if(r!=="quick")try{let S=l[0]?.id,b={limit:r==="deep"?5:3};S&&(b.symbol=S);let g=await xe("paradigm_lore_search",b,e);if(g.handled){let k=JSON.parse(g.text).entries||[];for(let B of k.slice(0,3))I.push({id:B.id,summary:(B.summary||B.title||"").slice(0,100),relevance:S?`Related to ${S}`:"Recent project history"});}}catch{}let _=Array.from(y),O=0;for(let S of _){let b=A.join(e.rootDir,S,".purpose");if(D.existsSync(b))try{D.readFileSync(b,"utf8").trim().length>50&&O++;}catch{}}let E=_.length>0?O/_.length:.5,h=jn(E),C=Dn(E,h,_.length),v=f.affectedSymbols.length+m.files.length,w=v>20?"large":v>8?"medium":v>2?"small":"tiny",P={territory:{directories:_.slice(0,10),files:m.files.slice(0,10),estimatedScope:w},symbols:l.slice(0,10),blastRadius:f,gates:j,protocol:$,warnings:R,coverage:{score:E,label:h,note:C},loreRefs:I,archMap:b$2(e.rootDir),renderedBrief:""};P.renderedBrief=Rn(P);try{let S={timestamp:new Date().toISOString(),taskDescription:o.slice(0,200),depth:r,coverageScore:E};D.writeFileSync(i,JSON.stringify(S,null,2),"utf8");}catch{}let T=JSON.stringify(P,null,2);return a$1(T.length,"paradigm_captain_brief"),{handled:true,text:T}}async function dn(n,e){let o=n.orchestrationId,t=n.sessionSummary,r=n.touchedFiles||[],s=n.newSymbols||[],i=n.notes,a$2=A.join(e.rootDir,".paradigm"),c=A.join(a$2,".cid-briefed"),l=A.join(a$2,".pending-review"),d=new Set;for(let w of r){let P=A.dirname(w);P&&P!=="."&&d.add(P);}let u=0,m=d.size;for(let w of d){let P=A.join(e.rootDir,w,".purpose");if(D.existsSync(P))try{D.readFileSync(P,"utf8").trim().length>50&&u++;}catch{}}let y=m>0?u/m:1,x=[],f=[];for(let w of d){let P=A.join(e.rootDir,w,".purpose"),T=A.join(e.rootDir,w),S=false;if(D.existsSync(P))try{S=D.readFileSync(P,"utf8").trim().length>50;}catch{}if(S){if(r.some(g=>A.dirname(g)===w&&s.length>0)){f.push(w);try{let g=JSON.stringify({path:w,reason:"captain-debrief-new-symbols",priority:"medium",context:`New symbols added during orchestration ${o}: ${s.join(", ")}`,timestamp:new Date().toISOString()});D.appendFileSync(l,g+`
6
+ `,"utf8");}catch{}}}else try{if(!D.existsSync(T))continue;let b=A.basename(w),g=Fn(b,w,r);D.writeFileSync(P,g,"utf8"),x.push(w),f.push(w);try{let p=JSON.stringify({path:w,reason:"captain-debrief",priority:"high",context:`Touched during orchestration ${o}. Files: ${r.filter(k=>A.dirname(k)===w).join(", ")}`,timestamp:new Date().toISOString()});D.appendFileSync(l,p+`
7
+ `,"utf8");}catch{}}catch{}}let j=0;for(let w of d){let P=A.join(e.rootDir,w,".purpose");if(D.existsSync(P))try{D.readFileSync(P,"utf8").trim().length>50&&j++;}catch{}}let N=m>0?j/m:1,R="";try{let w=await xe("paradigm_lore_record",{type:"agent-session",title:`Cid Debrief: ${t.slice(0,80)}`,summary:t,symbols_touched:s,files_modified:r,tags:["arc:cid-debrief",`orch:${o}`],meta:{orchestrationId:o,coverageScore:{before:y,after:N},coverageAdded:x,...i?{notes:i}:{}}},e);if(w.handled){let P=JSON.parse(w.text);R=P.id||P.entry?.id||"";}}catch{}let $={ranThisSession:false,selfHealed:false,blockProposed:false};if($.ranThisSession=mn(a$2),!$.ranThisSession)try{let{runPostflightLearning:w}=await import('./ambient-VCTUHHIG.js');await w(e.rootDir,{claimant:"navigation"}),$.selfHealed=!0,a.flow("$captain-board").info("Cid self-healed postflight (no prior liveness record)",{orchestrationId:o});}catch(w){$.selfHealError=w instanceof Error?w.message:String(w),a.flow("$captain-board").warn("Cid postflight self-heal threw \u2014 proposing advise block",{orchestrationId:o,error:$.selfHealError});try{let{handleProposeBlockTool:P}=await import('./propose-block-ZEMEWJQF.js');await P("paradigm_propose_block",{claimant:"navigation",severity:"advise",reason:`Postflight learning did not run and Cid's self-heal failed: ${$.selfHealError}`,unblock_hint:"Run `paradigm_ambient_learn_postflight` manually, or inspect .paradigm/events/settlement-liveness.jsonl for the severed stage."},e),$.blockProposed=!0;}catch{}}let I=false;try{let w={timestamp:new Date().toISOString(),sessionId:o,touchedFiles:r,coverageScore:N};D.mkdirSync(a$2,{recursive:!0}),D.writeFileSync(c,JSON.stringify(w,null,2),"utf8"),I=!0;}catch{}let _={taskDescription:t,orchestrationId:o,agentContributions:[],coverageDelta:{before:y,after:N},newSymbols:s,touchedFiles:r,notes:i||""};try{let w=A.join(a$2,"events","session-log.jsonl");if(D.existsSync(w)){let S=D.readFileSync(w,"utf8").split(`
8
+ `).filter(g=>g.trim().length>0).slice(-50),b=new Map;for(let g of S)try{let p=JSON.parse(g),k=p.agentId||p.agent||p.role||"";if(!k)continue;b.has(k)||b.set(k,{contributions:[],symbolsTouched:new Set,patternsObserved:[]});let B=b.get(k),ve=p.action||p.event||p.message||"";if(ve&&B.contributions.push(String(ve).slice(0,120)),Array.isArray(p.symbols))for(let K of p.symbols)B.symbolsTouched.add(String(K));let ke=p.symbol||"";if(ke&&B.symbolsTouched.add(ke),Array.isArray(p.patterns))for(let K of p.patterns)B.patternsObserved.includes(String(K))||B.patternsObserved.push(String(K));}catch{}for(let[g,p]of b.entries())_.agentContributions.push({agentId:g,contribution:p.contributions.slice(-3).join(" | "),symbolsTouched:Array.from(p.symbolsTouched).slice(0,10),patternsObserved:p.patternsObserved.slice(0,5)});}}catch{}let O=_.agentContributions.length;_.agentContributions.length===0&&_.agentContributions.push({agentId:"session",contribution:t.slice(0,200),symbolsTouched:s.slice(0,10),patternsObserved:[]}),O>0&&a$4(e.rootDir,{verdicts:O,source:"debrief"});let E={coverageAdded:x,delegatedToDocumentor:f,loreEntryId:R,coverageScore:{before:y,after:N,delta:N-y},stopHookCleared:I,postflight:$,sessionInsights:_},h=["","\u2501\u2501\u2501 LEARNING HANDOFF (\u2192 Loid) \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501","","Cid has prepared session insights for Loid's learning pass.","Call paradigm_ambient_learn_postflight with the sessionInsights","from this debrief to complete the session.","","sessionInsights available in: debrief.sessionInsights"].join(`
9
+ `),v=JSON.stringify(E,null,2)+`
10
+ `+h;return a$1(v.length,"paradigm_captain_debrief"),{handled:true,text:v}}var pn=A.join("events","settlement-liveness.jsonl"),fn=360*60*1e3;function mn(n){let e=A.join(n,pn);if(!D.existsSync(e))return false;try{let t=D.readFileSync(e,"utf8").split(`
11
+ `).filter(s=>s.trim().length>0),r=Date.now()-fn;for(let s of t.slice(-50))try{let i=JSON.parse(s),a=i.ts?new Date(i.ts).getTime():NaN;if(Number.isNaN(a)||a<r)continue;if(i.stages?.runPostflightLearning==="ok")return !0}catch{}}catch{return false}return false}async function un(n,e){let o=n.action||"read";if(o==="claim")return vn(n,e);if(o==="advance")return kn(n,e);let t=await Sn(e.rootDir,{},e),r=JSON.stringify(t,null,2);return a$1(r.length,"paradigm_captain_board"),{handled:true,text:r}}function gn(n,e){return n.settledAt?n.crashed_at||e.some(t=>t.crashed_at)?"crashed":"settled":e.length===0?"pending":e.some(t=>t.status==="in-progress")||n.status==="in-progress"?"in-progress":"pending"}function yn(n){return [...n].sort((e,o)=>{let t=e.stage??0,r=o.stage??0;if(t!==r)return t-r;let s=e.dependsOn?.length??0,i=o.dependsOn?.length??0;return s!==i?s-i:e.id.localeCompare(o.id)})}async function hn(n,e){let o=jt(n).slice(0,3),t=[];for(let r of o)try{let s=await se("paradigm_ripple",{symbol:r,depth:1,response_format:"concise"},e);s.handled&&JSON.parse(s.text).impact==="high"&&!t.includes(r)&&t.push(r);}catch{}return t}var bn=/[#$^!~][a-z][a-z0-9-]*/gi;function jt(n){let e=new Set;for(let t of n.tags||[])/^[#$^!~]/.test(t)&&e.add(t);let o=n.blurb?.match(bn)||[];for(let t of o)e.add(t);return Array.from(e)}async function wn(n,e){let o=jt(n).slice(0,3),t=0,r=[];for(let s of o)try{let i=await se("paradigm_ripple",{symbol:s,depth:2,response_format:"concise"},e);if(i.handled){let a=JSON.parse(i.text),c=a.analysis?.directlyAffected?.length??0,l=a.analysis?.indirectlyAffected?.length??0;t+=c*2+l,a.impact==="high"&&!r.includes(s)&&r.push(s);}}catch{}return {score:t,fragile:r}}var Ct={high:0,medium:1,low:2};async function Sn(n,e={},o){let t=o,{loadTasks:r}=await import('./task-loader-HBZ3KRH2.js'),s=[];try{s=await r(n,{status:"all",limit:9999});}catch(m){a.flow("$captain-board").warn("Board task load failed",{error:m instanceof Error?m.message:String(m)});}let i=s.filter(m=>m.external_ref?.provider==="orchestration"&&!m.parentTaskId&&!m.settledAt),a$1=[];for(let m of i){let y=yn(s.filter(f=>f.parentTaskId===m.id)),x=[];for(let f of y){let j=t?await hn(f,t):[];x.push({taskId:f.id,blurb:f.blurb,stage:f.stage,status:f.status,claimant:f.claimant,dependsOn:f.dependsOn||[],fragileSymbols:j});}a$1.push({epicTaskId:m.id,blurb:m.blurb,runStatus:gn(m,y),settledAt:m.settledAt,nodes:x});}let c=s.filter(m=>m.status==="open"&&!m.claimant),l=[];for(let m of c){let{score:y,fragile:x}=t?await wn(m,t):{score:0,fragile:[]},f;e.proposeClaimants&&(f=await xn(m,n)),l.push({taskId:m.id,blurb:m.blurb,priority:m.priority,tags:m.tags||[],rippleScore:y,fragileSymbols:x,proposedClaimant:f});}l.sort((m,y)=>{if(y.rippleScore!==m.rippleScore)return y.rippleScore-m.rippleScore;let x=(Ct[m.priority]??1)-(Ct[y.priority]??1);return x!==0?x:y.taskId.localeCompare(m.taskId)});let d=s.filter(m=>m.status==="in-progress").length,u=s.filter(m=>m.status==="open").length;return {runs:a$1,unclaimed:l,summary:{runs:a$1.length,open:u,inFlight:d,unclaimed:l.length}}}async function xn(n,e){try{let{suggestAgentsForTask:o,loadAgentsManifest:t}=await import('./orchestration-EVWQWTOV.js'),r=t(e);if(!r?.agents)return;let s=[n.blurb,...n.tags||[]].join(" "),i=o(s,r.agents);return i.length===0?void 0:{kind:"archetype",ref:i[0].name}}catch{return}}async function vn(n,e){let o=n.taskId,t=n.claimant;if(!o||!t?.kind||!t?.ref)return {handled:true,text:JSON.stringify({ok:false,error:"claim requires taskId and claimant {kind, ref}"})};let{loadTask:r,updateTask:s}=await import('./task-loader-HBZ3KRH2.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a$1=i.claimant;if(a$1&&a$1.kind!=="archetype"&&t.kind==="archetype")return a.flow("$captain-board").info("Claim rejected: archetype cannot override human/peer claim",{taskId:o,existing:a$1.kind,proposed:t.kind}),{handled:true,text:JSON.stringify({ok:false,error:`task ${o} is claimed by ${a$1.kind}:${a$1.ref}; archetype proposal cannot override`,claimant:a$1})};let c=await s(e.rootDir,o,{claimant:t});return a.flow("$captain-board").info("Captain claim written",{taskId:o,claimant:t,ok:c}),{handled:true,text:JSON.stringify({ok:c,taskId:o,claimant:t,status:"open"})}}async function kn(n,e){let o=n.taskId,t=n.blockedOn;if(!o||!t)return {handled:true,text:JSON.stringify({ok:false,error:"advance requires taskId and blockedOn (v7.0 has no 'blocked' status \u2014 advance records a reason only)"})};let{loadTask:r,updateTask:s}=await import('./task-loader-HBZ3KRH2.js'),i=await r(e.rootDir,o);if(!i)return {handled:true,text:JSON.stringify({ok:false,error:`task not found: ${o}`})};let a$1=await s(e.rootDir,o,{blocked_on:t});return a.flow("$captain-board").info("Captain advance: blocked_on recorded (status unchanged)",{taskId:o,blockedOn:t,status:i.status,ok:a$1}),{handled:true,text:JSON.stringify({ok:a$1,taskId:o,blocked_on:t,status:i.status})}}function _n(n){let e=new Set(["the","a","an","to","of","in","and","or","for","with","that","this","is","it","be","as","at","by","from","add","create","update","fix","implement","make","build","change","modify","new","old","get","set","use","using"]),o=n.match(/[#$^!~@&%?][a-z][a-z0-9-]*/g)||[],t=n.replace(/[#$^!~@&%?]/g," ").split(/[\s\-_\/.,;:'"()\[\]{}!?]+/).map(s=>s.toLowerCase()).filter(s=>s.length>2&&!e.has(s));return [...new Set([...o,...t])].slice(0,6)}function Cn(n){let e=[],o=/(?:GET|POST|PUT|PATCH|DELETE)\s+(\/[a-z0-9\-\/:_{}]+)/gi,t;for(;(t=o.exec(n))!==null;)e.push(t[1]);let r=/\/api\/[a-z0-9\-\/:_{}]+/g;for(;(t=r.exec(n))!==null;)e.includes(t[0])||e.push(t[0]);return e}function Pt(n){return n.startsWith("#")?"component":n.startsWith("$")?"flow":n.startsWith("^")?"gate":n.startsWith("!")?"signal":n.startsWith("~")?"aspect":"component"}function Pn(n){switch(n){case "component":return "component";case "flow":return "flow";case "gate":return "gate";case "signal":return "signal";case "aspect":return "aspect";default:return "component"}}function jn(n){return n>=.85?"comprehensive":n>=.6?"reliable":n>=.3?"partial":"sparse"}function Dn(n,e,o){let t=Math.round(n*100);switch(e){case "sparse":return `${t}% of ${o} director(ies) covered. Brief may be significantly incomplete. Builder should explore directly.`;case "partial":return `${t}% of ${o} director(ies) covered. Brief covers key symbols. Some areas uncharted.`;case "reliable":return `${t}% of ${o} director(ies) covered. Brief is reliable for this task.`;case "comprehensive":return `${t}% of ${o} director(ies) covered. Area is fully mapped.`}}function Rn(n){let e=[],o="\u2501".repeat(52);e.push(`${o}`),e.push("");let t=n.territory.directories.slice(0,3).join(", ")||"(none detected)";e.push(`Territory: ${t}`);let r=n.symbols.slice(0,5).map(d=>d.id).join(", ")||"(none found)";e.push(`Symbols: ${r}`);let s=n.blastRadius.affectedFiles.length+n.territory.files.length,i=n.blastRadius.affectedFlows.length,a=n.blastRadius.affectedGates.length,c=n.blastRadius.fragileSymbols.length>0?` \xB7 \u26A0 ${n.blastRadius.fragileSymbols.slice(0,2).join(", ")} (fragile)`:"";if(e.push(`Blast Radius: ${s} files \xB7 ${i} flows \xB7 ${a} gates${c}`),n.gates.length>0){let d=n.gates.slice(0,2).map(u=>`${u.route} \u2192 ${u.gate} (${u.declared?"declared \u2713":"UNDECLARED \u2717"})`);e.push(`Gates: ${d.join("; ")}`);}if(n.protocol.matched){let d=n.protocol.steps?.length?` (${n.protocol.steps.length} steps)`:"";e.push(`Protocol: ${n.protocol.name||n.protocol.id}${d} \u2014 matched`);}else e.push("Protocol: (none matched)");n.warnings.length>0&&e.push(`Warnings: "${n.warnings[0].slice(0,80)}"`);let l=Math.round(n.coverage.score*100);return e.push(`Coverage: ${l}% \u2014 brief is ${n.coverage.label}`),e.push(""),e.push(`${o}`),e.join(`
12
+ `)}function Fn(n,e,o){let r=o.filter(s=>A.dirname(s)===e).slice(0,3).map(s=>`# - ${A.basename(s)}`).join(`
13
+ `);return `# Auto-generated .purpose stub \u2014 created by Cid (captain debrief)
14
+ # Delegate to Scribe (Documentor) for rich documentation
15
+ name: ${n}
16
+ description: "TODO: describe what this directory/module does"
17
+ context:
18
+ - "Stub created by Cid during coverage audit \u2014 update with real context"
19
+ ${r?`# Key files touched:
20
+ ${r}`:""}
21
+ components:
22
+ ${n}:
23
+ description: "TODO: describe this component"
24
+ tags: []
25
+ `}export{xn as A,ge as a,Mn as b,tt as c,ot as d,rt as e,it as f,to as g,se as h,ao as i,co as j,tn as k,lo as l,vo as m,Ao as n,ht as o,$o as p,bt as q,Wo as r,we as s,St as t,Lo as u,Ko as v,xe as w,ls as x,ds as y,Sn as z};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import {b as b$1,a}from'./chunk-EK4ZRIFJ.js';import*as i from'fs';import*as o from'path';import*as f from'js-yaml';b$1();var g=".paradigm/tasks",T="entries",F="index.yaml";function k(e){if(e&&e.session_link&&!e.external_ref){let s=e.session_link,n=s.toLowerCase(),r;n.includes("github")?r="github":n.includes("session")?r="session":r="url",e.external_ref={provider:r,ref:s},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 j(e,t){let s=o.join(e,g,T,t);if(!i.existsSync(s))return `T-${t}-001`;let n=i.readdirSync(s).filter(a=>a.startsWith("T-")&&a.endsWith(".yaml")).map(a=>{let d=a.match(/T-\d{4}-\d{2}-\d{2}-(\d+)\.yaml/);return d?parseInt(d[1],10):0}),r=n.length>0?Math.max(...n)+1:1;return `T-${t}-${String(r).padStart(3,"0")}`}function O(e,t){return e===t?true:({open:["in-progress","done","shelved"],"in-progress":["done","open","shelved"],shelved:["open"],done:[]}[e]??[]).includes(t)}var _={high:0,medium:1,low:2},E=["open","in-progress"];function N(e,t){return t==="all"?true:t==="active"?E.includes(e.status):e.status===t}function b(e){let t=e.created?new Date(e.created).getTime():NaN;if(!Number.isNaN(t))return t;let s=e.id?.match(/^T-(\d{4}-\d{2}-\d{2})-/);if(s){let n=new Date(s[1]).getTime();if(!Number.isNaN(n))return n}return 0}function C(e,t){let s=e;return t.status&&t.status!=="all"&&(s=s.filter(n=>N(n,t.status))),t.priority&&(s=s.filter(n=>n.priority===t.priority)),t.tag&&(s=s.filter(n=>n.tags.includes(t.tag))),s.sort((n,r)=>{let a=(_[n.priority]??1)-(_[r.priority]??1);return a!==0?a:b(r)-b(n)}),t.limit&&(s=s.slice(0,t.limit)),s}async function D(e,t){let s=o.join(e,g,T);if(!i.existsSync(s))return [];let n={status:"open",limit:20,...t},r=[],a=i.readdirSync(s).filter(d=>/^\d{4}-\d{2}-\d{2}$/.test(d)).sort().reverse();for(let d of a){let m=o.join(s,d),l=i.readdirSync(m).filter(c=>c.endsWith(".yaml")).sort();for(let c of l)try{let u=i.readFileSync(o.join(m,c),"utf8"),h=k(f.load(u));r.push(h);}catch{}}return C(r,n)}async function $(e,t){let s=t.match(/^T-(\d{4}-\d{2}-\d{2})-/);if(s){let r=o.join(e,g,T,s[1],`${t}.yaml`);if(i.existsSync(r))try{return k(f.load(i.readFileSync(r,"utf8")))}catch{return null}}return (await D(e,{status:"all",limit:9999})).find(r=>r.id===t)||null}async function K(e,t){let s=new Date,n=s.toISOString().slice(0,10),r=o.join(e,g,T,n);i.mkdirSync(r,{recursive:true});let a=j(e,n),d={id:a,blurb:t.blurb,priority:t.priority||"medium",status:"open",tags:t.tags||[],created:s.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 k(d),i.writeFileSync(o.join(r,`${a}.yaml`),f.dump(w(d),{lineWidth:-1,noRefs:true})),await I(e),a}async function v(e,t,s){let n=await $(e,t);if(!n)return false;let r=n.created.slice(0,10),a$1=o.join(e,g,T,r,`${t}.yaml`);if(!i.existsSync(a$1))return false;let{id:d,created:m,...l}=s;if(l.status!==void 0&&l.status!==n.status){if(!O(n.status,l.status))return a.component("#task-loader").warn("Illegal task status transition rejected",{taskId:t,from:n.status,to:l.status}),false;l.status==="in-progress"&&!n.started_at&&l.started_at===void 0&&(l.started_at=new Date().toISOString());}let c={...n,...l};if(i.writeFileSync(a$1,f.dump(w(c),{lineWidth:-1,noRefs:true})),await I(e),W(c.status)&&c.parentTaskId)try{let{settleParentIfComplete:u}=await import('./task-settlement-TATNPY6L.js');await u(e,c.parentTaskId,c.id);}catch(u){a.component("#task-loader").warn("Settlement after updateTask failed (non-fatal)",{taskId:t,parentTaskId:c.parentTaskId,error:u instanceof Error?u.message:String(u)});}return true}function W(e){return e==="done"||e==="shelved"}async function L(e,t){return v(e,t,{status:"done",completed:new Date().toISOString()})}async function M(e,t){return v(e,t,{status:"shelved",shelved:new Date().toISOString()})}async function I(e){let t=o.join(e,g,T),s=o.join(e,g),n=0,r=0,a=0,d=0,m=0,l=[];if(i.existsSync(t)){let u=i.readdirSync(t).filter(h=>/^\d{4}-\d{2}-\d{2}$/.test(h));for(let h of u){let x=o.join(t,h),P=i.readdirSync(x).filter(y=>y.endsWith(".yaml"));for(let y of P)try{let p=k(f.load(i.readFileSync(o.join(x,y),"utf8")));n++,p.status==="open"?r++:p.status==="in-progress"?a++:p.status==="done"?d++:p.status==="shelved"&&m++,!p.parentTaskId&&p.id&&l.push(p.id);}catch{}}}let c={version:"1.1",total:n,open:r,in_progress:a,done:d,shelved:m,roots:l,last_updated:new Date().toISOString()};return i.mkdirSync(s,{recursive:true}),i.writeFileSync(o.join(s,F),f.dump(c,{lineWidth:-1,noRefs:true})),c}function w(e){let t={};for(let[s,n]of Object.entries(e))n!==void 0&&(t[s]=n);return t}export{k as a,j as b,O as c,D as d,$ as e,K as f,v as g,L as h,M as i,I as j};