trybeacon 0.1.63 → 0.1.65

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 (119) hide show
  1. package/.claude-plugin/plugin.json +19 -0
  2. package/.next/BUILD_ID +1 -1
  3. package/.next/app-path-routes-manifest.json +16 -16
  4. package/.next/build-manifest.json +2 -2
  5. package/.next/prerender-manifest.json +3 -3
  6. package/.next/required-server-files.js +1 -1
  7. package/.next/required-server-files.json +1 -1
  8. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  9. package/.next/server/app/_global-error.html +1 -1
  10. package/.next/server/app/_global-error.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  13. package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  14. package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  15. package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  16. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  17. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  18. package/.next/server/app/_not-found.html +1 -1
  19. package/.next/server/app/_not-found.rsc +2 -2
  20. package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  21. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  22. package/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  23. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  24. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  25. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  26. package/.next/server/app/api/share/create/route.js +1 -1
  27. package/.next/server/app/api/share/route.js +1 -1
  28. package/.next/server/app/docs/page_client-reference-manifest.js +1 -1
  29. package/.next/server/app/docs.html +1 -1
  30. package/.next/server/app/docs.rsc +3 -3
  31. package/.next/server/app/docs.segments/_full.segment.rsc +3 -3
  32. package/.next/server/app/docs.segments/_head.segment.rsc +1 -1
  33. package/.next/server/app/docs.segments/_index.segment.rsc +2 -2
  34. package/.next/server/app/docs.segments/_tree.segment.rsc +3 -3
  35. package/.next/server/app/docs.segments/docs/__PAGE__.segment.rsc +2 -2
  36. package/.next/server/app/docs.segments/docs.segment.rsc +1 -1
  37. package/.next/server/app/feedback/page_client-reference-manifest.js +1 -1
  38. package/.next/server/app/feedback.html +1 -1
  39. package/.next/server/app/feedback.rsc +2 -2
  40. package/.next/server/app/feedback.segments/_full.segment.rsc +2 -2
  41. package/.next/server/app/feedback.segments/_head.segment.rsc +1 -1
  42. package/.next/server/app/feedback.segments/_index.segment.rsc +2 -2
  43. package/.next/server/app/feedback.segments/_tree.segment.rsc +2 -2
  44. package/.next/server/app/feedback.segments/feedback/__PAGE__.segment.rsc +1 -1
  45. package/.next/server/app/feedback.segments/feedback.segment.rsc +1 -1
  46. package/.next/server/app/help/page_client-reference-manifest.js +1 -1
  47. package/.next/server/app/help.html +1 -1
  48. package/.next/server/app/help.rsc +2 -2
  49. package/.next/server/app/help.segments/_full.segment.rsc +2 -2
  50. package/.next/server/app/help.segments/_head.segment.rsc +1 -1
  51. package/.next/server/app/help.segments/_index.segment.rsc +2 -2
  52. package/.next/server/app/help.segments/_tree.segment.rsc +2 -2
  53. package/.next/server/app/help.segments/help/__PAGE__.segment.rsc +1 -1
  54. package/.next/server/app/help.segments/help.segment.rsc +1 -1
  55. package/.next/server/app/index.html +1 -1
  56. package/.next/server/app/index.rsc +4 -4
  57. package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  58. package/.next/server/app/index.segments/_full.segment.rsc +4 -4
  59. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  60. package/.next/server/app/index.segments/_index.segment.rsc +2 -2
  61. package/.next/server/app/index.segments/_tree.segment.rsc +3 -3
  62. package/.next/server/app/map/page.js +1 -1
  63. package/.next/server/app/map/page.js.nft.json +1 -1
  64. package/.next/server/app/map/page_client-reference-manifest.js +1 -1
  65. package/.next/server/app/page.js +1 -1
  66. package/.next/server/app/page_client-reference-manifest.js +1 -1
  67. package/.next/server/app/plan/page.js +2 -2
  68. package/.next/server/app/plan/page.js.nft.json +1 -1
  69. package/.next/server/app/plan/page_client-reference-manifest.js +1 -1
  70. package/.next/server/app/s/[token]/page.js +1 -1
  71. package/.next/server/app/s/[token]/page.js.nft.json +1 -1
  72. package/.next/server/app/s/[token]/page_client-reference-manifest.js +1 -1
  73. package/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  74. package/.next/server/app-paths-manifest.json +16 -16
  75. package/.next/server/chunks/2813.js +1 -0
  76. package/.next/server/chunks/3174.js +1 -0
  77. package/.next/server/middleware-build-manifest.js +1 -1
  78. package/.next/server/pages/404.html +1 -1
  79. package/.next/server/pages/500.html +1 -1
  80. package/.next/server/server-reference-manifest.js +1 -1
  81. package/.next/server/server-reference-manifest.json +1 -1
  82. package/.next/static/chunks/1909-98243a0473be2aae.js +1 -0
  83. package/.next/static/chunks/4491-0cd79f4195f4b111.js +1 -0
  84. package/.next/static/chunks/app/map/{page-af4a5a1f12413f4d.js → page-66ec4b62a4153de8.js} +1 -1
  85. package/.next/static/chunks/app/{page-6f46e6682942af3a.js → page-d08947a671077569.js} +1 -1
  86. package/.next/static/chunks/app/plan/{page-6213cdfdbee97ad6.js → page-008565f9049d55c9.js} +1 -1
  87. package/.next/static/chunks/app/s/[token]/{page-5c21314106b5ae91.js → page-1c10b26b300faffc.js} +1 -1
  88. package/.next/static/css/53e84df868515cf7.css +1 -0
  89. package/.next/static/css/f871d81e526502c1.css +1 -0
  90. package/.next/trace +42 -42
  91. package/.next/trace-build +1 -1
  92. package/LICENSE +201 -0
  93. package/README.md +40 -8
  94. package/bun.lock +2274 -0
  95. package/dist/bin/beacon.js +14 -14
  96. package/dist/bin/boot.js +4 -0
  97. package/dist/bin/doctor.js +32 -28
  98. package/dist/bin/hook.js +28 -24
  99. package/dist/bin/mcp.js +34 -30
  100. package/dist/bin/plan.js +29 -25
  101. package/dist/bin/uninstall.js +31 -27
  102. package/dist/lib/assets.js +4 -0
  103. package/dist/lib/codex-install.js +29 -25
  104. package/dist/lib/global-install.js +28 -24
  105. package/package.json +16 -3
  106. package/plugin/commands/beacon.md +11 -0
  107. package/plugin/hooks.json +70 -0
  108. package/plugin/mcp.json +10 -0
  109. package/plugin/skills/beacon-init/SKILL.md +47 -0
  110. package/plugin/skills/beacon-plan/SKILL.md +48 -0
  111. package/plugin/skills/beacon-refresh/SKILL.md +47 -0
  112. package/.next/server/chunks/2343.js +0 -1
  113. package/.next/server/chunks/2942.js +0 -1
  114. package/.next/static/chunks/5780-fd253c7329871c77.js +0 -1
  115. package/.next/static/chunks/874-c750840a8644deb1.js +0 -1
  116. package/.next/static/css/e63457bec0b3ee27.css +0 -1
  117. package/.next/static/css/f86b3e50f4e93bc8.css +0 -1
  118. /package/.next/static/{kt65bLHd8wfwQxMb3ivew → fwNWsob4GcVUD5_xV0f1h}/_buildManifest.js +0 -0
  119. /package/.next/static/{kt65bLHd8wfwQxMb3ivew → fwNWsob4GcVUD5_xV0f1h}/_ssgManifest.js +0 -0
