trybeacon 0.1.89 → 0.1.91

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 (151) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.next/BUILD_ID +1 -1
  3. package/.next/app-path-routes-manifest.json +17 -17
  4. package/.next/build-manifest.json +2 -2
  5. package/.next/prerender-manifest.json +3 -3
  6. package/.next/server/app/@modal/(.)settings/page.js +1 -1
  7. package/.next/server/app/@modal/(.)settings/page.js.nft.json +1 -1
  8. package/.next/server/app/@modal/(.)settings/page_client-reference-manifest.js +1 -1
  9. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  10. package/.next/server/app/_global-error.html +1 -1
  11. package/.next/server/app/_global-error.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  13. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  14. package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  15. package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  16. package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  17. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  18. package/.next/server/app/_not-found/page.js +1 -1
  19. package/.next/server/app/_not-found/page.js.nft.json +1 -1
  20. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  21. package/.next/server/app/_not-found.html +1 -1
  22. package/.next/server/app/_not-found.rsc +3 -3
  23. package/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
  24. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  25. package/.next/server/app/_not-found.segments/_index.segment.rsc +3 -3
  26. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  27. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  28. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  29. package/.next/server/app/api/linear/route.js +1 -17
  30. package/.next/server/app/api/linear/route.js.nft.json +1 -1
  31. package/.next/server/app/api/linear/scopes/route.js +1 -17
  32. package/.next/server/app/api/linear/scopes/route.js.nft.json +1 -1
  33. package/.next/server/app/api/linear/sync/route.js +1 -17
  34. package/.next/server/app/api/linear/sync/route.js.nft.json +1 -1
  35. package/.next/server/app/api/share/create/route.js +1 -1
  36. package/.next/server/app/docs/page.js +1 -1
  37. package/.next/server/app/docs/page.js.nft.json +1 -1
  38. package/.next/server/app/docs/page_client-reference-manifest.js +1 -1
  39. package/.next/server/app/docs.html +1 -1
  40. package/.next/server/app/docs.rsc +4 -4
  41. package/.next/server/app/docs.segments/@modal/__DEFAULT__.segment.rsc +1 -1
  42. package/.next/server/app/docs.segments/_full.segment.rsc +4 -4
  43. package/.next/server/app/docs.segments/_head.segment.rsc +1 -1
  44. package/.next/server/app/docs.segments/_index.segment.rsc +3 -3
  45. package/.next/server/app/docs.segments/_tree.segment.rsc +2 -2
  46. package/.next/server/app/docs.segments/docs/__PAGE__.segment.rsc +2 -2
  47. package/.next/server/app/docs.segments/docs.segment.rsc +1 -1
  48. package/.next/server/app/help/page.js +2 -2
  49. package/.next/server/app/help/page.js.nft.json +1 -1
  50. package/.next/server/app/help/page_client-reference-manifest.js +1 -1
  51. package/.next/server/app/help.html +1 -1
  52. package/.next/server/app/help.rsc +4 -4
  53. package/.next/server/app/help.segments/@modal/__DEFAULT__.segment.rsc +1 -1
  54. package/.next/server/app/help.segments/_full.segment.rsc +4 -4
  55. package/.next/server/app/help.segments/_head.segment.rsc +1 -1
  56. package/.next/server/app/help.segments/_index.segment.rsc +3 -3
  57. package/.next/server/app/help.segments/_tree.segment.rsc +2 -2
  58. package/.next/server/app/help.segments/help/__PAGE__.segment.rsc +2 -2
  59. package/.next/server/app/help.segments/help.segment.rsc +1 -1
  60. package/.next/server/app/index.html +1 -1
  61. package/.next/server/app/index.rsc +3 -3
  62. package/.next/server/app/index.segments/@modal/__DEFAULT__.segment.rsc +1 -1
  63. package/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  64. package/.next/server/app/index.segments/_full.segment.rsc +3 -3
  65. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  66. package/.next/server/app/index.segments/_index.segment.rsc +3 -3
  67. package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  68. package/.next/server/app/learn/page.js +3 -3
  69. package/.next/server/app/learn/page.js.nft.json +1 -1
  70. package/.next/server/app/learn/page_client-reference-manifest.js +1 -1
  71. package/.next/server/app/map/page.js +2 -2
  72. package/.next/server/app/map/page.js.nft.json +1 -1
  73. package/.next/server/app/map/page_client-reference-manifest.js +1 -1
  74. package/.next/server/app/page.js +1 -1
  75. package/.next/server/app/page.js.nft.json +1 -1
  76. package/.next/server/app/page_client-reference-manifest.js +1 -1
  77. package/.next/server/app/parked/page.js +1 -1
  78. package/.next/server/app/parked/page.js.nft.json +1 -1
  79. package/.next/server/app/parked/page_client-reference-manifest.js +1 -1
  80. package/.next/server/app/plan/page.js +3 -3
  81. package/.next/server/app/plan/page.js.nft.json +1 -1
  82. package/.next/server/app/plan/page_client-reference-manifest.js +1 -1
  83. package/.next/server/app/s/[token]/page.js +2 -2
  84. package/.next/server/app/s/[token]/page.js.nft.json +1 -1
  85. package/.next/server/app/s/[token]/page_client-reference-manifest.js +1 -1
  86. package/.next/server/app/settings/page.js +1 -1
  87. package/.next/server/app/settings/page.js.nft.json +1 -1
  88. package/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  89. package/.next/server/app-paths-manifest.json +17 -17
  90. package/.next/server/chunks/1495.js +18 -0
  91. package/.next/server/chunks/{7436.js → 1898.js} +3 -3
  92. package/.next/server/chunks/3825.js +1 -1
  93. package/.next/server/chunks/4378.js +1 -1
  94. package/.next/server/chunks/{5332.js → 473.js} +3 -3
  95. package/.next/server/chunks/5623.js +1 -1
  96. package/.next/server/chunks/799.js +1 -0
  97. package/.next/server/chunks/8709.js +8 -7
  98. package/.next/server/chunks/9683.js +1 -1
  99. package/.next/server/middleware-build-manifest.js +1 -1
  100. package/.next/server/pages/404.html +1 -1
  101. package/.next/server/pages/500.html +1 -1
  102. package/.next/server/server-reference-manifest.js +1 -1
  103. package/.next/server/server-reference-manifest.json +1 -1
  104. package/.next/static/chunks/2149-6eac4575d8a8281c.js +1 -0
  105. package/.next/static/chunks/{6283-20a6abe3453496ae.js → 3729-99f9edd66d1473ac.js} +3 -3
  106. package/.next/static/chunks/569-c70eb3d6c88282dc.js +1 -0
  107. package/.next/static/chunks/6818-051146427620d0f9.js +1 -0
  108. package/.next/static/chunks/8907-f1d97713a336fc2b.js +1 -0
  109. package/.next/static/chunks/app/@modal/(.)settings/page-77639f97e58859de.js +1 -0
  110. package/.next/static/chunks/app/docs/page-574e48b1b9519c80.js +1 -0
  111. package/.next/static/chunks/app/layout-6f04d1687adcd16e.js +1 -0
  112. package/.next/static/chunks/app/learn/page-ba0ec2cba32bd4e1.js +7 -0
  113. package/.next/static/chunks/app/map/page-a07e21cd94bae873.js +1 -0
  114. package/.next/static/chunks/app/plan/{page-809509b6149dbe6a.js → page-8e2a2edfb8fe69c5.js} +2 -2
  115. package/.next/static/chunks/app/s/[token]/page-b4dc768d9d1c6e29.js +1 -0
  116. package/.next/static/chunks/app/settings/page-c15764e1c2f54c5a.js +1 -0
  117. package/.next/static/css/b6c71ada5fa39830.css +1 -0
  118. package/.next/trace +47 -47
  119. package/.next/trace-build +1 -1
  120. package/dist/bin/ask.js +2 -2
  121. package/dist/bin/doctor.js +32 -30
  122. package/dist/bin/hook.js +31 -29
  123. package/dist/bin/mcp.js +41 -39
  124. package/dist/bin/plan.js +32 -30
  125. package/dist/bin/prompt.js +2 -2
  126. package/dist/bin/remove.js +3 -3
  127. package/dist/bin/stop-hook.js +4 -4
  128. package/dist/bin/uninstall.js +31 -29
  129. package/dist/lib/assets.js +20 -20
  130. package/dist/lib/codex-install.js +30 -28
  131. package/dist/lib/daemon-boot.js +11 -11
  132. package/dist/lib/global-install.js +31 -29
  133. package/drizzle/0013_quick_brother_voodoo.sql +1 -0
  134. package/drizzle/meta/0013_snapshot.json +1953 -0
  135. package/drizzle/meta/_journal.json +7 -0
  136. package/package.json +1 -1
  137. package/.next/server/chunks/2579.js +0 -1
  138. package/.next/static/chunks/2114-74736df56930b46c.js +0 -1
  139. package/.next/static/chunks/569-bfdcec83011428d3.js +0 -1
  140. package/.next/static/chunks/6579-1efe1d8b378c81a7.js +0 -1
  141. package/.next/static/chunks/6818-85b9a09bb74062ef.js +0 -1
  142. package/.next/static/chunks/app/@modal/(.)settings/page-58f068e66bf2fdf6.js +0 -1
  143. package/.next/static/chunks/app/docs/page-126c0e42c71731b2.js +0 -1
  144. package/.next/static/chunks/app/layout-a8bb07fb86893add.js +0 -1
  145. package/.next/static/chunks/app/learn/page-e6401368ea95de46.js +0 -7
  146. package/.next/static/chunks/app/map/page-374841ad0b729ce5.js +0 -1
  147. package/.next/static/chunks/app/s/[token]/page-57821fa904e9e018.js +0 -1
  148. package/.next/static/chunks/app/settings/page-435bfb2ac6f01744.js +0 -1
  149. package/.next/static/css/56890131dbc6daff.css +0 -1
  150. /package/.next/static/{CgztmUmahokH2oDzktISo → 5WK9Cj2xVeIioVVqODVpo}/_buildManifest.js +0 -0
  151. /package/.next/static/{CgztmUmahokH2oDzktISo → 5WK9Cj2xVeIioVVqODVpo}/_ssgManifest.js +0 -0
package/dist/bin/mcp.js CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var r9=Object.defineProperty;var a9=($)=>$;function t9($,Q){this[$]=a9.bind(null,Q)}var Y0=($,Q)=>{for(var Z in Q)r9($,Z,{get:Q[Z],enumerable:!0,configurable:!0,set:t9.bind(Q,Z)})};var t=($,Q)=>()=>($&&(Q=$($=0)),Q);import{existsSync as V0,mkdirSync as Y5,readdirSync as e9,readFileSync as e,rmSync as $$,writeFileSync as C0}from"fs";import{basename as Q$,dirname as b5,join as u}from"path";function m5(){return!!process.env.CLAUDE_PLUGIN_ROOT}function p5($=process.env.HOME||process.env.USERPROFILE||""){if(!$)return null;let Q=u($,".claude","plugins");if(!V0(Q))return null;let Z=[Q];for(let Y=0;Y<3&&Z.length;Y++){let V=[];for(let H of Z){let G=u(H,".claude-plugin","plugin.json");try{if(V0(G)&&JSON.parse(e(G,"utf8")).name==="beacon")return H}catch{}try{for(let W of e9(H,{withFileTypes:!0}))if(W.isDirectory())V.push(u(H,W.name))}catch{}}Z=V}return null}function c5($){return p5($)!==null}function Z$($){return/[\\/]\.claude[\\/]plugins[\\/]/.test($)}function c(){let $=process.env.BEACON_CLI_PATH;if($)return $;if(V0(z5))return z5;return"beacon"}function V5($){let Q=$.indexOf(" ");return Q===-1?$:$.slice(0,Q)}function O0($){let Q=c();if(Q==="beacon")return $;return $.replace(/^beacon(\s|$)/,`${Q}$1`)}function f($){let Q=V5($);return Q$(Q)+$.slice(Q.length)}function J$($=process.env.HOME||process.env.USERPROFILE||""){if(!$)return null;try{let Q=JSON.parse(e(u($,".claude","plugins","installed_plugins.json"),"utf8"));for(let Z of Object.keys(Q.plugins??{}))if(/^beacon@/.test(Z))return{key:Z,marketplace:Z.split("@")[1]??""}}catch{}return null}function D0($){try{return JSON.parse(e($,"utf8"))}catch{return{}}}function l5($,Q){Y5(b5($),{recursive:!0}),C0($,JSON.stringify(Q,null,2)+`
4
- `)}function A0($,Q){let Z=D0($);Z.hooks=Z.hooks??{},Z.hooks[Q.event]=Z.hooks[Q.event]??[];let Y=Z.hooks[Q.event];if(Y.some((H)=>H.matcher===Q.matcher&&H.hooks?.some((G)=>f(G.command)===f(Q.command))))return!1;return Y.push({matcher:Q.matcher,hooks:[{type:"command",command:Q.command}]}),l5($,Z),!0}function E0($,Q){return(D0($).hooks?.[Q.event]??[]).some((V)=>V.hooks?.some((H)=>f(H.command)===f(Q.command)))}function d5($,Q){let Y=D0($).hooks?.[Q.event]??[];for(let V of Y)for(let H of V.hooks??[])if(f(H.command)===f(Q.command))return H.command;return null}function I0($,Q){let Z=D0($),Y=Z.hooks?.[Q.event];if(!Y)return!1;let V=!1,H=Y.map((G)=>{let W=G.hooks?.length??0,j=(G.hooks??[]).filter((K)=>f(K.command)!==f(Q.command));if(j.length!==W)V=!0;return{...G,hooks:j}}).filter((G)=>(G.hooks??[]).length>0);if(!V)return!1;if(H.length)Z.hooks[Q.event]=H;else delete Z.hooks[Q.event];if(Z.hooks&&Object.keys(Z.hooks).length===0)delete Z.hooks;return l5($,Z),!0}function T0($,Q,Z,Y){let V=`${Q}
3
+ var a9=Object.defineProperty;var t9=($)=>$;function e9($,Q){this[$]=t9.bind(null,Q)}var Y0=($,Q)=>{for(var Z in Q)a9($,Z,{get:Q[Z],enumerable:!0,configurable:!0,set:e9.bind(Q,Z)})};var t=($,Q)=>()=>($&&(Q=$($=0)),Q);import{existsSync as V0,mkdirSync as H5,readdirSync as $$,readFileSync as e,rmSync as Q$,writeFileSync as O0}from"fs";import{basename as Z$,dirname as c5,join as g}from"path";function l5(){return!!process.env.CLAUDE_PLUGIN_ROOT}function d5($=process.env.HOME||process.env.USERPROFILE||""){if(!$)return null;let Q=g($,".claude","plugins");if(!V0(Q))return null;let Z=[Q];for(let Y=0;Y<3&&Z.length;Y++){let V=[];for(let H of Z){let G=g(H,".claude-plugin","plugin.json");try{if(V0(G)&&JSON.parse(e(G,"utf8")).name==="beacon")return H}catch{}try{for(let j of $$(H,{withFileTypes:!0}))if(j.isDirectory())V.push(g(H,j.name))}catch{}}Z=V}return null}function s5($){return d5($)!==null}function J$($){return/[\\/]\.claude[\\/]plugins[\\/]/.test($)}function h(){let $=process.env.BEACON_CLI_PATH;if($)return $;if(V0(m5))return m5;return"beacon"}function G5($){let Q=$.indexOf(" ");return Q===-1?$:$.slice(0,Q)}function X0($){let Q=h();if(Q==="beacon")return $;return $.replace(/^beacon(\s|$)/,`${Q}$1`)}function I($){let Q=G5($);return Z$(Q)+$.slice(Q.length)}function Y$($=process.env.HOME||process.env.USERPROFILE||""){if(!$)return null;try{let Q=JSON.parse(e(g($,".claude","plugins","installed_plugins.json"),"utf8"));for(let Z of Object.keys(Q.plugins??{}))if(/^beacon@/.test(Z))return{key:Z,marketplace:Z.split("@")[1]??""}}catch{}return null}function H0($){try{return JSON.parse(e($,"utf8"))}catch{return{}}}function j5($,Q){H5(c5($),{recursive:!0}),O0($,JSON.stringify(Q,null,2)+`
4
+ `)}function E0($,Q,Z={}){let Y=H0($);Y.hooks=Y.hooks??{},Y.hooks[Q.event]=Y.hooks[Q.event]??[];let V=Y.hooks[Q.event];if(V.some((G)=>G.hooks?.some((j)=>I(j.command)===I(Q.command)&&(Z.matchAnyMatcher||G.matcher===Q.matcher))))return!1;return V.push({matcher:Q.matcher,hooks:[{type:"command",command:Q.command}]}),j5($,Y),!0}function o5($,Q){let Z=H0($),Y=Z.hooks?.[Q.event];if(!Y)return!1;let V=Y.flatMap((j,U)=>(j.hooks??[]).flatMap((K,D)=>I(K.command)===I(Q.command)?[{matcherIndex:U,hookIndex:D,preferred:j.matcher===Q.matcher}]:[]));if(V.length<2)return!1;let H=V.find((j)=>j.preferred)??V[0],G=new Set(V.filter((j)=>j!==H).map((j)=>`${j.matcherIndex}:${j.hookIndex}`));return Z.hooks[Q.event]=Y.map((j,U)=>({...j,hooks:(j.hooks??[]).filter((K,D)=>!G.has(`${U}:${D}`))})).filter((j)=>(j.hooks??[]).length>0),j5($,Z),!0}function T0($,Q){return(H0($).hooks?.[Q.event]??[]).some((V)=>V.hooks?.some((H)=>I(H.command)===I(Q.command)))}function r5($,Q){let Y=H0($).hooks?.[Q.event]??[];for(let V of Y)for(let H of V.hooks??[])if(I(H.command)===I(Q.command))return H.command;return null}function k0($,Q){let Z=H0($),Y=Z.hooks?.[Q.event];if(!Y)return!1;let V=!1,H=Y.map((G)=>{let j=G.hooks?.length??0,U=(G.hooks??[]).filter((K)=>I(K.command)!==I(Q.command));if(U.length!==j)V=!0;return{...G,hooks:U}}).filter((G)=>(G.hooks??[]).length>0);if(!V)return!1;if(H.length)Z.hooks[Q.event]=H;else delete Z.hooks[Q.event];if(Z.hooks&&Object.keys(Z.hooks).length===0)delete Z.hooks;return j5($,Z),!0}function L0($,Q,Z,Y){let V=`${Q}
5
5
  ${Y.trim()}
6
6
  ${Z}`,H="";try{H=e($,"utf8")}catch{}let G=new RegExp(`${Q}[\\s\\S]*?${Z}`);H=G.test(H)?H.replace(G,V):H.trim()?`${H.trim()}
7
7
 
8
8
  ${V}
9
9
  `:`${V}
10
- `,Y5(b5($),{recursive:!0}),C0($,H.endsWith(`
10
+ `,H5(c5($),{recursive:!0}),O0($,H.endsWith(`
11
11
  `)?H:`${H}
12
- `)}function X0($,Q){try{return e($,"utf8").includes(Q)}catch{return!1}}function k0($,Q,Z){let Y="";try{Y=e($,"utf8")}catch{return!1}let V=new RegExp(`${Q}[\\s\\S]*?${Z}\\n?`);if(!V.test(Y))return!1;let H=Y.replace(V,"").replace(/\n{3,}/g,`
12
+ `)}function G0($,Q){try{return e($,"utf8").includes(Q)}catch{return!1}}function _0($,Q,Z){let Y="";try{Y=e($,"utf8")}catch{return!1}let V=new RegExp(`${Q}[\\s\\S]*?${Z}\\n?`);if(!V.test(Y))return!1;let H=Y.replace(V,"").replace(/\n{3,}/g,`
13
13
 
14
- `).trimStart();return C0($,H),!0}function L0($,Q,Z){let Y=u($,Q);Y5(Y,{recursive:!0});let V=u(Y,"SKILL.md");return C0(V,Z),V}function H0($,Q){return V0(u($,Q,"SKILL.md"))}function _0($,Q){let Z=u($,Q);if(!V0(Z))return!1;return $$(Z,{recursive:!0,force:!0}),!0}var h,z5="/Applications/Beacon.app/Contents/Resources/bin/beacon",R0=`## Beacon (visual planning panel)
14
+ `).trimStart();return O0($,H),!0}function I0($,Q,Z){let Y=g($,Q);H5(Y,{recursive:!0});let V=g(Y,"SKILL.md");return O0(V,Z),V}function j0($,Q){return V0(g($,Q,"SKILL.md"))}function y0($,Q){let Z=g($,Q);if(!V0(Z))return!1;return Q$(Z,{recursive:!0,force:!0}),!0}var z,m5="/Applications/Beacon.app/Contents/Resources/bin/beacon",A0=`## Beacon (visual planning panel)
15
15
 
16
16
  This machine has Beacon installed \u2014 a local visual planning surface for the terminal-side
17
17
  agent. Beacon proposes feature plans (roadmap features + DB schema + endpoints) via MCP,
@@ -35,23 +35,23 @@ the user reviews on a canvas at /plan, and feedback flows back as the next round
35
35
  Feedback bundles inline annotations on the markdown PLUS any edits the user made directly
36
36
  on the /map and /db boards (added features, attached subtasks, edited columns, new
37
37
  endpoints). Treat board edits as the user's revision intent \u2014 re-propose matching them
38
- verbatim. Do NOT implement until the tool returns approval.`;var y0=t(()=>{h=["beacon-init","beacon-refresh","beacon-plan","beacon-explain"]});var x0=1500,UZ=480000,S0=1800000,u0=3600000,s5=3000;var X5=()=>{};var W5={};Y0(W5,{stripAgentsPointer:()=>r5,repoMcpCliTarget:()=>K$,removeRepoAssets:()=>M$,installRefreshSkill:()=>V$,installPlanSkill:()=>X$,installInitSkill:()=>Y$,installExplainSkill:()=>H$,installCodexRepoSkills:()=>j$,ensureWorkflowDoc:()=>U$,ensureMcp:()=>W$,contextDocTargets:()=>U5,auditRepo:()=>B$,REFRESH_SKILL:()=>G5,PLAN_SKILL:()=>n5,INIT_SKILL:()=>H5,EXPLAIN_SKILL:()=>i5});import{existsSync as L,mkdirSync as G0,readFileSync as _,rmSync as f0,writeFileSync as I}from"fs";import{join as M}from"path";function Y$($){let Q=M($,".claude","skills","beacon-init");G0(Q,{recursive:!0});let Z=M(Q,"SKILL.md");return I(Z,H5),Z}function V$($){let Q=M($,".claude","skills","beacon-refresh");G0(Q,{recursive:!0});let Z=M(Q,"SKILL.md");return I(Z,G5),Z}function X$($){let Q=M($,".claude","skills","beacon-plan");G0(Q,{recursive:!0});let Z=M(Q,"SKILL.md");return I(Z,n5),Z}function H$($){let Q=M($,".claude","skills","beacon-explain");G0(Q,{recursive:!0});let Z=M(Q,"SKILL.md");return I(Z,i5),Z}function j$($){let Q=[];for(let Z of G$){let Y=M($,".agents","skills",Z.name);G0(Y,{recursive:!0});let V=M(Y,"SKILL.md");I(V,Z.body()),Q.push(V)}return Q}function U5($){let Q=M($,"AGENTS.md"),Z=M($,"CLAUDE.md"),Y=L(Q),V=L(Z);if(!Y&&!V)return[Q,Z];let H=[];if(Y)H.push(Q);if(V)H.push(Z);return H}function r5($){let Q=M($,"CLAUDE.md");if(!L(Q))return;let Z=_(Q,"utf8"),Y=Z.split(`
38
+ verbatim. Do NOT implement until the tool returns approval.`;var S0=t(()=>{z=["beacon-init","beacon-refresh","beacon-plan","beacon-explain"]});var x0=1500,KZ=480000,u0=1800000,f0=3600000,i5=3000;var U5=()=>{};var N5={};Y0(N5,{stripAgentsPointer:()=>e5,repoMcpCliTarget:()=>B$,removeRepoAssets:()=>N$,installRefreshSkill:()=>X$,installPlanSkill:()=>H$,installInitSkill:()=>V$,installExplainSkill:()=>G$,installCodexRepoSkills:()=>U$,ensureWorkflowDoc:()=>W$,ensureMcp:()=>K$,contextDocTargets:()=>q5,auditRepo:()=>q$,REFRESH_SKILL:()=>K5,PLAN_SKILL:()=>a5,INIT_SKILL:()=>W5,EXPLAIN_SKILL:()=>t5});import{existsSync as y,mkdirSync as U0,readFileSync as S,rmSync as g0,writeFileSync as k}from"fs";import{join as q}from"path";function V$($){let Q=q($,".claude","skills","beacon-init");U0(Q,{recursive:!0});let Z=q(Q,"SKILL.md");return k(Z,W5),Z}function X$($){let Q=q($,".claude","skills","beacon-refresh");U0(Q,{recursive:!0});let Z=q(Q,"SKILL.md");return k(Z,K5),Z}function H$($){let Q=q($,".claude","skills","beacon-plan");U0(Q,{recursive:!0});let Z=q(Q,"SKILL.md");return k(Z,a5),Z}function G$($){let Q=q($,".claude","skills","beacon-explain");U0(Q,{recursive:!0});let Z=q(Q,"SKILL.md");return k(Z,t5),Z}function U$($){let Q=[];for(let Z of j$){let Y=q($,".agents","skills",Z.name);U0(Y,{recursive:!0});let V=q(Y,"SKILL.md");k(V,Z.body()),Q.push(V)}return Q}function q5($){let Q=q($,"AGENTS.md"),Z=q($,"CLAUDE.md"),Y=y(Q),V=y(Z);if(!Y&&!V)return[Q,Z];let H=[];if(Y)H.push(Q);if(V)H.push(Z);return H}function e5($){let Q=q($,"CLAUDE.md");if(!y(Q))return;let Z=S(Q,"utf8"),Y=Z.split(`
39
39
  `).filter((V)=>!/^\s*@\.?\/?AGENTS\.md\s*$/.test(V)).join(`
40
- `).trim();if(Y&&Y!==Z.trim())I(Q,`${Y}
41
- `)}function U$($){let Q=new RegExp(`${h0}[\\s\\S]*?${j5}`);for(let Z of U5($)){let Y="";try{Y=_(Z,"utf8")}catch{}Y=Q.test(Y)?Y.replace(Q,o5):`${Y.trim()}
40
+ `).trim();if(Y&&Y!==Z.trim())k(Q,`${Y}
41
+ `)}function W$($){let Q=new RegExp(`${z0}[\\s\\S]*?${B5}`);for(let Z of q5($)){let Y="";try{Y=S(Z,"utf8")}catch{}Y=Q.test(Y)?Y.replace(Q,n5):`${Y.trim()}
42
42
 
43
- ${o5}
44
- `.trimStart(),I(Z,Y.endsWith(`
43
+ ${n5}
44
+ `.trimStart(),k(Z,Y.endsWith(`
45
45
  `)?Y:`${Y}
46
- `)}r5($)}function W$($){let Q=M($,".mcp.json"),Z={};try{Z=JSON.parse(_(Q,"utf8"))}catch{}Z.mcpServers=Z.mcpServers??{};let Y=Z.mcpServers.beacon;if(Y){if(!Y.timeout||Y.timeout<u0)return Y.timeout=u0,I(Q,JSON.stringify(Z,null,2)+`
47
- `),{path:Q,added:!1,updated:!0};return{path:Q,added:!1,updated:!1}}return Z.mcpServers.beacon={command:c(),args:["mcp"],timeout:u0},I(Q,JSON.stringify(Z,null,2)+`
48
- `),{path:Q,added:!0,updated:!1}}function K$($){try{return JSON.parse(_(M($,".mcp.json"),"utf8")).mcpServers?.beacon?.command??null}catch{return null}}function B$($){let Q=M($,".mcp.json"),Z=!1;try{Z=!!JSON.parse(_(Q,"utf8")).mcpServers?.beacon}catch{}let Y=U5($).some((V)=>{try{return _(V,"utf8").includes(h0)}catch{return!1}});return{repo:$,mcpRegistered:Z,workflowBlock:Y,skills:{"beacon-init":L(M($,".claude","skills","beacon-init","SKILL.md")),"beacon-refresh":L(M($,".claude","skills","beacon-refresh","SKILL.md"))},codexSkills:{"beacon-init":L(M($,".agents","skills","beacon-init","SKILL.md")),"beacon-refresh":L(M($,".agents","skills","beacon-refresh","SKILL.md"))}}}function M$($){let Q=[];for(let j of["beacon-init","beacon-refresh","beacon-db-design"]){let K=M($,".claude","skills",j);if(L(K))f0(K,{recursive:!0,force:!0}),Q.push(j)}for(let j of["beacon-init","beacon-refresh"]){let K=M($,".agents","skills",j);if(L(K))f0(K,{recursive:!0,force:!0}),Q.push(`codex:${j}`)}let Z=!1,Y=M($,".mcp.json");try{let j=JSON.parse(_(Y,"utf8"));if(j.mcpServers?.beacon){if(delete j.mcpServers.beacon,Z=!0,j.mcpServers&&Object.keys(j.mcpServers).length===0)delete j.mcpServers;if(Object.keys(j).length===0)f0(Y,{force:!0});else I(Y,JSON.stringify(j,null,2)+`
49
- `)}}catch{}let V=!1,H=new RegExp(`\\n?${h0}[\\s\\S]*?${j5}\\n?`);for(let j of[M($,"AGENTS.md"),M($,"CLAUDE.md")])try{let K=_(j,"utf8");if(H.test(K)){let p=K.replace(H,`
46
+ `)}e5($)}function K$($){let Q=q($,".mcp.json"),Z={};try{Z=JSON.parse(S(Q,"utf8"))}catch{}Z.mcpServers=Z.mcpServers??{};let Y=Z.mcpServers.beacon;if(Y){if(!Y.timeout||Y.timeout<f0)return Y.timeout=f0,k(Q,JSON.stringify(Z,null,2)+`
47
+ `),{path:Q,added:!1,updated:!0};return{path:Q,added:!1,updated:!1}}return Z.mcpServers.beacon={command:h(),args:["mcp"],timeout:f0},k(Q,JSON.stringify(Z,null,2)+`
48
+ `),{path:Q,added:!0,updated:!1}}function B$($){try{return JSON.parse(S(q($,".mcp.json"),"utf8")).mcpServers?.beacon?.command??null}catch{return null}}function q$($){let Q=q($,".mcp.json"),Z=!1;try{Z=!!JSON.parse(S(Q,"utf8")).mcpServers?.beacon}catch{}let Y=q5($).some((V)=>{try{return S(V,"utf8").includes(z0)}catch{return!1}});return{repo:$,mcpRegistered:Z,workflowBlock:Y,skills:{"beacon-init":y(q($,".claude","skills","beacon-init","SKILL.md")),"beacon-refresh":y(q($,".claude","skills","beacon-refresh","SKILL.md"))},codexSkills:{"beacon-init":y(q($,".agents","skills","beacon-init","SKILL.md")),"beacon-refresh":y(q($,".agents","skills","beacon-refresh","SKILL.md"))}}}function N$($){let Q=[];for(let U of["beacon-init","beacon-refresh","beacon-db-design"]){let K=q($,".claude","skills",U);if(y(K))g0(K,{recursive:!0,force:!0}),Q.push(U)}for(let U of["beacon-init","beacon-refresh"]){let K=q($,".agents","skills",U);if(y(K))g0(K,{recursive:!0,force:!0}),Q.push(`codex:${U}`)}let Z=!1,Y=q($,".mcp.json");try{let U=JSON.parse(S(Y,"utf8"));if(U.mcpServers?.beacon){if(delete U.mcpServers.beacon,Z=!0,U.mcpServers&&Object.keys(U.mcpServers).length===0)delete U.mcpServers;if(Object.keys(U).length===0)g0(Y,{force:!0});else k(Y,JSON.stringify(U,null,2)+`
49
+ `)}}catch{}let V=!1,H=new RegExp(`\\n?${z0}[\\s\\S]*?${B5}\\n?`);for(let U of[q($,"AGENTS.md"),q($,"CLAUDE.md")])try{let K=S(U,"utf8");if(H.test(K)){let D=K.replace(H,`
50
50
  `).replace(/\n{3,}/g,`
51
51
 
52
- `).trimStart();I(j,p.endsWith(`
53
- `)?p:`${p}
54
- `),V=!0}}catch{}let G=!1,W=M($,"CLAUDE.md");try{let j=_(W,"utf8"),K=j.replace(/^[ \t]*@AGENTS\.md[ \t]*\n?/m,"");if(K!==j){if(!K.trim())f0(W,{force:!0});else I(W,K);G=!0}}catch{}return{skillsRemoved:Q,mcpUnregistered:Z,agentsBlockRemoved:V,claudeImportRemoved:G}}var H5=`---
52
+ `).trimStart();k(U,D.endsWith(`
53
+ `)?D:`${D}
54
+ `),V=!0}}catch{}let G=!1,j=q($,"CLAUDE.md");try{let U=S(j,"utf8"),K=U.replace(/^[ \t]*@AGENTS\.md[ \t]*\n?/m,"");if(K!==U){if(!K.trim())g0(j,{force:!0});else k(j,K);G=!0}}catch{}return{skillsRemoved:Q,mcpUnregistered:Z,agentsBlockRemoved:V,claudeImportRemoved:G}}var W5=`---
55
55
  name: beacon-init
56
56
  description: Read this repository and map its architecture, schema, and roadmap into Beacon (the local visual planning panel). Use when the user runs /beacon-init, asks to "set up Beacon for this repo", or asks to initialize/bootstrap Beacon's map of this codebase.
57
57
  ---
@@ -98,7 +98,7 @@ beacon init-persist /tmp/beacon-init.json # or: beacon init-persist < /tmp/bea
98
98
  That one command wires the repo (writes \`.mcp.json\` + skills so your NEXT session gets the \`beacon_*\` tools natively, heals the global install), starts the Beacon daemon if it isn't running, registers + provisions this workspace, and POSTs your analysis to the same \`/api/init\` endpoint the MCP tool uses \u2014 so init completes in THIS session. Read the counts it prints and report them.
99
99
 
100
100
  After the tool (or \`beacon init-persist\`) returns, tell the user the counts (components / roadmap / tables / endpoints) and point them at the running Beacon panel.
101
- `,G5=`---
101
+ `,K5=`---
102
102
  name: beacon-refresh
103
103
  description: Re-survey the repo and update Beacon's architecture / schema / endpoints map after /beacon-init was already run \u2014 picks up new components, removed ones, schema changes, and new routes. Use when the user runs /beacon-refresh or asks to "refresh", "update", "re-sync", or "bring Beacon up to date" with the current code.
104
104
  ---
@@ -145,7 +145,7 @@ The one caveat: if the user manually edited an INIT-source node on the canvas (e
145
145
  If \`beacon_entities\` or \`beacon_init_persist\` isn't available, the Beacon panel isn't running in this repo. Tell the user to run \`beacon\` here first, then re-invoke /beacon-refresh.
146
146
 
147
147
  After the tool returns, report the final counts plus a one-line summary of the diff you surfaced.
148
- `,n5=`---
148
+ `,a5=`---
149
149
  name: beacon-plan
150
150
  description: Present your current plan or approach to the user on Beacon's /plan canvas for review \u2014 instead of asking for approval in prose. Use when the user says "present the plan", "show me the plan", "let me see it / the plan", or whenever you are about to end a turn asking whether to proceed with a plan, design, or approach.
151
151
  ---
@@ -194,7 +194,7 @@ If it returns feedback, revise and call it again.
194
194
  If \`beacon_present_plan\` isn't available, the panel isn't wired here \u2014 fall back to ExitPlanMode
195
195
  with the same \`\`\`beacon block (Claude Code only; Codex has no ExitPlanMode), or tell the user to
196
196
  run \`beacon\` in this repo once.
197
- `,i5=`---
197
+ `,t5=`---
198
198
  name: beacon-explain
199
199
  description: Teach the user part of THIS codebase as an interactive visual lesson on Beacon's /learn page \u2014 a concept map + plain-English narrative they can question \u2014 instead of a wall of text. Use when the user says "explain", "teach me", "walk me through", "how does X work", or "help me understand the Y category".
200
200
  ---
@@ -264,7 +264,7 @@ so the learner sees the table IN CONTEXT, wired to the code that uses it.
264
264
  Every answer must ADD understanding (rationale, trade-off) \u2014 never just restate the question. Expand
265
265
  the narrative or add nodes where it helps. Keep looping until the tool reports the user saved or closed
266
266
  the lesson.
267
- `,G$,h0="<!-- beacon:workflow:start -->",j5="<!-- beacon:workflow:end -->",o5;var K5=t(()=>{y0();X5();G$=[{name:"beacon-init",body:()=>H5},{name:"beacon-refresh",body:()=>G5}];o5=`${h0}
267
+ `,j$,z0="<!-- beacon:workflow:start -->",B5="<!-- beacon:workflow:end -->",n5;var M5=t(()=>{S0();U5();j$=[{name:"beacon-init",body:()=>W5},{name:"beacon-refresh",body:()=>K5}];n5=`${z0}
268
268
  ## Beacon \u2014 feature workflow
269
269
 
270
270
  This project uses Beacon (a local planning/visualization panel; run \`beacon\` to open it). When you start work on a FEATURE \u2014 whether referenced via an \`@beacon:feature://\u2026\` mention, an \`@beacon:note://\u2026\` note the user wrote in the Notes panel (treat its checkbox \`- [ ]\` todos as subtasks and order features by their dependencies), or just described in chat \u2014 follow these steps in order:
@@ -336,42 +336,44 @@ Register them all in that single batched call. If a plan added five features, th
336
336
  If the feature added or materially changed a REAL architectural component (a subsystem \u2014 NOT a file), also pass \`architecture: [{ title, domain, role, \u2026 }]\` so the Architecture map stays accurate. It upserts curated components by title; never list files as components. If you found a bug or something worth investigating in a component's code, add \`bugs: [{ note }]\` to its architecture entry \u2014 it renders as a bug flag on the node (attributed to the agent); identical open flags are not duplicated. Only flag what you actually saw in the code.
337
337
 
338
338
  Pull raw planning data anytime with \`beacon_entities\` (features / architecture / tables / endpoints).
339
- ${j5}`});import{mkdirSync as q$,renameSync as N$,rmSync as P$,writeFileSync as w$}from"fs";import{dirname as v$}from"path";function g0($,Q){q$(v$($),{recursive:!0});let Z=`${$}.tmp`;try{w$(Z,Q),N$(Z,$)}catch(Y){throw P$(Z,{force:!0}),Y}}function wZ($,Q,Z=!1){g0($,JSON.stringify(Q,null,Z?2:void 0))}var a5=()=>{};var G9={};Y0(G9,{setupCodexAssets:()=>T$,removeCodexMcp:()=>H9,removeCodexArtifacts:()=>L$,parseTomlBeacon:()=>V9,nodeWhich:()=>$9,hasCodexMcp:()=>N5,ensureCodexMcp:()=>X9,commandExists:()=>Q9,codexMcpProblem:()=>E$,codexMcpCliTarget:()=>I$,codexDetected:()=>Z9,auditCodex:()=>k$,CODEX_HOOKS:()=>p0});import{accessSync as F$,constants as C$,readFileSync as U0}from"fs";import{homedir as O$}from"os";import{delimiter as R$,join as Q0}from"path";function t5(){return process.env.HOME||process.env.USERPROFILE||O$()}function $9($,Q=process.env.PATH||"",Z=D$){if(!$)return null;for(let Y of Q.split(R$)){if(!Y)continue;let V=Q0(Y,$);if(Z(V))return V}return null}function D$($){try{return F$($,C$.X_OK),!0}catch{return!1}}function Q9($){if(typeof Bun<"u"&&typeof Bun.which==="function")return Bun.which($)!==null;return $9($)!==null}function Z9(){if(process.env.BEACON_CODEX==="1")return!0;if(process.env.BEACON_CODEX==="0")return!1;if(B5===void 0)B5=Q9("codex");return B5}function V9($){let Q={},Z=!1;for(let Y of $.split(`
340
- `)){let V=Y.trim();if(!V||V.startsWith("#"))continue;let H=/^\[([^\]]+)\]/.exec(V);if(H){if(Z=H[1].trim()==="mcp_servers.beacon",Z)Q.mcp_servers=Q.mcp_servers??{},Q.mcp_servers.beacon=Q.mcp_servers.beacon??{};continue}if(Z){let G=/^command\s*=\s*["']([^"']*)["']/.exec(V);if(G)Q.mcp_servers.beacon.command=G[1]}}return Q}function $0($){try{if(typeof Bun<"u"&&Bun.TOML?.parse)return Bun.TOML.parse($);return V9($)}catch{return null}}function N5(){try{return Boolean($0(U0(l(),"utf8"))?.mcp_servers?.beacon)}catch{return!1}}function E$(){let $="";try{$=U0(l(),"utf8")}catch{return null}let Q=$0($);if(!Q)return`~/.codex/config.toml does not parse \u2014 ${j0}`;if(Q.mcp_servers?.beacon)return null;if(/^\s*mcp_servers\s*=/m.test($))return`mcp_servers is an inline table \u2014 ${j0}`;return null}function X9(){let $="",Q=!1;try{$=U0(l(),"utf8"),Q=!0}catch{}if(Q){let H=$0($);if(!H)return{added:!1,error:`~/.codex/config.toml does not parse \u2014 ${j0}`};if(H.mcp_servers?.beacon)return{added:!1};if(/^\s*mcp_servers\s*=/m.test($))return{added:!1,error:`mcp_servers is an inline table \u2014 ${j0}`}}let Z=!$?"":$.endsWith(`
339
+ ${B5}`});import{mkdirSync as M$,renameSync as P$,rmSync as w$,writeFileSync as v$}from"fs";import{dirname as F$}from"path";function W0($,Q){M$(F$($),{recursive:!0});let Z=`${$}.tmp`;try{v$(Z,Q),P$(Z,$)}catch(Y){throw w$(Z,{force:!0}),Y}}function FZ($,Q,Z=!1){W0($,JSON.stringify(Q,null,Z?2:void 0))}var $9=()=>{};var j9={};Y0(j9,{setupCodexAssets:()=>_$,removeCodexMcp:()=>G9,removeCodexArtifacts:()=>y$,parseTomlBeacon:()=>X9,nodeWhich:()=>J9,hasCodexMcp:()=>v5,ensureCodexMcp:()=>H9,commandExists:()=>Y9,codexMcpProblem:()=>T$,codexMcpCliTarget:()=>L$,codexDetected:()=>V9,auditCodex:()=>I$,CODEX_HOOKS:()=>d0});import{accessSync as C$,constants as R$,readFileSync as B0}from"fs";import{homedir as D$}from"os";import{delimiter as O$,join as Q0}from"path";function Q9(){return process.env.HOME||process.env.USERPROFILE||D$()}function J9($,Q=process.env.PATH||"",Z=A$){if(!$)return null;for(let Y of Q.split(O$)){if(!Y)continue;let V=Q0(Y,$);if(Z(V))return V}return null}function A$($){try{return C$($,R$.X_OK),!0}catch{return!1}}function Y9($){if(typeof Bun<"u"&&typeof Bun.which==="function")return Bun.which($)!==null;return J9($)!==null}function V9(){if(process.env.BEACON_CODEX==="1")return!0;if(process.env.BEACON_CODEX==="0")return!1;if(P5===void 0)P5=Y9("codex");return P5}function X9($){let Q={},Z=!1;for(let Y of $.split(`
340
+ `)){let V=Y.trim();if(!V||V.startsWith("#"))continue;let H=/^\[([^\]]+)\]/.exec(V);if(H){if(Z=H[1].trim()==="mcp_servers.beacon",Z)Q.mcp_servers=Q.mcp_servers??{},Q.mcp_servers.beacon=Q.mcp_servers.beacon??{};continue}if(Z){let G=/^command\s*=\s*["']([^"']*)["']/.exec(V);if(G)Q.mcp_servers.beacon.command=G[1]}}return Q}function $0($){try{if(typeof Bun<"u"&&Bun.TOML?.parse)return Bun.TOML.parse($);return X9($)}catch{return null}}function v5(){try{return Boolean($0(B0(b(),"utf8"))?.mcp_servers?.beacon)}catch{return!1}}function T$(){let $="";try{$=B0(b(),"utf8")}catch{return null}let Q=$0($);if(!Q)return`~/.codex/config.toml does not parse \u2014 ${K0}`;if(Q.mcp_servers?.beacon)return null;if(/^\s*mcp_servers\s*=/m.test($))return`mcp_servers is an inline table \u2014 ${K0}`;return null}function k$($){let Q=$.split(`
341
+ `),Z=Q.indexOf(c0),Y=Q.indexOf(l0,Z);if(Z===-1||Y===-1)return null;let V=Q.findIndex((j,U)=>U>Z&&U<Y&&j.trim()==="[mcp_servers.beacon]");if(V===-1)return null;let H=V+1;while(H<Y&&!/^\s*\[/.test(Q[H]))H++;let G=Q.findIndex((j,U)=>U>V&&U<H&&/^\s*command\s*=/.test(j));if(G===-1)return null;return Q[G]=`command = ${JSON.stringify(h())}`,Q.join(`
342
+ `)}function H9(){let $="",Q=!1;try{$=B0(b(),"utf8"),Q=!0}catch{}if(Q){let H=$0($);if(!H)return{added:!1,error:`~/.codex/config.toml does not parse \u2014 ${K0}`};if(H.mcp_servers?.beacon){let G=k$($);if(G&&G!==$)W0(b(),G);return{added:!1}}if(/^\s*mcp_servers\s*=/m.test($))return{added:!1,error:`mcp_servers is an inline table \u2014 ${K0}`}}let Z=!$?"":$.endsWith(`
341
343
  `)?`
342
344
  `:`
343
345
 
344
- `,Y=$+Z+A$();if($0(Y)?.mcp_servers?.beacon?.command!==c())return{added:!1,error:`could not safely append [mcp_servers.beacon] \u2014 ${j0}`};return g0(l(),Y),{added:!0}}function I$(){try{return $0(U0(l(),"utf8"))?.mcp_servers?.beacon?.command??null}catch{return null}}function H9(){let $="";try{$=U0(l(),"utf8")}catch{return{removed:!1}}let Q=$.split(`
345
- `),Z=Q.indexOf(J9);if(Z===-1)return{removed:!1,skipped:N5()};let Y=Q.indexOf(Y9,Z);if(Y===-1)return{removed:!1,skipped:!0};Q.splice(Z,Y-Z+1);let V=Q.join(`
346
+ `,Y=$+Z+E$();if($0(Y)?.mcp_servers?.beacon?.command!==h())return{added:!1,error:`could not safely append [mcp_servers.beacon] \u2014 ${K0}`};return W0(b(),Y),{added:!0}}function L$(){try{return $0(B0(b(),"utf8"))?.mcp_servers?.beacon?.command??null}catch{return null}}function G9(){let $="";try{$=B0(b(),"utf8")}catch{return{removed:!1}}let Q=$.split(`
347
+ `),Z=Q.indexOf(c0);if(Z===-1)return{removed:!1,skipped:v5()};let Y=Q.indexOf(l0,Z);if(Y===-1)return{removed:!1,skipped:!0};let V=Q.findIndex((j,U)=>U>Z&&U<Y&&j.trim()==="[mcp_servers.beacon]");if(V===-1)return{removed:!1,skipped:!0};let H=V+1;while(H<Y&&!/^\s*\[/.test(Q[H]))H++;Q.splice(V,H-V),Q.splice(Q.indexOf(l0),1),Q.splice(Q.indexOf(c0),1);let G=Q.join(`
346
348
  `).replace(/\n{3,}/g,`
347
349
 
348
- `).replace(/^\n+/,"");if($0(V)===null)return{removed:!1,skipped:!0};return g0(l(),V),{removed:!0}}async function T$(){let{INIT_SKILL:$,REFRESH_SKILL:Q,PLAN_SKILL:Z,EXPLAIN_SKILL:Y}=await Promise.resolve().then(() => (K5(),W5)),V={"beacon-init":$,"beacon-refresh":Q,"beacon-plan":Z,"beacon-explain":Y},H=[];for(let K of h){if(!H0(b0(),K))H.push(K);L0(b0(),K,V[K])}let G=0;for(let K of p0)if(A0(q5(),{event:K.event,matcher:K.matcher,command:O0(K.command)}))G++;let W=X0(z0(),m0);T0(z0(),m0,e5,R0);let j=X9();return{skillsAdded:H,hooksAdded:G,agentsMdBlockTouched:!W,mcp:j}}function k$(){let $={};for(let Z of h)$[Z]=H0(b0(),Z);let Q={};for(let Z of p0)Q[Z.event]=E0(q5(),{event:Z.event,command:Z.command});return{detected:Z9(),skills:$,hooks:Q,agentsMdBlock:X0(z0(),m0),mcp:N5()}}function L$(){let $=[];for(let V of h)if(_0(b0(),V))$.push(V);let Q=0;for(let V of p0)if(I0(q5(),{event:V.event,command:V.command}))Q++;let Z=k0(z0(),m0,e5),Y=H9();return{skillsRemoved:$,hooksRemoved:Q,agentsMdBlockRemoved:Z,mcpRemoved:Y.removed,mcpSkipped:Y.skipped}}var M5=()=>Q0(t5(),".codex"),q5=()=>Q0(M5(),"hooks.json"),l=()=>Q0(M5(),"config.toml"),z0=()=>Q0(M5(),"AGENTS.md"),b0=()=>Q0(t5(),".agents","skills"),m0="<!-- beacon:global:start -->",e5="<!-- beacon:global:end -->",p0,B5,J9="# beacon:start (managed by Beacon \u2014 `beacon uninstall` removes this block)",Y9="# beacon:end",A$=()=>`${J9}
350
+ `).replace(/^\n+/,"");if($0(G)===null)return{removed:!1,skipped:!0};return W0(b(),G),{removed:!0}}async function _$(){let{INIT_SKILL:$,REFRESH_SKILL:Q,PLAN_SKILL:Z,EXPLAIN_SKILL:Y}=await Promise.resolve().then(() => (M5(),N5)),V={"beacon-init":$,"beacon-refresh":Q,"beacon-plan":Z,"beacon-explain":Y},H=[];for(let K of z){if(!j0(p0(),K))H.push(K);I0(p0(),K,V[K])}let G=0;for(let K of d0){let D=K.event==="UserPromptSubmit"||K.event==="Stop";if(D)o5(h0(),{event:K.event,matcher:K.matcher,command:X0(K.command)});if(E0(h0(),{event:K.event,matcher:K.matcher,command:X0(K.command)},{matchAnyMatcher:D}))G++}let j=G0(b0(),m0);L0(b0(),m0,Z9,A0);let U=H9();return{skillsAdded:H,hooksAdded:G,agentsMdBlockTouched:!j,mcp:U}}function I$(){let $={};for(let Z of z)$[Z]=j0(p0(),Z);let Q={};for(let Z of d0)Q[Z.event]=T0(h0(),{event:Z.event,command:Z.command});return{detected:V9(),skills:$,hooks:Q,agentsMdBlock:G0(b0(),m0),mcp:v5()}}function y$(){let $=[];for(let V of z)if(y0(p0(),V))$.push(V);let Q=0;for(let V of d0)if(k0(h0(),{event:V.event,command:V.command}))Q++;let Z=_0(b0(),m0,Z9),Y=G9();return{skillsRemoved:$,hooksRemoved:Q,agentsMdBlockRemoved:Z,mcpRemoved:Y.removed,mcpSkipped:Y.skipped}}var w5=()=>Q0(Q9(),".codex"),h0=()=>Q0(w5(),"hooks.json"),b=()=>Q0(w5(),"config.toml"),b0=()=>Q0(w5(),"AGENTS.md"),p0=()=>Q0(Q9(),".agents","skills"),m0="<!-- beacon:global:start -->",Z9="<!-- beacon:global:end -->",d0,P5,c0="# beacon:start (managed by Beacon \u2014 `beacon uninstall` removes this block)",l0="# beacon:end",E$=()=>`${c0}
349
351
  [mcp_servers.beacon]
350
- command = "${c()}"
352
+ command = "${h()}"
351
353
  args = ["mcp"]
352
- ${Y9}
353
- `,j0="add it manually: codex mcp add beacon -- beacon mcp";var j9=t(()=>{y0();a5();p0=[{event:"PostToolUse",matcher:"apply_patch",command:"beacon hook",description:"Report file edits to Beacon's active feature so the map stays fresh."},{event:"UserPromptSubmit",matcher:"*",command:"beacon prompt",description:"On feature-y prompts in a Beacon-wired repo, remind the agent to run the context\u2192propose\u2192describe loop (no-op otherwise)."},{event:"Stop",matcher:"*",command:"beacon stop-hook",description:"When the agent ends a turn asking for plan approval in prose, nudge it to present the plan on Beacon's /plan canvas."}]});var q9={};Y0(q9,{provisionDb:()=>QQ});import{createClient as l$}from"@libsql/client";import{drizzle as d$}from"drizzle-orm/libsql";import{migrate as s$}from"drizzle-orm/libsql/migrator";import{readMigrationFiles as o$}from"drizzle-orm/migrator";import{dirname as C5,join as n$}from"path";import{fileURLToPath as i$}from"url";async function s0($,Q){return(await $.execute({sql:"SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?",args:[Q]})).rows.length>0}async function e$($,Q){let Z=await $.execute(`PRAGMA table_info("${Q}")`);return new Set(Z.rows.map((Y)=>String(Y.name)))}async function M9($){if(!await s0($,"__drizzle_migrations"))return 0;let Q=await $.execute('SELECT count(*) AS n FROM "__drizzle_migrations"');return Number(Q.rows[0]?.n??0)}async function $Q($){for(let[Q,Z]of Object.entries(t$)){if(!await s0($,Q))continue;let Y=await e$($,Q);for(let V of Z){if(!Y.has(V))continue;await $.execute(`UPDATE "${Q}" SET "${V}" = CAST((julianday("${V}") - 2440587.5) * 86400000 AS INTEGER) WHERE typeof("${V}") = 'text'`)}}}async function QQ($,Q=a$){let Z=l$({url:$});try{await Z.execute("PRAGMA journal_mode = WAL;"),await Z.execute("PRAGMA foreign_keys = ON;"),await Z.execute("PRAGMA busy_timeout = 5000;");let Y=await s0(Z,"__drizzle_migrations"),V=await s0(Z,"Node"),H=!1;if(V&&!Y){let W=o$({migrationsFolder:Q})[0];if(W)await Z.execute('CREATE TABLE IF NOT EXISTS "__drizzle_migrations" (id SERIAL PRIMARY KEY, hash text NOT NULL, created_at numeric)'),await Z.execute({sql:'INSERT INTO "__drizzle_migrations" ("hash", "created_at") VALUES (?, ?)',args:[W.hash,W.folderMillis]}),H=!0}let G=await M9(Z);if(await s$(d$(Z),{migrationsFolder:Q}),await M9(Z)>G)H=!0;return await $Q(Z),{migrated:H}}finally{Z.close()}}var r$,a$,t$;var N9=t(async()=>{r$=C5(C5(C5(i$(import.meta.url)))),a$=process.env.BEACON_MIGRATIONS_DIR||n$(r$,"drizzle"),t$={Node:["createdAt","updatedAt"],Note:["createdAt","updatedAt"],DbTable:["createdAt","updatedAt"],Endpoint:["createdAt","updatedAt"],DraftTable:["createdAt"],SyncState:["codeGraphSyncedAt","updatedAt"],AppSetting:["updatedAt"],ProjectMeta:["updatedAt"],CodeFile:["updatedAt"]}});y0();import{existsSync as _$}from"fs";import{homedir as y$}from"os";import{join as c0}from"path";function x$(){return process.env.HOME||process.env.USERPROFILE||y$()}var l0=()=>c0(x$(),".claude"),P5=()=>c0(l0(),"skills"),d0=()=>c0(l0(),"settings.json"),w5=()=>c0(l0(),"CLAUDE.md"),v5="<!-- beacon:global:start -->",U9="<!-- beacon:global:end -->";var S$=R0,F5=[{event:"PreToolUse",matcher:"Edit|Write|MultiEdit",command:"beacon guard",description:"Gate edits against the active plan's scope contract: in-scope \u2192 allow, off-scope \u2192 ask the user to authorize. Fail-open when there's no active contract."},{event:"PostToolUse",matcher:"Edit|Write|MultiEdit",command:"beacon hook",description:"Report file edits to Beacon's active feature so the map stays fresh."},{event:"PermissionRequest",matcher:"ExitPlanMode",command:"beacon plan",description:"Pipe the agent's plan markdown into Beacon's /plan canvas for review."},{event:"PreToolUse",matcher:"AskUserQuestion",command:"beacon ask",description:"Surface the agent's AskUserQuestion in Beacon's modal; your pick flows back as the answer (falls through to the terminal if Beacon isn't open)."},{event:"PermissionRequest",matcher:"Edit|Write|MultiEdit|Bash|NotebookEdit",command:"beacon ask",description:"Surface edit/create/run approvals in Beacon's modal; your allow/deny flows back (falls through to the terminal prompt if Beacon isn't open)."},{event:"UserPromptSubmit",matcher:"*",command:"beacon prompt",description:"On feature-y prompts in a Beacon-wired repo, remind the agent to run the context\u2192propose\u2192describe loop (no-op otherwise)."},{event:"Stop",matcher:"*",command:"beacon stop-hook",description:"When the agent ends a turn asking for plan approval in prose (instead of presenting it), nudge it to present the plan on Beacon's /plan canvas. Bounded by stop_hook_active \u2014 at most one nudge."}];function u$($,Q){return L0(P5(),$,Q)}function W9($){return H0(P5(),$)}function f$($){return _0(P5(),$)}function h$($){return A0(d0(),$)}function g$($){return E0(d0(),$)}function z$($){return I0(d0(),$)}function b$($){T0(w5(),v5,U9,$)}function K9(){return X0(w5(),v5)}function m$(){return k0(w5(),v5,U9)}function kZ(){let $={};for(let Z of h)$[Z]=W9(Z);let Q={};for(let Z of F5)Q[Z.event]=g$({event:Z.event,command:Z.command});return{homeExists:_$(l0()),skills:$,hooks:Q,claudeMdBlock:K9()}}function LZ(){let $=d5(d0(),{event:"PostToolUse",command:"beacon hook"});return $?V5($):null}async function p$(){let{INIT_SKILL:$,REFRESH_SKILL:Q,PLAN_SKILL:Z,EXPLAIN_SKILL:Y}=await Promise.resolve().then(() => (K5(),W5)),V={"beacon-init":$,"beacon-refresh":Q,"beacon-plan":Z,"beacon-explain":Y},H=[];for(let j of h){if(!W9(j))H.push(j);u$(j,V[j])}let G=0;for(let j of F5)if(h$({event:j.event,matcher:j.matcher,command:O0(j.command)}))G++;let W=K9();return b$(S$),{skillsAdded:H,hooksAdded:G,claudeMdBlockTouched:!W}}async function B9(){if(m5())return{ok:!0,skipped:"plugin",skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1};let $;if(c5()){try{c$()}catch{}$={ok:!0,skipped:"plugin-present",skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1}}else try{$={ok:!0,...await p$()}}catch(Q){$={ok:!1,error:Q instanceof Error?Q.message:String(Q),skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1}}try{let Q=await Promise.resolve().then(() => (j9(),G9));if(Q.codexDetected())$.codex={ok:!0,...await Q.setupCodexAssets()}}catch(Q){$.codex={ok:!1,error:Q instanceof Error?Q.message:String(Q),skillsAdded:[],hooksAdded:0,agentsMdBlockTouched:!1,mcp:{added:!1}}}return $}function c$(){let $=[];for(let Y of h)if(f$(Y))$.push(Y);let Q=0;for(let Y of F5)if(z$(Y))Q++;let Z=m$();return{skillsRemoved:$,hooksRemoved:Q,claudeMdBlockRemoved:Z}}import{AsyncLocalStorage as ZQ}from"async_hooks";import{spawnSync as JQ}from"child_process";import{createHash as YQ}from"crypto";import{existsSync as w9,mkdirSync as W0,readFileSync as R5,writeFileSync as D5}from"fs";import{homedir as v9}from"os";import{basename as VQ,join as g,parse as XQ,resolve as P9}from"path";function y(){return process.env.BEACON_HOME||g(v9(),".beacon")}function A5(){return g(y(),"workspaces.json")}function d($){return YQ("sha256").update($).digest("hex").slice(0,12)}function E5($=process.cwd()){let Q=JQ("git",["rev-parse","--show-toplevel"],{cwd:$,stdio:["ignore","pipe","ignore"]});if(Q.status===0){let Z=Q.stdout?.toString().trim();if(Z)return Z}return $}function o0($){let Q=P9($);return Q!==P9(v9())&&Q!==XQ(Q).root}function F9(){return g(y(),"deleted.json")}function I5(){try{let $=JSON.parse(R5(F9(),"utf8"));return Array.isArray($)?$:[]}catch{return[]}}function C9($){W0(y(),{recursive:!0}),D5(F9(),JSON.stringify($,null,2))}function n0($){return I5().includes($)}function lZ($){let Q=I5();if(!Q.includes($))C9([...Q,$])}function HQ($){let Q=I5();if(Q.includes($))C9(Q.filter((Z)=>Z!==$))}function i0($){return g(y(),$)}function T5($){return`file:${g(i0($),"db.sqlite")}`}function K0(){try{let $=JSON.parse(R5(A5(),"utf8"));return Array.isArray($)?$:[]}catch{return[]}}function k5($){W0(y(),{recursive:!0}),D5(A5(),JSON.stringify($,null,2))}function r0(){return K0().sort(($,Q)=>Q.lastOpenedAt.localeCompare($.lastOpenedAt))}function s($){return K0().find((Q)=>Q.id===$)??null}function a0($,Q,Z=new Date().toISOString()){if(!o0($))throw Error(`beacon: refusing to register a non-repo path as a workspace: ${$}`);let Y=d($);if(n0(Y))throw Error(`beacon: workspace ${Y} (${$}) was deleted \u2014 run \`beacon\` or /beacon-init to re-add it`);let V=K0(),H=V.find((j)=>j.id===Y),G={id:Y,path:$,name:Q||H?.name||VQ($),lastOpenedAt:Z},W=[G,...V.filter((j)=>j.id!==Y)];return W0(i0(Y),{recursive:!0}),k5(W),G}function dZ($,Q){return HQ(d($)),a0($,Q)}function sZ($,Q=new Date().toISOString()){let Z=K0(),Y=Z.find((V)=>V.id===$);if(!Y)return;Y.lastOpenedAt=Q,k5(Z)}function oZ($){if(k5(K0().filter((Q)=>Q.id!==$)),B0()===$)GQ(r0()[0]?.id??null)}function O9(){return g(y(),"active")}function B0(){try{return R5(O9(),"utf8").trim()||null}catch{return null}}function GQ($){W0(y(),{recursive:!0}),D5(O9(),$??"")}function nZ(){let $=B0();return $?s($):null}function iZ(){let $=L5()??B0();return $?s($):null}function rZ($){return s($)?.path??null}function aZ(){return w9(A5())}var R9="beacon_ws";function D9($,Q){let Z=$.headers.get("cookie");if(!Z)return null;for(let Y of Z.split(";")){let V=Y.indexOf("=");if(V===-1)continue;if(Y.slice(0,V).trim()===Q)return decodeURIComponent(Y.slice(V+1).trim())}return null}function tZ($){let Q=$.headers.get("x-beacon-workspace");if(Q&&s(Q))return Q;let Z=D9($,R9);if(Z&&s(Z))return Z;return jQ()}function jQ(){let $=r0();return $.length===1?$[0].id:null}var t0="x-beacon-workspace-path";function eZ($=process.cwd()){let Q=E5($);return{"x-beacon-workspace":d(Q),[t0]:Q}}async function $1($){let Q=$.headers.get("x-beacon-workspace");if(Q&&s(Q))return Q;let Z=$.headers.get(t0);if(Z&&o0(Z)&&!n0(d(Z))&&(!Q||d(Z)===Q)){let V=a0(Z);return await _5(V.id),V.id}let Y=D9($,R9);if(Y&&s(Y))return Y;return null}var A9=new ZQ;function UQ($,Q){return $?A9.run($,Q):Q()}function L5(){return A9.getStore()??null}var O5=new Set;function Q1($){O5.delete(g(i0($),"db.sqlite"))}async function _5($){let Q=i0($),Z=g(Q,"db.sqlite"),Y=w9(Z);if(Y&&O5.has(Z))return{ok:!0,created:!1,migrated:!1};try{W0(Q,{recursive:!0});let{provisionDb:V}=await N9().then(() => q9),H=await V(T5($));return O5.add(Z),{ok:!0,created:!Y,migrated:Y&&H.migrated}}catch(V){return{ok:!1,created:!1,migrated:!1,error:V instanceof Error?V.message:String(V)}}}import{connect as WQ}from"net";var E9=4319;function KQ($,Q,Z=400){return new Promise((Y)=>{let V=WQ({host:$,port:Q}),H=!1,G=(W)=>{if(H)return;H=!0,V.destroy(),Y(W)};V.once("connect",()=>G(!0)),V.once("error",()=>G(!1)),V.setTimeout(Z,()=>G(!1))})}async function BQ($){for(let Q of["127.0.0.1","::1"])if(await KQ(Q,$))return!1;return!0}async function Y1($,Q=20){for(let Z=$;Z<$+Q;Z++)if(await BQ(Z))return Z;return $}import{McpServer as YZ,ResourceTemplate as h5}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as VZ}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as J}from"zod";import{z as B}from"zod";var MQ=new Set(["GET","HEAD","OPTIONS"]);function I9($){return MQ.has($.trim().toUpperCase())?"read":"write"}var qQ=B.preprocess(($)=>{if(typeof $==="string"){let[Q,...Z]=$.trim().split(/\s+/);return{name:Q,type:Z.join(" ")||"text"}}return $},B.object({name:B.string().trim().min(1),type:B.string().trim().min(1),isPk:B.boolean().optional(),isFk:B.boolean().optional(),nullable:B.boolean().optional(),note:B.string().nullish()})),T9=B.object({name:B.string().trim().min(1),domain:B.string().nullish(),description:B.string().nullish(),columns:B.array(qQ).default([])}),k9=B.object({fromTable:B.string(),fromColumn:B.string(),toTable:B.string(),toColumn:B.string(),label:B.string().nullish()}),L9=B.object({method:B.string().trim().min(1),path:B.string().trim().min(1),domain:B.string().nullish(),description:B.string().nullish(),uses:B.array(B.object({table:B.string().trim().min(1),access:B.string().optional()})).default([])}).transform(($)=>({...$,uses:$.uses.map((Q)=>({...Q,access:Q.access??I9($.method)}))})),j1=B.object({tables:B.array(T9).default([]),relations:B.array(k9).default([]),endpoints:B.array(L9).default([])});import{z as D}from"zod";import{and as y1,eq as x1,inArray as S1}from"drizzle-orm";import{drizzle as mQ}from"drizzle-orm/libsql";import{createClient as pQ}from"@libsql/client";var y5={};Y0(y5,{workspaceFlag:()=>RQ,tag:()=>Z0,syncState:()=>FQ,projectMeta:()=>OQ,planContract:()=>DQ,note:()=>wQ,nodeTags:()=>o,nodeFile:()=>M0,node:()=>N,endpointTable:()=>i,endpoint:()=>J0,edge:()=>z,draftTable:()=>T,draftRelation:()=>r,draftColumn:()=>P0,dbTable:()=>O,dbRelation:()=>n,dbColumn:()=>N0,codeFileEdge:()=>a,codeFile:()=>x,bugFlag:()=>q0,boardAnnotation:()=>vQ,appSetting:()=>CQ});import{sqliteTable as P,index as q,foreignKey as NQ,text as X,integer as U,real as R,uniqueIndex as k,primaryKey as PQ}from"drizzle-orm/sqlite-core";import{createId as v}from"@paralleldrive/cuid2";var N=P("Node",{id:X().primaryKey().$defaultFn(()=>v()),view:X().notNull(),kind:X().default("FEATURE").notNull(),cluster:X(),layer:X(),title:X().notNull(),role:X(),plain:X(),status:X().default("PENDING").notNull(),priority:U().default(2).notNull(),progress:U().default(0).notNull(),x:R().default(0).notNull(),y:R().default(0).notNull(),sourceRef:X(),externalId:X(),source:X().default("MANUAL").notNull(),planId:X(),parentId:X(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date),externalUpdatedAt:U({mode:"timestamp_ms"}),externalSyncedAt:U({mode:"timestamp_ms"}),externalSnapshot:X(),assigneeName:X(),assigneeAvatarUrl:X(),hiddenAt:U({mode:"timestamp_ms"})},($)=>[q("Node_cluster_idx").on($.cluster),q("Node_parentId_idx").on($.parentId),q("Node_view_idx").on($.view),NQ(()=>({columns:[$.parentId],foreignColumns:[$.id],name:"Node_parentId_Node_id_fk"})).onUpdate("cascade").onDelete("cascade")]),M0=P("NodeFile",{id:X().primaryKey().$defaultFn(()=>v()),nodeId:X().notNull().references(()=>N.id,{onDelete:"cascade",onUpdate:"cascade"}),path:X().notNull()},($)=>[k("NodeFile_nodeId_path_key").on($.nodeId,$.path),q("NodeFile_nodeId_idx").on($.nodeId)]),Z0=P("Tag",{id:X().primaryKey().$defaultFn(()=>v()),label:X().notNull(),color:X()},($)=>[k("Tag_label_key").on($.label)]),z=P("Edge",{id:X().primaryKey().$defaultFn(()=>v()),fromId:X().notNull().references(()=>N.id,{onDelete:"cascade",onUpdate:"cascade"}),toId:X().notNull().references(()=>N.id,{onDelete:"cascade",onUpdate:"cascade"}),kind:X().default("DEPENDS").notNull(),label:X(),sourceHandle:X(),targetHandle:X()},($)=>[k("Edge_fromId_toId_kind_key").on($.fromId,$.toId,$.kind),q("Edge_toId_idx").on($.toId),q("Edge_fromId_idx").on($.fromId)]),o=P("_NodeTags",{a:X("A").notNull().references(()=>N.id,{onDelete:"cascade",onUpdate:"cascade"}),b:X("B").notNull().references(()=>Z0.id,{onDelete:"cascade",onUpdate:"cascade"})},($)=>[k("_NodeTags_AB_unique").on($.a,$.b),q("_NodeTags_B_index").on($.b)]),wQ=P("Note",{id:X().primaryKey().$defaultFn(()=>v()),title:X().default("Untitled").notNull(),body:X().default("").notNull(),ord:R().default(0).notNull(),pinned:U({mode:"boolean"}).default(!1).notNull(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[q("Note_updatedAt_idx").on($.updatedAt)]),vQ=P("BoardAnnotation",{id:X().primaryKey().$defaultFn(()=>v()),targetKind:X().notNull(),targetId:X().notNull(),columnName:X(),body:X().default("").notNull(),x:R(),y:R(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[q("BoardAnnotation_target_idx").on($.targetId)]),q0=P("BugFlag",{id:X().primaryKey().$defaultFn(()=>v()),nodeId:X().notNull().references(()=>N.id,{onDelete:"cascade",onUpdate:"cascade"}),by:X().notNull(),note:X().notNull(),resolvedAt:U({mode:"timestamp_ms"}),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date)},($)=>[q("BugFlag_nodeId_idx").on($.nodeId)]),O=P("DbTable",{id:X().primaryKey().$defaultFn(()=>v()),name:X().notNull(),domain:X(),description:X(),source:X().default("MANUAL").notNull(),planId:X(),x:R().default(0).notNull(),y:R().default(0).notNull(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[q("DbTable_domain_idx").on($.domain),k("DbTable_name_key").on($.name)]),N0=P("DbColumn",{id:X().primaryKey().$defaultFn(()=>v()),tableId:X().notNull().references(()=>O.id,{onDelete:"cascade",onUpdate:"cascade"}),name:X().notNull(),type:X().notNull(),isPk:U({mode:"boolean"}).default(!1).notNull(),isFk:U({mode:"boolean"}).default(!1).notNull(),nullable:U({mode:"boolean"}).default(!0).notNull(),note:X(),ord:U().default(0).notNull()},($)=>[k("DbColumn_tableId_name_key").on($.tableId,$.name),q("DbColumn_tableId_idx").on($.tableId)]),n=P("DbRelation",{id:X().primaryKey().$defaultFn(()=>v()),fromTableId:X().notNull().references(()=>O.id,{onDelete:"cascade",onUpdate:"cascade"}),toTableId:X().notNull().references(()=>O.id,{onDelete:"cascade",onUpdate:"cascade"}),fromColumn:X().notNull(),toColumn:X().notNull(),label:X()},($)=>[q("DbRelation_toTableId_idx").on($.toTableId),q("DbRelation_fromTableId_idx").on($.fromTableId)]),J0=P("Endpoint",{id:X().primaryKey().$defaultFn(()=>v()),method:X().notNull(),path:X().notNull(),domain:X(),description:X(),source:X().default("MANUAL").notNull(),planId:X(),x:R().default(0).notNull(),y:R().default(0).notNull(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[k("Endpoint_method_path_key").on($.method,$.path),q("Endpoint_domain_idx").on($.domain)]),i=P("EndpointTable",{id:X().primaryKey().$defaultFn(()=>v()),endpointId:X().notNull().references(()=>J0.id,{onDelete:"cascade",onUpdate:"cascade"}),tableId:X().notNull().references(()=>O.id,{onDelete:"cascade",onUpdate:"cascade"}),access:X().default("read").notNull()},($)=>[k("EndpointTable_endpointId_tableId_key").on($.endpointId,$.tableId),q("EndpointTable_tableId_idx").on($.tableId)]),T=P("DraftTable",{id:X().primaryKey().$defaultFn(()=>v()),name:X().notNull(),domain:X(),description:X(),x:R().default(0).notNull(),y:R().default(0).notNull(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date)},($)=>[k("DraftTable_name_key").on($.name)]),P0=P("DraftColumn",{id:X().primaryKey().$defaultFn(()=>v()),tableId:X().notNull().references(()=>T.id,{onDelete:"cascade",onUpdate:"cascade"}),name:X().notNull(),type:X().notNull(),isPk:U({mode:"boolean"}).default(!1).notNull(),isFk:U({mode:"boolean"}).default(!1).notNull(),nullable:U({mode:"boolean"}).default(!0).notNull(),note:X(),ord:U().default(0).notNull()},($)=>[q("DraftColumn_tableId_idx").on($.tableId)]),r=P("DraftRelation",{id:X().primaryKey().$defaultFn(()=>v()),fromTableId:X().notNull().references(()=>T.id,{onDelete:"cascade",onUpdate:"cascade"}),toTableId:X().notNull().references(()=>T.id,{onDelete:"cascade",onUpdate:"cascade"}),fromColumn:X().notNull(),toColumn:X().notNull(),label:X()},($)=>[q("DraftRelation_toTableId_idx").on($.toTableId),q("DraftRelation_fromTableId_idx").on($.fromTableId)]),x=P("CodeFile",{path:X().primaryKey(),root:X(),lang:X(),x:R().default(0).notNull(),y:R().default(0).notNull(),mtimeMs:R(),size:U(),inDegree:U().default(0).notNull(),outDegree:U().default(0).notNull(),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),a=P("CodeFileEdge",{fromPath:X().notNull().references(()=>x.path,{onDelete:"cascade",onUpdate:"cascade"}),toPath:X().notNull().references(()=>x.path,{onDelete:"cascade",onUpdate:"cascade"}),circular:U({mode:"boolean"}).default(!1).notNull()},($)=>[q("CodeFileEdge_circular_idx").on($.circular),q("CodeFileEdge_toPath_idx").on($.toPath),q("CodeFileEdge_fromPath_idx").on($.fromPath),PQ({columns:[$.fromPath,$.toPath],name:"CodeFileEdge_fromPath_toPath_pk"})]),FQ=P("SyncState",{id:X().primaryKey().default("singleton"),version:U().default(0).notNull(),codeGraphSyncedAt:U({mode:"timestamp_ms"}),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),CQ=P("AppSetting",{id:X().primaryKey().default("singleton"),editor:X().default("auto").notNull(),currentFeatureId:X(),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),OQ=P("ProjectMeta",{id:X().primaryKey().default("singleton"),overview:X(),conventions:X().default("[]").notNull(),hasFrontend:U({mode:"boolean"}),classificationRoots:X().default("[]").notNull(),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),RQ=P("WorkspaceFlag",{id:X().primaryKey().$defaultFn(()=>v()),key:X().notNull(),enabled:U({mode:"boolean"}).default(!1).notNull(),config:X(),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[k("WorkspaceFlag_key_key").on($.key)]),DQ=P("PlanContract",{id:X().primaryKey().$defaultFn(()=>v()),planId:X().notNull(),declaredFiles:X().default("[]").notNull(),authorizedExtras:X().default("[]").notNull(),active:U({mode:"boolean"}).default(!1).notNull(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[k("PlanContract_planId_key").on($.planId),q("PlanContract_active_idx").on($.active)]);var x5={};Y0(x5,{tagRelations:()=>TQ,nodeTagsRelations:()=>kQ,nodeRelations:()=>AQ,nodeFileRelations:()=>EQ,endpointTableRelations:()=>uQ,endpointRelations:()=>SQ,edgeRelations:()=>LQ,draftTableRelations:()=>fQ,draftRelationRelations:()=>gQ,draftColumnRelations:()=>hQ,dbTableRelations:()=>_Q,dbRelationRelations:()=>xQ,dbColumnRelations:()=>yQ,codeFileRelations:()=>zQ,codeFileEdgeRelations:()=>bQ,bugFlagRelations:()=>IQ});import{relations as F}from"drizzle-orm";var AQ=F(N,({one:$,many:Q})=>({files:Q(M0),bugFlags:Q(q0),nodeTags:Q(o),edgesOut:Q(z,{relationName:"EdgeFrom"}),edgesIn:Q(z,{relationName:"EdgeTo"}),parent:$(N,{fields:[N.parentId],references:[N.id],relationName:"NodeTree"}),children:Q(N,{relationName:"NodeTree"})})),EQ=F(M0,({one:$})=>({node:$(N,{fields:[M0.nodeId],references:[N.id]})})),IQ=F(q0,({one:$})=>({node:$(N,{fields:[q0.nodeId],references:[N.id]})})),TQ=F(Z0,({many:$})=>({nodeTags:$(o)})),kQ=F(o,({one:$})=>({node:$(N,{fields:[o.a],references:[N.id]}),tag:$(Z0,{fields:[o.b],references:[Z0.id]})})),LQ=F(z,({one:$})=>({from:$(N,{fields:[z.fromId],references:[N.id],relationName:"EdgeFrom"}),to:$(N,{fields:[z.toId],references:[N.id],relationName:"EdgeTo"})})),_Q=F(O,({many:$})=>({columns:$(N0),fksOut:$(n,{relationName:"FkFrom"}),fksIn:$(n,{relationName:"FkTo"}),usages:$(i)})),yQ=F(N0,({one:$})=>({table:$(O,{fields:[N0.tableId],references:[O.id]})})),xQ=F(n,({one:$})=>({fromTable:$(O,{fields:[n.fromTableId],references:[O.id],relationName:"FkFrom"}),toTable:$(O,{fields:[n.toTableId],references:[O.id],relationName:"FkTo"})})),SQ=F(J0,({many:$})=>({tables:$(i)})),uQ=F(i,({one:$})=>({endpoint:$(J0,{fields:[i.endpointId],references:[J0.id]}),table:$(O,{fields:[i.tableId],references:[O.id]})})),fQ=F(T,({many:$})=>({columns:$(P0),fksOut:$(r,{relationName:"DraftFkFrom"}),fksIn:$(r,{relationName:"DraftFkTo"})})),hQ=F(P0,({one:$})=>({table:$(T,{fields:[P0.tableId],references:[T.id]})})),gQ=F(r,({one:$})=>({fromTable:$(T,{fields:[r.fromTableId],references:[T.id],relationName:"DraftFkFrom"}),toTable:$(T,{fields:[r.toTableId],references:[T.id],relationName:"DraftFkTo"})})),zQ=F(x,({many:$})=>({edgesOut:$(a,{relationName:"CFEFrom"}),edgesIn:$(a,{relationName:"CFETo"})})),bQ=F(a,({one:$})=>({fromFile:$(x,{fields:[a.fromPath],references:[x.path],relationName:"CFEFrom"}),toFile:$(x,{fields:[a.toPath],references:[x.path],relationName:"CFETo"})}));var cQ={...y5,...x5};function lQ(){let $=process.env.DATABASE_URL;if($&&/^(file:|libsql:|wss?:|https?:|:memory:)/i.test($))return $;return"file:./dev.db"}var dQ=lQ();function sQ($){let Q=pQ({url:$});return Q.execute("PRAGMA foreign_keys = ON;"),Q.execute("PRAGMA busy_timeout = 5000;"),mQ(Q,{schema:cQ})}var oQ=globalThis,e0=oQ.dzByUrl??=new Map;function _9(){return y9(dQ)}function y9($){let Q=e0.get($);if(!Q)Q=sQ($),e0.set($,Q);return Q}function w1($){let Q=e0.get($);e0.delete($);try{Q?.$client?.close?.()}catch{}}function nQ(){if(process.env.BEACON_REPO)return _9();let $=L5()??B0();if(!$)return _9();return y9(T5($))}var iQ=new Proxy({},{get($,Q){let Z=nQ(),Y=Z[Q];return typeof Y==="function"?Y.bind(Z):Y}});var rQ=["frontend","backend","fullstack"],aQ={fe:"frontend",front:"frontend",be:"backend",back:"backend",fs:"fullstack","full-stack":"fullstack","full stack":"fullstack"};function $5($){let Q=($??"").trim().toLowerCase();if(!Q)return null;if(rQ.includes(Q))return Q;return aQ[Q]??null}import{forceCenter as R1,forceCollide as D1,forceLink as A1,forceManyBody as E1,forceSimulation as I1}from"d3-force";var x9=D.object({title:D.string().trim().min(1),role:D.string().nullish(),plain:D.string().nullish(),cluster:D.string().nullish(),category:D.string().nullish(),domain:D.string().nullish(),priority:D.number().nullish(),kind:D.string().nullish(),layer:D.string().nullish(),dependsOn:D.array(D.string()).nullish()}).transform(({category:$,domain:Q,priority:Z,kind:Y,layer:V,...H})=>({...H,cluster:H.cluster??$??Q??null,priority:Z==null?null:Math.max(0,Math.min(3,Math.round(Z))),kind:Y?.trim().toUpperCase()==="BUG"?"BUG":"FEATURE",layer:$5(V)})),z1=D.object({features:D.array(x9).default([])});var tQ=/(\bmigrations?\b|\balembic\b|make revision|prisma migrate|unique\s?constraint|foreign\s?keys?|primary\s?keys?|\bFKs?\b|\bJSONB\b|create\s+table|alter\s+table|add\s+(a\s+)?column|new\s+(table|model|column)|app\/models\/|\bBaseModel\b|DeclarativeBase|schema\.prisma|@@unique|natural\s+keys?|\bpgvector\b|\bTSVECTOR\b|\bDbTable\b)/i;function S9($){return!!$&&tQ.test($)}function u9($,Q){switch($){case"add":return{path:"/api/map/start",body:{title:Q.title,id:Q.id,front:Q.front,detail:Q.detail,category:Q.category,priority:Q.priority,kind:Q.kind,layer:Q.layer,status:Q.status??"backlog",flagExisting:!1}};case"start":return{path:"/api/map/start",body:{title:Q.title,id:Q.id,front:Q.front,detail:Q.detail,category:Q.category,priority:Q.priority,kind:Q.kind,layer:Q.layer,status:"active",flagExisting:!0}};case"subtasks":return{path:"/api/nodes/subtasks",body:{parentId:Q.parentId,parentTitle:Q.parentTitle,items:Q.items}};case"done":return{path:"/api/map/describe",body:Q.features?.length?{features:Q.features}:{description:Q.description,files:Q.files,id:Q.id,title:Q.title,architecture:Q.architecture}};default:throw Error(`unknown beacon_feature action "${$}"`)}}function eQ($){return $.cluster??$.category??$.domain??null}function f9($,Q){let Z=Q?.requireLayer??!1,Y=$.map((H)=>{let G=[],W=eQ(H);if(!W||!W.trim())G.push("category");if(H.priority==null)G.push("priority");if(Z&&!$5(H.layer))G.push("layer");return G.length?` \u2022 "${H.title?.trim()||"(untitled)"}" \u2014 missing ${G.join(" + ")}`:null}).filter((H)=>H!==null);if(Y.length===0)return null;let V=Z?" This workspace has a frontend surface, so every feature must also carry `layer`: "+'"frontend" | "backend" | "fullstack" \u2014 which side of the stack the work lands on.':"";return"\u26D4 Every roadmap feature needs a category AND a priority \u2014 they drive grouping and ordering "+"on the board, and the user shouldn't have to add them by hand."+V+` Missing:
354
+ ${l0}
355
+ `,K0="add it manually: codex mcp add beacon -- beacon mcp";var U9=t(()=>{S0();$9();d0=[{event:"PostToolUse",matcher:"apply_patch",command:"beacon hook",description:"Report file edits to Beacon's active feature so the map stays fresh."},{event:"UserPromptSubmit",matcher:"*",command:"beacon prompt",description:"On feature-y prompts in a Beacon-wired repo, remind the agent to run the context\u2192propose\u2192describe loop (no-op otherwise)."},{event:"Stop",matcher:"*",command:"beacon stop-hook",description:"When the agent ends a turn asking for plan approval in prose, nudge it to present the plan on Beacon's /plan canvas."}]});var M9={};Y0(M9,{provisionDb:()=>JQ});import{createClient as s$}from"@libsql/client";import{drizzle as o$}from"drizzle-orm/libsql";import{migrate as r$}from"drizzle-orm/libsql/migrator";import{readMigrationFiles as i$}from"drizzle-orm/migrator";import{dirname as O5,join as n$}from"path";import{fileURLToPath as a$}from"url";async function i0($,Q){return(await $.execute({sql:"SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?",args:[Q]})).rows.length>0}async function QQ($,Q){let Z=await $.execute(`PRAGMA table_info("${Q}")`);return new Set(Z.rows.map((Y)=>String(Y.name)))}async function N9($){if(!await i0($,"__drizzle_migrations"))return 0;let Q=await $.execute('SELECT count(*) AS n FROM "__drizzle_migrations"');return Number(Q.rows[0]?.n??0)}async function ZQ($){for(let[Q,Z]of Object.entries($Q)){if(!await i0($,Q))continue;let Y=await QQ($,Q);for(let V of Z){if(!Y.has(V))continue;await $.execute(`UPDATE "${Q}" SET "${V}" = CAST((julianday("${V}") - 2440587.5) * 86400000 AS INTEGER) WHERE typeof("${V}") = 'text'`)}}}async function JQ($,Q=e$){let Z=s$({url:$});try{await Z.execute("PRAGMA journal_mode = WAL;"),await Z.execute("PRAGMA foreign_keys = ON;"),await Z.execute("PRAGMA busy_timeout = 5000;");let Y=await i0(Z,"__drizzle_migrations"),V=await i0(Z,"Node"),H=!1;if(V&&!Y){let j=i$({migrationsFolder:Q})[0];if(j)await Z.execute('CREATE TABLE IF NOT EXISTS "__drizzle_migrations" (id SERIAL PRIMARY KEY, hash text NOT NULL, created_at numeric)'),await Z.execute({sql:'INSERT INTO "__drizzle_migrations" ("hash", "created_at") VALUES (?, ?)',args:[j.hash,j.folderMillis]}),H=!0}let G=await N9(Z);if(await r$(o$(Z),{migrationsFolder:Q}),await N9(Z)>G)H=!0;return await ZQ(Z),{migrated:H}}finally{Z.close()}}var t$,e$,$Q;var P9=t(async()=>{t$=O5(O5(O5(a$(import.meta.url)))),e$=process.env.BEACON_MIGRATIONS_DIR||n$(t$,"drizzle"),$Q={Node:["createdAt","updatedAt"],Note:["createdAt","updatedAt"],DbTable:["createdAt","updatedAt"],Endpoint:["createdAt","updatedAt"],DraftTable:["createdAt"],SyncState:["codeGraphSyncedAt","updatedAt"],AppSetting:["updatedAt"],ProjectMeta:["updatedAt"],CodeFile:["updatedAt"]}});S0();import{existsSync as S$}from"fs";import{homedir as x$}from"os";import{join as s0}from"path";function u$(){return process.env.HOME||process.env.USERPROFILE||x$()}var o0=()=>s0(u$(),".claude"),F5=()=>s0(o0(),"skills"),r0=()=>s0(o0(),"settings.json"),C5=()=>s0(o0(),"CLAUDE.md"),R5="<!-- beacon:global:start -->",W9="<!-- beacon:global:end -->";var f$=A0,D5=[{event:"PreToolUse",matcher:"Edit|Write|MultiEdit",command:"beacon guard",description:"Gate edits against the active plan's scope contract: in-scope \u2192 allow, off-scope \u2192 ask the user to authorize. Fail-open when there's no active contract."},{event:"PostToolUse",matcher:"Edit|Write|MultiEdit",command:"beacon hook",description:"Report file edits to Beacon's active feature so the map stays fresh."},{event:"PermissionRequest",matcher:"ExitPlanMode",command:"beacon plan",description:"Pipe the agent's plan markdown into Beacon's /plan canvas for review."},{event:"PreToolUse",matcher:"AskUserQuestion",command:"beacon ask",description:"Surface the agent's AskUserQuestion in Beacon's modal; your pick flows back as the answer (falls through to the terminal if Beacon isn't open)."},{event:"PermissionRequest",matcher:"Edit|Write|MultiEdit|Bash|NotebookEdit",command:"beacon ask",description:"Surface edit/create/run approvals in Beacon's modal; your allow/deny flows back (falls through to the terminal prompt if Beacon isn't open)."},{event:"UserPromptSubmit",matcher:"*",command:"beacon prompt",description:"On feature-y prompts in a Beacon-wired repo, remind the agent to run the context\u2192propose\u2192describe loop (no-op otherwise)."},{event:"Stop",matcher:"*",command:"beacon stop-hook",description:"When the agent ends a turn asking for plan approval in prose (instead of presenting it), nudge it to present the plan on Beacon's /plan canvas. Bounded by stop_hook_active \u2014 at most one nudge."}];function g$($,Q){return I0(F5(),$,Q)}function K9($){return j0(F5(),$)}function z$($){return y0(F5(),$)}function h$($){return E0(r0(),$)}function b$($){return T0(r0(),$)}function p$($){return k0(r0(),$)}function m$($){L0(C5(),R5,W9,$)}function B9(){return G0(C5(),R5)}function c$(){return _0(C5(),R5,W9)}function IZ(){let $={};for(let Z of z)$[Z]=K9(Z);let Q={};for(let Z of D5)Q[Z.event]=b$({event:Z.event,command:Z.command});return{homeExists:S$(o0()),skills:$,hooks:Q,claudeMdBlock:B9()}}function yZ(){let $=r5(r0(),{event:"PostToolUse",command:"beacon hook"});return $?G5($):null}async function l$(){let{INIT_SKILL:$,REFRESH_SKILL:Q,PLAN_SKILL:Z,EXPLAIN_SKILL:Y}=await Promise.resolve().then(() => (M5(),N5)),V={"beacon-init":$,"beacon-refresh":Q,"beacon-plan":Z,"beacon-explain":Y},H=[];for(let U of z){if(!K9(U))H.push(U);g$(U,V[U])}let G=0;for(let U of D5)if(h$({event:U.event,matcher:U.matcher,command:X0(U.command)}))G++;let j=B9();return m$(f$),{skillsAdded:H,hooksAdded:G,claudeMdBlockTouched:!j}}async function q9(){if(l5())return{ok:!0,skipped:"plugin",skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1};let $;if(s5()){try{d$()}catch{}$={ok:!0,skipped:"plugin-present",skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1}}else try{$={ok:!0,...await l$()}}catch(Q){$={ok:!1,error:Q instanceof Error?Q.message:String(Q),skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1}}try{let Q=await Promise.resolve().then(() => (U9(),j9));if(Q.codexDetected())$.codex={ok:!0,...await Q.setupCodexAssets()}}catch(Q){$.codex={ok:!1,error:Q instanceof Error?Q.message:String(Q),skillsAdded:[],hooksAdded:0,agentsMdBlockTouched:!1,mcp:{added:!1}}}return $}function d$(){let $=[];for(let Y of z)if(z$(Y))$.push(Y);let Q=0;for(let Y of D5)if(p$(Y))Q++;let Z=c$();return{skillsRemoved:$,hooksRemoved:Q,claudeMdBlockRemoved:Z}}import{AsyncLocalStorage as YQ}from"async_hooks";import{spawnSync as VQ}from"child_process";import{createHash as XQ}from"crypto";import{existsSync as v9,mkdirSync as q0,readFileSync as E5,writeFileSync as T5}from"fs";import{homedir as F9}from"os";import{basename as HQ,join as p,parse as GQ,resolve as w9}from"path";function x(){return process.env.BEACON_HOME||p(F9(),".beacon")}function k5(){return p(x(),"workspaces.json")}function d($){return XQ("sha256").update($).digest("hex").slice(0,12)}function L5($=process.cwd()){let Q=VQ("git",["rev-parse","--show-toplevel"],{cwd:$,stdio:["ignore","pipe","ignore"]});if(Q.status===0){let Z=Q.stdout?.toString().trim();if(Z)return Z}return $}function n0($){let Q=w9($);return Q!==w9(F9())&&Q!==GQ(Q).root}function C9(){return p(x(),"deleted.json")}function _5(){try{let $=JSON.parse(E5(C9(),"utf8"));return Array.isArray($)?$:[]}catch{return[]}}function R9($){q0(x(),{recursive:!0}),T5(C9(),JSON.stringify($,null,2))}function a0($){return _5().includes($)}function sZ($){let Q=_5();if(!Q.includes($))R9([...Q,$])}function jQ($){let Q=_5();if(Q.includes($))R9(Q.filter((Z)=>Z!==$))}function t0($){return p(x(),$)}function I5($){return`file:${p(t0($),"db.sqlite")}`}function N0(){try{let $=JSON.parse(E5(k5(),"utf8"));return Array.isArray($)?$:[]}catch{return[]}}function y5($){q0(x(),{recursive:!0}),T5(k5(),JSON.stringify($,null,2))}function e0(){return N0().sort(($,Q)=>Q.lastOpenedAt.localeCompare($.lastOpenedAt))}function s($){return N0().find((Q)=>Q.id===$)??null}function $5($,Q,Z=new Date().toISOString()){if(!n0($))throw Error(`beacon: refusing to register a non-repo path as a workspace: ${$}`);let Y=d($);if(a0(Y))throw Error(`beacon: workspace ${Y} (${$}) was deleted \u2014 run \`beacon\` or /beacon-init to re-add it`);let V=N0(),H=V.find((U)=>U.id===Y),G={id:Y,path:$,name:Q||H?.name||HQ($),lastOpenedAt:Z},j=[G,...V.filter((U)=>U.id!==Y)];return q0(t0(Y),{recursive:!0}),y5(j),G}function oZ($,Q){return jQ(d($)),$5($,Q)}function rZ($,Q=new Date().toISOString()){let Z=N0(),Y=Z.find((V)=>V.id===$);if(!Y)return;Y.lastOpenedAt=Q,y5(Z)}function iZ($){if(y5(N0().filter((Q)=>Q.id!==$)),M0()===$)UQ(e0()[0]?.id??null)}function D9(){return p(x(),"active")}function M0(){try{return E5(D9(),"utf8").trim()||null}catch{return null}}function UQ($){q0(x(),{recursive:!0}),T5(D9(),$??"")}function nZ(){let $=M0();return $?s($):null}function aZ(){let $=S5()??M0();return $?s($):null}function tZ($){return s($)?.path??null}function eZ(){return v9(k5())}var O9="beacon_ws";function A9($,Q){let Z=$.headers.get("cookie");if(!Z)return null;for(let Y of Z.split(";")){let V=Y.indexOf("=");if(V===-1)continue;if(Y.slice(0,V).trim()===Q)return decodeURIComponent(Y.slice(V+1).trim())}return null}function $1($){let Q=$.headers.get("x-beacon-workspace");if(Q&&s(Q))return Q;let Z=A9($,O9);if(Z&&s(Z))return Z;return WQ()}function WQ(){let $=e0();return $.length===1?$[0].id:null}var Q5="x-beacon-workspace-path";function Q1($=process.cwd()){let Q=L5($);return{"x-beacon-workspace":d(Q),[Q5]:Q}}async function Z1($){let Q=$.headers.get("x-beacon-workspace");if(Q&&s(Q))return Q;let Z=$.headers.get(Q5);if(Z&&n0(Z)&&!a0(d(Z))&&(!Q||d(Z)===Q)){let V=$5(Z);return await x5(V.id),V.id}let Y=A9($,O9);if(Y&&s(Y))return Y;return null}var E9=new YQ;function KQ($,Q){return $?E9.run($,Q):Q()}function S5(){return E9.getStore()??null}var A5=new Set;function J1($){A5.delete(p(t0($),"db.sqlite"))}async function x5($){let Q=t0($),Z=p(Q,"db.sqlite"),Y=v9(Z);if(Y&&A5.has(Z))return{ok:!0,created:!1,migrated:!1};try{q0(Q,{recursive:!0});let{provisionDb:V}=await P9().then(() => M9),H=await V(I5($));return A5.add(Z),{ok:!0,created:!Y,migrated:Y&&H.migrated}}catch(V){return{ok:!1,created:!1,migrated:!1,error:V instanceof Error?V.message:String(V)}}}import{connect as BQ}from"net";var T9=4319;function qQ($,Q,Z=400){return new Promise((Y)=>{let V=BQ({host:$,port:Q}),H=!1,G=(j)=>{if(H)return;H=!0,V.destroy(),Y(j)};V.once("connect",()=>G(!0)),V.once("error",()=>G(!1)),V.setTimeout(Z,()=>G(!1))})}async function NQ($){for(let Q of["127.0.0.1","::1"])if(await qQ(Q,$))return!1;return!0}async function X1($,Q=20){for(let Z=$;Z<$+Q;Z++)if(await NQ(Z))return Z;return $}import{McpServer as XZ,ResourceTemplate as b5}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as HZ}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as J}from"zod";import{z as B}from"zod";var MQ=new Set(["GET","HEAD","OPTIONS"]);function k9($){return MQ.has($.trim().toUpperCase())?"read":"write"}var PQ=B.preprocess(($)=>{if(typeof $==="string"){let[Q,...Z]=$.trim().split(/\s+/);return{name:Q,type:Z.join(" ")||"text"}}return $},B.object({name:B.string().trim().min(1),type:B.string().trim().min(1),isPk:B.boolean().optional(),isFk:B.boolean().optional(),nullable:B.boolean().optional(),note:B.string().nullish()})),L9=B.object({name:B.string().trim().min(1),domain:B.string().nullish(),description:B.string().nullish(),columns:B.array(PQ).default([])}),_9=B.object({fromTable:B.string(),fromColumn:B.string(),toTable:B.string(),toColumn:B.string(),label:B.string().nullish()}),I9=B.object({method:B.string().trim().min(1),path:B.string().trim().min(1),domain:B.string().nullish(),description:B.string().nullish(),uses:B.array(B.object({table:B.string().trim().min(1),access:B.string().optional()})).default([])}).transform(($)=>({...$,uses:$.uses.map((Q)=>({...Q,access:Q.access??k9($.method)}))})),W1=B.object({tables:B.array(L9).default([]),relations:B.array(_9).default([]),endpoints:B.array(I9).default([])});import{z as A}from"zod";import{and as x1,eq as u1,inArray as f1}from"drizzle-orm";import{drizzle as cQ}from"drizzle-orm/libsql";import{createClient as lQ}from"@libsql/client";var u5={};Y0(u5,{workspaceFlag:()=>AQ,tag:()=>Z0,syncState:()=>RQ,projectMeta:()=>OQ,planContract:()=>EQ,note:()=>FQ,nodeTags:()=>o,nodeFile:()=>P0,node:()=>M,endpointTable:()=>i,endpoint:()=>J0,edge:()=>m,draftTable:()=>L,draftRelation:()=>n,draftColumn:()=>F0,dbTable:()=>R,dbRelation:()=>r,dbColumn:()=>v0,codeFileEdge:()=>a,codeFile:()=>u,bugFlag:()=>w0,boardAnnotation:()=>CQ,appSetting:()=>DQ});import{sqliteTable as P,index as N,foreignKey as wQ,text as X,integer as W,real as O,uniqueIndex as _,primaryKey as vQ}from"drizzle-orm/sqlite-core";import{createId as v}from"@paralleldrive/cuid2";var M=P("Node",{id:X().primaryKey().$defaultFn(()=>v()),view:X().notNull(),kind:X().default("FEATURE").notNull(),cluster:X(),layer:X(),title:X().notNull(),role:X(),plain:X(),status:X().default("PENDING").notNull(),priority:W().default(2).notNull(),progress:W().default(0).notNull(),x:O().default(0).notNull(),y:O().default(0).notNull(),sourceRef:X(),externalId:X(),source:X().default("MANUAL").notNull(),planId:X(),parentId:X(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date),externalUpdatedAt:W({mode:"timestamp_ms"}),externalSyncedAt:W({mode:"timestamp_ms"}),externalSnapshot:X(),assigneeName:X(),assigneeAvatarUrl:X(),externalMeta:X(),hiddenAt:W({mode:"timestamp_ms"})},($)=>[N("Node_cluster_idx").on($.cluster),N("Node_parentId_idx").on($.parentId),N("Node_view_idx").on($.view),wQ(()=>({columns:[$.parentId],foreignColumns:[$.id],name:"Node_parentId_Node_id_fk"})).onUpdate("cascade").onDelete("cascade")]),P0=P("NodeFile",{id:X().primaryKey().$defaultFn(()=>v()),nodeId:X().notNull().references(()=>M.id,{onDelete:"cascade",onUpdate:"cascade"}),path:X().notNull()},($)=>[_("NodeFile_nodeId_path_key").on($.nodeId,$.path),N("NodeFile_nodeId_idx").on($.nodeId)]),Z0=P("Tag",{id:X().primaryKey().$defaultFn(()=>v()),label:X().notNull(),color:X()},($)=>[_("Tag_label_key").on($.label)]),m=P("Edge",{id:X().primaryKey().$defaultFn(()=>v()),fromId:X().notNull().references(()=>M.id,{onDelete:"cascade",onUpdate:"cascade"}),toId:X().notNull().references(()=>M.id,{onDelete:"cascade",onUpdate:"cascade"}),kind:X().default("DEPENDS").notNull(),label:X(),sourceHandle:X(),targetHandle:X()},($)=>[_("Edge_fromId_toId_kind_key").on($.fromId,$.toId,$.kind),N("Edge_toId_idx").on($.toId),N("Edge_fromId_idx").on($.fromId)]),o=P("_NodeTags",{a:X("A").notNull().references(()=>M.id,{onDelete:"cascade",onUpdate:"cascade"}),b:X("B").notNull().references(()=>Z0.id,{onDelete:"cascade",onUpdate:"cascade"})},($)=>[_("_NodeTags_AB_unique").on($.a,$.b),N("_NodeTags_B_index").on($.b)]),FQ=P("Note",{id:X().primaryKey().$defaultFn(()=>v()),title:X().default("Untitled").notNull(),body:X().default("").notNull(),ord:O().default(0).notNull(),pinned:W({mode:"boolean"}).default(!1).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[N("Note_updatedAt_idx").on($.updatedAt)]),CQ=P("BoardAnnotation",{id:X().primaryKey().$defaultFn(()=>v()),targetKind:X().notNull(),targetId:X().notNull(),columnName:X(),body:X().default("").notNull(),x:O(),y:O(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[N("BoardAnnotation_target_idx").on($.targetId)]),w0=P("BugFlag",{id:X().primaryKey().$defaultFn(()=>v()),nodeId:X().notNull().references(()=>M.id,{onDelete:"cascade",onUpdate:"cascade"}),by:X().notNull(),note:X().notNull(),resolvedAt:W({mode:"timestamp_ms"}),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date)},($)=>[N("BugFlag_nodeId_idx").on($.nodeId)]),R=P("DbTable",{id:X().primaryKey().$defaultFn(()=>v()),name:X().notNull(),domain:X(),description:X(),source:X().default("MANUAL").notNull(),planId:X(),x:O().default(0).notNull(),y:O().default(0).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[N("DbTable_domain_idx").on($.domain),_("DbTable_name_key").on($.name)]),v0=P("DbColumn",{id:X().primaryKey().$defaultFn(()=>v()),tableId:X().notNull().references(()=>R.id,{onDelete:"cascade",onUpdate:"cascade"}),name:X().notNull(),type:X().notNull(),isPk:W({mode:"boolean"}).default(!1).notNull(),isFk:W({mode:"boolean"}).default(!1).notNull(),nullable:W({mode:"boolean"}).default(!0).notNull(),note:X(),ord:W().default(0).notNull()},($)=>[_("DbColumn_tableId_name_key").on($.tableId,$.name),N("DbColumn_tableId_idx").on($.tableId)]),r=P("DbRelation",{id:X().primaryKey().$defaultFn(()=>v()),fromTableId:X().notNull().references(()=>R.id,{onDelete:"cascade",onUpdate:"cascade"}),toTableId:X().notNull().references(()=>R.id,{onDelete:"cascade",onUpdate:"cascade"}),fromColumn:X().notNull(),toColumn:X().notNull(),label:X()},($)=>[N("DbRelation_toTableId_idx").on($.toTableId),N("DbRelation_fromTableId_idx").on($.fromTableId)]),J0=P("Endpoint",{id:X().primaryKey().$defaultFn(()=>v()),method:X().notNull(),path:X().notNull(),domain:X(),description:X(),source:X().default("MANUAL").notNull(),planId:X(),x:O().default(0).notNull(),y:O().default(0).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[_("Endpoint_method_path_key").on($.method,$.path),N("Endpoint_domain_idx").on($.domain)]),i=P("EndpointTable",{id:X().primaryKey().$defaultFn(()=>v()),endpointId:X().notNull().references(()=>J0.id,{onDelete:"cascade",onUpdate:"cascade"}),tableId:X().notNull().references(()=>R.id,{onDelete:"cascade",onUpdate:"cascade"}),access:X().default("read").notNull()},($)=>[_("EndpointTable_endpointId_tableId_key").on($.endpointId,$.tableId),N("EndpointTable_tableId_idx").on($.tableId)]),L=P("DraftTable",{id:X().primaryKey().$defaultFn(()=>v()),name:X().notNull(),domain:X(),description:X(),x:O().default(0).notNull(),y:O().default(0).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date)},($)=>[_("DraftTable_name_key").on($.name)]),F0=P("DraftColumn",{id:X().primaryKey().$defaultFn(()=>v()),tableId:X().notNull().references(()=>L.id,{onDelete:"cascade",onUpdate:"cascade"}),name:X().notNull(),type:X().notNull(),isPk:W({mode:"boolean"}).default(!1).notNull(),isFk:W({mode:"boolean"}).default(!1).notNull(),nullable:W({mode:"boolean"}).default(!0).notNull(),note:X(),ord:W().default(0).notNull()},($)=>[N("DraftColumn_tableId_idx").on($.tableId)]),n=P("DraftRelation",{id:X().primaryKey().$defaultFn(()=>v()),fromTableId:X().notNull().references(()=>L.id,{onDelete:"cascade",onUpdate:"cascade"}),toTableId:X().notNull().references(()=>L.id,{onDelete:"cascade",onUpdate:"cascade"}),fromColumn:X().notNull(),toColumn:X().notNull(),label:X()},($)=>[N("DraftRelation_toTableId_idx").on($.toTableId),N("DraftRelation_fromTableId_idx").on($.fromTableId)]),u=P("CodeFile",{path:X().primaryKey(),root:X(),lang:X(),x:O().default(0).notNull(),y:O().default(0).notNull(),mtimeMs:O(),size:W(),inDegree:W().default(0).notNull(),outDegree:W().default(0).notNull(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),a=P("CodeFileEdge",{fromPath:X().notNull().references(()=>u.path,{onDelete:"cascade",onUpdate:"cascade"}),toPath:X().notNull().references(()=>u.path,{onDelete:"cascade",onUpdate:"cascade"}),circular:W({mode:"boolean"}).default(!1).notNull()},($)=>[N("CodeFileEdge_circular_idx").on($.circular),N("CodeFileEdge_toPath_idx").on($.toPath),N("CodeFileEdge_fromPath_idx").on($.fromPath),vQ({columns:[$.fromPath,$.toPath],name:"CodeFileEdge_fromPath_toPath_pk"})]),RQ=P("SyncState",{id:X().primaryKey().default("singleton"),version:W().default(0).notNull(),codeGraphSyncedAt:W({mode:"timestamp_ms"}),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),DQ=P("AppSetting",{id:X().primaryKey().default("singleton"),editor:X().default("auto").notNull(),currentFeatureId:X(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),OQ=P("ProjectMeta",{id:X().primaryKey().default("singleton"),overview:X(),conventions:X().default("[]").notNull(),hasFrontend:W({mode:"boolean"}),classificationRoots:X().default("[]").notNull(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),AQ=P("WorkspaceFlag",{id:X().primaryKey().$defaultFn(()=>v()),key:X().notNull(),enabled:W({mode:"boolean"}).default(!1).notNull(),config:X(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[_("WorkspaceFlag_key_key").on($.key)]),EQ=P("PlanContract",{id:X().primaryKey().$defaultFn(()=>v()),planId:X().notNull(),declaredFiles:X().default("[]").notNull(),authorizedExtras:X().default("[]").notNull(),active:W({mode:"boolean"}).default(!1).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[_("PlanContract_planId_key").on($.planId),N("PlanContract_active_idx").on($.active)]);var f5={};Y0(f5,{tagRelations:()=>_Q,nodeTagsRelations:()=>IQ,nodeRelations:()=>TQ,nodeFileRelations:()=>kQ,endpointTableRelations:()=>gQ,endpointRelations:()=>fQ,edgeRelations:()=>yQ,draftTableRelations:()=>zQ,draftRelationRelations:()=>bQ,draftColumnRelations:()=>hQ,dbTableRelations:()=>SQ,dbRelationRelations:()=>uQ,dbColumnRelations:()=>xQ,codeFileRelations:()=>pQ,codeFileEdgeRelations:()=>mQ,bugFlagRelations:()=>LQ});import{relations as F}from"drizzle-orm";var TQ=F(M,({one:$,many:Q})=>({files:Q(P0),bugFlags:Q(w0),nodeTags:Q(o),edgesOut:Q(m,{relationName:"EdgeFrom"}),edgesIn:Q(m,{relationName:"EdgeTo"}),parent:$(M,{fields:[M.parentId],references:[M.id],relationName:"NodeTree"}),children:Q(M,{relationName:"NodeTree"})})),kQ=F(P0,({one:$})=>({node:$(M,{fields:[P0.nodeId],references:[M.id]})})),LQ=F(w0,({one:$})=>({node:$(M,{fields:[w0.nodeId],references:[M.id]})})),_Q=F(Z0,({many:$})=>({nodeTags:$(o)})),IQ=F(o,({one:$})=>({node:$(M,{fields:[o.a],references:[M.id]}),tag:$(Z0,{fields:[o.b],references:[Z0.id]})})),yQ=F(m,({one:$})=>({from:$(M,{fields:[m.fromId],references:[M.id],relationName:"EdgeFrom"}),to:$(M,{fields:[m.toId],references:[M.id],relationName:"EdgeTo"})})),SQ=F(R,({many:$})=>({columns:$(v0),fksOut:$(r,{relationName:"FkFrom"}),fksIn:$(r,{relationName:"FkTo"}),usages:$(i)})),xQ=F(v0,({one:$})=>({table:$(R,{fields:[v0.tableId],references:[R.id]})})),uQ=F(r,({one:$})=>({fromTable:$(R,{fields:[r.fromTableId],references:[R.id],relationName:"FkFrom"}),toTable:$(R,{fields:[r.toTableId],references:[R.id],relationName:"FkTo"})})),fQ=F(J0,({many:$})=>({tables:$(i)})),gQ=F(i,({one:$})=>({endpoint:$(J0,{fields:[i.endpointId],references:[J0.id]}),table:$(R,{fields:[i.tableId],references:[R.id]})})),zQ=F(L,({many:$})=>({columns:$(F0),fksOut:$(n,{relationName:"DraftFkFrom"}),fksIn:$(n,{relationName:"DraftFkTo"})})),hQ=F(F0,({one:$})=>({table:$(L,{fields:[F0.tableId],references:[L.id]})})),bQ=F(n,({one:$})=>({fromTable:$(L,{fields:[n.fromTableId],references:[L.id],relationName:"DraftFkFrom"}),toTable:$(L,{fields:[n.toTableId],references:[L.id],relationName:"DraftFkTo"})})),pQ=F(u,({many:$})=>({edgesOut:$(a,{relationName:"CFEFrom"}),edgesIn:$(a,{relationName:"CFETo"})})),mQ=F(a,({one:$})=>({fromFile:$(u,{fields:[a.fromPath],references:[u.path],relationName:"CFEFrom"}),toFile:$(u,{fields:[a.toPath],references:[u.path],relationName:"CFETo"})}));var dQ={...u5,...f5};function sQ(){let $=process.env.DATABASE_URL;if($&&/^(file:|libsql:|wss?:|https?:|:memory:)/i.test($))return $;return"file:./dev.db"}var oQ=sQ();function rQ($){let Q=lQ({url:$});return Q.execute("PRAGMA foreign_keys = ON;"),Q.execute("PRAGMA busy_timeout = 5000;"),cQ(Q,{schema:dQ})}var iQ=globalThis,Z5=iQ.dzByUrl??=new Map;function y9(){return S9(oQ)}function S9($){let Q=Z5.get($);if(!Q)Q=rQ($),Z5.set($,Q);return Q}function F1($){let Q=Z5.get($);Z5.delete($);try{Q?.$client?.close?.()}catch{}}function nQ(){if(process.env.BEACON_REPO)return y9();let $=S5()??M0();if(!$)return y9();return S9(I5($))}var aQ=new Proxy({},{get($,Q){let Z=nQ(),Y=Z[Q];return typeof Y==="function"?Y.bind(Z):Y}});var tQ=["frontend","backend","fullstack"],eQ={fe:"frontend",front:"frontend",be:"backend",back:"backend",fs:"fullstack","full-stack":"fullstack","full stack":"fullstack"};function J5($){let Q=($??"").trim().toLowerCase();if(!Q)return null;if(tQ.includes(Q))return Q;return eQ[Q]??null}import{forceCenter as A1,forceCollide as E1,forceLink as T1,forceManyBody as k1,forceSimulation as L1}from"d3-force";var x9=A.object({title:A.string().trim().min(1),role:A.string().nullish(),plain:A.string().nullish(),cluster:A.string().nullish(),category:A.string().nullish(),domain:A.string().nullish(),priority:A.number().nullish(),kind:A.string().nullish(),layer:A.string().nullish(),dependsOn:A.array(A.string()).nullish()}).transform(({category:$,domain:Q,priority:Z,kind:Y,layer:V,...H})=>({...H,cluster:H.cluster??$??Q??null,priority:Z==null?null:Math.max(0,Math.min(3,Math.round(Z))),kind:Y?.trim().toUpperCase()==="BUG"?"BUG":"FEATURE",layer:J5(V)})),p1=A.object({features:A.array(x9).default([])});var $Z=/(\bmigrations?\b|\balembic\b|make revision|prisma migrate|unique\s?constraint|foreign\s?keys?|primary\s?keys?|\bFKs?\b|\bJSONB\b|create\s+table|alter\s+table|add\s+(a\s+)?column|new\s+(table|model|column)|app\/models\/|\bBaseModel\b|DeclarativeBase|schema\.prisma|@@unique|natural\s+keys?|\bpgvector\b|\bTSVECTOR\b|\bDbTable\b)/i;function u9($){return!!$&&$Z.test($)}function f9($,Q){switch($){case"add":return{path:"/api/map/start",body:{title:Q.title,id:Q.id,front:Q.front,detail:Q.detail,category:Q.category,priority:Q.priority,kind:Q.kind,layer:Q.layer,status:Q.status??"backlog",flagExisting:!1}};case"start":return{path:"/api/map/start",body:{title:Q.title,id:Q.id,front:Q.front,detail:Q.detail,category:Q.category,priority:Q.priority,kind:Q.kind,layer:Q.layer,status:"active",flagExisting:!0}};case"subtasks":return{path:"/api/nodes/subtasks",body:{parentId:Q.parentId,parentTitle:Q.parentTitle,items:Q.items}};case"done":return{path:"/api/map/describe",body:Q.features?.length?{features:Q.features}:{description:Q.description,files:Q.files,id:Q.id,title:Q.title,architecture:Q.architecture}};default:throw Error(`unknown beacon_feature action "${$}"`)}}function QZ($){return $.cluster??$.category??$.domain??null}function g9($,Q){let Z=Q?.requireLayer??!1,Y=$.map((H)=>{let G=[],j=QZ(H);if(!j||!j.trim())G.push("category");if(H.priority==null)G.push("priority");if(Z&&!J5(H.layer))G.push("layer");return G.length?` \u2022 "${H.title?.trim()||"(untitled)"}" \u2014 missing ${G.join(" + ")}`:null}).filter((H)=>H!==null);if(Y.length===0)return null;let V=Z?" This workspace has a frontend surface, so every feature must also carry `layer`: "+'"frontend" | "backend" | "fullstack" \u2014 which side of the stack the work lands on.':"";return"\u26D4 Every roadmap feature needs a category AND a priority \u2014 they drive grouping and ordering "+"on the board, and the user shouldn't have to add them by hand."+V+` Missing:
354
356
  `+Y.join(`
355
- `)+"\n\nRe-present with each feature carrying its category as `category` (or `cluster` \u2014 both "+"work; e.g. AUTH, SEARCH, DATA, INTEL, BILLING \u2026) and `priority` (0 = P0 critical, 1 = P1 "+"high, 2 = P2 medium, 3 = P3 low)."+(Z?" Set `layer` on EVERY feature too.":"")+" Don't rely on defaults."}function S5($){if(!$?.length)return"";let Q=$.map((Y)=>Y.id?` \u2022 ${Y.title} \u2014 id: ${Y.id}`:` \u2022 ${Y.title}`),Z=$.some((Y)=>Y.id);return`
357
+ `)+"\n\nRe-present with each feature carrying its category as `category` (or `cluster` \u2014 both "+"work; e.g. AUTH, SEARCH, DATA, INTEL, BILLING \u2026) and `priority` (0 = P0 critical, 1 = P1 "+"high, 2 = P2 medium, 3 = P3 low)."+(Z?" Set `layer` on EVERY feature too.":"")+" Don't rely on defaults."}function g5($){if(!$?.length)return"";let Q=$.map((Y)=>Y.id?` \u2022 ${Y.title} \u2014 id: ${Y.id}`:` \u2022 ${Y.title}`),Z=$.some((Y)=>Y.id);return`
356
358
 
357
359
  This plan created these roadmap feature(s):
358
360
  `+Q.join(`
359
- `)+'\n\nWhen the work ships, register them in ONE call: `beacon_feature({ action: "done" })` with a '+"`features` array \u2014 one entry per feature"+(Z?", each keyed by the `id` above (no title-matching needed)":"")+", each with the files you touched + a short markdown summary. Do them all in that single "+"batched call so every feature flips to Done \u2014 do NOT register only the umbrella, and do "+"NOT make one call per feature."}import{readFileSync as $Z}from"fs";import{join as QZ}from"path";function ZZ(){try{return JSON.parse($Z(QZ(y(),"server.json"),"utf8"))}catch{return null}}function b(){if(process.env.BEACON_URL)return process.env.BEACON_URL;return`http://localhost:${ZZ()?.port||process.env.PORT||E9}`}import{execSync as JZ}from"child_process";import{platform as h9}from"os";function u5($){if(process.env.BEACON_NO_OPEN)return;let Q=h9()==="darwin"?"open":h9()==="win32"?"start":"xdg-open";try{JZ(`${Q} "${$}"`,{stdio:"ignore"})}catch{}}async function f5($,Q){if(await fetch(`${$}/api/plan/presence`,{headers:{"x-beacon-workspace":Q}}).then((V)=>V.json()).then((V)=>!!V?.live).catch(()=>!1))return;let Y=encodeURIComponent(`/plan?ws=${Q}`);u5(`${$}/api/workspace/activate?id=${Q}&redirect=${Y}`)}async function g9($,Q){if(await fetch(`${$}/api/lesson/presence`,{headers:{"x-beacon-workspace":Q}}).then((V)=>V.json()).then((V)=>!!V?.live).catch(()=>!1))return;let Y=encodeURIComponent(`/learn?ws=${Q}`);u5(`${$}/api/workspace/activate?id=${Q}&redirect=${Y}`)}var z9=["imports","calls","persists to","reads from","writes to","routes to","depends on","emits","returns","contains","extends"];X5();function w0($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036F]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50)||"item"}function b9($){return`${w0($.title)}-${$.id.slice(-6)}`}function m9($){return{resources:$.map((Q)=>({uri:`note://${b9(Q)}`,name:Q.title||"Untitled",description:`${Q.title||"Untitled"}${Q.pinned?" \xB7 pinned":""} \xB7 note`,mimeType:"text/markdown"}))}}function p9($,Q){return $.find((Z)=>b9(Z)===Q)}function c9($){let Q=$.body.trim()||"(this note is empty)";return[`# ${$.title||"Untitled"}`,"","_User note from Beacon. To turn it into roadmap work, call `beacon_propose_plan` \u2014"+" checkbox `- [ ]` / `- [x]` items become subtasks, and order the features with `dependsOn`. Do NOT implement until it returns approval._","","---","",Q].join(`
360
- `)}await B9();var m=E5(),S=d(m);if(!o0(m)){let $=r0();if($.length===1)console.error(`[beacon mcp] cwd ${m} isn't a registered repo \u2014 falling back to your only Beacon workspace "${$[0].name}".`);else if($.length>1)console.error(`[beacon mcp] cwd ${m} isn't a registered repo and you have ${$.length} Beacon workspaces \u2014 can't auto-detect which. Run /beacon-init in this repo, or name the project explicitly in your request.`);else console.error(`[beacon mcp] not registering ${m} \u2014 home/non-repo dir.`)}else if(n0(S))console.error(`[beacon mcp] not registering ${m} \u2014 workspace was deleted; run /beacon-init to re-add it.`);else try{a0(m);let $=await _5(S);if(!$.ok)console.error(`[beacon mcp] db provisioning failed: ${$.error}`)}catch($){console.error(`[beacon mcp] workspace registration failed: ${$ instanceof Error?$.message:$}`)}async function E($,Q){let Z=new Headers(Q?.headers);Z.set("x-beacon-workspace",S),Z.set(t0,m);let Y=await fetch(`${b()}${$}`,{...Q,headers:Z}),V=await Y.text();if(!Y.ok)throw Error(`Beacon ${$} -> ${Y.status} ${V}`);return V?JSON.parse(V):null}function v0($,Q){return E($,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Q)})}function g5($){let Q=$ instanceof Error?$.message:String($),Z=Q.match(/\{[\s\S]*\}$/);if(Z)try{let Y=JSON.parse(Z[0]);if(Y?.error)return{content:[{type:"text",text:Y.error}],isError:!0}}catch{}return{content:[{type:"text",text:Q}],isError:!0}}var A=new YZ({name:"beacon",version:"0.1.0"});A.registerTool("beacon_map",{description:"List the roadmap: every feature + its sub-tasks with `category`, `priority`, `layer`, `kind`, and `status`. Call this BEFORE creating anything with `beacon_feature` \u2014 it's the cheap way to learn which categories already exist (reuse one instead of inventing a synonym) and whether a card already exists. You do NOT need `beacon_entities` just to see categories."},async()=>{let $=await E("/api/map");return{content:[{type:"text",text:JSON.stringify($)}]}});var l9=J.array(J.object({title:J.string().describe("real component/subsystem name (e.g. 'Plan review loop') \u2014 NEVER a file"),domain:J.string().describe("uppercase lane: PLAN | DATA | UI | MCP | INTEL | \u2026"),role:J.string().optional().describe("one-line technical role"),plain:J.string().optional().describe("one plain-language sentence"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack the component lives on (only when the repo has a frontend); omitting it on an update keeps the prior value"),status:J.enum(["KEEP","REBUILD","REPLACE","DROP"]).optional(),files:J.array(J.string()).optional(),depends:J.array(J.string()).optional().describe("titles of components this one depends on"),bugs:J.array(J.object({note:J.string().describe("what was found / worth investigating")})).optional().describe("bugs or things worth investigating you found in this component's code \u2014 flagged on the node (by=agent); identical open flags are not duplicated")})).optional().describe("Only when the feature adds/changes a REAL architectural component \u2014 upserts curated nodes, never one-per-file");A.registerTool("beacon_feature",{description:'Manage a roadmap feature\'s whole lifecycle in ONE tool \u2014 no approval gate (that\'s `beacon_propose_plan`/`beacon_present_plan`). `action:"add"` puts a card on the board, defaulting to BACKLOG/PENDING (pass `status:"active"` to start it now); `"start"` marks an existing card IN_PROGRESS (create-or-flag); `"subtasks"` adds child tasks under a card; `"done"` completes feature(s) and registers the files/architecture touched (marks DONE + cascades to sub-tasks). A NEW card REQUIRES `category` + `priority` (and `layer` when the workspace has a frontend). Call `beacon_map` FIRST \u2014 it lists every card\'s category/priority/layer/status, so reuse a category and avoid an EXACT duplicate (same title + category + layer) \u2014 a same-named card in a different category, or on a different layer (FE/BE/FS), is allowed as its own card. `add` never activates an existing match \u2014 it returns `exists` so you can reuse it.',inputSchema:{action:J.enum(["add","start","subtasks","done"]).describe("add = put a card on the board (defaults to BACKLOG/PENDING); start = mark an existing card IN_PROGRESS; subtasks = add child tasks under a card; done = complete feature(s) + register files/architecture."),title:J.string().optional().describe("card title (add/start); for done's single form, the feature title (id preferred)."),id:J.string().optional().describe("node id from beacon_map (preferred over title) \u2014 start/done, or add to reference a known card."),category:J.string().optional().describe("REQUIRED for a NEW card (add/start): domain lane \u2014 AUTH | SEARCH | DATA | INTEL | BILLING | INFRA | UI | \u2026 Reuse one from beacon_map; ignored when matching an existing card or nesting under a `front`."),priority:J.number().int().min(0).max(3).optional().describe("priority of a NEW card (add/start): 0=P0 critical .. 3=P3 low. Defaults to P2."),front:J.string().optional().describe("title of an EXISTING parent feature to nest a NEW card under (add/start). NOT a domain tag (use `category`); a `front` matching nothing is REJECTED."),detail:J.string().optional().describe("one-line plain-language description shown on the card (add/start)."),kind:J.enum(["FEATURE","BUG"]).optional().describe("BUG renders a typed bug card; defaults to FEATURE (add/start)."),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack a NEW card lands on (add/start). REQUIRED when the workspace has a frontend; a card nested under a `front` inherits the parent's. Omit in pure-backend repos."),status:J.enum(["backlog","active"]).optional().describe(`add only: "backlog" (default) creates a PENDING card you're not working on yet; "active" creates it IN_PROGRESS.`),parentId:J.string().optional().describe("subtasks: node id of the parent card (preferred)."),parentTitle:J.string().optional().describe("subtasks: fuzzy title of the parent card; ignored if parentId is given."),items:J.array(J.object({title:J.string().describe("short sub-task title"),plain:J.string().optional().describe("one-paragraph description / why / acceptance hint"),kind:J.enum(["FEATURE","BUG"]).optional().describe("BUG for a bug discovered during work; defaults to FEATURE"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack the sub-task lands on; defaults to the parent's layer")})).optional().describe("subtasks: the child tasks to add under the parent."),features:J.array(J.object({id:J.string().optional().describe("node id from plan approval / beacon_map (preferred over title)"),title:J.string().optional().describe("feature title (fuzzy-matched if no id)"),description:J.string().describe("Markdown: ### Overview ... ### Files - `path` \u2014 what it does"),files:J.array(J.string()).optional().describe("repo-relative files this feature touches"),architecture:l9})).optional().describe("done: register MANY features at once \u2014 one entry per feature the plan created, each id-keyed. Use this instead of N separate calls."),description:J.string().optional().describe("done (single form, omit when using `features`): the markdown summary of the shipped feature."),files:J.array(J.string()).optional().describe("done (single form): repo-relative files the feature touched."),architecture:l9}},async($)=>{try{let{path:Q,body:Z}=u9($.action,$),Y=await v0(Q,Z);return{content:[{type:"text",text:JSON.stringify(Y)}]}}catch(Q){return g5(Q)}});A.registerTool("beacon_init_persist",{description:"Use ONLY inside the `beacon-init` skill. After YOU (Claude Code) have read the repo and built the architecture analysis, call this once to persist it into Beacon. Replaces any prior init-derived map. Same DB shape as `beacon_propose_plan` for tables/endpoints, but it commits directly (no /plan review step) because the user explicitly invoked init.",inputSchema:{overview:J.string().optional().describe("one-paragraph summary of the project \u2014 written to ProjectMeta + AGENTS.md"),conventions:J.array(J.string()).optional().describe("3-8 concrete conventions/gotchas a contributor must follow"),hasFrontend:J.boolean().optional().describe("Whether this repo has a frontend surface (UI code) \u2014 you just read the repo, so you know. Gates the per-item `layer` requirement + the layer UI on the boards. Set it explicitly (true or false); omitting leaves Beacon to detect it from the code graph."),classificationRoots:J.array(J.string()).optional().describe("Top-level dirs whose immediate children are the meaningful groups on the Files canvas \u2014 e.g. ['frontend','backend/app']. The canvas groups files ONE level below each (so 'frontend' \u2192 'frontend/components', 'frontend/app', \u2026). Pick the dir sitting directly ABOVE the real package dirs (use 'frontend/src' if there's a src/ wrapper). Not every dir \u2014 just where grouping should start. Omit for a simple single-root repo (the canvas auto-groups)."),components:J.array(J.object({title:J.string(),domain:J.string().describe("short UPPERCASE area: AUTH, API, DATA, UI, JOBS, INFRA, \u2026"),role:J.string().optional().describe("one-line technical role"),plain:J.string().optional().describe("one plain-language sentence"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack the component lives on \u2014 set it when hasFrontend is true"),files:J.array(J.string()).optional().describe("repo-relative key files"),depends:J.array(J.string()).optional().describe("titles of other components it depends on"),bugs:J.array(J.object({note:J.string().describe("what was found / worth investigating")})).optional().describe("bugs or things worth investigating you found while examining this component \u2014 flagged on the node (by=agent)")})).describe("8-25 main building blocks, not every file"),roadmap:J.array(J.object({title:J.string(),why:J.string().optional(),category:J.string().optional().describe("category for the board (AUTH | SEARCH | DATA | INTEL | \u2026) \u2014 set it so the item isn't category-less"),priority:J.number().int().min(0).max(3).optional().describe("0=P0 critical .. 3=P3 low"),kind:J.enum(["FEATURE","BUG"]).optional().describe("BUG when the survey found a concrete bug to fix \u2014 renders as a typed bug card; defaults to FEATURE"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack the item lands on \u2014 set it when hasFrontend is true")})).optional().describe("3-6 broad strategic directions (NOT detailed tasks); each with a `category` + `priority`. Re-runs DEDUPE roadmap features by title, so re-persisting won't double up existing ones."),snapshot:J.object({tables:J.array(J.object({name:J.string(),domain:J.string().optional(),description:J.string().optional(),columns:J.array(J.object({name:J.string(),type:J.string(),isPk:J.boolean().optional(),isFk:J.boolean().optional(),nullable:J.boolean().optional(),note:J.string().optional()}))})).optional(),relations:J.array(J.object({fromTable:J.string(),fromColumn:J.string(),toTable:J.string(),toColumn:J.string(),label:J.string().optional()})).optional(),endpoints:J.array(J.object({method:J.string(),path:J.string(),domain:J.string().optional(),description:J.string().optional(),uses:J.array(J.object({table:J.string(),access:J.string().optional()})).optional()})).optional()}).optional().describe("optional: also seed /db with the schema you discovered from prisma/SQLAlchemy/etc.")}},async($)=>{let Q=await v0("/api/init",$);return{content:[{type:"text",text:JSON.stringify(Q)}]}});A.registerTool("beacon_context_for_feature",{description:"Use BEFORE Glob/Grep/Read when starting work on a feature. Returns a single bundle of everything Beacon knows about it: attached files, what those files import + what imports them (1-hop blast radius from the live code graph), endpoints in the feature's domain + the tables each touches, those tables' FK relations, sibling architecture components, and the project's conventions. Saves an entire discovery-phase round of file reads. Match by id (preferred), exact title, or a natural-language query.",inputSchema:{id:J.string().optional().describe("node id from beacon_map (preferred)"),title:J.string().optional().describe("feature title (case-insensitive contains)"),query:J.string().optional().describe("natural-language phrase \u2014 OR-matched against title + plain description")}},async({id:$,title:Q,query:Z})=>{let Y=new URLSearchParams;if($)Y.set("id",$);if(Q)Y.set("title",Q);if(Z)Y.set("query",Z);let V=await E(`/api/context/feature?${Y.toString()}`);return{content:[{type:"text",text:JSON.stringify(V)}]}});A.registerTool("beacon_blast_radius",{description:"For 'if I change this file, what else cares?' \u2014 returns the file's 1-hop imports + importedBy, the TRANSITIVE blast radius both directions (downstream = who depends on it, upstream = what it depends on, grouped by depth), hub/centrality scoring (inDegree/outDegree + isHub), and every feature/component that has the file attached. Use mid-feature when deciding the impact of a change, or before refactoring a hub file.",inputSchema:{path:J.string().describe("repo-relative POSIX file path"),depth:J.number().optional().describe("how far to walk the transitive graph (default 2, capped at 5)")}},async({path:$,depth:Q})=>{let Z=new URLSearchParams({path:$});if(Q!=null)Z.set("depth",String(Q));let Y=await E(`/api/context/file?${Z.toString()}`);return{content:[{type:"text",text:JSON.stringify(Y)}]}});A.registerTool("beacon_entities",{description:"Read raw planning data: `features` (roadmap), `architecture` (components), `tables`/`endpoints` (DB map). Descriptions are truncated to ~160 chars by default to stay within the tool-result limit \u2014 pass `full:true` for complete text and `limit` to cap rows. For just titles + categories + status, prefer the lighter `beacon_map`.",inputSchema:{kind:J.enum(["features","architecture","tables","endpoints"]),full:J.boolean().optional().describe("return complete descriptions instead of the truncated default (features/architecture)"),limit:J.number().int().positive().optional().describe("cap the number of rows returned")}},async({kind:$,full:Q,limit:Z})=>{let Y=new URLSearchParams({kind:$});if(Q)Y.set("full","1");if(Z)Y.set("limit",String(Z));let V=await E(`/api/entities?${Y.toString()}`);return{content:[{type:"text",text:JSON.stringify(V)}]}});A.registerTool("beacon_propose_plan",{description:"BLOCKS until the user reviews. Pushes a feature plan (top-level roadmap features + DB tables + endpoints) to Beacon's /plan page. Use when the user asks you to plan a feature. EVERY feature MUST include `cluster` (its category) and `priority` (0=P0 critical .. 3=P3 low) \u2014 and, when the workspace has a frontend, `layer` (frontend | backend | fullstack). The tool REJECTS a plan whose features omit any required field, so set them on every feature. Do not implement code or migrations until this returns approval. If it returns inline feedback, revise and call again.",inputSchema:{description:J.string().describe("Short summary the user will see in the review header. In any prose (here or a feature's `plain`), write file references as repo-relative paths in `backticks` \u2014 on /plan, paths matching a REAL repo file render clickable to open in the user's editor."),features:J.array(J.object({title:J.string(),role:J.string().optional().describe("one-line technical role"),plain:J.string().optional().describe("one plain-language sentence for the user"),category:J.string().optional().describe("REQUIRED category for the board (AUTH | SEARCH | BILLING | DATA | INTEL | \u2026)"),cluster:J.string().optional().describe("alias for `category`"),domain:J.string().optional().describe("alias for `category`"),priority:J.number().int().min(0).max(3).optional().describe("REQUIRED priority: 0=P0 critical, 1=P1 high, 2=P2 medium, 3=P3 low"),dependsOn:J.array(J.string()).optional().describe("titles of other features in THIS plan that must ship first \u2014 drawn as 'depends on' links so the board shows the dependency chain, not loose cards"),kind:J.enum(["FEATURE","BUG"]).optional().describe("BUG when this roadmap item is a bug to fix \u2014 renders as a typed bug card; defaults to FEATURE"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("Which side of the stack the work lands on. REQUIRED on every feature when the workspace has a frontend (the tool rejects the plan otherwise); omit in pure-backend repos.")})).optional().describe("the top-level roadmap features this plan adds"),tables:J.array(J.object({name:J.string(),domain:J.string().optional(),description:J.string().optional(),columns:J.array(J.object({name:J.string(),type:J.string(),isPk:J.boolean().optional(),isFk:J.boolean().optional(),nullable:J.boolean().optional(),note:J.string().optional()}))})).optional(),relations:J.array(J.object({fromTable:J.string(),fromColumn:J.string(),toTable:J.string(),toColumn:J.string(),label:J.string().optional()})).optional(),endpoints:J.array(J.object({method:J.string().describe("GET|POST|PUT|PATCH|DELETE"),path:J.string(),domain:J.string().optional(),description:J.string().optional(),uses:J.array(J.object({table:J.string(),access:J.string().optional()})).optional()})).optional(),contract:J.array(J.string()).optional().describe("Repo-relative files THIS plan will touch \u2014 the scope contract. Frozen at approval; you're held to them while implementing: editing an undeclared file pauses for the user's authorization (which adds it to the contract), and the /plan Changes view groups your edits On-plan vs Strayed against this set. Always list the files you genuinely expect to edit \u2014 if omitted, the scope is inferred from the files you name in backticks.")}},async({description:$,features:Q,tables:Z,relations:Y,endpoints:V,contract:H})=>{let G=(w)=>new Promise((F0)=>setTimeout(F0,w)),W=(w)=>({content:[{type:"text",text:w}]}),j=(Z?.length??0)>0,K=(Q??[]).map((w)=>`${w.title} ${w.role??""} ${w.plain??""}`).join(`
361
- `),p=(V?.length??0)>0||S9(`${$}
362
- ${K}`);if(!j&&p)return W("\u26D4 This plan touches the database \u2014 it declares endpoints and/or its text describes "+"models/tables/migrations \u2014 but you passed NO `tables`. Beacon's schema board renders "+"ONLY from structured `tables`; prose is never parsed, so the /db tab would be empty and nothing would persist on approve.\n\nRe-call `beacon_propose_plan` with every table in `tables` (each with its `columns`), the `relations` (FKs), and keep the `endpoints` (each with `uses:[{table,access}]`). Mirror EVERY database entity your plan mentions into the structured fields.");if(Q?.length){let w=await E("/api/project-meta").then((i9)=>!!i9?.hasFrontend).catch(()=>!1),F0=f9(Q,{requireLayer:w});if(F0)return W(F0)}let C=(Z?.length??0)+(V?.length??0)>0;try{await v0("/api/plan",{description:$,draft:C?{tables:Z??[],relations:Y??[],endpoints:V??[]}:void 0,features:Q?.length?Q:void 0,contract:H?.length?H:void 0})}catch(w){return g5(w)}await fetch(`${b()}/api/workspace/activate?id=${S}`).catch(()=>{}),await f5(b(),S);let J5=Date.now()+S0;while(Date.now()<J5){await G(x0);let w=await E("/api/plan/verdict").catch(()=>null);if(!w)continue;if(w.kind==="feedback")return W("\uD83D\uDCAC The user left feedback on the plan in Beacon \u2014 text comments and/or edits they "+"made directly on the /map and /db boards. Read everything below, revise the plan accordingly (matching the board changes verbatim), and call `beacon_propose_plan` "+`again with the revised version \u2014 DO NOT implement yet:
361
+ `)+'\n\nWhen the work ships, register them in ONE call: `beacon_feature({ action: "done" })` with a '+"`features` array \u2014 one entry per feature"+(Z?", each keyed by the `id` above (no title-matching needed)":"")+", each with the files you touched + a short markdown summary. Do them all in that single "+"batched call so every feature flips to Done \u2014 do NOT register only the umbrella, and do "+"NOT make one call per feature."}import{readFileSync as ZZ}from"fs";import{join as JZ}from"path";function YZ(){try{return JSON.parse(ZZ(JZ(x(),"server.json"),"utf8"))}catch{return null}}function c(){if(process.env.BEACON_URL)return process.env.BEACON_URL;return`http://localhost:${YZ()?.port||process.env.PORT||T9}`}import{execSync as VZ}from"child_process";import{platform as z9}from"os";function z5($){if(process.env.BEACON_NO_OPEN)return;let Q=z9()==="darwin"?"open":z9()==="win32"?"start":"xdg-open";try{VZ(`${Q} "${$}"`,{stdio:"ignore"})}catch{}}async function h5($,Q){if(await fetch(`${$}/api/plan/presence`,{headers:{"x-beacon-workspace":Q}}).then((V)=>V.json()).then((V)=>!!V?.live).catch(()=>!1))return;let Y=encodeURIComponent(`/plan?ws=${Q}`);z5(`${$}/api/workspace/activate?id=${Q}&redirect=${Y}`)}async function h9($,Q){if(await fetch(`${$}/api/lesson/presence`,{headers:{"x-beacon-workspace":Q}}).then((V)=>V.json()).then((V)=>!!V?.live).catch(()=>!1))return;let Y=encodeURIComponent(`/learn?ws=${Q}`);z5(`${$}/api/workspace/activate?id=${Q}&redirect=${Y}`)}var b9=["imports","calls","persists to","reads from","writes to","routes to","depends on","emits","returns","contains","extends"];U5();function C0($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036F]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50)||"item"}function p9($){return`${C0($.title)}-${$.id.slice(-6)}`}function m9($){return{resources:$.map((Q)=>({uri:`note://${p9(Q)}`,name:Q.title||"Untitled",description:`${Q.title||"Untitled"}${Q.pinned?" \xB7 pinned":""} \xB7 note`,mimeType:"text/markdown"}))}}function c9($,Q){return $.find((Z)=>p9(Z)===Q)}function l9($){let Q=$.body.trim()||"(this note is empty)";return[`# ${$.title||"Untitled"}`,"","_User note from Beacon. To turn it into roadmap work, call `beacon_propose_plan` \u2014"+" checkbox `- [ ]` / `- [x]` items become subtasks, and order the features with `dependsOn`. Do NOT implement until it returns approval._","","---","",Q].join(`
362
+ `)}await q9();var l=L5(),f=d(l);if(!n0(l)){let $=e0();if($.length===1)console.error(`[beacon mcp] cwd ${l} isn't a registered repo \u2014 falling back to your only Beacon workspace "${$[0].name}".`);else if($.length>1)console.error(`[beacon mcp] cwd ${l} isn't a registered repo and you have ${$.length} Beacon workspaces \u2014 can't auto-detect which. Run /beacon-init in this repo, or name the project explicitly in your request.`);else console.error(`[beacon mcp] not registering ${l} \u2014 home/non-repo dir.`)}else if(a0(f))console.error(`[beacon mcp] not registering ${l} \u2014 workspace was deleted; run /beacon-init to re-add it.`);else try{$5(l);let $=await x5(f);if(!$.ok)console.error(`[beacon mcp] db provisioning failed: ${$.error}`)}catch($){console.error(`[beacon mcp] workspace registration failed: ${$ instanceof Error?$.message:$}`)}async function T($,Q){let Z=new Headers(Q?.headers);Z.set("x-beacon-workspace",f),Z.set(Q5,l);let Y=await fetch(`${c()}${$}`,{...Q,headers:Z}),V=await Y.text();if(!Y.ok)throw Error(`Beacon ${$} -> ${Y.status} ${V}`);return V?JSON.parse(V):null}function R0($,Q){return T($,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Q)})}function p5($){let Q=$ instanceof Error?$.message:String($),Z=Q.match(/\{[\s\S]*\}$/);if(Z)try{let Y=JSON.parse(Z[0]);if(Y?.error)return{content:[{type:"text",text:Y.error}],isError:!0}}catch{}return{content:[{type:"text",text:Q}],isError:!0}}var E=new XZ({name:"beacon",version:"0.1.0"});E.registerTool("beacon_map",{description:"List the roadmap: every feature + its sub-tasks with `category`, `priority`, `layer`, `kind`, and `status`. Call this BEFORE creating anything with `beacon_feature` \u2014 it's the cheap way to learn which categories already exist (reuse one instead of inventing a synonym) and whether a card already exists. You do NOT need `beacon_entities` just to see categories."},async()=>{let $=await T("/api/map");return{content:[{type:"text",text:JSON.stringify($)}]}});var d9=J.array(J.object({title:J.string().describe("real component/subsystem name (e.g. 'Plan review loop') \u2014 NEVER a file"),domain:J.string().describe("uppercase lane: PLAN | DATA | UI | MCP | INTEL | \u2026"),role:J.string().optional().describe("one-line technical role"),plain:J.string().optional().describe("one plain-language sentence"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack the component lives on (only when the repo has a frontend); omitting it on an update keeps the prior value"),status:J.enum(["KEEP","REBUILD","REPLACE","DROP"]).optional(),files:J.array(J.string()).optional(),depends:J.array(J.string()).optional().describe("titles of components this one depends on"),bugs:J.array(J.object({note:J.string().describe("what was found / worth investigating")})).optional().describe("bugs or things worth investigating you found in this component's code \u2014 flagged on the node (by=agent); identical open flags are not duplicated")})).optional().describe("Only when the feature adds/changes a REAL architectural component \u2014 upserts curated nodes, never one-per-file");E.registerTool("beacon_feature",{description:'Manage a roadmap feature\'s whole lifecycle in ONE tool \u2014 no approval gate (that\'s `beacon_propose_plan`/`beacon_present_plan`). `action:"add"` puts a card on the board, defaulting to BACKLOG/PENDING (pass `status:"active"` to start it now); `"start"` marks an existing card IN_PROGRESS (create-or-flag); `"subtasks"` adds child tasks under a card; `"done"` completes feature(s) and registers the files/architecture touched (marks DONE + cascades to sub-tasks). A NEW card REQUIRES `category` + `priority` (and `layer` when the workspace has a frontend). Call `beacon_map` FIRST \u2014 it lists every card\'s category/priority/layer/status, so reuse a category and avoid an EXACT duplicate (same title + category + layer) \u2014 a same-named card in a different category, or on a different layer (FE/BE/FS), is allowed as its own card. `add` never activates an existing match \u2014 it returns `exists` so you can reuse it.',inputSchema:{action:J.enum(["add","start","subtasks","done"]).describe("add = put a card on the board (defaults to BACKLOG/PENDING); start = mark an existing card IN_PROGRESS; subtasks = add child tasks under a card; done = complete feature(s) + register files/architecture."),title:J.string().optional().describe("card title (add/start); for done's single form, the feature title (id preferred)."),id:J.string().optional().describe("node id from beacon_map (preferred over title) \u2014 start/done, or add to reference a known card."),category:J.string().optional().describe("REQUIRED for a NEW card (add/start): domain lane \u2014 AUTH | SEARCH | DATA | INTEL | BILLING | INFRA | UI | \u2026 Reuse one from beacon_map; ignored when matching an existing card or nesting under a `front`."),priority:J.number().int().min(0).max(3).optional().describe("priority of a NEW card (add/start): 0=P0 critical .. 3=P3 low. Defaults to P2."),front:J.string().optional().describe("title of an EXISTING parent feature to nest a NEW card under (add/start). NOT a domain tag (use `category`); a `front` matching nothing is REJECTED."),detail:J.string().optional().describe("one-line plain-language description shown on the card (add/start)."),kind:J.enum(["FEATURE","BUG"]).optional().describe("BUG renders a typed bug card; defaults to FEATURE (add/start)."),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack a NEW card lands on (add/start). REQUIRED when the workspace has a frontend; a card nested under a `front` inherits the parent's. Omit in pure-backend repos."),status:J.enum(["backlog","active"]).optional().describe(`add only: "backlog" (default) creates a PENDING card you're not working on yet; "active" creates it IN_PROGRESS.`),parentId:J.string().optional().describe("subtasks: node id of the parent card (preferred)."),parentTitle:J.string().optional().describe("subtasks: fuzzy title of the parent card; ignored if parentId is given."),items:J.array(J.object({title:J.string().describe("short sub-task title"),plain:J.string().optional().describe("one-paragraph description / why / acceptance hint"),kind:J.enum(["FEATURE","BUG"]).optional().describe("BUG for a bug discovered during work; defaults to FEATURE"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack the sub-task lands on; defaults to the parent's layer")})).optional().describe("subtasks: the child tasks to add under the parent."),features:J.array(J.object({id:J.string().optional().describe("node id from plan approval / beacon_map (preferred over title)"),title:J.string().optional().describe("feature title (fuzzy-matched if no id)"),description:J.string().describe("Markdown: ### Overview ... ### Files - `path` \u2014 what it does"),files:J.array(J.string()).optional().describe("repo-relative files this feature touches"),architecture:d9})).optional().describe("done: register MANY features at once \u2014 one entry per feature the plan created, each id-keyed. Use this instead of N separate calls."),description:J.string().optional().describe("done (single form, omit when using `features`): the markdown summary of the shipped feature."),files:J.array(J.string()).optional().describe("done (single form): repo-relative files the feature touched."),architecture:d9}},async($)=>{try{let{path:Q,body:Z}=f9($.action,$),Y=await R0(Q,Z);return{content:[{type:"text",text:JSON.stringify(Y)}]}}catch(Q){return p5(Q)}});E.registerTool("beacon_init_persist",{description:"Use ONLY inside the `beacon-init` skill. After YOU (Claude Code) have read the repo and built the architecture analysis, call this once to persist it into Beacon. Replaces any prior init-derived map. Same DB shape as `beacon_propose_plan` for tables/endpoints, but it commits directly (no /plan review step) because the user explicitly invoked init.",inputSchema:{overview:J.string().optional().describe("one-paragraph summary of the project \u2014 written to ProjectMeta + AGENTS.md"),conventions:J.array(J.string()).optional().describe("3-8 concrete conventions/gotchas a contributor must follow"),hasFrontend:J.boolean().optional().describe("Whether this repo has a frontend surface (UI code) \u2014 you just read the repo, so you know. Gates the per-item `layer` requirement + the layer UI on the boards. Set it explicitly (true or false); omitting leaves Beacon to detect it from the code graph."),classificationRoots:J.array(J.string()).optional().describe("Top-level dirs whose immediate children are the meaningful groups on the Files canvas \u2014 e.g. ['frontend','backend/app']. The canvas groups files ONE level below each (so 'frontend' \u2192 'frontend/components', 'frontend/app', \u2026). Pick the dir sitting directly ABOVE the real package dirs (use 'frontend/src' if there's a src/ wrapper). Not every dir \u2014 just where grouping should start. Omit for a simple single-root repo (the canvas auto-groups)."),components:J.array(J.object({title:J.string(),domain:J.string().describe("short UPPERCASE area: AUTH, API, DATA, UI, JOBS, INFRA, \u2026"),role:J.string().optional().describe("one-line technical role"),plain:J.string().optional().describe("one plain-language sentence"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack the component lives on \u2014 set it when hasFrontend is true"),files:J.array(J.string()).optional().describe("repo-relative key files"),depends:J.array(J.string()).optional().describe("titles of other components it depends on"),bugs:J.array(J.object({note:J.string().describe("what was found / worth investigating")})).optional().describe("bugs or things worth investigating you found while examining this component \u2014 flagged on the node (by=agent)")})).describe("8-25 main building blocks, not every file"),roadmap:J.array(J.object({title:J.string(),why:J.string().optional(),category:J.string().optional().describe("category for the board (AUTH | SEARCH | DATA | INTEL | \u2026) \u2014 set it so the item isn't category-less"),priority:J.number().int().min(0).max(3).optional().describe("0=P0 critical .. 3=P3 low"),kind:J.enum(["FEATURE","BUG"]).optional().describe("BUG when the survey found a concrete bug to fix \u2014 renders as a typed bug card; defaults to FEATURE"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack the item lands on \u2014 set it when hasFrontend is true")})).optional().describe("3-6 broad strategic directions (NOT detailed tasks); each with a `category` + `priority`. Re-runs DEDUPE roadmap features by title, so re-persisting won't double up existing ones."),snapshot:J.object({tables:J.array(J.object({name:J.string(),domain:J.string().optional(),description:J.string().optional(),columns:J.array(J.object({name:J.string(),type:J.string(),isPk:J.boolean().optional(),isFk:J.boolean().optional(),nullable:J.boolean().optional(),note:J.string().optional()}))})).optional(),relations:J.array(J.object({fromTable:J.string(),fromColumn:J.string(),toTable:J.string(),toColumn:J.string(),label:J.string().optional()})).optional(),endpoints:J.array(J.object({method:J.string(),path:J.string(),domain:J.string().optional(),description:J.string().optional(),uses:J.array(J.object({table:J.string(),access:J.string().optional()})).optional()})).optional()}).optional().describe("optional: also seed /db with the schema you discovered from prisma/SQLAlchemy/etc.")}},async($)=>{let Q=await R0("/api/init",$);return{content:[{type:"text",text:JSON.stringify(Q)}]}});E.registerTool("beacon_context_for_feature",{description:"Use BEFORE Glob/Grep/Read when starting work on a feature. Returns a single bundle of everything Beacon knows about it: attached files, what those files import + what imports them (1-hop blast radius from the live code graph), endpoints in the feature's domain + the tables each touches, those tables' FK relations, sibling architecture components, and the project's conventions. Saves an entire discovery-phase round of file reads. Match by id (preferred), exact title, or a natural-language query.",inputSchema:{id:J.string().optional().describe("node id from beacon_map (preferred)"),title:J.string().optional().describe("feature title (case-insensitive contains)"),query:J.string().optional().describe("natural-language phrase \u2014 OR-matched against title + plain description")}},async({id:$,title:Q,query:Z})=>{let Y=new URLSearchParams;if($)Y.set("id",$);if(Q)Y.set("title",Q);if(Z)Y.set("query",Z);let V=await T(`/api/context/feature?${Y.toString()}`);return{content:[{type:"text",text:JSON.stringify(V)}]}});E.registerTool("beacon_blast_radius",{description:"For 'if I change this file, what else cares?' \u2014 returns the file's 1-hop imports + importedBy, the TRANSITIVE blast radius both directions (downstream = who depends on it, upstream = what it depends on, grouped by depth), hub/centrality scoring (inDegree/outDegree + isHub), and every feature/component that has the file attached. Use mid-feature when deciding the impact of a change, or before refactoring a hub file.",inputSchema:{path:J.string().describe("repo-relative POSIX file path"),depth:J.number().optional().describe("how far to walk the transitive graph (default 2, capped at 5)")}},async({path:$,depth:Q})=>{let Z=new URLSearchParams({path:$});if(Q!=null)Z.set("depth",String(Q));let Y=await T(`/api/context/file?${Z.toString()}`);return{content:[{type:"text",text:JSON.stringify(Y)}]}});E.registerTool("beacon_entities",{description:"Read raw planning data: `features` (roadmap), `architecture` (components), `tables`/`endpoints` (DB map). Descriptions are truncated to ~160 chars by default to stay within the tool-result limit \u2014 pass `full:true` for complete text and `limit` to cap rows. For just titles + categories + status, prefer the lighter `beacon_map`.",inputSchema:{kind:J.enum(["features","architecture","tables","endpoints"]),full:J.boolean().optional().describe("return complete descriptions instead of the truncated default (features/architecture)"),limit:J.number().int().positive().optional().describe("cap the number of rows returned")}},async({kind:$,full:Q,limit:Z})=>{let Y=new URLSearchParams({kind:$});if(Q)Y.set("full","1");if(Z)Y.set("limit",String(Z));let V=await T(`/api/entities?${Y.toString()}`);return{content:[{type:"text",text:JSON.stringify(V)}]}});E.registerTool("beacon_propose_plan",{description:"BLOCKS until the user reviews. Pushes a feature plan (top-level roadmap features + DB tables + endpoints) to Beacon's /plan page. Use when the user asks you to plan a feature. EVERY feature MUST include `cluster` (its category) and `priority` (0=P0 critical .. 3=P3 low) \u2014 and, when the workspace has a frontend, `layer` (frontend | backend | fullstack). The tool REJECTS a plan whose features omit any required field, so set them on every feature. Do not implement code or migrations until this returns approval. If it returns inline feedback, revise and call again.",inputSchema:{description:J.string().describe("Short summary the user will see in the review header. In any prose (here or a feature's `plain`), write file references as repo-relative paths in `backticks` \u2014 on /plan, paths matching a REAL repo file render clickable to open in the user's editor."),features:J.array(J.object({title:J.string(),role:J.string().optional().describe("one-line technical role"),plain:J.string().optional().describe("one plain-language sentence for the user"),category:J.string().optional().describe("REQUIRED category for the board (AUTH | SEARCH | BILLING | DATA | INTEL | \u2026)"),cluster:J.string().optional().describe("alias for `category`"),domain:J.string().optional().describe("alias for `category`"),priority:J.number().int().min(0).max(3).optional().describe("REQUIRED priority: 0=P0 critical, 1=P1 high, 2=P2 medium, 3=P3 low"),dependsOn:J.array(J.string()).optional().describe("titles of other features in THIS plan that must ship first \u2014 drawn as 'depends on' links so the board shows the dependency chain, not loose cards"),kind:J.enum(["FEATURE","BUG"]).optional().describe("BUG when this roadmap item is a bug to fix \u2014 renders as a typed bug card; defaults to FEATURE"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("Which side of the stack the work lands on. REQUIRED on every feature when the workspace has a frontend (the tool rejects the plan otherwise); omit in pure-backend repos.")})).optional().describe("the top-level roadmap features this plan adds"),tables:J.array(J.object({name:J.string(),domain:J.string().optional(),description:J.string().optional(),columns:J.array(J.object({name:J.string(),type:J.string(),isPk:J.boolean().optional(),isFk:J.boolean().optional(),nullable:J.boolean().optional(),note:J.string().optional()}))})).optional(),relations:J.array(J.object({fromTable:J.string(),fromColumn:J.string(),toTable:J.string(),toColumn:J.string(),label:J.string().optional()})).optional(),endpoints:J.array(J.object({method:J.string().describe("GET|POST|PUT|PATCH|DELETE"),path:J.string(),domain:J.string().optional(),description:J.string().optional(),uses:J.array(J.object({table:J.string(),access:J.string().optional()})).optional()})).optional(),contract:J.array(J.string()).optional().describe("Repo-relative files THIS plan will touch \u2014 the scope contract. Frozen at approval; you're held to them while implementing: editing an undeclared file pauses for the user's authorization (which adds it to the contract), and the /plan Changes view groups your edits On-plan vs Strayed against this set. Always list the files you genuinely expect to edit \u2014 if omitted, the scope is inferred from the files you name in backticks.")}},async({description:$,features:Q,tables:Z,relations:Y,endpoints:V,contract:H})=>{let G=(w)=>new Promise((D0)=>setTimeout(D0,w)),j=(w)=>({content:[{type:"text",text:w}]}),U=(Z?.length??0)>0,K=(Q??[]).map((w)=>`${w.title} ${w.role??""} ${w.plain??""}`).join(`
363
+ `),D=(V?.length??0)>0||u9(`${$}
364
+ ${K}`);if(!U&&D)return j("\u26D4 This plan touches the database \u2014 it declares endpoints and/or its text describes "+"models/tables/migrations \u2014 but you passed NO `tables`. Beacon's schema board renders "+"ONLY from structured `tables`; prose is never parsed, so the /db tab would be empty and nothing would persist on approve.\n\nRe-call `beacon_propose_plan` with every table in `tables` (each with its `columns`), the `relations` (FKs), and keep the `endpoints` (each with `uses:[{table,access}]`). Mirror EVERY database entity your plan mentions into the structured fields.");if(Q?.length){let w=await T("/api/project-meta").then((n9)=>!!n9?.hasFrontend).catch(()=>!1),D0=g9(Q,{requireLayer:w});if(D0)return j(D0)}let C=(Z?.length??0)+(V?.length??0)>0;try{await R0("/api/plan",{description:$,draft:C?{tables:Z??[],relations:Y??[],endpoints:V??[]}:void 0,features:Q?.length?Q:void 0,contract:H?.length?H:void 0})}catch(w){return p5(w)}await fetch(`${c()}/api/workspace/activate?id=${f}`).catch(()=>{}),await h5(c(),f);let X5=Date.now()+u0;while(Date.now()<X5){await G(x0);let w=await T("/api/plan/verdict").catch(()=>null);if(!w)continue;if(w.kind==="feedback")return j("\uD83D\uDCAC The user left feedback on the plan in Beacon \u2014 text comments and/or edits they "+"made directly on the /map and /db boards. Read everything below, revise the plan accordingly (matching the board changes verbatim), and call `beacon_propose_plan` "+`again with the revised version \u2014 DO NOT implement yet:
363
365
 
364
- `+w.feedback);if(w.kind==="approved")return W(`\u2705 Plan approved by the user. ${w.summary}`+(w.detail?`
366
+ `+w.feedback);if(w.kind==="approved")return j(`\u2705 Plan approved by the user. ${w.summary}`+(w.detail?`
365
367
 
366
368
  Implement EXACTLY the schema below (migrations + code) \u2014 the user may have `+`edited columns on the canvas:
367
369
 
368
- `+w.detail:"")+S5(w.features));if(w.kind==="discarded")return W(`\u274C The user discarded the plan in Beacon. ${w.summary} Ask what they want to adjust before proposing again.`)}return W("Still waiting for the user to review in Beacon. Your plan is preserved \u2014 call "+"`beacon_propose_plan` again with the SAME plan to resume (the verdict is picked up immediately if they've since decided), or ask whether they've reviewed it.")});A.registerTool("beacon_explain",{description:"BLOCKS until the user is done learning. Use when the user asks you to EXPLAIN / TEACH / walk "+"them through part of the codebase (architecture, a category, how X works) \u2014 NOT to plan a "+"build (that's beacon_propose_plan). Pushes an interactive Lesson to Beacon's /learn page: a curated concept map (nodes + verb-labeled arrows) beside a plain-English narrative. The user highlights text to ask questions and drops question notes; this returns their questions so you ANSWER them and call beacon_explain AGAIN with the same lesson plus `answers:[{questionId,answer}]`, looping until they Save.\n\nWrite like a great teacher (the house style): open each component with the PROBLEM it solves and a concrete scenario; give a numbered step-by-step flow naming every real identifier in `backticks` (files become clickable on /learn); add 'Why X?' sections that explain why the alternative is worse; include a worked example with a small data table; use **bold** for decisions, *italic* for concepts. Map every piece you name to a node, "+"and every 'A does X to B' to a labeled edge. Plain English throughout \u2014 define terms inline.",inputSchema:{title:J.string().describe("the lesson title, e.g. 'How a plan flows to /plan'"),topic:J.string().optional().describe("the user's request, verbatim (shown in the library)"),narrative:J.string().describe("The house-style explanation as markdown (problem-first \u2192 numbered flow \u2192 'Why X?' \u2192 worked example). Write file references as repo-relative paths in `backticks` \u2014 they render clickable on /learn."),nodes:J.array(J.object({id:J.string().describe("a short stable id you assign (e.g. 'n1') \u2014 edges reference it"),title:J.string(),summary:J.string().optional().describe("one-line plain-English summary shown on the node face"),detail:J.string().optional().describe("fuller plain-English explanation, markdown, shown on click"),files:J.array(J.string()).optional().describe("real repo-relative paths this node maps to \u2014 clickable chips"),group:J.string().optional().describe("optional cluster label for landmark regions"),x:J.number().optional(),y:J.number().optional()})).optional().describe("the curated concept-map boxes \u2014 keep the resting set small (~4-7 per view)"),edges:J.array(J.object({fromId:J.string(),toId:J.string(),verb:J.enum(z9).describe("the relationship \u2014 a labeled directional arrow, never a bare line")})).optional(),tables:J.array(J.object({id:J.string().describe("a short stable id you assign (e.g. 't1') \u2014 edges + fkTo reference it"),name:J.string(),domain:J.string().optional(),note:J.string().optional().describe("one plain-English line: why this table exists"),group:J.string().optional(),columns:J.array(J.object({name:J.string(),type:J.string().optional(),isPk:J.boolean().optional(),isFk:J.boolean().optional(),fkTo:J.string().optional().describe("id of the table this column references \u2014 draws an FK link"),note:J.string().optional().describe("plain-English: what this column is for")})).optional(),sample:J.array(J.record(J.string(),J.string())).optional().describe("worked-example rows (column name \u2192 value) shown when the card is expanded")})).optional().describe("database tables the lesson teaches \u2014 rendered as annotated schema cards on the SAME board. Connect a concept to a table with an edge whose toId is the table id (verb 'persists to' / 'reads from'); give key columns isPk, FKs an fkTo, and EVERY column a plain-English note. Add a sample row."),steps:J.array(J.object({title:J.string(),summary:J.string().optional(),focusIds:J.array(J.string()).optional().describe("node/table ids to spotlight this step; omit/[] = whole-board overview"),narrativeAnchor:J.string().optional()})).optional().describe("the guided-walkthrough order \u2014 reveal one node/step at a time; first step should be the overview"),answers:J.array(J.object({questionId:J.string(),answer:J.string()})).optional().describe("on a re-push: your answers to the user's questions, keyed by the [q:ID] they came with")}},async({title:$,topic:Q,narrative:Z,nodes:Y,edges:V,tables:H,steps:G,answers:W})=>{let j=(C)=>new Promise((J5)=>setTimeout(J5,C)),K=(C)=>({content:[{type:"text",text:C}]});try{await v0("/api/lesson",{title:$,topic:Q,narrative:Z,nodes:Y,edges:V,tables:H,steps:G,answers:W})}catch(C){return g5(C)}await fetch(`${b()}/api/workspace/activate?id=${S}`).catch(()=>{}),await g9(b(),S);let p=Date.now()+S0;while(Date.now()<p){await j(x0);let C=await E("/api/lesson/verdict").catch(()=>null);if(!C)continue;if(C.kind==="questions")return K("\uD83D\uDCAC The user asked questions about the lesson in Beacon. Answer each one, then call "+"`beacon_explain` AGAIN with the SAME lesson plus `answers:[{questionId,answer}]` (keyed by the [q:ID] below). Expand the narrative or add nodes where it helps the explanation. "+`Keep looping until the user saves \u2014 DO NOT stop after one round:
370
+ `+w.detail:"")+g5(w.features));if(w.kind==="discarded")return j(`\u274C The user discarded the plan in Beacon. ${w.summary} Ask what they want to adjust before proposing again.`)}return j("Still waiting for the user to review in Beacon. Your plan is preserved \u2014 call "+"`beacon_propose_plan` again with the SAME plan to resume (the verdict is picked up immediately if they've since decided), or ask whether they've reviewed it.")});E.registerTool("beacon_explain",{description:"BLOCKS until the user is done learning. Use when the user asks you to EXPLAIN / TEACH / walk "+"them through part of the codebase (architecture, a category, how X works) \u2014 NOT to plan a "+"build (that's beacon_propose_plan). Pushes an interactive Lesson to Beacon's /learn page: a curated concept map (nodes + verb-labeled arrows) beside a plain-English narrative. The user highlights text to ask questions and drops question notes; this returns their questions so you ANSWER them and call beacon_explain AGAIN with the same lesson plus `answers:[{questionId,answer}]`, looping until they Save.\n\nWrite like a great teacher (the house style): open each component with the PROBLEM it solves and a concrete scenario; give a numbered step-by-step flow naming every real identifier in `backticks` (files become clickable on /learn); add 'Why X?' sections that explain why the alternative is worse; include a worked example with a small data table; use **bold** for decisions, *italic* for concepts. Map every piece you name to a node, "+"and every 'A does X to B' to a labeled edge. Plain English throughout \u2014 define terms inline.",inputSchema:{title:J.string().describe("the lesson title, e.g. 'How a plan flows to /plan'"),topic:J.string().optional().describe("the user's request, verbatim (shown in the library)"),narrative:J.string().describe("The house-style explanation as markdown (problem-first \u2192 numbered flow \u2192 'Why X?' \u2192 worked example). Write file references as repo-relative paths in `backticks` \u2014 they render clickable on /learn."),nodes:J.array(J.object({id:J.string().describe("a short stable id you assign (e.g. 'n1') \u2014 edges reference it"),title:J.string(),summary:J.string().optional().describe("one-line plain-English summary shown on the node face"),detail:J.string().optional().describe("fuller plain-English explanation, markdown, shown on click"),files:J.array(J.string()).optional().describe("real repo-relative paths this node maps to \u2014 clickable chips"),group:J.string().optional().describe("optional cluster label for landmark regions"),x:J.number().optional(),y:J.number().optional()})).optional().describe("the curated concept-map boxes \u2014 keep the resting set small (~4-7 per view)"),edges:J.array(J.object({fromId:J.string(),toId:J.string(),verb:J.enum(b9).describe("the relationship \u2014 a labeled directional arrow, never a bare line")})).optional(),tables:J.array(J.object({id:J.string().describe("a short stable id you assign (e.g. 't1') \u2014 edges + fkTo reference it"),name:J.string(),domain:J.string().optional(),note:J.string().optional().describe("one plain-English line: why this table exists"),group:J.string().optional(),columns:J.array(J.object({name:J.string(),type:J.string().optional(),isPk:J.boolean().optional(),isFk:J.boolean().optional(),fkTo:J.string().optional().describe("id of the table this column references \u2014 draws an FK link"),note:J.string().optional().describe("plain-English: what this column is for")})).optional(),sample:J.array(J.record(J.string(),J.string())).optional().describe("worked-example rows (column name \u2192 value) shown when the card is expanded")})).optional().describe("database tables the lesson teaches \u2014 rendered as annotated schema cards on the SAME board. Connect a concept to a table with an edge whose toId is the table id (verb 'persists to' / 'reads from'); give key columns isPk, FKs an fkTo, and EVERY column a plain-English note. Add a sample row."),steps:J.array(J.object({title:J.string(),summary:J.string().optional(),focusIds:J.array(J.string()).optional().describe("node/table ids to spotlight this step; omit/[] = whole-board overview"),narrativeAnchor:J.string().optional()})).optional().describe("the guided-walkthrough order \u2014 reveal one node/step at a time; first step should be the overview"),answers:J.array(J.object({questionId:J.string(),answer:J.string()})).optional().describe("on a re-push: your answers to the user's questions, keyed by the [q:ID] they came with")}},async({title:$,topic:Q,narrative:Z,nodes:Y,edges:V,tables:H,steps:G,answers:j})=>{let U=(C)=>new Promise((X5)=>setTimeout(X5,C)),K=(C)=>({content:[{type:"text",text:C}]});try{await R0("/api/lesson",{title:$,topic:Q,narrative:Z,nodes:Y,edges:V,tables:H,steps:G,answers:j})}catch(C){return p5(C)}await fetch(`${c()}/api/workspace/activate?id=${f}`).catch(()=>{}),await h9(c(),f);let D=Date.now()+u0;while(Date.now()<D){await U(x0);let C=await T("/api/lesson/verdict").catch(()=>null);if(!C)continue;if(C.kind==="questions")return K("\uD83D\uDCAC The user asked questions about the lesson in Beacon. Answer each one, then call "+"`beacon_explain` AGAIN with the SAME lesson plus `answers:[{questionId,answer}]` (keyed by the [q:ID] below). Expand the narrative or add nodes where it helps the explanation. "+`Keep looping until the user saves \u2014 DO NOT stop after one round:
369
371
 
370
- `+(C.rendered??""));if(C.kind==="saved")return K(`\u2705 The user saved the lesson to their library. ${C.summary} You're done explaining \u2014 `+"they can reopen it anytime from /learn.");if(C.kind==="closed")return K(`The user closed the lesson without saving. ${C.summary} Stop here; ask if they'd like a different explanation.`)}return K("Still waiting for the user to finish the lesson in Beacon. It's preserved \u2014 call "+"`beacon_explain` again with the SAME lesson to resume.")});A.registerTool("beacon_present_plan",{description:"BLOCKS until the user reviews. Pushes ANY plan (as markdown) to Beacon's /plan page so the user reviews it on the canvas instead of in the terminal \u2014 use this whenever you'd otherwise end a turn asking 'does this look right / should I proceed?'. Embed ONE fenced ```beacon block of JSON ({tables,relations,endpoints,features}) for any DB/roadmap entities so they render as an editable board. Returns the verdict (approved / discarded / feedback). Do NOT implement until it returns approval; on feedback, revise and call again. (For a pure schema+features plan, beacon_propose_plan is the structured alternative.)",inputSchema:{description:J.string().describe("One-line summary shown in the review header"),markdown:J.string().describe("The full plan as markdown. Embed a ```beacon block for tables/endpoints/features. Write file references as repo-relative paths in `backticks` (e.g. `app/api/plan/route.ts`) \u2014 on /plan, paths matching a REAL repo file render clickable to open in the user's editor.")}},async({description:$,markdown:Q})=>{let Z=(H)=>new Promise((G)=>setTimeout(G,H)),Y=(H)=>({content:[{type:"text",text:H}]});await v0("/api/plan",{description:$,markdown:Q}),await fetch(`${b()}/api/workspace/activate?id=${S}`).catch(()=>{}),await f5(b(),S);let V=Date.now()+S0;while(Date.now()<V){await Z(x0);let H=await E("/api/plan/verdict").catch(()=>null);if(!H)continue;if(H.kind==="feedback")return Y("\uD83D\uDCAC The user left feedback on the plan in Beacon (inline comments and/or edits on the "+"/map and /db boards). Revise the plan accordingly and call `beacon_present_plan` "+`again \u2014 do NOT implement yet:
372
+ `+(C.rendered??""));if(C.kind==="saved")return K(`\u2705 The user saved the lesson to their library. ${C.summary} You're done explaining \u2014 `+"they can reopen it anytime from /learn.");if(C.kind==="closed")return K(`The user closed the lesson without saving. ${C.summary} Stop here; ask if they'd like a different explanation.`)}return K("Still waiting for the user to finish the lesson in Beacon. It's preserved \u2014 call "+"`beacon_explain` again with the SAME lesson to resume.")});E.registerTool("beacon_present_plan",{description:"BLOCKS until the user reviews. Pushes ANY plan (as markdown) to Beacon's /plan page so the user reviews it on the canvas instead of in the terminal \u2014 use this whenever you'd otherwise end a turn asking 'does this look right / should I proceed?'. Embed ONE fenced ```beacon block of JSON ({tables,relations,endpoints,features}) for any DB/roadmap entities so they render as an editable board. Returns the verdict (approved / discarded / feedback). Do NOT implement until it returns approval; on feedback, revise and call again. (For a pure schema+features plan, beacon_propose_plan is the structured alternative.)",inputSchema:{description:J.string().describe("One-line summary shown in the review header"),markdown:J.string().describe("The full plan as markdown. Embed a ```beacon block for tables/endpoints/features. Write file references as repo-relative paths in `backticks` (e.g. `app/api/plan/route.ts`) \u2014 on /plan, paths matching a REAL repo file render clickable to open in the user's editor.")}},async({description:$,markdown:Q})=>{let Z=(H)=>new Promise((G)=>setTimeout(G,H)),Y=(H)=>({content:[{type:"text",text:H}]});await R0("/api/plan",{description:$,markdown:Q}),await fetch(`${c()}/api/workspace/activate?id=${f}`).catch(()=>{}),await h5(c(),f);let V=Date.now()+u0;while(Date.now()<V){await Z(x0);let H=await T("/api/plan/verdict").catch(()=>null);if(!H)continue;if(H.kind==="feedback")return Y("\uD83D\uDCAC The user left feedback on the plan in Beacon (inline comments and/or edits on the "+"/map and /db boards). Revise the plan accordingly and call `beacon_present_plan` "+`again \u2014 do NOT implement yet:
371
373
 
372
374
  `+H.feedback);if(H.kind==="approved")return Y(`\u2705 Plan approved by the user. ${H.summary??""}`.trim()+(H.detail?`
373
375
 
374
376
  Implement exactly what's on the board:
375
377
 
376
- ${H.detail}`:"")+S5(H.features));if(H.kind==="discarded")return Y(`\u274C The user discarded the plan in Beacon. ${H.summary??""} Ask what they want to adjust before presenting again.`.trim())}return Y("Still waiting for the user to review in Beacon. Your plan is preserved \u2014 call "+"`beacon_present_plan` again with the SAME plan to resume, or ask whether they've reviewed it.")});var s9=($)=>Array.isArray($)?$[0]:$;async function Z5($){return(await E(`/api/entities?kind=${$}&full=1`)).items}function o9($,Q){return{resources:$.map((Z)=>({uri:`${Q}${w0(Z.title)}`,name:Z.title,description:`${Z.title}${Z.cluster?` \xB7 ${Z.cluster}`:""} \xB7 ${Z.status}`,mimeType:"text/markdown"}))}}async function n9($,Q,Z){let Y=(await Z5(Z)).find((W)=>w0(W.title)===s9(Q));if(!Y)return{contents:[{uri:$.href,mimeType:"text/markdown",text:"(not found)"}]};let H=((await E("/api/entities?kind=tables")).items??[]).map((W)=>W.name),G=[`# ${Y.title}`];if(Y.cluster)G.push(`*Domain:* \`${Y.cluster}\``);if(Y.status)G.push(`*Status:* \`${Y.status}\``);if(G.push(""),G.push(Y.plain?.trim()||"(this node has no description yet \u2014 add one on Beacon's /map page)"),G.push("","## Existing DB tables in this project"),G.push(H.length?H.join(", "):"(none yet)"),Z==="features"){let W=await Z5("features"),j=[...new Set(W.map((K)=>K.cluster?.trim()).filter((K)=>!!K))].sort();G.push("","## Existing feature categories \u2014 reuse one before inventing a new one"),G.push(j.length?j.join(", "):"(none yet)"),G.push("","## Beacon feature loop \u2014 follow IN ORDER (do not jump to Glob/Grep/Read)","1. **Load context FIRST.** Call `beacon_context_for_feature({ title })` for this feature BEFORE any Glob/Grep/Read. It returns the attached files, 1-hop import blast radius, the domain's endpoints + tables + FK relations, sibling components, and the project conventions \u2014 and marks this feature active so your edits attach to it. That bundle replaces the discovery phase; Glob is a last resort.","2. **Design data before code.** Identify the tables this feature needs. If ANY are missing from the list above, design the schema and call `beacon_propose_plan` (tables + relations + endpoints, each endpoint with `uses:[{table,access}]`). It BLOCKS until the user approves on /plan \u2014 do NOT write migrations or code until it returns approval.","3. **Register at the end \u2014 in ONE call.** When the work is done, call `beacon_feature({ action: \"done\" })` ONCE with a `features` array (one entry per feature the plan created, each keyed by the `id` you got back at approval, with the files you touched + a short markdown summary). Don't make one call per feature, and don't register only the umbrella \u2014 that leaves the rest Pending.")}return{contents:[{uri:$.href,mimeType:"text/markdown",text:G.join(`
377
- `)}]}}A.registerResource("beacon-feature",new h5("feature://{slug}",{list:async()=>o9(await Z5("features"),"feature://")}),{title:"Beacon: features",description:"Roadmap features \u2014 picking one imports the node's description plus existing-DB context.",mimeType:"text/markdown"},($,{slug:Q})=>n9($,Q,"features"));A.registerResource("beacon-component",new h5("component://{slug}",{list:async()=>o9(await Z5("architecture"),"component://")}),{title:"Beacon: architecture",description:"Architecture components \u2014 picking one imports 'what the agent sees'.",mimeType:"text/markdown"},($,{slug:Q})=>n9($,Q,"architecture"));async function d9(){return await E("/api/notes")}A.registerResource("beacon-note",new h5("note://{slug}",{list:async()=>m9(await d9())}),{title:"Beacon: notes",description:"Your Beacon notes \u2014 picking one imports its markdown verbatim so you can turn it into features.",mimeType:"text/markdown"},async($,{slug:Q})=>{let Z=p9(await d9(),s9(Q)),Y=Z?c9(Z):"(not found)";return{contents:[{uri:$.href,mimeType:"text/markdown",text:Y}]}});await A.connect(new VZ);var Q5=-1;setInterval(async()=>{try{let{version:$}=await E("/api/version");if(Q5===-1)Q5=$;else if($!==Q5)Q5=$,A.sendResourceListChanged()}catch{}},s5);
378
+ ${H.detail}`:"")+g5(H.features));if(H.kind==="discarded")return Y(`\u274C The user discarded the plan in Beacon. ${H.summary??""} Ask what they want to adjust before presenting again.`.trim())}return Y("Still waiting for the user to review in Beacon. Your plan is preserved \u2014 call "+"`beacon_present_plan` again with the SAME plan to resume, or ask whether they've reviewed it.")});var o9=($)=>Array.isArray($)?$[0]:$;async function V5($){return(await T(`/api/entities?kind=${$}&full=1`)).items}function r9($,Q){return{resources:$.map((Z)=>({uri:`${Q}${C0(Z.title)}`,name:Z.title,description:`${Z.title}${Z.cluster?` \xB7 ${Z.cluster}`:""} \xB7 ${Z.status}`,mimeType:"text/markdown"}))}}async function i9($,Q,Z){let Y=(await V5(Z)).find((j)=>C0(j.title)===o9(Q));if(!Y)return{contents:[{uri:$.href,mimeType:"text/markdown",text:"(not found)"}]};let H=((await T("/api/entities?kind=tables")).items??[]).map((j)=>j.name),G=[`# ${Y.title}`];if(Y.cluster)G.push(`*Domain:* \`${Y.cluster}\``);if(Y.status)G.push(`*Status:* \`${Y.status}\``);if(G.push(""),G.push(Y.plain?.trim()||"(this node has no description yet \u2014 add one on Beacon's /map page)"),G.push("","## Existing DB tables in this project"),G.push(H.length?H.join(", "):"(none yet)"),Z==="features"){let j=await V5("features"),U=[...new Set(j.map((K)=>K.cluster?.trim()).filter((K)=>!!K))].sort();G.push("","## Existing feature categories \u2014 reuse one before inventing a new one"),G.push(U.length?U.join(", "):"(none yet)"),G.push("","## Beacon feature loop \u2014 follow IN ORDER (do not jump to Glob/Grep/Read)","1. **Load context FIRST.** Call `beacon_context_for_feature({ title })` for this feature BEFORE any Glob/Grep/Read. It returns the attached files, 1-hop import blast radius, the domain's endpoints + tables + FK relations, sibling components, and the project conventions \u2014 and marks this feature active so your edits attach to it. That bundle replaces the discovery phase; Glob is a last resort.","2. **Design data before code.** Identify the tables this feature needs. If ANY are missing from the list above, design the schema and call `beacon_propose_plan` (tables + relations + endpoints, each endpoint with `uses:[{table,access}]`). It BLOCKS until the user approves on /plan \u2014 do NOT write migrations or code until it returns approval.","3. **Register at the end \u2014 in ONE call.** When the work is done, call `beacon_feature({ action: \"done\" })` ONCE with a `features` array (one entry per feature the plan created, each keyed by the `id` you got back at approval, with the files you touched + a short markdown summary). Don't make one call per feature, and don't register only the umbrella \u2014 that leaves the rest Pending.")}return{contents:[{uri:$.href,mimeType:"text/markdown",text:G.join(`
379
+ `)}]}}E.registerResource("beacon-feature",new b5("feature://{slug}",{list:async()=>r9(await V5("features"),"feature://")}),{title:"Beacon: features",description:"Roadmap features \u2014 picking one imports the node's description plus existing-DB context.",mimeType:"text/markdown"},($,{slug:Q})=>i9($,Q,"features"));E.registerResource("beacon-component",new b5("component://{slug}",{list:async()=>r9(await V5("architecture"),"component://")}),{title:"Beacon: architecture",description:"Architecture components \u2014 picking one imports 'what the agent sees'.",mimeType:"text/markdown"},($,{slug:Q})=>i9($,Q,"architecture"));async function s9(){return await T("/api/notes")}E.registerResource("beacon-note",new b5("note://{slug}",{list:async()=>m9(await s9())}),{title:"Beacon: notes",description:"Your Beacon notes \u2014 picking one imports its markdown verbatim so you can turn it into features.",mimeType:"text/markdown"},async($,{slug:Q})=>{let Z=c9(await s9(),o9(Q)),Y=Z?l9(Z):"(not found)";return{contents:[{uri:$.href,mimeType:"text/markdown",text:Y}]}});await E.connect(new HZ);var Y5=-1;setInterval(async()=>{try{let{version:$}=await T("/api/version");if(Y5===-1)Y5=$;else if($!==Y5)Y5=$,E.sendResourceListChanged()}catch{}},i5);