package/dist/bin/mcp.js CHANGED
@@ -1,22 +1,22 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var x9=Object.defineProperty;var z9=($)=>$;function S9($,Q){this[$]=z9.bind(null,Q)}var r=($,Q)=>{for(var Z in Q)x9($,Z,{get:Q[Z],enumerable:!0,configurable:!0,set:S9.bind(Q,Z)})};var c=($,Q)=>()=>($&&(Q=$($=0)),Q);var s0=1500,yQ=480000,o0=1800000,B0=3600000,_5=3000;var n0=()=>{};var t0={};r(t0,{removeRepoAssets:()=>l9,installRefreshSkill:()=>g9,installPlanSkill:()=>f9,installInitSkill:()=>h9,installCodexRepoSkills:()=>b9,ensureWorkflowDoc:()=>m9,ensureMcp:()=>p9,auditRepo:()=>c9,REFRESH_SKILL:()=>a0,PLAN_SKILL:()=>y5,INIT_SKILL:()=>i0});import{existsSync as l,mkdirSync as N0,readFileSync as L,rmSync as K0,writeFileSync as I}from"fs";import{join as K}from"path";function h9($){let Q=K($,".claude","skills","beacon-init");N0(Q,{recursive:!0});let Z=K(Q,"SKILL.md");return I(Z,i0),Z}function g9($){let Q=K($,".claude","skills","beacon-refresh");N0(Q,{recursive:!0});let Z=K(Q,"SKILL.md");return I(Z,a0),Z}function f9($){let Q=K($,".claude","skills","beacon-plan");N0(Q,{recursive:!0});let Z=K(Q,"SKILL.md");return I(Z,y5),Z}function b9($){let Q=[];for(let Z of u9){let Y=K($,".agents","skills",Z.name);N0(Y,{recursive:!0});let X=K(Y,"SKILL.md");I(X,Z.body()),Q.push(X)}return Q}function m9($){let Q=K($,"AGENTS.md"),Z="";try{Z=L(Q,"utf8")}catch{}let Y=new RegExp(`${M0}[\\s\\S]*?${r0}`);Z=Y.test(Z)?Z.replace(Y,k5):`${Z.trim()}
3
+ var h9=Object.defineProperty;var f9=($)=>$;function g9($,Q){this[$]=f9.bind(null,Q)}var t=($,Q)=>{for(var Z in Q)h9($,Z,{get:Q[Z],enumerable:!0,configurable:!0,set:g9.bind(Q,Z)})};var l=($,Q)=>()=>($&&(Q=$($=0)),Q);var o0=1500,fQ=480000,n0=1800000,N0=3600000,k5=3000;var i0=()=>{};var e0={};t(e0,{removeRepoAssets:()=>o9,installRefreshSkill:()=>b9,installPlanSkill:()=>m9,installInitSkill:()=>u9,installCodexRepoSkills:()=>c9,ensureWorkflowDoc:()=>l9,ensureMcp:()=>d9,auditRepo:()=>s9,REFRESH_SKILL:()=>a0,PLAN_SKILL:()=>x5,INIT_SKILL:()=>r0});import{existsSync as d,mkdirSync as q0,readFileSync as L,rmSync as M0,writeFileSync as I}from"fs";import{join as K}from"path";function u9($){let Q=K($,".claude","skills","beacon-init");q0(Q,{recursive:!0});let Z=K(Q,"SKILL.md");return I(Z,r0),Z}function b9($){let Q=K($,".claude","skills","beacon-refresh");q0(Q,{recursive:!0});let Z=K(Q,"SKILL.md");return I(Z,a0),Z}function m9($){let Q=K($,".claude","skills","beacon-plan");q0(Q,{recursive:!0});let Z=K(Q,"SKILL.md");return I(Z,x5),Z}function c9($){let Q=[];for(let Z of p9){let Y=K($,".agents","skills",Z.name);q0(Y,{recursive:!0});let X=K(Y,"SKILL.md");I(X,Z.body()),Q.push(X)}return Q}function l9($){let Q=K($,"AGENTS.md"),Z="";try{Z=L(Q,"utf8")}catch{}let Y=new RegExp(`${P0}[\\s\\S]*?${t0}`);Z=Y.test(Z)?Z.replace(Y,y5):`${Z.trim()}
4
4
 
5
- ${k5}
5
+ ${y5}
6
6
  `.trimStart(),I(Q,Z.endsWith(`
7
7
  `)?Z:`${Z}
8
8
  `);let X=K($,"CLAUDE.md"),H="";try{H=L(X,"utf8")}catch{}if(!/@AGENTS\.md/.test(H))I(X,`${H?`${H.trim()}
9
9
 
10
10
  `:""}@AGENTS.md
11
- `)}function p9($){let Q=K($,".mcp.json"),Z={};try{Z=JSON.parse(L(Q,"utf8"))}catch{}Z.mcpServers=Z.mcpServers??{};let Y=Z.mcpServers.beacon;if(Y){if(!Y.timeout||Y.timeout<B0)return Y.timeout=B0,I(Q,JSON.stringify(Z,null,2)+`
12
- `),{path:Q,added:!1,updated:!0};return{path:Q,added:!1,updated:!1}}return Z.mcpServers.beacon={command:"beacon",args:["mcp"],timeout:B0},I(Q,JSON.stringify(Z,null,2)+`
13
- `),{path:Q,added:!0,updated:!1}}function c9($){let Q=K($,".mcp.json"),Z=!1;try{Z=!!JSON.parse(L(Q,"utf8")).mcpServers?.beacon}catch{}let Y=!1;try{Y=L(K($,"AGENTS.md"),"utf8").includes(M0)}catch{}let X=!1;try{X=/@AGENTS\.md/.test(L(K($,"CLAUDE.md"),"utf8"))}catch{}return{repo:$,mcpRegistered:Z,agentsMdBlock:Y,claudeMdImport:X,skills:{"beacon-init":l(K($,".claude","skills","beacon-init","SKILL.md")),"beacon-refresh":l(K($,".claude","skills","beacon-refresh","SKILL.md"))},codexSkills:{"beacon-init":l(K($,".agents","skills","beacon-init","SKILL.md")),"beacon-refresh":l(K($,".agents","skills","beacon-refresh","SKILL.md"))}}}function l9($){let Q=[];for(let U of["beacon-init","beacon-refresh","beacon-db-design"]){let w=K($,".claude","skills",U);if(l(w))K0(w,{recursive:!0,force:!0}),Q.push(U)}for(let U of["beacon-init","beacon-refresh"]){let w=K($,".agents","skills",U);if(l(w))K0(w,{recursive:!0,force:!0}),Q.push(`codex:${U}`)}let Z=!1,Y=K($,".mcp.json");try{let U=JSON.parse(L(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)K0(Y,{force:!0});else I(Y,JSON.stringify(U,null,2)+`
14
- `)}}catch{}let X=!1,H=K($,"AGENTS.md");try{let U=L(H,"utf8"),w=new RegExp(`\\n?${M0}[\\s\\S]*?${r0}\\n?`);if(w.test(U)){let a=U.replace(w,`
11
+ `)}function d9($){let Q=K($,".mcp.json"),Z={};try{Z=JSON.parse(L(Q,"utf8"))}catch{}Z.mcpServers=Z.mcpServers??{};let Y=Z.mcpServers.beacon;if(Y){if(!Y.timeout||Y.timeout<N0)return Y.timeout=N0,I(Q,JSON.stringify(Z,null,2)+`
12
+ `),{path:Q,added:!1,updated:!0};return{path:Q,added:!1,updated:!1}}return Z.mcpServers.beacon={command:"beacon",args:["mcp"],timeout:N0},I(Q,JSON.stringify(Z,null,2)+`
13
+ `),{path:Q,added:!0,updated:!1}}function s9($){let Q=K($,".mcp.json"),Z=!1;try{Z=!!JSON.parse(L(Q,"utf8")).mcpServers?.beacon}catch{}let Y=!1;try{Y=L(K($,"AGENTS.md"),"utf8").includes(P0)}catch{}let X=!1;try{X=/@AGENTS\.md/.test(L(K($,"CLAUDE.md"),"utf8"))}catch{}return{repo:$,mcpRegistered:Z,agentsMdBlock:Y,claudeMdImport:X,skills:{"beacon-init":d(K($,".claude","skills","beacon-init","SKILL.md")),"beacon-refresh":d(K($,".claude","skills","beacon-refresh","SKILL.md"))},codexSkills:{"beacon-init":d(K($,".agents","skills","beacon-init","SKILL.md")),"beacon-refresh":d(K($,".agents","skills","beacon-refresh","SKILL.md"))}}}function o9($){let Q=[];for(let U of["beacon-init","beacon-refresh","beacon-db-design"]){let w=K($,".claude","skills",U);if(d(w))M0(w,{recursive:!0,force:!0}),Q.push(U)}for(let U of["beacon-init","beacon-refresh"]){let w=K($,".agents","skills",U);if(d(w))M0(w,{recursive:!0,force:!0}),Q.push(`codex:${U}`)}let Z=!1,Y=K($,".mcp.json");try{let U=JSON.parse(L(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)M0(Y,{force:!0});else I(Y,JSON.stringify(U,null,2)+`
14
+ `)}}catch{}let X=!1,H=K($,"AGENTS.md");try{let U=L(H,"utf8"),w=new RegExp(`\\n?${P0}[\\s\\S]*?${t0}\\n?`);if(w.test(U)){let a=U.replace(w,`
15
15
  `).replace(/\n{3,}/g,`
16
16
 
17
17
  `).trimStart();I(H,a.endsWith(`
18
18
  `)?a:`${a}
19
- `),X=!0}}catch{}let j=!1,G=K($,"CLAUDE.md");try{let U=L(G,"utf8"),w=U.replace(/^[ \t]*@AGENTS\.md[ \t]*\n?/m,"");if(w!==U){if(!w.trim())K0(G,{force:!0});else I(G,w);j=!0}}catch{}return{skillsRemoved:Q,mcpUnregistered:Z,agentsBlockRemoved:X,claudeImportRemoved:j}}var i0=`---
19
+ `),X=!0}}catch{}let G=!1,j=K($,"CLAUDE.md");try{let U=L(j,"utf8"),w=U.replace(/^[ \t]*@AGENTS\.md[ \t]*\n?/m,"");if(w!==U){if(!w.trim())M0(j,{force:!0});else I(j,w);G=!0}}catch{}return{skillsRemoved:Q,mcpUnregistered:Z,agentsBlockRemoved:X,claudeImportRemoved:G}}var r0=`---
20
20
  name: beacon-init
21
21
  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.
22
22
  ---
@@ -110,7 +110,7 @@ The one caveat: if the user manually edited an INIT-source node on the canvas (e
110
110
  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.
111
111
 
112
112
  After the tool returns, report the final counts plus a one-line summary of the diff you surfaced.
113
- `,y5=`---
113
+ `,x5=`---
114
114
  name: beacon-plan
115
115
  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.
116
116
  ---
@@ -158,7 +158,7 @@ If it returns feedback, revise and call it again.
158
158
  If \`beacon_present_plan\` isn't available, the panel isn't wired here \u2014 fall back to ExitPlanMode
159
159
  with the same \`\`\`beacon block (Claude Code only; Codex has no ExitPlanMode), or tell the user to
160
160
  run \`beacon\` in this repo once.
161
- `,u9,M0="<!-- beacon:workflow:start -->",r0="<!-- beacon:workflow:end -->",k5;var e0=c(()=>{n0();u9=[{name:"beacon-init",body:()=>i0},{name:"beacon-refresh",body:()=>a0}];k5=`${M0}
161
+ `,p9,P0="<!-- beacon:workflow:start -->",t0="<!-- beacon:workflow:end -->",y5;var $5=l(()=>{i0();p9=[{name:"beacon-init",body:()=>r0},{name:"beacon-refresh",body:()=>a0}];y5=`${P0}
162
162
  ## Beacon \u2014 feature workflow
163
163
 
164
164
  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:
@@ -215,6 +215,10 @@ Beacon extracts it deterministically and **strips the block from the prose** (it
215
215
 
216
216
  **The board is built ONLY from the block \u2014 prose is NOT parsed.** If your plan describes ANY database models/tables/columns in the prose (e.g. "Model \`legal_precedent.py\` \u2014 natural key (court, \u2026)"), you MUST also put them in the block's \`tables\` array (with \`columns\`), or the /db tab will be empty for that plan. Same for endpoints (\`endpoints\` with \`uses:[{table,access}]\`) and features (\`features\`). A plan that lists five tables in prose but ships a block with only \`features\` renders an empty database board \u2014 exactly the "I described models but the DB tab is empty" failure. Mirror every DB entity you mention into the block.
217
217
 
218
+ ### 2c. Mark the files you mention \u2014 write repo-relative paths in backticks
219
+
220
+ When a plan, feature, or architecture-component description mentions a source file, write its **repo-relative path inside backticks** \u2014 \`app/api/plan/route.ts\`, not "the plan route". On the /plan canvas Beacon turns every backticked token that matches a REAL repo file into a clickable mention that opens it in the user's editor; a bare filename matching several files (e.g. \`route.ts\`) opens a pick-one dropdown of the same-named candidates. The match is deterministic against the live code graph, so a path that isn't a real file just stays plain text \u2014 there's no special syntax to learn and no downside to over-marking: always name files by their real path so the reader can jump straight to the code.
221
+
218
222
  ### 3. At the end, register the work \u2014 in ONE call
219
223
 
220
224
  Call \`beacon_feature({ action: "done" })\` **ONCE** with a \`features\` array \u2014 one entry per feature the plan created \u2014 each with the files you touched and a short markdown description. This flips each one to **Done** \u2014 including its sub-tasks (the cascade completes every PENDING/IN_PROGRESS child; a sub-task you did NOT finish must be set BLOCKED or CANCELLED before registering, so it survives visibly) \u2014 and keeps \`beacon_context_for_feature\` accurate for the next session.
@@ -226,18 +230,18 @@ Register them all in that single batched call. If a plan added five features, th
226
230
  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.
227
231
 
228
232
  Pull raw planning data anytime with \`beacon_entities\` (features / architecture / tables / endpoints).
229
- ${r0}`});import{existsSync as x5,mkdirSync as $5,readFileSync as q0,rmSync as d9,writeFileSync as w0}from"fs";import{dirname as z5,join as P0}from"path";function Q5($){try{return JSON.parse(q0($,"utf8"))}catch{return{}}}function S5($,Q){$5(z5($),{recursive:!0}),w0($,JSON.stringify(Q,null,2)+`
230
- `)}function v0($,Q){let Z=Q5($);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((j)=>j.command===Q.command)))return!1;return Y.push({matcher:Q.matcher,hooks:[{type:"command",command:Q.command}]}),S5($,Z),!0}function F0($,Q){return(Q5($).hooks?.[Q.event]??[]).some((X)=>X.hooks?.some((H)=>H.command===Q.command))}function D0($,Q){let Z=Q5($),Y=Z.hooks?.[Q.event];if(!Y)return!1;let X=!1,H=Y.map((j)=>{let G=j.hooks?.length??0,U=(j.hooks??[]).filter((w)=>w.command!==Q.command);if(U.length!==G)X=!0;return{...j,hooks:U}}).filter((j)=>(j.hooks??[]).length>0);if(!X)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 S5($,Z),!0}function O0($,Q,Z,Y){let X=`${Q}
233
+ ${t0}`});import{existsSync as w0,mkdirSync as Q5,readdirSync as n9,readFileSync as e,rmSync as i9,writeFileSync as C0}from"fs";import{dirname as z5,join as h}from"path";function S5(){return!!process.env.CLAUDE_PLUGIN_ROOT}function h5($=process.env.HOME||process.env.USERPROFILE||""){if(!$)return null;let Q=h($,".claude","plugins");if(!w0(Q))return null;let Z=[Q];for(let Y=0;Y<3&&Z.length;Y++){let X=[];for(let H of Z){let G=h(H,".claude-plugin","plugin.json");try{if(w0(G)&&JSON.parse(e(G,"utf8")).name==="beacon")return H}catch{}try{for(let j of n9(H,{withFileTypes:!0}))if(j.isDirectory())X.push(h(H,j.name))}catch{}}Z=X}return null}function f5($){return h5($)!==null}function Z5($){try{return JSON.parse(e($,"utf8"))}catch{return{}}}function g5($,Q){Q5(z5($),{recursive:!0}),C0($,JSON.stringify(Q,null,2)+`
234
+ `)}function F0($,Q){let Z=Z5($);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)=>G.command===Q.command)))return!1;return Y.push({matcher:Q.matcher,hooks:[{type:"command",command:Q.command}]}),g5($,Z),!0}function O0($,Q){return(Z5($).hooks?.[Q.event]??[]).some((X)=>X.hooks?.some((H)=>H.command===Q.command))}function D0($,Q){let Z=Z5($),Y=Z.hooks?.[Q.event];if(!Y)return!1;let X=!1,H=Y.map((G)=>{let j=G.hooks?.length??0,U=(G.hooks??[]).filter((w)=>w.command!==Q.command);if(U.length!==j)X=!0;return{...G,hooks:U}}).filter((G)=>(G.hooks??[]).length>0);if(!X)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 g5($,Z),!0}function R0($,Q,Z,Y){let X=`${Q}
231
235
  ${Y.trim()}
232
- ${Z}`,H="";try{H=q0($,"utf8")}catch{}let j=new RegExp(`${Q}[\\s\\S]*?${Z}`);H=j.test(H)?H.replace(j,X):H.trim()?`${H.trim()}
236
+ ${Z}`,H="";try{H=e($,"utf8")}catch{}let G=new RegExp(`${Q}[\\s\\S]*?${Z}`);H=G.test(H)?H.replace(G,X):H.trim()?`${H.trim()}
233
237
 
234
238
  ${X}
235
239
  `:`${X}
236
- `,$5(z5($),{recursive:!0}),w0($,H.endsWith(`
240
+ `,Q5(z5($),{recursive:!0}),C0($,H.endsWith(`
237
241
  `)?H:`${H}
238
- `)}function t($,Q){try{return q0($,"utf8").includes(Q)}catch{return!1}}function R0($,Q,Z){let Y="";try{Y=q0($,"utf8")}catch{return!1}let X=new RegExp(`${Q}[\\s\\S]*?${Z}\\n?`);if(!X.test(Y))return!1;let H=Y.replace(X,"").replace(/\n{3,}/g,`
242
+ `)}function $0($,Q){try{return e($,"utf8").includes(Q)}catch{return!1}}function A0($,Q,Z){let Y="";try{Y=e($,"utf8")}catch{return!1}let X=new RegExp(`${Q}[\\s\\S]*?${Z}\\n?`);if(!X.test(Y))return!1;let H=Y.replace(X,"").replace(/\n{3,}/g,`
239
243
 
240
- `).trimStart();return w0($,H),!0}function A0($,Q,Z){let Y=P0($,Q);$5(Y,{recursive:!0});let X=P0(Y,"SKILL.md");return w0(X,Z),X}function e($,Q){return x5(P0($,Q,"SKILL.md"))}function E0($,Q){let Z=P0($,Q);if(!x5(Z))return!1;return d9(Z,{recursive:!0,force:!0}),!0}var y,C0=`## Beacon (visual planning panel)
244
+ `).trimStart();return C0($,H),!0}function E0($,Q,Z){let Y=h($,Q);Q5(Y,{recursive:!0});let X=h(Y,"SKILL.md");return C0(X,Z),X}function Q0($,Q){return w0(h($,Q,"SKILL.md"))}function I0($,Q){let Z=h($,Q);if(!w0(Z))return!1;return i9(Z,{recursive:!0,force:!0}),!0}var y,v0=`## Beacon (visual planning panel)
241
245
 
242
246
  This machine has Beacon installed \u2014 a local visual planning surface for the terminal-side
243
247
  agent. Beacon proposes feature plans (roadmap features + DB schema + endpoints) via MCP,
@@ -258,39 +262,39 @@ the user reviews on a canvas at /plan, and feedback flows back as the next round
258
262
  Feedback bundles inline annotations on the markdown PLUS any edits the user made directly
259
263
  on the /map and /db boards (added features, attached subtasks, edited columns, new
260
264
  endpoints). Treat board edits as the user's revision intent \u2014 re-propose matching them
261
- verbatim. Do NOT implement until the tool returns approval.`;var Z5=c(()=>{y=["beacon-init","beacon-refresh","beacon-plan"]});import{mkdirSync as s9,renameSync as o9,rmSync as n9,writeFileSync as i9}from"fs";import{dirname as a9}from"path";function I0($,Q){s9(a9($),{recursive:!0});let Z=`${$}.tmp`;try{i9(Z,Q),o9(Z,$)}catch(Y){throw n9(Z,{force:!0}),Y}}function pQ($,Q,Z=!1){I0($,JSON.stringify(Q,null,Z?2:void 0))}var h5=()=>{};var l5={};r(l5,{setupCodexAssets:()=>$$,removeCodexMcp:()=>c5,removeCodexArtifacts:()=>Z$,hasCodexMcp:()=>X5,ensureCodexMcp:()=>p5,codexMcpProblem:()=>e9,codexDetected:()=>u5,auditCodex:()=>Q$,CODEX_HOOKS:()=>y0});import{readFileSync as k0}from"fs";import{homedir as r9}from"os";import{join as Z0}from"path";function g5(){return process.env.HOME||process.env.USERPROFILE||r9()}function u5(){if(process.env.BEACON_CODEX==="1")return!0;if(process.env.BEACON_CODEX==="0")return!1;if(J5===void 0)J5=Bun.which("codex")!==null;return J5}function Q0($){try{return Bun.TOML.parse($)}catch{return null}}function X5(){try{return Boolean(Q0(k0(d(),"utf8"))?.mcp_servers?.beacon)}catch{return!1}}function e9(){let $="";try{$=k0(d(),"utf8")}catch{return null}let Q=Q0($);if(!Q)return`~/.codex/config.toml does not parse \u2014 ${$0}`;if(Q.mcp_servers?.beacon)return null;if(/^\s*mcp_servers\s*=/m.test($))return`mcp_servers is an inline table \u2014 ${$0}`;return null}function p5(){let $="",Q=!1;try{$=k0(d(),"utf8"),Q=!0}catch{}if(Q){let H=Q0($);if(!H)return{added:!1,error:`~/.codex/config.toml does not parse \u2014 ${$0}`};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 ${$0}`}}let Z=!$?"":$.endsWith(`
265
+ verbatim. Do NOT implement until the tool returns approval.`;var J5=l(()=>{y=["beacon-init","beacon-refresh","beacon-plan"]});import{mkdirSync as r9,renameSync as a9,rmSync as t9,writeFileSync as e9}from"fs";import{dirname as $$}from"path";function T0($,Q){r9($$($),{recursive:!0});let Z=`${$}.tmp`;try{e9(Z,Q),a9(Z,$)}catch(Y){throw t9(Z,{force:!0}),Y}}function oQ($,Q,Z=!1){T0($,JSON.stringify(Q,null,Z?2:void 0))}var u5=()=>{};var o5={};t(o5,{setupCodexAssets:()=>Y$,removeCodexMcp:()=>s5,removeCodexArtifacts:()=>X$,hasCodexMcp:()=>H5,ensureCodexMcp:()=>d5,codexMcpProblem:()=>J$,codexDetected:()=>p5,auditCodex:()=>V$,CODEX_HOOKS:()=>x0});import{readFileSync as y0}from"fs";import{homedir as Q$}from"os";import{join as Y0}from"path";function b5(){return process.env.HOME||process.env.USERPROFILE||Q$()}function p5(){if(process.env.BEACON_CODEX==="1")return!0;if(process.env.BEACON_CODEX==="0")return!1;if(Y5===void 0)Y5=Bun.which("codex")!==null;return Y5}function J0($){try{return Bun.TOML.parse($)}catch{return null}}function H5(){try{return Boolean(J0(y0(s(),"utf8"))?.mcp_servers?.beacon)}catch{return!1}}function J$(){let $="";try{$=y0(s(),"utf8")}catch{return null}let Q=J0($);if(!Q)return`~/.codex/config.toml does not parse \u2014 ${Z0}`;if(Q.mcp_servers?.beacon)return null;if(/^\s*mcp_servers\s*=/m.test($))return`mcp_servers is an inline table \u2014 ${Z0}`;return null}function d5(){let $="",Q=!1;try{$=y0(s(),"utf8"),Q=!0}catch{}if(Q){let H=J0($);if(!H)return{added:!1,error:`~/.codex/config.toml does not parse \u2014 ${Z0}`};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 ${Z0}`}}let Z=!$?"":$.endsWith(`
262
266
  `)?`
263
267
  `:`
264
268
 
265
- `,Y=$+Z+t9;if(Q0(Y)?.mcp_servers?.beacon?.command!=="beacon")return{added:!1,error:`could not safely append [mcp_servers.beacon] \u2014 ${$0}`};return I0(d(),Y),{added:!0}}function c5(){let $="";try{$=k0(d(),"utf8")}catch{return{removed:!1}}let Q=$.split(`
266
- `),Z=Q.indexOf(b5);if(Z===-1)return{removed:!1,skipped:X5()};let Y=Q.indexOf(m5,Z);if(Y===-1)return{removed:!1,skipped:!0};Q.splice(Z,Y-Z+1);let X=Q.join(`
269
+ `,Y=$+Z+Z$;if(J0(Y)?.mcp_servers?.beacon?.command!=="beacon")return{added:!1,error:`could not safely append [mcp_servers.beacon] \u2014 ${Z0}`};return T0(s(),Y),{added:!0}}function s5(){let $="";try{$=y0(s(),"utf8")}catch{return{removed:!1}}let Q=$.split(`
270
+ `),Z=Q.indexOf(c5);if(Z===-1)return{removed:!1,skipped:H5()};let Y=Q.indexOf(l5,Z);if(Y===-1)return{removed:!1,skipped:!0};Q.splice(Z,Y-Z+1);let X=Q.join(`
267
271
  `).replace(/\n{3,}/g,`
268
272
 
269
- `).replace(/^\n+/,"");if(Q0(X)===null)return{removed:!1,skipped:!0};return I0(d(),X),{removed:!0}}async function $$(){let{INIT_SKILL:$,REFRESH_SKILL:Q,PLAN_SKILL:Z}=await Promise.resolve().then(() => (e0(),t0)),Y={"beacon-init":$,"beacon-refresh":Q,"beacon-plan":Z},X=[];for(let U of y){if(!e(L0(),U))X.push(U);A0(L0(),U,Y[U])}let H=0;for(let U of y0)if(v0(V5(),{event:U.event,matcher:U.matcher,command:U.command}))H++;let j=t(T0(),_0);O0(T0(),_0,f5,C0);let G=p5();return{skillsAdded:X,hooksAdded:H,agentsMdBlockTouched:!j,mcp:G}}function Q$(){let $={};for(let Z of y)$[Z]=e(L0(),Z);let Q={};for(let Z of y0)Q[Z.event]=F0(V5(),{event:Z.event,command:Z.command});return{detected:u5(),skills:$,hooks:Q,agentsMdBlock:t(T0(),_0),mcp:X5()}}function Z$(){let $=[];for(let X of y)if(E0(L0(),X))$.push(X);let Q=0;for(let X of y0)if(D0(V5(),{event:X.event,command:X.command}))Q++;let Z=R0(T0(),_0,f5),Y=c5();return{skillsRemoved:$,hooksRemoved:Q,agentsMdBlockRemoved:Z,mcpRemoved:Y.removed,mcpSkipped:Y.skipped}}var Y5=()=>Z0(g5(),".codex"),V5=()=>Z0(Y5(),"hooks.json"),d=()=>Z0(Y5(),"config.toml"),T0=()=>Z0(Y5(),"AGENTS.md"),L0=()=>Z0(g5(),".agents","skills"),_0="<!-- beacon:global:start -->",f5="<!-- beacon:global:end -->",y0,J5,b5="# beacon:start (managed by Beacon \u2014 `beacon uninstall` removes this block)",m5="# beacon:end",t9,$0="add it manually: codex mcp add beacon -- beacon mcp";var d5=c(()=>{Z5();h5();y0=[{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."}];t9=`${b5}
273
+ `).replace(/^\n+/,"");if(J0(X)===null)return{removed:!1,skipped:!0};return T0(s(),X),{removed:!0}}async function Y$(){let{INIT_SKILL:$,REFRESH_SKILL:Q,PLAN_SKILL:Z}=await Promise.resolve().then(() => ($5(),e0)),Y={"beacon-init":$,"beacon-refresh":Q,"beacon-plan":Z},X=[];for(let U of y){if(!Q0(_0(),U))X.push(U);E0(_0(),U,Y[U])}let H=0;for(let U of x0)if(F0(X5(),{event:U.event,matcher:U.matcher,command:U.command}))H++;let G=$0(L0(),k0);R0(L0(),k0,m5,v0);let j=d5();return{skillsAdded:X,hooksAdded:H,agentsMdBlockTouched:!G,mcp:j}}function V$(){let $={};for(let Z of y)$[Z]=Q0(_0(),Z);let Q={};for(let Z of x0)Q[Z.event]=O0(X5(),{event:Z.event,command:Z.command});return{detected:p5(),skills:$,hooks:Q,agentsMdBlock:$0(L0(),k0),mcp:H5()}}function X$(){let $=[];for(let X of y)if(I0(_0(),X))$.push(X);let Q=0;for(let X of x0)if(D0(X5(),{event:X.event,command:X.command}))Q++;let Z=A0(L0(),k0,m5),Y=s5();return{skillsRemoved:$,hooksRemoved:Q,agentsMdBlockRemoved:Z,mcpRemoved:Y.removed,mcpSkipped:Y.skipped}}var V5=()=>Y0(b5(),".codex"),X5=()=>Y0(V5(),"hooks.json"),s=()=>Y0(V5(),"config.toml"),L0=()=>Y0(V5(),"AGENTS.md"),_0=()=>Y0(b5(),".agents","skills"),k0="<!-- beacon:global:start -->",m5="<!-- beacon:global:end -->",x0,Y5,c5="# beacon:start (managed by Beacon \u2014 `beacon uninstall` removes this block)",l5="# beacon:end",Z$,Z0="add it manually: codex mcp add beacon -- beacon mcp";var n5=l(()=>{J5();u5();x0=[{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."}];Z$=`${c5}
270
274
  [mcp_servers.beacon]
271
275
  command = "beacon"
272
276
  args = ["mcp"]
273
- ${m5}
274
- `});var r5={};r(r5,{provisionDb:()=>E$});import{createClient as M$}from"@libsql/client";import{drizzle as P$}from"drizzle-orm/libsql";import{migrate as q$}from"drizzle-orm/libsql/migrator";import{readMigrationFiles as w$}from"drizzle-orm/migrator";import{dirname as B5,join as C$}from"path";import{fileURLToPath as v$}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 R$($,Q){let Z=await $.execute(`PRAGMA table_info("${Q}")`);return new Set(Z.rows.map((Y)=>String(Y.name)))}async function a5($){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 A$($){for(let[Q,Z]of Object.entries(O$)){if(!await S0($,Q))continue;let Y=await R$($,Q);for(let X of Z){if(!Y.has(X))continue;await $.execute(`UPDATE "${Q}" SET "${X}" = CAST((julianday("${X}") - 2440587.5) * 86400000 AS INTEGER) WHERE typeof("${X}") = 'text'`)}}}async function E$($,Q=D$){let Z=M$({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"),X=await S0(Z,"Node"),H=!1;if(X&&!Y){let G=w$({migrationsFolder:Q})[0];if(G)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:[G.hash,G.folderMillis]}),H=!0}let j=await a5(Z);if(await q$(P$(Z),{migrationsFolder:Q}),await a5(Z)>j)H=!0;return await A$(Z),{migrated:H}}finally{Z.close()}}var F$,D$,O$;var t5=c(async()=>{F$=B5(B5(B5(v$(import.meta.url)))),D$=process.env.BEACON_MIGRATIONS_DIR||C$(F$,"drizzle"),O$={Node:["createdAt","updatedAt"],Note:["createdAt","updatedAt"],DbTable:["createdAt","updatedAt"],Endpoint:["createdAt","updatedAt"],DraftTable:["createdAt"],SyncState:["codeGraphSyncedAt","updatedAt"],AppSetting:["updatedAt"],ProjectMeta:["updatedAt"],CodeFile:["updatedAt"]}});Z5();import{existsSync as J$}from"fs";import{homedir as Y$}from"os";import{join as x0}from"path";function V$(){return process.env.HOME||process.env.USERPROFILE||Y$()}var z0=()=>x0(V$(),".claude"),H5=()=>x0(z0(),"skills"),j5=()=>x0(z0(),"settings.json"),G5=()=>x0(z0(),"CLAUDE.md"),U5="<!-- beacon:global:start -->",s5="<!-- beacon:global:end -->";var X$=C0,W5=[{event:"PreToolUse",matcher:"Edit|Write|MultiEdit",command:"beacon guard",description:"Gate edits against the active plan's scope contract (when the scope-guard flag is on): in-scope \u2192 allow, off-scope \u2192 ask the user to authorize. No-op + fail-open otherwise."},{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:"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 H$($,Q){return A0(H5(),$,Q)}function o5($){return e(H5(),$)}function j$($){return E0(H5(),$)}function G$($){return v0(j5(),$)}function U$($){return F0(j5(),$)}function W$($){return D0(j5(),$)}function B$($){O0(G5(),U5,s5,$)}function n5(){return t(G5(),U5)}function K$(){return R0(G5(),U5,s5)}function eQ(){let $={};for(let Z of y)$[Z]=o5(Z);let Q={};for(let Z of W5)Q[Z.event]=U$({event:Z.event,command:Z.command});return{homeExists:J$(z0()),skills:$,hooks:Q,claudeMdBlock:n5()}}async function N$(){let{INIT_SKILL:$,REFRESH_SKILL:Q,PLAN_SKILL:Z}=await Promise.resolve().then(() => (e0(),t0)),Y={"beacon-init":$,"beacon-refresh":Q,"beacon-plan":Z},X=[];for(let G of y){if(!o5(G))X.push(G);H$(G,Y[G])}let H=0;for(let G of W5)if(G$({event:G.event,matcher:G.matcher,command:G.command}))H++;let j=n5();return B$(X$),{skillsAdded:X,hooksAdded:H,claudeMdBlockTouched:!j}}async function i5(){let $;try{$={ok:!0,...await N$()}}catch(Q){$={ok:!1,error:Q instanceof Error?Q.message:String(Q),skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1}}try{let Q=await Promise.resolve().then(() => (d5(),l5));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 $Z(){let $=[];for(let Y of y)if(j$(Y))$.push(Y);let Q=0;for(let Y of W5)if(W$(Y))Q++;let Z=K$();return{skillsRemoved:$,hooksRemoved:Q,claudeMdBlockRemoved:Z}}import{AsyncLocalStorage as I$}from"async_hooks";import{spawnSync as T$}from"child_process";import{createHash as L$}from"crypto";import{existsSync as $9,mkdirSync as J0,readFileSync as N5,writeFileSync as M5}from"fs";import{homedir as Q9}from"os";import{basename as _$,join as x,parse as k$,resolve as e5}from"path";function _(){return process.env.BEACON_HOME||x(Q9(),".beacon")}function P5(){return x(_(),"workspaces.json")}function s($){return L$("sha256").update($).digest("hex").slice(0,12)}function Z9($=process.cwd()){let Q=T$("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 h0($){let Q=e5($);return Q!==e5(Q9())&&Q!==k$(Q).root}function J9(){return x(_(),"deleted.json")}function q5(){try{let $=JSON.parse(N5(J9(),"utf8"));return Array.isArray($)?$:[]}catch{return[]}}function Y9($){J0(_(),{recursive:!0}),M5(J9(),JSON.stringify($,null,2))}function g0($){return q5().includes($)}function NZ($){let Q=q5();if(!Q.includes($))Y9([...Q,$])}function y$($){let Q=q5();if(Q.includes($))Y9(Q.filter((Z)=>Z!==$))}function f0($){return x(_(),$)}function w5($){return`file:${x(f0($),"db.sqlite")}`}function Y0(){try{let $=JSON.parse(N5(P5(),"utf8"));return Array.isArray($)?$:[]}catch{return[]}}function C5($){J0(_(),{recursive:!0}),M5(P5(),JSON.stringify($,null,2))}function u0(){return Y0().sort(($,Q)=>Q.lastOpenedAt.localeCompare($.lastOpenedAt))}function h($){return Y0().find((Q)=>Q.id===$)??null}function b0($,Q,Z=new Date().toISOString()){if(!h0($))throw Error(`beacon: refusing to register a non-repo path as a workspace: ${$}`);let Y=s($);if(g0(Y))throw Error(`beacon: workspace ${Y} (${$}) was deleted \u2014 run \`beacon\` or /beacon-init to re-add it`);let X=Y0(),H=X.find((U)=>U.id===Y),j={id:Y,path:$,name:Q||H?.name||_$($),lastOpenedAt:Z},G=[j,...X.filter((U)=>U.id!==Y)];return J0(f0(Y),{recursive:!0}),C5(G),j}function MZ($,Q){return y$(s($)),b0($,Q)}function PZ($,Q=new Date().toISOString()){let Z=Y0(),Y=Z.find((X)=>X.id===$);if(!Y)return;Y.lastOpenedAt=Q,C5(Z)}function qZ($){if(C5(Y0().filter((Q)=>Q.id!==$)),V0()===$)x$(u0()[0]?.id??null)}function V9(){return x(_(),"active")}function V0(){try{return N5(V9(),"utf8").trim()||null}catch{return null}}function x$($){J0(_(),{recursive:!0}),M5(V9(),$??"")}function wZ(){let $=V0();return $?h($):null}function CZ(){let $=F5()??V0();return $?h($):null}function vZ($){return h($)?.path??null}function FZ(){return $9(P5())}var X9="beacon_ws";function H9($,Q){let Z=$.headers.get("cookie");if(!Z)return null;for(let Y of Z.split(";")){let X=Y.indexOf("=");if(X===-1)continue;if(Y.slice(0,X).trim()===Q)return decodeURIComponent(Y.slice(X+1).trim())}return null}function DZ($){let Q=$.headers.get("x-beacon-workspace");if(Q&&h(Q))return Q;let Z=H9($,X9);if(Z&&h(Z))return Z;return z$()}function z$(){let $=u0();return $.length===1?$[0].id:null}var v5="x-beacon-workspace-path";async function OZ($){let Q=$.headers.get("x-beacon-workspace");if(Q&&h(Q))return Q;let Z=$.headers.get(v5);if(Z&&h0(Z)&&!g0(s(Z))&&(!Q||s(Z)===Q)){let X=b0(Z);return await D5(X.id),X.id}let Y=H9($,X9);if(Y&&h(Y))return Y;return null}var j9=new I$;function S$($,Q){return $?j9.run($,Q):Q()}function F5(){return j9.getStore()??null}var K5=new Set;function RZ($){K5.delete(x(f0($),"db.sqlite"))}async function D5($){let Q=f0($),Z=x(Q,"db.sqlite"),Y=$9(Z);if(Y&&K5.has(Z))return{ok:!0,created:!1,migrated:!1};try{J0(Q,{recursive:!0});let{provisionDb:X}=await t5().then(() => r5),H=await X(w5($));return K5.add(Z),{ok:!0,created:!Y,migrated:Y&&H.migrated}}catch(X){return{ok:!1,created:!1,migrated:!1,error:X instanceof Error?X.message:String(X)}}}import{connect as h$}from"net";var G9=4319;function g$($,Q,Z=400){return new Promise((Y)=>{let X=h$({host:$,port:Q}),H=!1,j=(G)=>{if(H)return;H=!0,X.destroy(),Y(G)};X.once("connect",()=>j(!0)),X.once("error",()=>j(!1)),X.setTimeout(Z,()=>j(!1))})}async function f$($){for(let Q of["127.0.0.1","::1"])if(await g$(Q,$))return!1;return!0}async function IZ($,Q=20){for(let Z=$;Z<$+Q;Z++)if(await f$(Z))return Z;return $}import{McpServer as LQ,ResourceTemplate as L5}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as _Q}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as J}from"zod";import{z as B}from"zod";var u$=new Set(["GET","HEAD","OPTIONS"]);function U9($){return u$.has($.trim().toUpperCase())?"read":"write"}var b$=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()})),W9=B.object({name:B.string().trim().min(1),domain:B.string().nullish(),description:B.string().nullish(),columns:B.array(b$).default([])}),B9=B.object({fromTable:B.string(),fromColumn:B.string(),toTable:B.string(),toColumn:B.string(),label:B.string().nullish()}),K9=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??U9($.method)}))})),yZ=B.object({tables:B.array(W9).default([]),relations:B.array(B9).default([]),endpoints:B.array(K9).default([])});import{z as O}from"zod";import{and as Q1,eq as Z1,inArray as J1}from"drizzle-orm";import{drizzle as BQ}from"drizzle-orm/libsql";import{createClient as KQ}from"@libsql/client";var O5={};r(O5,{workspaceFlag:()=>n$,tag:()=>o,syncState:()=>d$,projectMeta:()=>o$,planContract:()=>i$,note:()=>c$,nodeTags:()=>g,nodeFile:()=>X0,node:()=>M,endpointTable:()=>u,endpoint:()=>n,edge:()=>z,draftTable:()=>A,draftRelation:()=>b,draftColumn:()=>G0,dbTable:()=>F,dbRelation:()=>f,dbColumn:()=>j0,codeFileEdge:()=>m,codeFile:()=>k,bugFlag:()=>H0,boardAnnotation:()=>l$,appSetting:()=>s$});import{sqliteTable as P,index as N,foreignKey as m$,text as V,integer as W,real as D,uniqueIndex as T,primaryKey as p$}from"drizzle-orm/sqlite-core";import{createId as C}from"@paralleldrive/cuid2";var M=P("Node",{id:V().primaryKey().$defaultFn(()=>C()),view:V().notNull(),kind:V().default("FEATURE").notNull(),cluster:V(),layer:V(),title:V().notNull(),role:V(),plain:V(),status:V().default("PENDING").notNull(),priority:W().default(2).notNull(),progress:W().default(0).notNull(),x:D().default(0).notNull(),y:D().default(0).notNull(),sourceRef:V(),externalId:V(),source:V().default("MANUAL").notNull(),planId:V(),parentId:V(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[N("Node_cluster_idx").on($.cluster),N("Node_parentId_idx").on($.parentId),N("Node_view_idx").on($.view),m$(()=>({columns:[$.parentId],foreignColumns:[$.id],name:"Node_parentId_Node_id_fk"})).onUpdate("cascade").onDelete("cascade")]),X0=P("NodeFile",{id:V().primaryKey().$defaultFn(()=>C()),nodeId:V().notNull().references(()=>M.id,{onDelete:"cascade",onUpdate:"cascade"}),path:V().notNull()},($)=>[T("NodeFile_nodeId_path_key").on($.nodeId,$.path),N("NodeFile_nodeId_idx").on($.nodeId)]),o=P("Tag",{id:V().primaryKey().$defaultFn(()=>C()),label:V().notNull(),color:V()},($)=>[T("Tag_label_key").on($.label)]),z=P("Edge",{id:V().primaryKey().$defaultFn(()=>C()),fromId:V().notNull().references(()=>M.id,{onDelete:"cascade",onUpdate:"cascade"}),toId:V().notNull().references(()=>M.id,{onDelete:"cascade",onUpdate:"cascade"}),kind:V().default("DEPENDS").notNull(),label:V(),sourceHandle:V(),targetHandle:V()},($)=>[T("Edge_fromId_toId_kind_key").on($.fromId,$.toId,$.kind),N("Edge_toId_idx").on($.toId),N("Edge_fromId_idx").on($.fromId)]),g=P("_NodeTags",{a:V("A").notNull().references(()=>M.id,{onDelete:"cascade",onUpdate:"cascade"}),b:V("B").notNull().references(()=>o.id,{onDelete:"cascade",onUpdate:"cascade"})},($)=>[T("_NodeTags_AB_unique").on($.a,$.b),N("_NodeTags_B_index").on($.b)]),c$=P("Note",{id:V().primaryKey().$defaultFn(()=>C()),title:V().default("Untitled").notNull(),body:V().default("").notNull(),ord:D().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)]),l$=P("BoardAnnotation",{id:V().primaryKey().$defaultFn(()=>C()),targetKind:V().notNull(),targetId:V().notNull(),columnName:V(),body:V().default("").notNull(),x:D(),y:D(),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)]),H0=P("BugFlag",{id:V().primaryKey().$defaultFn(()=>C()),nodeId:V().notNull().references(()=>M.id,{onDelete:"cascade",onUpdate:"cascade"}),by:V().notNull(),note:V().notNull(),resolvedAt:W({mode:"timestamp_ms"}),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date)},($)=>[N("BugFlag_nodeId_idx").on($.nodeId)]),F=P("DbTable",{id:V().primaryKey().$defaultFn(()=>C()),name:V().notNull(),domain:V(),description:V(),source:V().default("MANUAL").notNull(),planId:V(),x:D().default(0).notNull(),y:D().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),T("DbTable_name_key").on($.name)]),j0=P("DbColumn",{id:V().primaryKey().$defaultFn(()=>C()),tableId:V().notNull().references(()=>F.id,{onDelete:"cascade",onUpdate:"cascade"}),name:V().notNull(),type:V().notNull(),isPk:W({mode:"boolean"}).default(!1).notNull(),isFk:W({mode:"boolean"}).default(!1).notNull(),nullable:W({mode:"boolean"}).default(!0).notNull(),note:V(),ord:W().default(0).notNull()},($)=>[T("DbColumn_tableId_name_key").on($.tableId,$.name),N("DbColumn_tableId_idx").on($.tableId)]),f=P("DbRelation",{id:V().primaryKey().$defaultFn(()=>C()),fromTableId:V().notNull().references(()=>F.id,{onDelete:"cascade",onUpdate:"cascade"}),toTableId:V().notNull().references(()=>F.id,{onDelete:"cascade",onUpdate:"cascade"}),fromColumn:V().notNull(),toColumn:V().notNull(),label:V()},($)=>[N("DbRelation_toTableId_idx").on($.toTableId),N("DbRelation_fromTableId_idx").on($.fromTableId)]),n=P("Endpoint",{id:V().primaryKey().$defaultFn(()=>C()),method:V().notNull(),path:V().notNull(),domain:V(),description:V(),source:V().default("MANUAL").notNull(),planId:V(),x:D().default(0).notNull(),y:D().default(0).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[T("Endpoint_method_path_key").on($.method,$.path),N("Endpoint_domain_idx").on($.domain)]),u=P("EndpointTable",{id:V().primaryKey().$defaultFn(()=>C()),endpointId:V().notNull().references(()=>n.id,{onDelete:"cascade",onUpdate:"cascade"}),tableId:V().notNull().references(()=>F.id,{onDelete:"cascade",onUpdate:"cascade"}),access:V().default("read").notNull()},($)=>[T("EndpointTable_endpointId_tableId_key").on($.endpointId,$.tableId),N("EndpointTable_tableId_idx").on($.tableId)]),A=P("DraftTable",{id:V().primaryKey().$defaultFn(()=>C()),name:V().notNull(),domain:V(),description:V(),x:D().default(0).notNull(),y:D().default(0).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date)},($)=>[T("DraftTable_name_key").on($.name)]),G0=P("DraftColumn",{id:V().primaryKey().$defaultFn(()=>C()),tableId:V().notNull().references(()=>A.id,{onDelete:"cascade",onUpdate:"cascade"}),name:V().notNull(),type:V().notNull(),isPk:W({mode:"boolean"}).default(!1).notNull(),isFk:W({mode:"boolean"}).default(!1).notNull(),nullable:W({mode:"boolean"}).default(!0).notNull(),note:V(),ord:W().default(0).notNull()},($)=>[N("DraftColumn_tableId_idx").on($.tableId)]),b=P("DraftRelation",{id:V().primaryKey().$defaultFn(()=>C()),fromTableId:V().notNull().references(()=>A.id,{onDelete:"cascade",onUpdate:"cascade"}),toTableId:V().notNull().references(()=>A.id,{onDelete:"cascade",onUpdate:"cascade"}),fromColumn:V().notNull(),toColumn:V().notNull(),label:V()},($)=>[N("DraftRelation_toTableId_idx").on($.toTableId),N("DraftRelation_fromTableId_idx").on($.fromTableId)]),k=P("CodeFile",{path:V().primaryKey(),root:V(),lang:V(),x:D().default(0).notNull(),y:D().default(0).notNull(),mtimeMs:D(),size:W(),inDegree:W().default(0).notNull(),outDegree:W().default(0).notNull(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),m=P("CodeFileEdge",{fromPath:V().notNull().references(()=>k.path,{onDelete:"cascade",onUpdate:"cascade"}),toPath:V().notNull().references(()=>k.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),p$({columns:[$.fromPath,$.toPath],name:"CodeFileEdge_fromPath_toPath_pk"})]),d$=P("SyncState",{id:V().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)}),s$=P("AppSetting",{id:V().primaryKey().default("singleton"),editor:V().default("auto").notNull(),currentFeatureId:V(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),o$=P("ProjectMeta",{id:V().primaryKey().default("singleton"),overview:V(),conventions:V().default("[]").notNull(),hasFrontend:W({mode:"boolean"}),classificationRoots:V().default("[]").notNull(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),n$=P("WorkspaceFlag",{id:V().primaryKey().$defaultFn(()=>C()),key:V().notNull(),enabled:W({mode:"boolean"}).default(!1).notNull(),config:V(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[T("WorkspaceFlag_key_key").on($.key)]),i$=P("PlanContract",{id:V().primaryKey().$defaultFn(()=>C()),planId:V().notNull(),declaredFiles:V().default("[]").notNull(),authorizedExtras:V().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)},($)=>[T("PlanContract_planId_key").on($.planId),N("PlanContract_active_idx").on($.active)]);var R5={};r(R5,{tagRelations:()=>e$,nodeTagsRelations:()=>$Q,nodeRelations:()=>a$,nodeFileRelations:()=>r$,endpointTableRelations:()=>XQ,endpointRelations:()=>VQ,edgeRelations:()=>QQ,draftTableRelations:()=>HQ,draftRelationRelations:()=>GQ,draftColumnRelations:()=>jQ,dbTableRelations:()=>ZQ,dbRelationRelations:()=>YQ,dbColumnRelations:()=>JQ,codeFileRelations:()=>UQ,codeFileEdgeRelations:()=>WQ,bugFlagRelations:()=>t$});import{relations as v}from"drizzle-orm";var a$=v(M,({one:$,many:Q})=>({files:Q(X0),bugFlags:Q(H0),nodeTags:Q(g),edgesOut:Q(z,{relationName:"EdgeFrom"}),edgesIn:Q(z,{relationName:"EdgeTo"}),parent:$(M,{fields:[M.parentId],references:[M.id],relationName:"NodeTree"}),children:Q(M,{relationName:"NodeTree"})})),r$=v(X0,({one:$})=>({node:$(M,{fields:[X0.nodeId],references:[M.id]})})),t$=v(H0,({one:$})=>({node:$(M,{fields:[H0.nodeId],references:[M.id]})})),e$=v(o,({many:$})=>({nodeTags:$(g)})),$Q=v(g,({one:$})=>({node:$(M,{fields:[g.a],references:[M.id]}),tag:$(o,{fields:[g.b],references:[o.id]})})),QQ=v(z,({one:$})=>({from:$(M,{fields:[z.fromId],references:[M.id],relationName:"EdgeFrom"}),to:$(M,{fields:[z.toId],references:[M.id],relationName:"EdgeTo"})})),ZQ=v(F,({many:$})=>({columns:$(j0),fksOut:$(f,{relationName:"FkFrom"}),fksIn:$(f,{relationName:"FkTo"}),usages:$(u)})),JQ=v(j0,({one:$})=>({table:$(F,{fields:[j0.tableId],references:[F.id]})})),YQ=v(f,({one:$})=>({fromTable:$(F,{fields:[f.fromTableId],references:[F.id],relationName:"FkFrom"}),toTable:$(F,{fields:[f.toTableId],references:[F.id],relationName:"FkTo"})})),VQ=v(n,({many:$})=>({tables:$(u)})),XQ=v(u,({one:$})=>({endpoint:$(n,{fields:[u.endpointId],references:[n.id]}),table:$(F,{fields:[u.tableId],references:[F.id]})})),HQ=v(A,({many:$})=>({columns:$(G0),fksOut:$(b,{relationName:"DraftFkFrom"}),fksIn:$(b,{relationName:"DraftFkTo"})})),jQ=v(G0,({one:$})=>({table:$(A,{fields:[G0.tableId],references:[A.id]})})),GQ=v(b,({one:$})=>({fromTable:$(A,{fields:[b.fromTableId],references:[A.id],relationName:"DraftFkFrom"}),toTable:$(A,{fields:[b.toTableId],references:[A.id],relationName:"DraftFkTo"})})),UQ=v(k,({many:$})=>({edgesOut:$(m,{relationName:"CFEFrom"}),edgesIn:$(m,{relationName:"CFETo"})})),WQ=v(m,({one:$})=>({fromFile:$(k,{fields:[m.fromPath],references:[k.path],relationName:"CFEFrom"}),toFile:$(k,{fields:[m.toPath],references:[k.path],relationName:"CFETo"})}));var NQ={...O5,...R5};function MQ(){let $=process.env.DATABASE_URL;if($&&/^(file:|libsql:|wss?:|https?:|:memory:)/i.test($))return $;return"file:./dev.db"}var PQ=MQ();function N9($){let Q=KQ({url:$});return Q.execute("PRAGMA foreign_keys = ON;"),Q.execute("PRAGMA busy_timeout = 5000;"),BQ(Q,{schema:NQ})}var E5=globalThis,A5=E5.dzDefault??N9(PQ);E5.dzDefault=A5;var m0=E5.dzByUrl??=new Map;function qQ($){let Q=m0.get($);if(!Q)Q=N9($),m0.set($,Q);return Q}function mZ($){let Q=m0.get($);m0.delete($);try{Q?.$client?.close?.()}catch{}}function wQ(){if(process.env.BEACON_REPO)return A5;let $=F5()??V0();if(!$)return A5;return qQ(w5($))}var CQ=new Proxy({},{get($,Q){let Z=wQ(),Y=Z[Q];return typeof Y==="function"?Y.bind(Z):Y}});var vQ=["frontend","backend","fullstack"],FQ={fe:"frontend",front:"frontend",be:"backend",back:"backend",fs:"fullstack","full-stack":"fullstack","full stack":"fullstack"};function p0($){let Q=($??"").trim().toLowerCase();if(!Q)return null;if(vQ.includes(Q))return Q;return FQ[Q]??null}import{forceCenter as sZ,forceCollide as oZ,forceLink as nZ,forceManyBody as iZ,forceSimulation as aZ}from"d3-force";var M9=O.object({title:O.string().trim().min(1),role:O.string().nullish(),plain:O.string().nullish(),cluster:O.string().nullish(),category:O.string().nullish(),domain:O.string().nullish(),priority:O.number().nullish(),kind:O.string().nullish(),layer:O.string().nullish(),dependsOn:O.array(O.string()).nullish()}).transform(({category:$,domain:Q,priority:Z,kind:Y,layer:X,...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:p0(X)})),j1=O.object({features:O.array(M9).default([])});var DQ=/(\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 P9($){return!!$&&DQ.test($)}function q9($,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 OQ($){return $.cluster??$.category??$.domain??null}function w9($,Q){let Z=Q?.requireLayer??!1,Y=$.map((H)=>{let j=[],G=OQ(H);if(!G||!G.trim())j.push("category");if(H.priority==null)j.push("priority");if(Z&&!p0(H.layer))j.push("layer");return j.length?` \u2022 "${H.title?.trim()||"(untitled)"}" \u2014 missing ${j.join(" + ")}`:null}).filter((H)=>H!==null);if(Y.length===0)return null;let X=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."+X+` Missing:
277
+ ${l5}
278
+ `});var $9={};t($9,{provisionDb:()=>k$});import{createClient as v$}from"@libsql/client";import{drizzle as F$}from"drizzle-orm/libsql";import{migrate as O$}from"drizzle-orm/libsql/migrator";import{readMigrationFiles as D$}from"drizzle-orm/migrator";import{dirname as K5,join as R$}from"path";import{fileURLToPath as A$}from"url";async function h0($,Q){return(await $.execute({sql:"SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?",args:[Q]})).rows.length>0}async function L$($,Q){let Z=await $.execute(`PRAGMA table_info("${Q}")`);return new Set(Z.rows.map((Y)=>String(Y.name)))}async function e5($){if(!await h0($,"__drizzle_migrations"))return 0;let Q=await $.execute('SELECT count(*) AS n FROM "__drizzle_migrations"');return Number(Q.rows[0]?.n??0)}async function _$($){for(let[Q,Z]of Object.entries(T$)){if(!await h0($,Q))continue;let Y=await L$($,Q);for(let X of Z){if(!Y.has(X))continue;await $.execute(`UPDATE "${Q}" SET "${X}" = CAST((julianday("${X}") - 2440587.5) * 86400000 AS INTEGER) WHERE typeof("${X}") = 'text'`)}}}async function k$($,Q=I$){let Z=v$({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 h0(Z,"__drizzle_migrations"),X=await h0(Z,"Node"),H=!1;if(X&&!Y){let j=D$({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 e5(Z);if(await O$(F$(Z),{migrationsFolder:Q}),await e5(Z)>G)H=!0;return await _$(Z),{migrated:H}}finally{Z.close()}}var E$,I$,T$;var Q9=l(async()=>{E$=K5(K5(K5(A$(import.meta.url)))),I$=process.env.BEACON_MIGRATIONS_DIR||R$(E$,"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"]}});J5();import{existsSync as H$}from"fs";import{homedir as G$}from"os";import{join as z0}from"path";function j$(){return process.env.HOME||process.env.USERPROFILE||G$()}var S0=()=>z0(j$(),".claude"),G5=()=>z0(S0(),"skills"),j5=()=>z0(S0(),"settings.json"),U5=()=>z0(S0(),"CLAUDE.md"),W5="<!-- beacon:global:start -->",i5="<!-- beacon:global:end -->";var U$=v0,B5=[{event:"PreToolUse",matcher:"Edit|Write|MultiEdit",command:"beacon guard",description:"Gate edits against the active plan's scope contract (when the scope-guard flag is on): in-scope \u2192 allow, off-scope \u2192 ask the user to authorize. No-op + fail-open otherwise."},{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:"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 W$($,Q){return E0(G5(),$,Q)}function r5($){return Q0(G5(),$)}function B$($){return I0(G5(),$)}function K$($){return F0(j5(),$)}function N$($){return O0(j5(),$)}function M$($){return D0(j5(),$)}function q$($){R0(U5(),W5,i5,$)}function a5(){return $0(U5(),W5)}function P$(){return A0(U5(),W5,i5)}function YZ(){let $={};for(let Z of y)$[Z]=r5(Z);let Q={};for(let Z of B5)Q[Z.event]=N$({event:Z.event,command:Z.command});return{homeExists:H$(S0()),skills:$,hooks:Q,claudeMdBlock:a5()}}async function w$(){let{INIT_SKILL:$,REFRESH_SKILL:Q,PLAN_SKILL:Z}=await Promise.resolve().then(() => ($5(),e0)),Y={"beacon-init":$,"beacon-refresh":Q,"beacon-plan":Z},X=[];for(let j of y){if(!r5(j))X.push(j);W$(j,Y[j])}let H=0;for(let j of B5)if(K$({event:j.event,matcher:j.matcher,command:j.command}))H++;let G=a5();return q$(U$),{skillsAdded:X,hooksAdded:H,claudeMdBlockTouched:!G}}async function t5(){if(S5())return{ok:!0,skipped:"plugin",skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1};let $;if(f5()){try{C$()}catch{}$={ok:!0,skipped:"plugin-present",skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1}}else try{$={ok:!0,...await w$()}}catch(Q){$={ok:!1,error:Q instanceof Error?Q.message:String(Q),skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1}}try{let Q=await Promise.resolve().then(() => (n5(),o5));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 y)if(B$(Y))$.push(Y);let Q=0;for(let Y of B5)if(M$(Y))Q++;let Z=P$();return{skillsRemoved:$,hooksRemoved:Q,claudeMdBlockRemoved:Z}}import{AsyncLocalStorage as y$}from"async_hooks";import{spawnSync as x$}from"child_process";import{createHash as z$}from"crypto";import{existsSync as J9,mkdirSync as V0,readFileSync as M5,writeFileSync as q5}from"fs";import{homedir as Y9}from"os";import{basename as S$,join as x,parse as h$,resolve as Z9}from"path";function _(){return process.env.BEACON_HOME||x(Y9(),".beacon")}function P5(){return x(_(),"workspaces.json")}function o($){return z$("sha256").update($).digest("hex").slice(0,12)}function V9($=process.cwd()){let Q=x$("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 f0($){let Q=Z9($);return Q!==Z9(Y9())&&Q!==h$(Q).root}function X9(){return x(_(),"deleted.json")}function w5(){try{let $=JSON.parse(M5(X9(),"utf8"));return Array.isArray($)?$:[]}catch{return[]}}function H9($){V0(_(),{recursive:!0}),q5(X9(),JSON.stringify($,null,2))}function g0($){return w5().includes($)}function wZ($){let Q=w5();if(!Q.includes($))H9([...Q,$])}function f$($){let Q=w5();if(Q.includes($))H9(Q.filter((Z)=>Z!==$))}function u0($){return x(_(),$)}function C5($){return`file:${x(u0($),"db.sqlite")}`}function X0(){try{let $=JSON.parse(M5(P5(),"utf8"));return Array.isArray($)?$:[]}catch{return[]}}function v5($){V0(_(),{recursive:!0}),q5(P5(),JSON.stringify($,null,2))}function b0(){return X0().sort(($,Q)=>Q.lastOpenedAt.localeCompare($.lastOpenedAt))}function f($){return X0().find((Q)=>Q.id===$)??null}function m0($,Q,Z=new Date().toISOString()){if(!f0($))throw Error(`beacon: refusing to register a non-repo path as a workspace: ${$}`);let Y=o($);if(g0(Y))throw Error(`beacon: workspace ${Y} (${$}) was deleted \u2014 run \`beacon\` or /beacon-init to re-add it`);let X=X0(),H=X.find((U)=>U.id===Y),G={id:Y,path:$,name:Q||H?.name||S$($),lastOpenedAt:Z},j=[G,...X.filter((U)=>U.id!==Y)];return V0(u0(Y),{recursive:!0}),v5(j),G}function CZ($,Q){return f$(o($)),m0($,Q)}function vZ($,Q=new Date().toISOString()){let Z=X0(),Y=Z.find((X)=>X.id===$);if(!Y)return;Y.lastOpenedAt=Q,v5(Z)}function FZ($){if(v5(X0().filter((Q)=>Q.id!==$)),H0()===$)g$(b0()[0]?.id??null)}function G9(){return x(_(),"active")}function H0(){try{return M5(G9(),"utf8").trim()||null}catch{return null}}function g$($){V0(_(),{recursive:!0}),q5(G9(),$??"")}function OZ(){let $=H0();return $?f($):null}function DZ(){let $=O5()??H0();return $?f($):null}function RZ($){return f($)?.path??null}function AZ(){return J9(P5())}var j9="beacon_ws";function U9($,Q){let Z=$.headers.get("cookie");if(!Z)return null;for(let Y of Z.split(";")){let X=Y.indexOf("=");if(X===-1)continue;if(Y.slice(0,X).trim()===Q)return decodeURIComponent(Y.slice(X+1).trim())}return null}function EZ($){let Q=$.headers.get("x-beacon-workspace");if(Q&&f(Q))return Q;let Z=U9($,j9);if(Z&&f(Z))return Z;return u$()}function u$(){let $=b0();return $.length===1?$[0].id:null}var F5="x-beacon-workspace-path";async function IZ($){let Q=$.headers.get("x-beacon-workspace");if(Q&&f(Q))return Q;let Z=$.headers.get(F5);if(Z&&f0(Z)&&!g0(o(Z))&&(!Q||o(Z)===Q)){let X=m0(Z);return await D5(X.id),X.id}let Y=U9($,j9);if(Y&&f(Y))return Y;return null}var W9=new y$;function b$($,Q){return $?W9.run($,Q):Q()}function O5(){return W9.getStore()??null}var N5=new Set;function TZ($){N5.delete(x(u0($),"db.sqlite"))}async function D5($){let Q=u0($),Z=x(Q,"db.sqlite"),Y=J9(Z);if(Y&&N5.has(Z))return{ok:!0,created:!1,migrated:!1};try{V0(Q,{recursive:!0});let{provisionDb:X}=await Q9().then(() => $9),H=await X(C5($));return N5.add(Z),{ok:!0,created:!Y,migrated:Y&&H.migrated}}catch(X){return{ok:!1,created:!1,migrated:!1,error:X instanceof Error?X.message:String(X)}}}import{connect as m$}from"net";var B9=4319;function p$($,Q,Z=400){return new Promise((Y)=>{let X=m$({host:$,port:Q}),H=!1,G=(j)=>{if(H)return;H=!0,X.destroy(),Y(j)};X.once("connect",()=>G(!0)),X.once("error",()=>G(!1)),X.setTimeout(Z,()=>G(!1))})}async function c$($){for(let Q of["127.0.0.1","::1"])if(await p$(Q,$))return!1;return!0}async function kZ($,Q=20){for(let Z=$;Z<$+Q;Z++)if(await c$(Z))return Z;return $}import{McpServer as zQ,ResourceTemplate as _5}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as SQ}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as J}from"zod";import{z as B}from"zod";var l$=new Set(["GET","HEAD","OPTIONS"]);function K9($){return l$.has($.trim().toUpperCase())?"read":"write"}var d$=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()})),N9=B.object({name:B.string().trim().min(1),domain:B.string().nullish(),description:B.string().nullish(),columns:B.array(d$).default([])}),M9=B.object({fromTable:B.string(),fromColumn:B.string(),toTable:B.string(),toColumn:B.string(),label:B.string().nullish()}),q9=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)}))})),hZ=B.object({tables:B.array(N9).default([]),relations:B.array(M9).default([]),endpoints:B.array(q9).default([])});import{z as D}from"zod";import{and as V1,eq as X1,inArray as H1}from"drizzle-orm";import{drizzle as PQ}from"drizzle-orm/libsql";import{createClient as wQ}from"@libsql/client";var R5={};t(R5,{workspaceFlag:()=>e$,tag:()=>n,syncState:()=>r$,projectMeta:()=>t$,planContract:()=>$Q,note:()=>n$,nodeTags:()=>g,nodeFile:()=>G0,node:()=>M,endpointTable:()=>b,endpoint:()=>i,edge:()=>z,draftTable:()=>A,draftRelation:()=>m,draftColumn:()=>W0,dbTable:()=>F,dbRelation:()=>u,dbColumn:()=>U0,codeFileEdge:()=>p,codeFile:()=>k,bugFlag:()=>j0,boardAnnotation:()=>i$,appSetting:()=>a$});import{sqliteTable as q,index as N,foreignKey as s$,text as V,integer as W,real as O,uniqueIndex as T,primaryKey as o$}from"drizzle-orm/sqlite-core";import{createId as C}from"@paralleldrive/cuid2";var M=q("Node",{id:V().primaryKey().$defaultFn(()=>C()),view:V().notNull(),kind:V().default("FEATURE").notNull(),cluster:V(),layer:V(),title:V().notNull(),role:V(),plain:V(),status:V().default("PENDING").notNull(),priority:W().default(2).notNull(),progress:W().default(0).notNull(),x:O().default(0).notNull(),y:O().default(0).notNull(),sourceRef:V(),externalId:V(),source:V().default("MANUAL").notNull(),planId:V(),parentId:V(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[N("Node_cluster_idx").on($.cluster),N("Node_parentId_idx").on($.parentId),N("Node_view_idx").on($.view),s$(()=>({columns:[$.parentId],foreignColumns:[$.id],name:"Node_parentId_Node_id_fk"})).onUpdate("cascade").onDelete("cascade")]),G0=q("NodeFile",{id:V().primaryKey().$defaultFn(()=>C()),nodeId:V().notNull().references(()=>M.id,{onDelete:"cascade",onUpdate:"cascade"}),path:V().notNull()},($)=>[T("NodeFile_nodeId_path_key").on($.nodeId,$.path),N("NodeFile_nodeId_idx").on($.nodeId)]),n=q("Tag",{id:V().primaryKey().$defaultFn(()=>C()),label:V().notNull(),color:V()},($)=>[T("Tag_label_key").on($.label)]),z=q("Edge",{id:V().primaryKey().$defaultFn(()=>C()),fromId:V().notNull().references(()=>M.id,{onDelete:"cascade",onUpdate:"cascade"}),toId:V().notNull().references(()=>M.id,{onDelete:"cascade",onUpdate:"cascade"}),kind:V().default("DEPENDS").notNull(),label:V(),sourceHandle:V(),targetHandle:V()},($)=>[T("Edge_fromId_toId_kind_key").on($.fromId,$.toId,$.kind),N("Edge_toId_idx").on($.toId),N("Edge_fromId_idx").on($.fromId)]),g=q("_NodeTags",{a:V("A").notNull().references(()=>M.id,{onDelete:"cascade",onUpdate:"cascade"}),b:V("B").notNull().references(()=>n.id,{onDelete:"cascade",onUpdate:"cascade"})},($)=>[T("_NodeTags_AB_unique").on($.a,$.b),N("_NodeTags_B_index").on($.b)]),n$=q("Note",{id:V().primaryKey().$defaultFn(()=>C()),title:V().default("Untitled").notNull(),body:V().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)]),i$=q("BoardAnnotation",{id:V().primaryKey().$defaultFn(()=>C()),targetKind:V().notNull(),targetId:V().notNull(),columnName:V(),body:V().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)]),j0=q("BugFlag",{id:V().primaryKey().$defaultFn(()=>C()),nodeId:V().notNull().references(()=>M.id,{onDelete:"cascade",onUpdate:"cascade"}),by:V().notNull(),note:V().notNull(),resolvedAt:W({mode:"timestamp_ms"}),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date)},($)=>[N("BugFlag_nodeId_idx").on($.nodeId)]),F=q("DbTable",{id:V().primaryKey().$defaultFn(()=>C()),name:V().notNull(),domain:V(),description:V(),source:V().default("MANUAL").notNull(),planId:V(),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),T("DbTable_name_key").on($.name)]),U0=q("DbColumn",{id:V().primaryKey().$defaultFn(()=>C()),tableId:V().notNull().references(()=>F.id,{onDelete:"cascade",onUpdate:"cascade"}),name:V().notNull(),type:V().notNull(),isPk:W({mode:"boolean"}).default(!1).notNull(),isFk:W({mode:"boolean"}).default(!1).notNull(),nullable:W({mode:"boolean"}).default(!0).notNull(),note:V(),ord:W().default(0).notNull()},($)=>[T("DbColumn_tableId_name_key").on($.tableId,$.name),N("DbColumn_tableId_idx").on($.tableId)]),u=q("DbRelation",{id:V().primaryKey().$defaultFn(()=>C()),fromTableId:V().notNull().references(()=>F.id,{onDelete:"cascade",onUpdate:"cascade"}),toTableId:V().notNull().references(()=>F.id,{onDelete:"cascade",onUpdate:"cascade"}),fromColumn:V().notNull(),toColumn:V().notNull(),label:V()},($)=>[N("DbRelation_toTableId_idx").on($.toTableId),N("DbRelation_fromTableId_idx").on($.fromTableId)]),i=q("Endpoint",{id:V().primaryKey().$defaultFn(()=>C()),method:V().notNull(),path:V().notNull(),domain:V(),description:V(),source:V().default("MANUAL").notNull(),planId:V(),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)},($)=>[T("Endpoint_method_path_key").on($.method,$.path),N("Endpoint_domain_idx").on($.domain)]),b=q("EndpointTable",{id:V().primaryKey().$defaultFn(()=>C()),endpointId:V().notNull().references(()=>i.id,{onDelete:"cascade",onUpdate:"cascade"}),tableId:V().notNull().references(()=>F.id,{onDelete:"cascade",onUpdate:"cascade"}),access:V().default("read").notNull()},($)=>[T("EndpointTable_endpointId_tableId_key").on($.endpointId,$.tableId),N("EndpointTable_tableId_idx").on($.tableId)]),A=q("DraftTable",{id:V().primaryKey().$defaultFn(()=>C()),name:V().notNull(),domain:V(),description:V(),x:O().default(0).notNull(),y:O().default(0).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date)},($)=>[T("DraftTable_name_key").on($.name)]),W0=q("DraftColumn",{id:V().primaryKey().$defaultFn(()=>C()),tableId:V().notNull().references(()=>A.id,{onDelete:"cascade",onUpdate:"cascade"}),name:V().notNull(),type:V().notNull(),isPk:W({mode:"boolean"}).default(!1).notNull(),isFk:W({mode:"boolean"}).default(!1).notNull(),nullable:W({mode:"boolean"}).default(!0).notNull(),note:V(),ord:W().default(0).notNull()},($)=>[N("DraftColumn_tableId_idx").on($.tableId)]),m=q("DraftRelation",{id:V().primaryKey().$defaultFn(()=>C()),fromTableId:V().notNull().references(()=>A.id,{onDelete:"cascade",onUpdate:"cascade"}),toTableId:V().notNull().references(()=>A.id,{onDelete:"cascade",onUpdate:"cascade"}),fromColumn:V().notNull(),toColumn:V().notNull(),label:V()},($)=>[N("DraftRelation_toTableId_idx").on($.toTableId),N("DraftRelation_fromTableId_idx").on($.fromTableId)]),k=q("CodeFile",{path:V().primaryKey(),root:V(),lang:V(),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)}),p=q("CodeFileEdge",{fromPath:V().notNull().references(()=>k.path,{onDelete:"cascade",onUpdate:"cascade"}),toPath:V().notNull().references(()=>k.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),o$({columns:[$.fromPath,$.toPath],name:"CodeFileEdge_fromPath_toPath_pk"})]),r$=q("SyncState",{id:V().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)}),a$=q("AppSetting",{id:V().primaryKey().default("singleton"),editor:V().default("auto").notNull(),currentFeatureId:V(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),t$=q("ProjectMeta",{id:V().primaryKey().default("singleton"),overview:V(),conventions:V().default("[]").notNull(),hasFrontend:W({mode:"boolean"}),classificationRoots:V().default("[]").notNull(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),e$=q("WorkspaceFlag",{id:V().primaryKey().$defaultFn(()=>C()),key:V().notNull(),enabled:W({mode:"boolean"}).default(!1).notNull(),config:V(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[T("WorkspaceFlag_key_key").on($.key)]),$Q=q("PlanContract",{id:V().primaryKey().$defaultFn(()=>C()),planId:V().notNull(),declaredFiles:V().default("[]").notNull(),authorizedExtras:V().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)},($)=>[T("PlanContract_planId_key").on($.planId),N("PlanContract_active_idx").on($.active)]);var A5={};t(A5,{tagRelations:()=>YQ,nodeTagsRelations:()=>VQ,nodeRelations:()=>QQ,nodeFileRelations:()=>ZQ,endpointTableRelations:()=>WQ,endpointRelations:()=>UQ,edgeRelations:()=>XQ,draftTableRelations:()=>BQ,draftRelationRelations:()=>NQ,draftColumnRelations:()=>KQ,dbTableRelations:()=>HQ,dbRelationRelations:()=>jQ,dbColumnRelations:()=>GQ,codeFileRelations:()=>MQ,codeFileEdgeRelations:()=>qQ,bugFlagRelations:()=>JQ});import{relations as v}from"drizzle-orm";var QQ=v(M,({one:$,many:Q})=>({files:Q(G0),bugFlags:Q(j0),nodeTags:Q(g),edgesOut:Q(z,{relationName:"EdgeFrom"}),edgesIn:Q(z,{relationName:"EdgeTo"}),parent:$(M,{fields:[M.parentId],references:[M.id],relationName:"NodeTree"}),children:Q(M,{relationName:"NodeTree"})})),ZQ=v(G0,({one:$})=>({node:$(M,{fields:[G0.nodeId],references:[M.id]})})),JQ=v(j0,({one:$})=>({node:$(M,{fields:[j0.nodeId],references:[M.id]})})),YQ=v(n,({many:$})=>({nodeTags:$(g)})),VQ=v(g,({one:$})=>({node:$(M,{fields:[g.a],references:[M.id]}),tag:$(n,{fields:[g.b],references:[n.id]})})),XQ=v(z,({one:$})=>({from:$(M,{fields:[z.fromId],references:[M.id],relationName:"EdgeFrom"}),to:$(M,{fields:[z.toId],references:[M.id],relationName:"EdgeTo"})})),HQ=v(F,({many:$})=>({columns:$(U0),fksOut:$(u,{relationName:"FkFrom"}),fksIn:$(u,{relationName:"FkTo"}),usages:$(b)})),GQ=v(U0,({one:$})=>({table:$(F,{fields:[U0.tableId],references:[F.id]})})),jQ=v(u,({one:$})=>({fromTable:$(F,{fields:[u.fromTableId],references:[F.id],relationName:"FkFrom"}),toTable:$(F,{fields:[u.toTableId],references:[F.id],relationName:"FkTo"})})),UQ=v(i,({many:$})=>({tables:$(b)})),WQ=v(b,({one:$})=>({endpoint:$(i,{fields:[b.endpointId],references:[i.id]}),table:$(F,{fields:[b.tableId],references:[F.id]})})),BQ=v(A,({many:$})=>({columns:$(W0),fksOut:$(m,{relationName:"DraftFkFrom"}),fksIn:$(m,{relationName:"DraftFkTo"})})),KQ=v(W0,({one:$})=>({table:$(A,{fields:[W0.tableId],references:[A.id]})})),NQ=v(m,({one:$})=>({fromTable:$(A,{fields:[m.fromTableId],references:[A.id],relationName:"DraftFkFrom"}),toTable:$(A,{fields:[m.toTableId],references:[A.id],relationName:"DraftFkTo"})})),MQ=v(k,({many:$})=>({edgesOut:$(p,{relationName:"CFEFrom"}),edgesIn:$(p,{relationName:"CFETo"})})),qQ=v(p,({one:$})=>({fromFile:$(k,{fields:[p.fromPath],references:[k.path],relationName:"CFEFrom"}),toFile:$(k,{fields:[p.toPath],references:[k.path],relationName:"CFETo"})}));var CQ={...R5,...A5};function vQ(){let $=process.env.DATABASE_URL;if($&&/^(file:|libsql:|wss?:|https?:|:memory:)/i.test($))return $;return"file:./dev.db"}var FQ=vQ();function P9($){let Q=wQ({url:$});return Q.execute("PRAGMA foreign_keys = ON;"),Q.execute("PRAGMA busy_timeout = 5000;"),PQ(Q,{schema:CQ})}var I5=globalThis,E5=I5.dzDefault??P9(FQ);I5.dzDefault=E5;var p0=I5.dzByUrl??=new Map;function OQ($){let Q=p0.get($);if(!Q)Q=P9($),p0.set($,Q);return Q}function dZ($){let Q=p0.get($);p0.delete($);try{Q?.$client?.close?.()}catch{}}function DQ(){if(process.env.BEACON_REPO)return E5;let $=O5()??H0();if(!$)return E5;return OQ(C5($))}var RQ=new Proxy({},{get($,Q){let Z=DQ(),Y=Z[Q];return typeof Y==="function"?Y.bind(Z):Y}});var AQ=["frontend","backend","fullstack"],EQ={fe:"frontend",front:"frontend",be:"backend",back:"backend",fs:"fullstack","full-stack":"fullstack","full stack":"fullstack"};function c0($){let Q=($??"").trim().toLowerCase();if(!Q)return null;if(AQ.includes(Q))return Q;return EQ[Q]??null}import{forceCenter as rZ,forceCollide as aZ,forceLink as tZ,forceManyBody as eZ,forceSimulation as $1}from"d3-force";var w9=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:X,...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:c0(X)})),B1=D.object({features:D.array(w9).default([])});var IQ=/(\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 C9($){return!!$&&IQ.test($)}function v9($,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 TQ($){return $.cluster??$.category??$.domain??null}function F9($,Q){let Z=Q?.requireLayer??!1,Y=$.map((H)=>{let G=[],j=TQ(H);if(!j||!j.trim())G.push("category");if(H.priority==null)G.push("priority");if(Z&&!c0(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 X=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."+X+` Missing:
275
279
  `+Y.join(`
276
- `)+"\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 I5($){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`
280
+ `)+"\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 T5($){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`
277
281
 
278
282
  This plan created these roadmap feature(s):
279
283
  `+Q.join(`
280
- `)+'\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 RQ}from"fs";import{join as AQ}from"path";function EQ(){try{return JSON.parse(RQ(AQ(_(),"server.json"),"utf8"))}catch{return null}}function i(){if(process.env.BEACON_URL)return process.env.BEACON_URL;return`http://localhost:${EQ()?.port||process.env.PORT||G9}`}import{execSync as IQ}from"child_process";import{platform as C9}from"os";function TQ($){if(process.env.BEACON_NO_OPEN)return;let Q=C9()==="darwin"?"open":C9()==="win32"?"start":"xdg-open";try{IQ(`${Q} "${$}"`,{stdio:"ignore"})}catch{}}async function T5($,Q){if(await fetch(`${$}/api/plan/presence`,{headers:{"x-beacon-workspace":Q}}).then((X)=>X.json()).then((X)=>!!X?.live).catch(()=>!1))return;let Y=encodeURIComponent(`/plan?ws=${Q}`);TQ(`${$}/api/workspace/activate?id=${Q}&redirect=${Y}`)}n0();function U0($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036F]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50)||"item"}function v9($){return`${U0($.title)}-${$.id.slice(-6)}`}function F9($){return{resources:$.map((Q)=>({uri:`note://${v9(Q)}`,name:Q.title||"Untitled",description:`${Q.title||"Untitled"}${Q.pinned?" \xB7 pinned":""} \xB7 note`,mimeType:"text/markdown"}))}}function D9($,Q){return $.find((Z)=>v9(Z)===Q)}function O9($){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(`
281
- `)}await i5();var S=Z9(),p=s(S);if(!h0(S)){let $=u0();if($.length===1)console.error(`[beacon mcp] cwd ${S} isn't a registered repo \u2014 falling back to your only Beacon workspace "${$[0].name}".`);else if($.length>1)console.error(`[beacon mcp] cwd ${S} 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 ${S} \u2014 home/non-repo dir.`)}else if(g0(p))console.error(`[beacon mcp] not registering ${S} \u2014 workspace was deleted; run /beacon-init to re-add it.`);else try{b0(S);let $=await D5(p);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",p),Z.set(v5,S);let Y=await fetch(`${i()}${$}`,{...Q,headers:Z}),X=await Y.text();if(!Y.ok)throw Error(`Beacon ${$} -> ${Y.status} ${X}`);return X?JSON.parse(X):null}function d0($,Q){return E($,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Q)})}function E9($){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 R=new LQ({name:"beacon",version:"0.1.0"});R.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 R9=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");R.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:R9})).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:R9}},async($)=>{try{let{path:Q,body:Z}=q9($.action,$),Y=await d0(Q,Z);return{content:[{type:"text",text:JSON.stringify(Y)}]}}catch(Q){return E9(Q)}});R.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 d0("/api/init",$);return{content:[{type:"text",text:JSON.stringify(Q)}]}});R.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 X=await E(`/api/context/feature?${Y.toString()}`);return{content:[{type:"text",text:JSON.stringify(X)}]}});R.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)}]}});R.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 X=await E(`/api/entities?${Y.toString()}`);return{content:[{type:"text",text:JSON.stringify(X)}]}});R.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"),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. When the user has the plan scope-guard enabled, these are frozen at approval and you are held to them while implementing: editing an undeclared file pauses for the user's authorization (which adds it to the contract). Safe to always include; ignored when the guard is off.")}},async({description:$,features:Q,tables:Z,relations:Y,endpoints:X,contract:H})=>{let j=(q)=>new Promise((W0)=>setTimeout(W0,q)),G=(q)=>({content:[{type:"text",text:q}]}),U=(Z?.length??0)>0,w=(Q??[]).map((q)=>`${q.title} ${q.role??""} ${q.plain??""}`).join(`
282
- `),a=(X?.length??0)>0||P9(`${$}
283
- ${w}`);if(!U&&a)return G("\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 q=await E("/api/project-meta").then((y9)=>!!y9?.hasFrontend).catch(()=>!1),W0=w9(Q,{requireLayer:q});if(W0)return G(W0)}let _9=(Z?.length??0)+(X?.length??0)>0;try{await d0("/api/plan",{description:$,draft:_9?{tables:Z??[],relations:Y??[],endpoints:X??[]}:void 0,features:Q?.length?Q:void 0,contract:H?.length?H:void 0})}catch(q){return E9(q)}await fetch(`${i()}/api/workspace/activate?id=${p}`).catch(()=>{}),await T5(i(),p);let k9=Date.now()+o0;while(Date.now()<k9){await j(s0);let q=await E("/api/plan/verdict").catch(()=>null);if(!q)continue;if(q.kind==="feedback")return G("\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:
284
+ `)+'\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 LQ}from"fs";import{join as _Q}from"path";function kQ(){try{return JSON.parse(LQ(_Q(_(),"server.json"),"utf8"))}catch{return null}}function r(){if(process.env.BEACON_URL)return process.env.BEACON_URL;return`http://localhost:${kQ()?.port||process.env.PORT||B9}`}import{execSync as yQ}from"child_process";import{platform as O9}from"os";function xQ($){if(process.env.BEACON_NO_OPEN)return;let Q=O9()==="darwin"?"open":O9()==="win32"?"start":"xdg-open";try{yQ(`${Q} "${$}"`,{stdio:"ignore"})}catch{}}async function L5($,Q){if(await fetch(`${$}/api/plan/presence`,{headers:{"x-beacon-workspace":Q}}).then((X)=>X.json()).then((X)=>!!X?.live).catch(()=>!1))return;let Y=encodeURIComponent(`/plan?ws=${Q}`);xQ(`${$}/api/workspace/activate?id=${Q}&redirect=${Y}`)}i0();function B0($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036F]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50)||"item"}function D9($){return`${B0($.title)}-${$.id.slice(-6)}`}function R9($){return{resources:$.map((Q)=>({uri:`note://${D9(Q)}`,name:Q.title||"Untitled",description:`${Q.title||"Untitled"}${Q.pinned?" \xB7 pinned":""} \xB7 note`,mimeType:"text/markdown"}))}}function A9($,Q){return $.find((Z)=>D9(Z)===Q)}function E9($){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(`
285
+ `)}await t5();var S=V9(),c=o(S);if(!f0(S)){let $=b0();if($.length===1)console.error(`[beacon mcp] cwd ${S} isn't a registered repo \u2014 falling back to your only Beacon workspace "${$[0].name}".`);else if($.length>1)console.error(`[beacon mcp] cwd ${S} 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 ${S} \u2014 home/non-repo dir.`)}else if(g0(c))console.error(`[beacon mcp] not registering ${S} \u2014 workspace was deleted; run /beacon-init to re-add it.`);else try{m0(S);let $=await D5(c);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",c),Z.set(F5,S);let Y=await fetch(`${r()}${$}`,{...Q,headers:Z}),X=await Y.text();if(!Y.ok)throw Error(`Beacon ${$} -> ${Y.status} ${X}`);return X?JSON.parse(X):null}function s0($,Q){return E($,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Q)})}function L9($){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 R=new zQ({name:"beacon",version:"0.1.0"});R.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 I9=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");R.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:I9})).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:I9}},async($)=>{try{let{path:Q,body:Z}=v9($.action,$),Y=await s0(Q,Z);return{content:[{type:"text",text:JSON.stringify(Y)}]}}catch(Q){return L9(Q)}});R.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 s0("/api/init",$);return{content:[{type:"text",text:JSON.stringify(Q)}]}});R.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 X=await E(`/api/context/feature?${Y.toString()}`);return{content:[{type:"text",text:JSON.stringify(X)}]}});R.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)}]}});R.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 X=await E(`/api/entities?${Y.toString()}`);return{content:[{type:"text",text:JSON.stringify(X)}]}});R.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. When the user has the plan scope-guard enabled, these are frozen at approval and you are held to them while implementing: editing an undeclared file pauses for the user's authorization (which adds it to the contract). Safe to always include; ignored when the guard is off.")}},async({description:$,features:Q,tables:Z,relations:Y,endpoints:X,contract:H})=>{let G=(P)=>new Promise((K0)=>setTimeout(K0,P)),j=(P)=>({content:[{type:"text",text:P}]}),U=(Z?.length??0)>0,w=(Q??[]).map((P)=>`${P.title} ${P.role??""} ${P.plain??""}`).join(`
286
+ `),a=(X?.length??0)>0||C9(`${$}
287
+ ${w}`);if(!U&&a)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 P=await E("/api/project-meta").then((S9)=>!!S9?.hasFrontend).catch(()=>!1),K0=F9(Q,{requireLayer:P});if(K0)return j(K0)}let x9=(Z?.length??0)+(X?.length??0)>0;try{await s0("/api/plan",{description:$,draft:x9?{tables:Z??[],relations:Y??[],endpoints:X??[]}:void 0,features:Q?.length?Q:void 0,contract:H?.length?H:void 0})}catch(P){return L9(P)}await fetch(`${r()}/api/workspace/activate?id=${c}`).catch(()=>{}),await L5(r(),c);let z9=Date.now()+n0;while(Date.now()<z9){await G(o0);let P=await E("/api/plan/verdict").catch(()=>null);if(!P)continue;if(P.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:
284
288
 
285
- `+q.feedback);if(q.kind==="approved")return G(`\u2705 Plan approved by the user. ${q.summary}`+(q.detail?`
289
+ `+P.feedback);if(P.kind==="approved")return j(`\u2705 Plan approved by the user. ${P.summary}`+(P.detail?`
286
290
 
287
291
  Implement EXACTLY the schema below (migrations + code) \u2014 the user may have `+`edited columns on the canvas:
288
292
 
289
- `+q.detail:"")+I5(q.features));if(q.kind==="discarded")return G(`\u274C The user discarded the plan in Beacon. ${q.summary} Ask what they want to adjust before proposing again.`)}return G("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.")});R.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.")}},async({description:$,markdown:Q})=>{let Z=(H)=>new Promise((j)=>setTimeout(j,H)),Y=(H)=>({content:[{type:"text",text:H}]});await d0("/api/plan",{description:$,markdown:Q}),await fetch(`${i()}/api/workspace/activate?id=${p}`).catch(()=>{}),await T5(i(),p);let X=Date.now()+o0;while(Date.now()<X){await Z(s0);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:
293
+ `+P.detail:"")+T5(P.features));if(P.kind==="discarded")return j(`\u274C The user discarded the plan in Beacon. ${P.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.")});R.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 s0("/api/plan",{description:$,markdown:Q}),await fetch(`${r()}/api/workspace/activate?id=${c}`).catch(()=>{}),await L5(r(),c);let X=Date.now()+n0;while(Date.now()<X){await Z(o0);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:
290
294
 
291
295
  `+H.feedback);if(H.kind==="approved")return Y(`\u2705 Plan approved by the user. ${H.summary??""}`.trim()+(H.detail?`
292
296
 
293
297
  Implement exactly what's on the board:
294
298
 
295
- ${H.detail}`:"")+I5(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 I9=($)=>Array.isArray($)?$[0]:$;async function l0($){return(await E(`/api/entities?kind=${$}&full=1`)).items}function T9($,Q){return{resources:$.map((Z)=>({uri:`${Q}${U0(Z.title)}`,name:Z.title,description:`${Z.title}${Z.cluster?` \xB7 ${Z.cluster}`:""} \xB7 ${Z.status}`,mimeType:"text/markdown"}))}}async function L9($,Q,Z){let Y=(await l0(Z)).find((G)=>U0(G.title)===I9(Q));if(!Y)return{contents:[{uri:$.href,mimeType:"text/markdown",text:"(not found)"}]};let H=((await E("/api/entities?kind=tables")).items??[]).map((G)=>G.name),j=[`# ${Y.title}`];if(Y.cluster)j.push(`*Domain:* \`${Y.cluster}\``);if(Y.status)j.push(`*Status:* \`${Y.status}\``);if(j.push(""),j.push(Y.plain?.trim()||"(this node has no description yet \u2014 add one on Beacon's /map page)"),j.push("","## Existing DB tables in this project"),j.push(H.length?H.join(", "):"(none yet)"),Z==="features"){let G=await l0("features"),U=[...new Set(G.map((w)=>w.cluster?.trim()).filter((w)=>!!w))].sort();j.push("","## Existing feature categories \u2014 reuse one before inventing a new one"),j.push(U.length?U.join(", "):"(none yet)"),j.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:j.join(`
296
- `)}]}}R.registerResource("beacon-feature",new L5("feature://{slug}",{list:async()=>T9(await l0("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})=>L9($,Q,"features"));R.registerResource("beacon-component",new L5("component://{slug}",{list:async()=>T9(await l0("architecture"),"component://")}),{title:"Beacon: architecture",description:"Architecture components \u2014 picking one imports 'what the agent sees'.",mimeType:"text/markdown"},($,{slug:Q})=>L9($,Q,"architecture"));async function A9(){return await E("/api/notes")}R.registerResource("beacon-note",new L5("note://{slug}",{list:async()=>F9(await A9())}),{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=D9(await A9(),I9(Q)),Y=Z?O9(Z):"(not found)";return{contents:[{uri:$.href,mimeType:"text/markdown",text:Y}]}});await R.connect(new _Q);var c0=-1;setInterval(async()=>{try{let{version:$}=await E("/api/version");if(c0===-1)c0=$;else if($!==c0)c0=$,R.sendResourceListChanged()}catch{}},_5);
299
+ ${H.detail}`:"")+T5(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 _9=($)=>Array.isArray($)?$[0]:$;async function d0($){return(await E(`/api/entities?kind=${$}&full=1`)).items}function k9($,Q){return{resources:$.map((Z)=>({uri:`${Q}${B0(Z.title)}`,name:Z.title,description:`${Z.title}${Z.cluster?` \xB7 ${Z.cluster}`:""} \xB7 ${Z.status}`,mimeType:"text/markdown"}))}}async function y9($,Q,Z){let Y=(await d0(Z)).find((j)=>B0(j.title)===_9(Q));if(!Y)return{contents:[{uri:$.href,mimeType:"text/markdown",text:"(not found)"}]};let H=((await E("/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 d0("features"),U=[...new Set(j.map((w)=>w.cluster?.trim()).filter((w)=>!!w))].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(`
300
+ `)}]}}R.registerResource("beacon-feature",new _5("feature://{slug}",{list:async()=>k9(await d0("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})=>y9($,Q,"features"));R.registerResource("beacon-component",new _5("component://{slug}",{list:async()=>k9(await d0("architecture"),"component://")}),{title:"Beacon: architecture",description:"Architecture components \u2014 picking one imports 'what the agent sees'.",mimeType:"text/markdown"},($,{slug:Q})=>y9($,Q,"architecture"));async function T9(){return await E("/api/notes")}R.registerResource("beacon-note",new _5("note://{slug}",{list:async()=>R9(await T9())}),{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=A9(await T9(),_9(Q)),Y=Z?E9(Z):"(not found)";return{contents:[{uri:$.href,mimeType:"text/markdown",text:Y}]}});await R.connect(new SQ);var l0=-1;setInterval(async()=>{try{let{version:$}=await E("/api/version");if(l0===-1)l0=$;else if($!==l0)l0=$,R.sendResourceListChanged()}catch{}},k5);