trybeacon 0.1.74 → 0.1.76

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 (92) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.next/BUILD_ID +1 -1
  3. package/.next/app-path-routes-manifest.json +18 -18
  4. package/.next/build-manifest.json +2 -2
  5. package/.next/prerender-manifest.json +3 -3
  6. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  7. package/.next/server/app/_global-error.html +1 -1
  8. package/.next/server/app/_global-error.rsc +1 -1
  9. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  13. package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  14. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  15. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  16. package/.next/server/app/_not-found.html +1 -1
  17. package/.next/server/app/_not-found.rsc +12 -12
  18. package/.next/server/app/_not-found.segments/_full.segment.rsc +12 -12
  19. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  20. package/.next/server/app/_not-found.segments/_index.segment.rsc +12 -12
  21. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  22. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  23. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  24. package/.next/server/app/docs/page_client-reference-manifest.js +1 -1
  25. package/.next/server/app/docs.html +1 -1
  26. package/.next/server/app/docs.rsc +12 -12
  27. package/.next/server/app/docs.segments/_full.segment.rsc +12 -12
  28. package/.next/server/app/docs.segments/_head.segment.rsc +1 -1
  29. package/.next/server/app/docs.segments/_index.segment.rsc +12 -12
  30. package/.next/server/app/docs.segments/_tree.segment.rsc +2 -2
  31. package/.next/server/app/docs.segments/docs/__PAGE__.segment.rsc +1 -1
  32. package/.next/server/app/docs.segments/docs.segment.rsc +1 -1
  33. package/.next/server/app/help/page_client-reference-manifest.js +1 -1
  34. package/.next/server/app/help.html +1 -1
  35. package/.next/server/app/help.rsc +12 -12
  36. package/.next/server/app/help.segments/_full.segment.rsc +12 -12
  37. package/.next/server/app/help.segments/_head.segment.rsc +1 -1
  38. package/.next/server/app/help.segments/_index.segment.rsc +12 -12
  39. package/.next/server/app/help.segments/_tree.segment.rsc +2 -2
  40. package/.next/server/app/help.segments/help/__PAGE__.segment.rsc +1 -1
  41. package/.next/server/app/help.segments/help.segment.rsc +1 -1
  42. package/.next/server/app/index.html +1 -1
  43. package/.next/server/app/index.rsc +12 -12
  44. package/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  45. package/.next/server/app/index.segments/_full.segment.rsc +12 -12
  46. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  47. package/.next/server/app/index.segments/_index.segment.rsc +12 -12
  48. package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  49. package/.next/server/app/learn/page.js +3 -3
  50. package/.next/server/app/learn/page.js.nft.json +1 -1
  51. package/.next/server/app/learn/page_client-reference-manifest.js +1 -1
  52. package/.next/server/app/map/page.js +1 -1
  53. package/.next/server/app/map/page.js.nft.json +1 -1
  54. package/.next/server/app/map/page_client-reference-manifest.js +1 -1
  55. package/.next/server/app/page_client-reference-manifest.js +1 -1
  56. package/.next/server/app/plan/page.js +3 -3
  57. package/.next/server/app/plan/page.js.nft.json +1 -1
  58. package/.next/server/app/plan/page_client-reference-manifest.js +1 -1
  59. package/.next/server/app/s/[token]/page.js +1 -1
  60. package/.next/server/app/s/[token]/page.js.nft.json +1 -1
  61. package/.next/server/app/s/[token]/page_client-reference-manifest.js +1 -1
  62. package/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  63. package/.next/server/app-paths-manifest.json +18 -18
  64. package/.next/server/chunks/4378.js +1 -1
  65. package/.next/server/chunks/7581.js +1 -0
  66. package/.next/server/chunks/9683.js +1 -1
  67. package/.next/server/middleware-build-manifest.js +1 -1
  68. package/.next/server/pages/404.html +1 -1
  69. package/.next/server/pages/500.html +1 -1
  70. package/.next/server/server-reference-manifest.js +1 -1
  71. package/.next/server/server-reference-manifest.json +1 -1
  72. package/.next/static/chunks/4477-cda153702c7812d2.js +1 -0
  73. package/.next/static/chunks/809-bda460eadcda74a9.js +1 -0
  74. package/.next/static/chunks/app/layout-3bda91675bae86b9.js +1 -0
  75. package/.next/static/chunks/app/learn/{page-bc40746566d115e5.js → page-994afbcd8b4208be.js} +1 -1
  76. package/.next/static/chunks/app/map/{page-233ccd830873114b.js → page-0f243453c8d81ae1.js} +1 -1
  77. package/.next/static/chunks/app/plan/page-d39e44fc9381d32b.js +11 -0
  78. package/.next/static/chunks/app/s/[token]/{page-2a3f04bc3f60ec49.js → page-b80e34ae23ee7dea.js} +1 -1
  79. package/.next/static/css/{60048003a8c96562.css → ee94ed0880eabb76.css} +1 -1
  80. package/.next/trace +46 -46
  81. package/.next/trace-build +1 -1
  82. package/dist/bin/mcp.js +29 -29
  83. package/dist/bin/prompt.js +6 -2
  84. package/dist/bin/remove.js +6 -6
  85. package/package.json +1 -1
  86. package/.next/server/chunks/6962.js +0 -1
  87. package/.next/static/chunks/3151-861a6caa40f70f79.js +0 -1
  88. package/.next/static/chunks/654-8e68a43e4c589e9c.js +0 -1
  89. package/.next/static/chunks/app/layout-f908dc26e06f4302.js +0 -1
  90. package/.next/static/chunks/app/plan/page-8ec1e1d8ea40686a.js +0 -11
  91. /package/.next/static/{yescmIM6BeSzGgwZ-Dwpq → gJG5my_v2pE9kO341PEf0}/_buildManifest.js +0 -0
  92. /package/.next/static/{yescmIM6BeSzGgwZ-Dwpq → gJG5my_v2pE9kO341PEf0}/_ssgManifest.js +0 -0
package/.next/trace-build CHANGED
@@ -1 +1 @@
1
- [{"name":"run-webpack","duration":29939069,"timestamp":40968115,"id":14,"parentId":1,"tags":{},"startTime":1783105666912,"traceId":"1cefd0ed47001bde"},{"name":"run-typescript","duration":10928403,"timestamp":70909456,"id":4847,"parentId":1,"tags":{},"startTime":1783105696853,"traceId":"1cefd0ed47001bde"},{"name":"static-check","duration":789738,"timestamp":81853137,"id":4850,"parentId":1,"tags":{},"startTime":1783105707797,"traceId":"1cefd0ed47001bde"},{"name":"static-generation","duration":3913606,"timestamp":83118568,"id":5034,"parentId":1,"tags":{},"startTime":1783105709063,"traceId":"1cefd0ed47001bde"},{"name":"collect-build-traces","duration":10715111,"timestamp":82645540,"id":5031,"parentId":1,"tags":{},"startTime":1783105708590,"traceId":"1cefd0ed47001bde"},{"name":"telemetry-flush","duration":63,"timestamp":93364330,"id":5043,"parentId":1,"tags":{},"startTime":1783105719308,"traceId":"1cefd0ed47001bde"},{"name":"next-build","duration":52511780,"timestamp":40852623,"id":1,"tags":{"buildMode":"default","version":"16.2.7","bundler":"webpack","has-custom-webpack-config":"false","use-build-worker":"true"},"startTime":1783105666797,"traceId":"1cefd0ed47001bde"}]
1
+ [{"name":"run-webpack","duration":30983847,"timestamp":231480933,"id":14,"parentId":1,"tags":{},"startTime":1783183727174,"traceId":"0fdb49d083d4f739"},{"name":"run-typescript","duration":11584465,"timestamp":262467028,"id":4855,"parentId":1,"tags":{},"startTime":1783183758160,"traceId":"0fdb49d083d4f739"},{"name":"static-check","duration":784485,"timestamp":274067611,"id":4858,"parentId":1,"tags":{},"startTime":1783183769760,"traceId":"0fdb49d083d4f739"},{"name":"static-generation","duration":3881408,"timestamp":275299913,"id":5042,"parentId":1,"tags":{},"startTime":1783183770993,"traceId":"0fdb49d083d4f739"},{"name":"collect-build-traces","duration":10589601,"timestamp":274854877,"id":5039,"parentId":1,"tags":{},"startTime":1783183770547,"traceId":"0fdb49d083d4f739"},{"name":"telemetry-flush","duration":56,"timestamp":285448206,"id":5051,"parentId":1,"tags":{},"startTime":1783183781141,"traceId":"0fdb49d083d4f739"},{"name":"next-build","duration":54085940,"timestamp":231362332,"id":1,"tags":{"buildMode":"default","version":"16.2.7","bundler":"webpack","has-custom-webpack-config":"false","use-build-worker":"true"},"startTime":1783183727055,"traceId":"0fdb49d083d4f739"}]
package/dist/bin/mcp.js CHANGED
@@ -1,22 +1,22 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var p9=Object.defineProperty;var c9=($)=>$;function l9($,Q){this[$]=c9.bind(null,Q)}var $0=($,Q)=>{for(var Z in Q)p9($,Z,{get:Q[Z],enumerable:!0,configurable:!0,set:l9.bind(Q,Z)})};var i=($,Q)=>()=>($&&(Q=$($=0)),Q);var P0=1500,dQ=480000,C0=1800000,w0=3600000,g5=3000;var t0=()=>{};var J5={};$0(J5,{stripAgentsPointer:()=>m5,removeRepoAssets:()=>$$,installRefreshSkill:()=>o9,installPlanSkill:()=>s9,installInitSkill:()=>d9,installExplainSkill:()=>n9,installCodexRepoSkills:()=>a9,ensureWorkflowDoc:()=>r9,ensureMcp:()=>t9,contextDocTargets:()=>Z5,auditRepo:()=>e9,REFRESH_SKILL:()=>$5,PLAN_SKILL:()=>z5,INIT_SKILL:()=>e0,EXPLAIN_SKILL:()=>b5});import{existsSync as _,mkdirSync as Q0,readFileSync as S,rmSync as v0,writeFileSync as T}from"fs";import{join as M}from"path";function d9($){let Q=M($,".claude","skills","beacon-init");Q0(Q,{recursive:!0});let Z=M(Q,"SKILL.md");return T(Z,e0),Z}function o9($){let Q=M($,".claude","skills","beacon-refresh");Q0(Q,{recursive:!0});let Z=M(Q,"SKILL.md");return T(Z,$5),Z}function s9($){let Q=M($,".claude","skills","beacon-plan");Q0(Q,{recursive:!0});let Z=M(Q,"SKILL.md");return T(Z,z5),Z}function n9($){let Q=M($,".claude","skills","beacon-explain");Q0(Q,{recursive:!0});let Z=M(Q,"SKILL.md");return T(Z,b5),Z}function a9($){let Q=[];for(let Z of i9){let Y=M($,".agents","skills",Z.name);Q0(Y,{recursive:!0});let V=M(Y,"SKILL.md");T(V,Z.body()),Q.push(V)}return Q}function Z5($){let Q=M($,"AGENTS.md"),Z=M($,"CLAUDE.md"),Y=_(Q),V=_(Z);if(!Y&&!V)return[Q,Z];let H=[];if(Y)H.push(Q);if(V)H.push(Z);return H}function m5($){let Q=M($,"CLAUDE.md");if(!_(Q))return;let Z=S(Q,"utf8"),Y=Z.split(`
3
+ var m9=Object.defineProperty;var p9=($)=>$;function c9($,Q){this[$]=p9.bind(null,Q)}var $0=($,Q)=>{for(var Z in Q)m9($,Z,{get:Q[Z],enumerable:!0,configurable:!0,set:c9.bind(Q,Z)})};var i=($,Q)=>()=>($&&(Q=$($=0)),Q);var P0=1500,dQ=480000,C0=1800000,w0=3600000,f5=3000;var t0=()=>{};var J5={};$0(J5,{stripAgentsPointer:()=>z5,removeRepoAssets:()=>e9,installRefreshSkill:()=>d9,installPlanSkill:()=>o9,installInitSkill:()=>l9,installExplainSkill:()=>s9,installCodexRepoSkills:()=>i9,ensureWorkflowDoc:()=>a9,ensureMcp:()=>r9,contextDocTargets:()=>Z5,auditRepo:()=>t9,REFRESH_SKILL:()=>$5,PLAN_SKILL:()=>g5,INIT_SKILL:()=>e0,EXPLAIN_SKILL:()=>h5});import{existsSync as _,mkdirSync as Q0,readFileSync as S,rmSync as F0,writeFileSync as T}from"fs";import{join as M}from"path";function l9($){let Q=M($,".claude","skills","beacon-init");Q0(Q,{recursive:!0});let Z=M(Q,"SKILL.md");return T(Z,e0),Z}function d9($){let Q=M($,".claude","skills","beacon-refresh");Q0(Q,{recursive:!0});let Z=M(Q,"SKILL.md");return T(Z,$5),Z}function o9($){let Q=M($,".claude","skills","beacon-plan");Q0(Q,{recursive:!0});let Z=M(Q,"SKILL.md");return T(Z,g5),Z}function s9($){let Q=M($,".claude","skills","beacon-explain");Q0(Q,{recursive:!0});let Z=M(Q,"SKILL.md");return T(Z,h5),Z}function i9($){let Q=[];for(let Z of n9){let Y=M($,".agents","skills",Z.name);Q0(Y,{recursive:!0});let V=M(Y,"SKILL.md");T(V,Z.body()),Q.push(V)}return Q}function Z5($){let Q=M($,"AGENTS.md"),Z=M($,"CLAUDE.md"),Y=_(Q),V=_(Z);if(!Y&&!V)return[Q,Z];let H=[];if(Y)H.push(Q);if(V)H.push(Z);return H}function z5($){let Q=M($,"CLAUDE.md");if(!_(Q))return;let Z=S(Q,"utf8"),Y=Z.split(`
4
4
  `).filter((V)=>!/^\s*@\.?\/?AGENTS\.md\s*$/.test(V)).join(`
5
5
  `).trim();if(Y&&Y!==Z.trim())T(Q,`${Y}
6
- `)}function r9($){let Q=new RegExp(`${F0}[\\s\\S]*?${Q5}`);for(let Z of Z5($)){let Y="";try{Y=S(Z,"utf8")}catch{}Y=Q.test(Y)?Y.replace(Q,h5):`${Y.trim()}
6
+ `)}function a9($){let Q=new RegExp(`${v0}[\\s\\S]*?${Q5}`);for(let Z of Z5($)){let Y="";try{Y=S(Z,"utf8")}catch{}Y=Q.test(Y)?Y.replace(Q,u5):`${Y.trim()}
7
7
 
8
- ${h5}
8
+ ${u5}
9
9
  `.trimStart(),T(Z,Y.endsWith(`
10
10
  `)?Y:`${Y}
11
- `)}m5($)}function t9($){let Q=M($,".mcp.json"),Z={};try{Z=JSON.parse(S(Q,"utf8"))}catch{}Z.mcpServers=Z.mcpServers??{};let Y=Z.mcpServers.beacon;if(Y){if(!Y.timeout||Y.timeout<w0)return Y.timeout=w0,T(Q,JSON.stringify(Z,null,2)+`
11
+ `)}z5($)}function r9($){let Q=M($,".mcp.json"),Z={};try{Z=JSON.parse(S(Q,"utf8"))}catch{}Z.mcpServers=Z.mcpServers??{};let Y=Z.mcpServers.beacon;if(Y){if(!Y.timeout||Y.timeout<w0)return Y.timeout=w0,T(Q,JSON.stringify(Z,null,2)+`
12
12
  `),{path:Q,added:!1,updated:!0};return{path:Q,added:!1,updated:!1}}return Z.mcpServers.beacon={command:"beacon",args:["mcp"],timeout:w0},T(Q,JSON.stringify(Z,null,2)+`
13
- `),{path:Q,added:!0,updated:!1}}function e9($){let Q=M($,".mcp.json"),Z=!1;try{Z=!!JSON.parse(S(Q,"utf8")).mcpServers?.beacon}catch{}let Y=Z5($).some((V)=>{try{return S(V,"utf8").includes(F0)}catch{return!1}});return{repo:$,mcpRegistered:Z,workflowBlock:Y,skills:{"beacon-init":_(M($,".claude","skills","beacon-init","SKILL.md")),"beacon-refresh":_(M($,".claude","skills","beacon-refresh","SKILL.md"))},codexSkills:{"beacon-init":_(M($,".agents","skills","beacon-init","SKILL.md")),"beacon-refresh":_(M($,".agents","skills","beacon-refresh","SKILL.md"))}}}function $$($){let Q=[];for(let j of["beacon-init","beacon-refresh","beacon-db-design"]){let B=M($,".claude","skills",j);if(_(B))v0(B,{recursive:!0,force:!0}),Q.push(j)}for(let j of["beacon-init","beacon-refresh"]){let B=M($,".agents","skills",j);if(_(B))v0(B,{recursive:!0,force:!0}),Q.push(`codex:${j}`)}let Z=!1,Y=M($,".mcp.json");try{let j=JSON.parse(S(Y,"utf8"));if(j.mcpServers?.beacon){if(delete j.mcpServers.beacon,Z=!0,j.mcpServers&&Object.keys(j.mcpServers).length===0)delete j.mcpServers;if(Object.keys(j).length===0)v0(Y,{force:!0});else T(Y,JSON.stringify(j,null,2)+`
14
- `)}}catch{}let V=!1,H=new RegExp(`\\n?${F0}[\\s\\S]*?${Q5}\\n?`);for(let j of[M($,"AGENTS.md"),M($,"CLAUDE.md")])try{let B=S(j,"utf8");if(H.test(B)){let m=B.replace(H,`
13
+ `),{path:Q,added:!0,updated:!1}}function t9($){let Q=M($,".mcp.json"),Z=!1;try{Z=!!JSON.parse(S(Q,"utf8")).mcpServers?.beacon}catch{}let Y=Z5($).some((V)=>{try{return S(V,"utf8").includes(v0)}catch{return!1}});return{repo:$,mcpRegistered:Z,workflowBlock:Y,skills:{"beacon-init":_(M($,".claude","skills","beacon-init","SKILL.md")),"beacon-refresh":_(M($,".claude","skills","beacon-refresh","SKILL.md"))},codexSkills:{"beacon-init":_(M($,".agents","skills","beacon-init","SKILL.md")),"beacon-refresh":_(M($,".agents","skills","beacon-refresh","SKILL.md"))}}}function e9($){let Q=[];for(let j of["beacon-init","beacon-refresh","beacon-db-design"]){let B=M($,".claude","skills",j);if(_(B))F0(B,{recursive:!0,force:!0}),Q.push(j)}for(let j of["beacon-init","beacon-refresh"]){let B=M($,".agents","skills",j);if(_(B))F0(B,{recursive:!0,force:!0}),Q.push(`codex:${j}`)}let Z=!1,Y=M($,".mcp.json");try{let j=JSON.parse(S(Y,"utf8"));if(j.mcpServers?.beacon){if(delete j.mcpServers.beacon,Z=!0,j.mcpServers&&Object.keys(j.mcpServers).length===0)delete j.mcpServers;if(Object.keys(j).length===0)F0(Y,{force:!0});else T(Y,JSON.stringify(j,null,2)+`
14
+ `)}}catch{}let V=!1,H=new RegExp(`\\n?${v0}[\\s\\S]*?${Q5}\\n?`);for(let j of[M($,"AGENTS.md"),M($,"CLAUDE.md")])try{let B=S(j,"utf8");if(H.test(B)){let m=B.replace(H,`
15
15
  `).replace(/\n{3,}/g,`
16
16
 
17
17
  `).trimStart();T(j,m.endsWith(`
18
18
  `)?m:`${m}
19
- `),V=!0}}catch{}let G=!1,W=M($,"CLAUDE.md");try{let j=S(W,"utf8"),B=j.replace(/^[ \t]*@AGENTS\.md[ \t]*\n?/m,"");if(B!==j){if(!B.trim())v0(W,{force:!0});else T(W,B);G=!0}}catch{}return{skillsRemoved:Q,mcpUnregistered:Z,agentsBlockRemoved:V,claudeImportRemoved:G}}var e0=`---
19
+ `),V=!0}}catch{}let G=!1,W=M($,"CLAUDE.md");try{let j=S(W,"utf8"),B=j.replace(/^[ \t]*@AGENTS\.md[ \t]*\n?/m,"");if(B!==j){if(!B.trim())F0(W,{force:!0});else T(W,B);G=!0}}catch{}return{skillsRemoved:Q,mcpUnregistered:Z,agentsBlockRemoved:V,claudeImportRemoved:G}}var e0=`---
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
- `,z5=`---
113
+ `,g5=`---
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
  ---
@@ -159,7 +159,7 @@ If it returns feedback, revise and call it again.
159
159
  If \`beacon_present_plan\` isn't available, the panel isn't wired here \u2014 fall back to ExitPlanMode
160
160
  with the same \`\`\`beacon block (Claude Code only; Codex has no ExitPlanMode), or tell the user to
161
161
  run \`beacon\` in this repo once.
162
- `,b5=`---
162
+ `,h5=`---
163
163
  name: beacon-explain
164
164
  description: Teach the user part of THIS codebase as an interactive visual lesson on Beacon's /learn page \u2014 a concept map + plain-English narrative they can question \u2014 instead of a wall of text. Use when the user says "explain", "teach me", "walk me through", "how does X work", or "help me understand the Y category".
165
165
  ---
@@ -229,7 +229,7 @@ so the learner sees the table IN CONTEXT, wired to the code that uses it.
229
229
  Every answer must ADD understanding (rationale, trade-off) \u2014 never just restate the question. Expand
230
230
  the narrative or add nodes where it helps. Keep looping until the tool reports the user saved or closed
231
231
  the lesson.
232
- `,i9,F0="<!-- beacon:workflow:start -->",Q5="<!-- beacon:workflow:end -->",h5;var Y5=i(()=>{t0();i9=[{name:"beacon-init",body:()=>e0},{name:"beacon-refresh",body:()=>$5}];h5=`${F0}
232
+ `,n9,v0="<!-- beacon:workflow:start -->",Q5="<!-- beacon:workflow:end -->",u5;var Y5=i(()=>{t0();n9=[{name:"beacon-init",body:()=>e0},{name:"beacon-refresh",body:()=>$5}];u5=`${v0}
233
233
  ## Beacon \u2014 feature workflow
234
234
 
235
235
  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:
@@ -301,18 +301,18 @@ Register them all in that single batched call. If a plan added five features, th
301
301
  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.
302
302
 
303
303
  Pull raw planning data anytime with \`beacon_entities\` (features / architecture / tables / endpoints).
304
- ${Q5}`});import{existsSync as D0,mkdirSync as V5,readdirSync as Q$,readFileSync as a,rmSync as Z$,writeFileSync as O0}from"fs";import{dirname as p5,join as f}from"path";function c5(){return!!process.env.CLAUDE_PLUGIN_ROOT}function l5($=process.env.HOME||process.env.USERPROFILE||""){if(!$)return null;let Q=f($,".claude","plugins");if(!D0(Q))return null;let Z=[Q];for(let Y=0;Y<3&&Z.length;Y++){let V=[];for(let H of Z){let G=f(H,".claude-plugin","plugin.json");try{if(D0(G)&&JSON.parse(a(G,"utf8")).name==="beacon")return H}catch{}try{for(let W of Q$(H,{withFileTypes:!0}))if(W.isDirectory())V.push(f(H,W.name))}catch{}}Z=V}return null}function d5($){return l5($)!==null}function J$($){return/[\\/]\.claude[\\/]plugins[\\/]/.test($)}function Y$($=process.env.HOME||process.env.USERPROFILE||""){if(!$)return null;try{let Q=JSON.parse(a(f($,".claude","plugins","installed_plugins.json"),"utf8"));for(let Z of Object.keys(Q.plugins??{}))if(/^beacon@/.test(Z))return{key:Z,marketplace:Z.split("@")[1]??""}}catch{}return null}function X5($){try{return JSON.parse(a($,"utf8"))}catch{return{}}}function o5($,Q){V5(p5($),{recursive:!0}),O0($,JSON.stringify(Q,null,2)+`
305
- `)}function A0($,Q){let Z=X5($);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}]}),o5($,Z),!0}function E0($,Q){return(X5($).hooks?.[Q.event]??[]).some((V)=>V.hooks?.some((H)=>H.command===Q.command))}function T0($,Q){let Z=X5($),Y=Z.hooks?.[Q.event];if(!Y)return!1;let V=!1,H=Y.map((G)=>{let W=G.hooks?.length??0,j=(G.hooks??[]).filter((B)=>B.command!==Q.command);if(j.length!==W)V=!0;return{...G,hooks:j}}).filter((G)=>(G.hooks??[]).length>0);if(!V)return!1;if(H.length)Z.hooks[Q.event]=H;else delete Z.hooks[Q.event];if(Z.hooks&&Object.keys(Z.hooks).length===0)delete Z.hooks;return o5($,Z),!0}function I0($,Q,Z,Y){let V=`${Q}
304
+ ${Q5}`});import{existsSync as D0,mkdirSync as V5,readdirSync as $$,readFileSync as a,rmSync as Q$,writeFileSync as O0}from"fs";import{dirname as b5,join as f}from"path";function m5(){return!!process.env.CLAUDE_PLUGIN_ROOT}function p5($=process.env.HOME||process.env.USERPROFILE||""){if(!$)return null;let Q=f($,".claude","plugins");if(!D0(Q))return null;let Z=[Q];for(let Y=0;Y<3&&Z.length;Y++){let V=[];for(let H of Z){let G=f(H,".claude-plugin","plugin.json");try{if(D0(G)&&JSON.parse(a(G,"utf8")).name==="beacon")return H}catch{}try{for(let W of $$(H,{withFileTypes:!0}))if(W.isDirectory())V.push(f(H,W.name))}catch{}}Z=V}return null}function c5($){return p5($)!==null}function Z$($){return/[\\/]\.claude[\\/]plugins[\\/]/.test($)}function J$($=process.env.HOME||process.env.USERPROFILE||""){if(!$)return null;try{let Q=JSON.parse(a(f($,".claude","plugins","installed_plugins.json"),"utf8"));for(let Z of Object.keys(Q.plugins??{}))if(/^beacon@/.test(Z))return{key:Z,marketplace:Z.split("@")[1]??""}}catch{}return null}function X5($){try{return JSON.parse(a($,"utf8"))}catch{return{}}}function l5($,Q){V5(b5($),{recursive:!0}),O0($,JSON.stringify(Q,null,2)+`
305
+ `)}function A0($,Q){let Z=X5($);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}]}),l5($,Z),!0}function E0($,Q){return(X5($).hooks?.[Q.event]??[]).some((V)=>V.hooks?.some((H)=>H.command===Q.command))}function T0($,Q){let Z=X5($),Y=Z.hooks?.[Q.event];if(!Y)return!1;let V=!1,H=Y.map((G)=>{let W=G.hooks?.length??0,j=(G.hooks??[]).filter((B)=>B.command!==Q.command);if(j.length!==W)V=!0;return{...G,hooks:j}}).filter((G)=>(G.hooks??[]).length>0);if(!V)return!1;if(H.length)Z.hooks[Q.event]=H;else delete Z.hooks[Q.event];if(Z.hooks&&Object.keys(Z.hooks).length===0)delete Z.hooks;return l5($,Z),!0}function I0($,Q,Z,Y){let V=`${Q}
306
306
  ${Y.trim()}
307
307
  ${Z}`,H="";try{H=a($,"utf8")}catch{}let G=new RegExp(`${Q}[\\s\\S]*?${Z}`);H=G.test(H)?H.replace(G,V):H.trim()?`${H.trim()}
308
308
 
309
309
  ${V}
310
310
  `:`${V}
311
- `,V5(p5($),{recursive:!0}),O0($,H.endsWith(`
311
+ `,V5(b5($),{recursive:!0}),O0($,H.endsWith(`
312
312
  `)?H:`${H}
313
313
  `)}function Z0($,Q){try{return a($,"utf8").includes(Q)}catch{return!1}}function k0($,Q,Z){let Y="";try{Y=a($,"utf8")}catch{return!1}let V=new RegExp(`${Q}[\\s\\S]*?${Z}\\n?`);if(!V.test(Y))return!1;let H=Y.replace(V,"").replace(/\n{3,}/g,`
314
314
 
315
- `).trimStart();return O0($,H),!0}function _0($,Q,Z){let Y=f($,Q);V5(Y,{recursive:!0});let V=f(Y,"SKILL.md");return O0(V,Z),V}function J0($,Q){return D0(f($,Q,"SKILL.md"))}function L0($,Q){let Z=f($,Q);if(!D0(Z))return!1;return Z$(Z,{recursive:!0,force:!0}),!0}var u,R0=`## Beacon (visual planning panel)
315
+ `).trimStart();return O0($,H),!0}function _0($,Q,Z){let Y=f($,Q);V5(Y,{recursive:!0});let V=f(Y,"SKILL.md");return O0(V,Z),V}function J0($,Q){return D0(f($,Q,"SKILL.md"))}function L0($,Q){let Z=f($,Q);if(!D0(Z))return!1;return Q$(Z,{recursive:!0,force:!0}),!0}var u,R0=`## Beacon (visual planning panel)
316
316
 
317
317
  This machine has Beacon installed \u2014 a local visual planning surface for the terminal-side
318
318
  agent. Beacon proposes feature plans (roadmap features + DB schema + endpoints) via MCP,
@@ -336,41 +336,41 @@ the user reviews on a canvas at /plan, and feedback flows back as the next round
336
336
  Feedback bundles inline annotations on the markdown PLUS any edits the user made directly
337
337
  on the /map and /db boards (added features, attached subtasks, edited columns, new
338
338
  endpoints). Treat board edits as the user's revision intent \u2014 re-propose matching them
339
- verbatim. Do NOT implement until the tool returns approval.`;var H5=i(()=>{u=["beacon-init","beacon-refresh","beacon-plan","beacon-explain"]});import{mkdirSync as V$,renameSync as X$,rmSync as H$,writeFileSync as G$}from"fs";import{dirname as j$}from"path";function y0($,Q){V$(j$($),{recursive:!0});let Z=`${$}.tmp`;try{G$(Z,Q),X$(Z,$)}catch(Y){throw H$(Z,{force:!0}),Y}}function QZ($,Q,Z=!1){y0($,JSON.stringify(Q,null,Z?2:void 0))}var s5=()=>{};var Q9={};$0(Q9,{setupCodexAssets:()=>K$,removeCodexMcp:()=>$9,removeCodexArtifacts:()=>N$,hasCodexMcp:()=>W5,ensureCodexMcp:()=>e5,codexMcpProblem:()=>B$,codexDetected:()=>a5,auditCodex:()=>M$,CODEX_HOOKS:()=>g0});import{readFileSync as u0}from"fs";import{homedir as U$}from"os";import{join as X0}from"path";function n5(){return process.env.HOME||process.env.USERPROFILE||U$()}function a5(){if(process.env.BEACON_CODEX==="1")return!0;if(process.env.BEACON_CODEX==="0")return!1;if(G5===void 0)G5=Bun.which("codex")!==null;return G5}function V0($){try{return Bun.TOML.parse($)}catch{return null}}function W5(){try{return Boolean(V0(u0(r(),"utf8"))?.mcp_servers?.beacon)}catch{return!1}}function B$(){let $="";try{$=u0(r(),"utf8")}catch{return null}let Q=V0($);if(!Q)return`~/.codex/config.toml does not parse \u2014 ${Y0}`;if(Q.mcp_servers?.beacon)return null;if(/^\s*mcp_servers\s*=/m.test($))return`mcp_servers is an inline table \u2014 ${Y0}`;return null}function e5(){let $="",Q=!1;try{$=u0(r(),"utf8"),Q=!0}catch{}if(Q){let H=V0($);if(!H)return{added:!1,error:`~/.codex/config.toml does not parse \u2014 ${Y0}`};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 ${Y0}`}}let Z=!$?"":$.endsWith(`
339
+ verbatim. Do NOT implement until the tool returns approval.`;var H5=i(()=>{u=["beacon-init","beacon-refresh","beacon-plan","beacon-explain"]});import{mkdirSync as Y$,renameSync as V$,rmSync as X$,writeFileSync as H$}from"fs";import{dirname as G$}from"path";function y0($,Q){Y$(G$($),{recursive:!0});let Z=`${$}.tmp`;try{H$(Z,Q),V$(Z,$)}catch(Y){throw X$(Z,{force:!0}),Y}}function QZ($,Q,Z=!1){y0($,JSON.stringify(Q,null,Z?2:void 0))}var d5=()=>{};var e5={};$0(e5,{setupCodexAssets:()=>B$,removeCodexMcp:()=>t5,removeCodexArtifacts:()=>M$,hasCodexMcp:()=>W5,ensureCodexMcp:()=>r5,codexMcpProblem:()=>W$,codexDetected:()=>n5,auditCodex:()=>K$,CODEX_HOOKS:()=>g0});import{readFileSync as u0}from"fs";import{homedir as j$}from"os";import{join as X0}from"path";function o5(){return process.env.HOME||process.env.USERPROFILE||j$()}function n5(){if(process.env.BEACON_CODEX==="1")return!0;if(process.env.BEACON_CODEX==="0")return!1;if(G5===void 0)G5=Bun.which("codex")!==null;return G5}function V0($){try{return Bun.TOML.parse($)}catch{return null}}function W5(){try{return Boolean(V0(u0(r(),"utf8"))?.mcp_servers?.beacon)}catch{return!1}}function W$(){let $="";try{$=u0(r(),"utf8")}catch{return null}let Q=V0($);if(!Q)return`~/.codex/config.toml does not parse \u2014 ${Y0}`;if(Q.mcp_servers?.beacon)return null;if(/^\s*mcp_servers\s*=/m.test($))return`mcp_servers is an inline table \u2014 ${Y0}`;return null}function r5(){let $="",Q=!1;try{$=u0(r(),"utf8"),Q=!0}catch{}if(Q){let H=V0($);if(!H)return{added:!1,error:`~/.codex/config.toml does not parse \u2014 ${Y0}`};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 ${Y0}`}}let Z=!$?"":$.endsWith(`
340
340
  `)?`
341
341
  `:`
342
342
 
343
- `,Y=$+Z+W$;if(V0(Y)?.mcp_servers?.beacon?.command!=="beacon")return{added:!1,error:`could not safely append [mcp_servers.beacon] \u2014 ${Y0}`};return y0(r(),Y),{added:!0}}function $9(){let $="";try{$=u0(r(),"utf8")}catch{return{removed:!1}}let Q=$.split(`
344
- `),Z=Q.indexOf(r5);if(Z===-1)return{removed:!1,skipped:W5()};let Y=Q.indexOf(t5,Z);if(Y===-1)return{removed:!1,skipped:!0};Q.splice(Z,Y-Z+1);let V=Q.join(`
343
+ `,Y=$+Z+U$;if(V0(Y)?.mcp_servers?.beacon?.command!=="beacon")return{added:!1,error:`could not safely append [mcp_servers.beacon] \u2014 ${Y0}`};return y0(r(),Y),{added:!0}}function t5(){let $="";try{$=u0(r(),"utf8")}catch{return{removed:!1}}let Q=$.split(`
344
+ `),Z=Q.indexOf(i5);if(Z===-1)return{removed:!1,skipped:W5()};let Y=Q.indexOf(a5,Z);if(Y===-1)return{removed:!1,skipped:!0};Q.splice(Z,Y-Z+1);let V=Q.join(`
345
345
  `).replace(/\n{3,}/g,`
346
346
 
347
- `).replace(/^\n+/,"");if(V0(V)===null)return{removed:!1,skipped:!0};return y0(r(),V),{removed:!0}}async function K$(){let{INIT_SKILL:$,REFRESH_SKILL:Q,PLAN_SKILL:Z,EXPLAIN_SKILL:Y}=await Promise.resolve().then(() => (Y5(),J5)),V={"beacon-init":$,"beacon-refresh":Q,"beacon-plan":Z,"beacon-explain":Y},H=[];for(let B of u){if(!J0(S0(),B))H.push(B);_0(S0(),B,V[B])}let G=0;for(let B of g0)if(A0(U5(),{event:B.event,matcher:B.matcher,command:B.command}))G++;let W=Z0(x0(),f0);I0(x0(),f0,i5,R0);let j=e5();return{skillsAdded:H,hooksAdded:G,agentsMdBlockTouched:!W,mcp:j}}function M$(){let $={};for(let Z of u)$[Z]=J0(S0(),Z);let Q={};for(let Z of g0)Q[Z.event]=E0(U5(),{event:Z.event,command:Z.command});return{detected:a5(),skills:$,hooks:Q,agentsMdBlock:Z0(x0(),f0),mcp:W5()}}function N$(){let $=[];for(let V of u)if(L0(S0(),V))$.push(V);let Q=0;for(let V of g0)if(T0(U5(),{event:V.event,command:V.command}))Q++;let Z=k0(x0(),f0,i5),Y=$9();return{skillsRemoved:$,hooksRemoved:Q,agentsMdBlockRemoved:Z,mcpRemoved:Y.removed,mcpSkipped:Y.skipped}}var j5=()=>X0(n5(),".codex"),U5=()=>X0(j5(),"hooks.json"),r=()=>X0(j5(),"config.toml"),x0=()=>X0(j5(),"AGENTS.md"),S0=()=>X0(n5(),".agents","skills"),f0="<!-- beacon:global:start -->",i5="<!-- beacon:global:end -->",g0,G5,r5="# beacon:start (managed by Beacon \u2014 `beacon uninstall` removes this block)",t5="# beacon:end",W$,Y0="add it manually: codex mcp add beacon -- beacon mcp";var Z9=i(()=>{H5();s5();g0=[{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."}];W$=`${r5}
347
+ `).replace(/^\n+/,"");if(V0(V)===null)return{removed:!1,skipped:!0};return y0(r(),V),{removed:!0}}async function B$(){let{INIT_SKILL:$,REFRESH_SKILL:Q,PLAN_SKILL:Z,EXPLAIN_SKILL:Y}=await Promise.resolve().then(() => (Y5(),J5)),V={"beacon-init":$,"beacon-refresh":Q,"beacon-plan":Z,"beacon-explain":Y},H=[];for(let B of u){if(!J0(S0(),B))H.push(B);_0(S0(),B,V[B])}let G=0;for(let B of g0)if(A0(U5(),{event:B.event,matcher:B.matcher,command:B.command}))G++;let W=Z0(x0(),f0);I0(x0(),f0,s5,R0);let j=r5();return{skillsAdded:H,hooksAdded:G,agentsMdBlockTouched:!W,mcp:j}}function K$(){let $={};for(let Z of u)$[Z]=J0(S0(),Z);let Q={};for(let Z of g0)Q[Z.event]=E0(U5(),{event:Z.event,command:Z.command});return{detected:n5(),skills:$,hooks:Q,agentsMdBlock:Z0(x0(),f0),mcp:W5()}}function M$(){let $=[];for(let V of u)if(L0(S0(),V))$.push(V);let Q=0;for(let V of g0)if(T0(U5(),{event:V.event,command:V.command}))Q++;let Z=k0(x0(),f0,s5),Y=t5();return{skillsRemoved:$,hooksRemoved:Q,agentsMdBlockRemoved:Z,mcpRemoved:Y.removed,mcpSkipped:Y.skipped}}var j5=()=>X0(o5(),".codex"),U5=()=>X0(j5(),"hooks.json"),r=()=>X0(j5(),"config.toml"),x0=()=>X0(j5(),"AGENTS.md"),S0=()=>X0(o5(),".agents","skills"),f0="<!-- beacon:global:start -->",s5="<!-- beacon:global:end -->",g0,G5,i5="# beacon:start (managed by Beacon \u2014 `beacon uninstall` removes this block)",a5="# beacon:end",U$,Y0="add it manually: codex mcp add beacon -- beacon mcp";var $9=i(()=>{H5();d5();g0=[{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."}];U$=`${i5}
348
348
  [mcp_servers.beacon]
349
349
  command = "beacon"
350
350
  args = ["mcp"]
351
- ${t5}
352
- `});var G9={};$0(G9,{provisionDb:()=>b$});import{createClient as k$}from"@libsql/client";import{drizzle as _$}from"drizzle-orm/libsql";import{migrate as L$}from"drizzle-orm/libsql/migrator";import{readMigrationFiles as y$}from"drizzle-orm/migrator";import{dirname as P5,join as x$}from"path";import{fileURLToPath as S$}from"url";async function b0($,Q){return(await $.execute({sql:"SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?",args:[Q]})).rows.length>0}async function h$($,Q){let Z=await $.execute(`PRAGMA table_info("${Q}")`);return new Set(Z.rows.map((Y)=>String(Y.name)))}async function H9($){if(!await b0($,"__drizzle_migrations"))return 0;let Q=await $.execute('SELECT count(*) AS n FROM "__drizzle_migrations"');return Number(Q.rows[0]?.n??0)}async function z$($){for(let[Q,Z]of Object.entries(g$)){if(!await b0($,Q))continue;let Y=await h$($,Q);for(let V of Z){if(!Y.has(V))continue;await $.execute(`UPDATE "${Q}" SET "${V}" = CAST((julianday("${V}") - 2440587.5) * 86400000 AS INTEGER) WHERE typeof("${V}") = 'text'`)}}}async function b$($,Q=u$){let Z=k$({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 b0(Z,"__drizzle_migrations"),V=await b0(Z,"Node"),H=!1;if(V&&!Y){let W=y$({migrationsFolder:Q})[0];if(W)await Z.execute('CREATE TABLE IF NOT EXISTS "__drizzle_migrations" (id SERIAL PRIMARY KEY, hash text NOT NULL, created_at numeric)'),await Z.execute({sql:'INSERT INTO "__drizzle_migrations" ("hash", "created_at") VALUES (?, ?)',args:[W.hash,W.folderMillis]}),H=!0}let G=await H9(Z);if(await L$(_$(Z),{migrationsFolder:Q}),await H9(Z)>G)H=!0;return await z$(Z),{migrated:H}}finally{Z.close()}}var f$,u$,g$;var j9=i(async()=>{f$=P5(P5(P5(S$(import.meta.url)))),u$=process.env.BEACON_MIGRATIONS_DIR||x$(f$,"drizzle"),g$={Node:["createdAt","updatedAt"],Note:["createdAt","updatedAt"],DbTable:["createdAt","updatedAt"],Endpoint:["createdAt","updatedAt"],DraftTable:["createdAt"],SyncState:["codeGraphSyncedAt","updatedAt"],AppSetting:["updatedAt"],ProjectMeta:["updatedAt"],CodeFile:["updatedAt"]}});H5();import{existsSync as q$}from"fs";import{homedir as P$}from"os";import{join as h0}from"path";function C$(){return process.env.HOME||process.env.USERPROFILE||P$()}var z0=()=>h0(C$(),".claude"),B5=()=>h0(z0(),"skills"),K5=()=>h0(z0(),"settings.json"),M5=()=>h0(z0(),"CLAUDE.md"),N5="<!-- beacon:global:start -->",J9="<!-- beacon:global:end -->";var w$=R0,q5=[{event:"PreToolUse",matcher:"Edit|Write|MultiEdit",command:"beacon guard",description:"Gate edits against the active plan's scope contract: in-scope \u2192 allow, off-scope \u2192 ask the user to authorize. Fail-open when there's no active contract."},{event:"PostToolUse",matcher:"Edit|Write|MultiEdit",command:"beacon hook",description:"Report file edits to Beacon's active feature so the map stays fresh."},{event:"PermissionRequest",matcher:"ExitPlanMode",command:"beacon plan",description:"Pipe the agent's plan markdown into Beacon's /plan canvas for review."},{event:"PreToolUse",matcher:"AskUserQuestion",command:"beacon ask",description:"Surface the agent's AskUserQuestion in Beacon's modal; your pick flows back as the answer (falls through to the terminal if Beacon isn't open)."},{event:"PermissionRequest",matcher:"Edit|Write|MultiEdit|Bash|NotebookEdit",command:"beacon ask",description:"Surface edit/create/run approvals in Beacon's modal; your allow/deny flows back (falls through to the terminal prompt if Beacon isn't open)."},{event:"UserPromptSubmit",matcher:"*",command:"beacon prompt",description:"On feature-y prompts in a Beacon-wired repo, remind the agent to run the context\u2192propose\u2192describe loop (no-op otherwise)."},{event:"Stop",matcher:"*",command:"beacon stop-hook",description:"When the agent ends a turn asking for plan approval in prose (instead of presenting it), nudge it to present the plan on Beacon's /plan canvas. Bounded by stop_hook_active \u2014 at most one nudge."}];function v$($,Q){return _0(B5(),$,Q)}function Y9($){return J0(B5(),$)}function F$($){return L0(B5(),$)}function D$($){return A0(K5(),$)}function O$($){return E0(K5(),$)}function R$($){return T0(K5(),$)}function A$($){I0(M5(),N5,J9,$)}function V9(){return Z0(M5(),N5)}function E$(){return k0(M5(),N5,J9)}function BZ(){let $={};for(let Z of u)$[Z]=Y9(Z);let Q={};for(let Z of q5)Q[Z.event]=O$({event:Z.event,command:Z.command});return{homeExists:q$(z0()),skills:$,hooks:Q,claudeMdBlock:V9()}}async function T$(){let{INIT_SKILL:$,REFRESH_SKILL:Q,PLAN_SKILL:Z,EXPLAIN_SKILL:Y}=await Promise.resolve().then(() => (Y5(),J5)),V={"beacon-init":$,"beacon-refresh":Q,"beacon-plan":Z,"beacon-explain":Y},H=[];for(let j of u){if(!Y9(j))H.push(j);v$(j,V[j])}let G=0;for(let j of q5)if(D$({event:j.event,matcher:j.matcher,command:j.command}))G++;let W=V9();return A$(w$),{skillsAdded:H,hooksAdded:G,claudeMdBlockTouched:!W}}async function X9(){if(c5())return{ok:!0,skipped:"plugin",skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1};let $;if(d5()){try{I$()}catch{}$={ok:!0,skipped:"plugin-present",skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1}}else try{$={ok:!0,...await T$()}}catch(Q){$={ok:!1,error:Q instanceof Error?Q.message:String(Q),skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1}}try{let Q=await Promise.resolve().then(() => (Z9(),Q9));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 I$(){let $=[];for(let Y of u)if(F$(Y))$.push(Y);let Q=0;for(let Y of q5)if(R$(Y))Q++;let Z=E$();return{skillsRemoved:$,hooksRemoved:Q,claudeMdBlockRemoved:Z}}import{AsyncLocalStorage as m$}from"async_hooks";import{spawnSync as p$}from"child_process";import{createHash as c$}from"crypto";import{existsSync as W9,mkdirSync as H0,readFileSync as w5,writeFileSync as v5}from"fs";import{homedir as B9}from"os";import{basename as l$,join as g,parse as d$,resolve as U9}from"path";function L(){return process.env.BEACON_HOME||g(B9(),".beacon")}function F5(){return g(L(),"workspaces.json")}function p($){return c$("sha256").update($).digest("hex").slice(0,12)}function D5($=process.cwd()){let Q=p$("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 m0($){let Q=U9($);return Q!==U9(B9())&&Q!==d$(Q).root}function K9(){return g(L(),"deleted.json")}function O5(){try{let $=JSON.parse(w5(K9(),"utf8"));return Array.isArray($)?$:[]}catch{return[]}}function M9($){H0(L(),{recursive:!0}),v5(K9(),JSON.stringify($,null,2))}function p0($){return O5().includes($)}function EZ($){let Q=O5();if(!Q.includes($))M9([...Q,$])}function o$($){let Q=O5();if(Q.includes($))M9(Q.filter((Z)=>Z!==$))}function c0($){return g(L(),$)}function R5($){return`file:${g(c0($),"db.sqlite")}`}function G0(){try{let $=JSON.parse(w5(F5(),"utf8"));return Array.isArray($)?$:[]}catch{return[]}}function A5($){H0(L(),{recursive:!0}),v5(F5(),JSON.stringify($,null,2))}function l0(){return G0().sort(($,Q)=>Q.lastOpenedAt.localeCompare($.lastOpenedAt))}function c($){return G0().find((Q)=>Q.id===$)??null}function d0($,Q,Z=new Date().toISOString()){if(!m0($))throw Error(`beacon: refusing to register a non-repo path as a workspace: ${$}`);let Y=p($);if(p0(Y))throw Error(`beacon: workspace ${Y} (${$}) was deleted \u2014 run \`beacon\` or /beacon-init to re-add it`);let V=G0(),H=V.find((j)=>j.id===Y),G={id:Y,path:$,name:Q||H?.name||l$($),lastOpenedAt:Z},W=[G,...V.filter((j)=>j.id!==Y)];return H0(c0(Y),{recursive:!0}),A5(W),G}function TZ($,Q){return o$(p($)),d0($,Q)}function IZ($,Q=new Date().toISOString()){let Z=G0(),Y=Z.find((V)=>V.id===$);if(!Y)return;Y.lastOpenedAt=Q,A5(Z)}function kZ($){if(A5(G0().filter((Q)=>Q.id!==$)),j0()===$)s$(l0()[0]?.id??null)}function N9(){return g(L(),"active")}function j0(){try{return w5(N9(),"utf8").trim()||null}catch{return null}}function s$($){H0(L(),{recursive:!0}),v5(N9(),$??"")}function _Z(){let $=j0();return $?c($):null}function LZ(){let $=E5()??j0();return $?c($):null}function yZ($){return c($)?.path??null}function xZ(){return W9(F5())}var q9="beacon_ws";function P9($,Q){let Z=$.headers.get("cookie");if(!Z)return null;for(let Y of Z.split(";")){let V=Y.indexOf("=");if(V===-1)continue;if(Y.slice(0,V).trim()===Q)return decodeURIComponent(Y.slice(V+1).trim())}return null}function SZ($){let Q=$.headers.get("x-beacon-workspace");if(Q&&c(Q))return Q;let Z=P9($,q9);if(Z&&c(Z))return Z;return n$()}function n$(){let $=l0();return $.length===1?$[0].id:null}var o0="x-beacon-workspace-path";function fZ($=process.cwd()){let Q=D5($);return{"x-beacon-workspace":p(Q),[o0]:Q}}async function uZ($){let Q=$.headers.get("x-beacon-workspace");if(Q&&c(Q))return Q;let Z=$.headers.get(o0);if(Z&&m0(Z)&&!p0(p(Z))&&(!Q||p(Z)===Q)){let V=d0(Z);return await T5(V.id),V.id}let Y=P9($,q9);if(Y&&c(Y))return Y;return null}var C9=new m$;function i$($,Q){return $?C9.run($,Q):Q()}function E5(){return C9.getStore()??null}var C5=new Set;function gZ($){C5.delete(g(c0($),"db.sqlite"))}async function T5($){let Q=c0($),Z=g(Q,"db.sqlite"),Y=W9(Z);if(Y&&C5.has(Z))return{ok:!0,created:!1,migrated:!1};try{H0(Q,{recursive:!0});let{provisionDb:V}=await j9().then(() => G9),H=await V(R5($));return C5.add(Z),{ok:!0,created:!Y,migrated:Y&&H.migrated}}catch(V){return{ok:!1,created:!1,migrated:!1,error:V instanceof Error?V.message:String(V)}}}import{connect as a$}from"net";var w9=4319;function r$($,Q,Z=400){return new Promise((Y)=>{let V=a$({host:$,port:Q}),H=!1,G=(W)=>{if(H)return;H=!0,V.destroy(),Y(W)};V.once("connect",()=>G(!0)),V.once("error",()=>G(!1)),V.setTimeout(Z,()=>G(!1))})}async function t$($){for(let Q of["127.0.0.1","::1"])if(await r$(Q,$))return!1;return!0}async function bZ($,Q=20){for(let Z=$;Z<$+Q;Z++)if(await t$(Z))return Z;return $}import{McpServer as pQ,ResourceTemplate as f5}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as cQ}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as J}from"zod";import{z as K}from"zod";var e$=new Set(["GET","HEAD","OPTIONS"]);function v9($){return e$.has($.trim().toUpperCase())?"read":"write"}var $Q=K.preprocess(($)=>{if(typeof $==="string"){let[Q,...Z]=$.trim().split(/\s+/);return{name:Q,type:Z.join(" ")||"text"}}return $},K.object({name:K.string().trim().min(1),type:K.string().trim().min(1),isPk:K.boolean().optional(),isFk:K.boolean().optional(),nullable:K.boolean().optional(),note:K.string().nullish()})),F9=K.object({name:K.string().trim().min(1),domain:K.string().nullish(),description:K.string().nullish(),columns:K.array($Q).default([])}),D9=K.object({fromTable:K.string(),fromColumn:K.string(),toTable:K.string(),toColumn:K.string(),label:K.string().nullish()}),O9=K.object({method:K.string().trim().min(1),path:K.string().trim().min(1),domain:K.string().nullish(),description:K.string().nullish(),uses:K.array(K.object({table:K.string().trim().min(1),access:K.string().optional()})).default([])}).transform(($)=>({...$,uses:$.uses.map((Q)=>({...Q,access:Q.access??v9($.method)}))})),dZ=K.object({tables:K.array(F9).default([]),relations:K.array(D9).default([]),endpoints:K.array(O9).default([])});import{z as R}from"zod";import{and as M1,eq as N1,inArray as q1}from"drizzle-orm";import{drizzle as EQ}from"drizzle-orm/libsql";import{createClient as TQ}from"@libsql/client";var I5={};$0(I5,{workspaceFlag:()=>GQ,tag:()=>t,syncState:()=>VQ,projectMeta:()=>HQ,planContract:()=>jQ,note:()=>JQ,nodeTags:()=>l,nodeFile:()=>U0,node:()=>q,endpointTable:()=>o,endpoint:()=>e,edge:()=>h,draftTable:()=>I,draftRelation:()=>s,draftColumn:()=>K0,dbTable:()=>D,dbRelation:()=>d,dbColumn:()=>B0,codeFileEdge:()=>n,codeFile:()=>y,bugFlag:()=>W0,boardAnnotation:()=>YQ,appSetting:()=>XQ});import{sqliteTable as P,index as N,foreignKey as QQ,text as X,integer as U,real as O,uniqueIndex as k,primaryKey as ZQ}from"drizzle-orm/sqlite-core";import{createId as w}from"@paralleldrive/cuid2";var q=P("Node",{id:X().primaryKey().$defaultFn(()=>w()),view:X().notNull(),kind:X().default("FEATURE").notNull(),cluster:X(),layer:X(),title:X().notNull(),role:X(),plain:X(),status:X().default("PENDING").notNull(),priority:U().default(2).notNull(),progress:U().default(0).notNull(),x:O().default(0).notNull(),y:O().default(0).notNull(),sourceRef:X(),externalId:X(),source:X().default("MANUAL").notNull(),planId:X(),parentId:X(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[N("Node_cluster_idx").on($.cluster),N("Node_parentId_idx").on($.parentId),N("Node_view_idx").on($.view),QQ(()=>({columns:[$.parentId],foreignColumns:[$.id],name:"Node_parentId_Node_id_fk"})).onUpdate("cascade").onDelete("cascade")]),U0=P("NodeFile",{id:X().primaryKey().$defaultFn(()=>w()),nodeId:X().notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),path:X().notNull()},($)=>[k("NodeFile_nodeId_path_key").on($.nodeId,$.path),N("NodeFile_nodeId_idx").on($.nodeId)]),t=P("Tag",{id:X().primaryKey().$defaultFn(()=>w()),label:X().notNull(),color:X()},($)=>[k("Tag_label_key").on($.label)]),h=P("Edge",{id:X().primaryKey().$defaultFn(()=>w()),fromId:X().notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),toId:X().notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),kind:X().default("DEPENDS").notNull(),label:X(),sourceHandle:X(),targetHandle:X()},($)=>[k("Edge_fromId_toId_kind_key").on($.fromId,$.toId,$.kind),N("Edge_toId_idx").on($.toId),N("Edge_fromId_idx").on($.fromId)]),l=P("_NodeTags",{a:X("A").notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),b:X("B").notNull().references(()=>t.id,{onDelete:"cascade",onUpdate:"cascade"})},($)=>[k("_NodeTags_AB_unique").on($.a,$.b),N("_NodeTags_B_index").on($.b)]),JQ=P("Note",{id:X().primaryKey().$defaultFn(()=>w()),title:X().default("Untitled").notNull(),body:X().default("").notNull(),ord:O().default(0).notNull(),pinned:U({mode:"boolean"}).default(!1).notNull(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[N("Note_updatedAt_idx").on($.updatedAt)]),YQ=P("BoardAnnotation",{id:X().primaryKey().$defaultFn(()=>w()),targetKind:X().notNull(),targetId:X().notNull(),columnName:X(),body:X().default("").notNull(),x:O(),y:O(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[N("BoardAnnotation_target_idx").on($.targetId)]),W0=P("BugFlag",{id:X().primaryKey().$defaultFn(()=>w()),nodeId:X().notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),by:X().notNull(),note:X().notNull(),resolvedAt:U({mode:"timestamp_ms"}),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date)},($)=>[N("BugFlag_nodeId_idx").on($.nodeId)]),D=P("DbTable",{id:X().primaryKey().$defaultFn(()=>w()),name:X().notNull(),domain:X(),description:X(),source:X().default("MANUAL").notNull(),planId:X(),x:O().default(0).notNull(),y:O().default(0).notNull(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[N("DbTable_domain_idx").on($.domain),k("DbTable_name_key").on($.name)]),B0=P("DbColumn",{id:X().primaryKey().$defaultFn(()=>w()),tableId:X().notNull().references(()=>D.id,{onDelete:"cascade",onUpdate:"cascade"}),name:X().notNull(),type:X().notNull(),isPk:U({mode:"boolean"}).default(!1).notNull(),isFk:U({mode:"boolean"}).default(!1).notNull(),nullable:U({mode:"boolean"}).default(!0).notNull(),note:X(),ord:U().default(0).notNull()},($)=>[k("DbColumn_tableId_name_key").on($.tableId,$.name),N("DbColumn_tableId_idx").on($.tableId)]),d=P("DbRelation",{id:X().primaryKey().$defaultFn(()=>w()),fromTableId:X().notNull().references(()=>D.id,{onDelete:"cascade",onUpdate:"cascade"}),toTableId:X().notNull().references(()=>D.id,{onDelete:"cascade",onUpdate:"cascade"}),fromColumn:X().notNull(),toColumn:X().notNull(),label:X()},($)=>[N("DbRelation_toTableId_idx").on($.toTableId),N("DbRelation_fromTableId_idx").on($.fromTableId)]),e=P("Endpoint",{id:X().primaryKey().$defaultFn(()=>w()),method:X().notNull(),path:X().notNull(),domain:X(),description:X(),source:X().default("MANUAL").notNull(),planId:X(),x:O().default(0).notNull(),y:O().default(0).notNull(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[k("Endpoint_method_path_key").on($.method,$.path),N("Endpoint_domain_idx").on($.domain)]),o=P("EndpointTable",{id:X().primaryKey().$defaultFn(()=>w()),endpointId:X().notNull().references(()=>e.id,{onDelete:"cascade",onUpdate:"cascade"}),tableId:X().notNull().references(()=>D.id,{onDelete:"cascade",onUpdate:"cascade"}),access:X().default("read").notNull()},($)=>[k("EndpointTable_endpointId_tableId_key").on($.endpointId,$.tableId),N("EndpointTable_tableId_idx").on($.tableId)]),I=P("DraftTable",{id:X().primaryKey().$defaultFn(()=>w()),name:X().notNull(),domain:X(),description:X(),x:O().default(0).notNull(),y:O().default(0).notNull(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date)},($)=>[k("DraftTable_name_key").on($.name)]),K0=P("DraftColumn",{id:X().primaryKey().$defaultFn(()=>w()),tableId:X().notNull().references(()=>I.id,{onDelete:"cascade",onUpdate:"cascade"}),name:X().notNull(),type:X().notNull(),isPk:U({mode:"boolean"}).default(!1).notNull(),isFk:U({mode:"boolean"}).default(!1).notNull(),nullable:U({mode:"boolean"}).default(!0).notNull(),note:X(),ord:U().default(0).notNull()},($)=>[N("DraftColumn_tableId_idx").on($.tableId)]),s=P("DraftRelation",{id:X().primaryKey().$defaultFn(()=>w()),fromTableId:X().notNull().references(()=>I.id,{onDelete:"cascade",onUpdate:"cascade"}),toTableId:X().notNull().references(()=>I.id,{onDelete:"cascade",onUpdate:"cascade"}),fromColumn:X().notNull(),toColumn:X().notNull(),label:X()},($)=>[N("DraftRelation_toTableId_idx").on($.toTableId),N("DraftRelation_fromTableId_idx").on($.fromTableId)]),y=P("CodeFile",{path:X().primaryKey(),root:X(),lang:X(),x:O().default(0).notNull(),y:O().default(0).notNull(),mtimeMs:O(),size:U(),inDegree:U().default(0).notNull(),outDegree:U().default(0).notNull(),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),n=P("CodeFileEdge",{fromPath:X().notNull().references(()=>y.path,{onDelete:"cascade",onUpdate:"cascade"}),toPath:X().notNull().references(()=>y.path,{onDelete:"cascade",onUpdate:"cascade"}),circular:U({mode:"boolean"}).default(!1).notNull()},($)=>[N("CodeFileEdge_circular_idx").on($.circular),N("CodeFileEdge_toPath_idx").on($.toPath),N("CodeFileEdge_fromPath_idx").on($.fromPath),ZQ({columns:[$.fromPath,$.toPath],name:"CodeFileEdge_fromPath_toPath_pk"})]),VQ=P("SyncState",{id:X().primaryKey().default("singleton"),version:U().default(0).notNull(),codeGraphSyncedAt:U({mode:"timestamp_ms"}),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),XQ=P("AppSetting",{id:X().primaryKey().default("singleton"),editor:X().default("auto").notNull(),currentFeatureId:X(),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),HQ=P("ProjectMeta",{id:X().primaryKey().default("singleton"),overview:X(),conventions:X().default("[]").notNull(),hasFrontend:U({mode:"boolean"}),classificationRoots:X().default("[]").notNull(),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),GQ=P("WorkspaceFlag",{id:X().primaryKey().$defaultFn(()=>w()),key:X().notNull(),enabled:U({mode:"boolean"}).default(!1).notNull(),config:X(),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[k("WorkspaceFlag_key_key").on($.key)]),jQ=P("PlanContract",{id:X().primaryKey().$defaultFn(()=>w()),planId:X().notNull(),declaredFiles:X().default("[]").notNull(),authorizedExtras:X().default("[]").notNull(),active:U({mode:"boolean"}).default(!1).notNull(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[k("PlanContract_planId_key").on($.planId),N("PlanContract_active_idx").on($.active)]);var k5={};$0(k5,{tagRelations:()=>KQ,nodeTagsRelations:()=>MQ,nodeRelations:()=>UQ,nodeFileRelations:()=>WQ,endpointTableRelations:()=>vQ,endpointRelations:()=>wQ,edgeRelations:()=>NQ,draftTableRelations:()=>FQ,draftRelationRelations:()=>OQ,draftColumnRelations:()=>DQ,dbTableRelations:()=>qQ,dbRelationRelations:()=>CQ,dbColumnRelations:()=>PQ,codeFileRelations:()=>RQ,codeFileEdgeRelations:()=>AQ,bugFlagRelations:()=>BQ});import{relations as v}from"drizzle-orm";var UQ=v(q,({one:$,many:Q})=>({files:Q(U0),bugFlags:Q(W0),nodeTags:Q(l),edgesOut:Q(h,{relationName:"EdgeFrom"}),edgesIn:Q(h,{relationName:"EdgeTo"}),parent:$(q,{fields:[q.parentId],references:[q.id],relationName:"NodeTree"}),children:Q(q,{relationName:"NodeTree"})})),WQ=v(U0,({one:$})=>({node:$(q,{fields:[U0.nodeId],references:[q.id]})})),BQ=v(W0,({one:$})=>({node:$(q,{fields:[W0.nodeId],references:[q.id]})})),KQ=v(t,({many:$})=>({nodeTags:$(l)})),MQ=v(l,({one:$})=>({node:$(q,{fields:[l.a],references:[q.id]}),tag:$(t,{fields:[l.b],references:[t.id]})})),NQ=v(h,({one:$})=>({from:$(q,{fields:[h.fromId],references:[q.id],relationName:"EdgeFrom"}),to:$(q,{fields:[h.toId],references:[q.id],relationName:"EdgeTo"})})),qQ=v(D,({many:$})=>({columns:$(B0),fksOut:$(d,{relationName:"FkFrom"}),fksIn:$(d,{relationName:"FkTo"}),usages:$(o)})),PQ=v(B0,({one:$})=>({table:$(D,{fields:[B0.tableId],references:[D.id]})})),CQ=v(d,({one:$})=>({fromTable:$(D,{fields:[d.fromTableId],references:[D.id],relationName:"FkFrom"}),toTable:$(D,{fields:[d.toTableId],references:[D.id],relationName:"FkTo"})})),wQ=v(e,({many:$})=>({tables:$(o)})),vQ=v(o,({one:$})=>({endpoint:$(e,{fields:[o.endpointId],references:[e.id]}),table:$(D,{fields:[o.tableId],references:[D.id]})})),FQ=v(I,({many:$})=>({columns:$(K0),fksOut:$(s,{relationName:"DraftFkFrom"}),fksIn:$(s,{relationName:"DraftFkTo"})})),DQ=v(K0,({one:$})=>({table:$(I,{fields:[K0.tableId],references:[I.id]})})),OQ=v(s,({one:$})=>({fromTable:$(I,{fields:[s.fromTableId],references:[I.id],relationName:"DraftFkFrom"}),toTable:$(I,{fields:[s.toTableId],references:[I.id],relationName:"DraftFkTo"})})),RQ=v(y,({many:$})=>({edgesOut:$(n,{relationName:"CFEFrom"}),edgesIn:$(n,{relationName:"CFETo"})})),AQ=v(n,({one:$})=>({fromFile:$(y,{fields:[n.fromPath],references:[y.path],relationName:"CFEFrom"}),toFile:$(y,{fields:[n.toPath],references:[y.path],relationName:"CFETo"})}));var IQ={...I5,...k5};function kQ(){let $=process.env.DATABASE_URL;if($&&/^(file:|libsql:|wss?:|https?:|:memory:)/i.test($))return $;return"file:./dev.db"}var _Q=kQ();function R9($){let Q=TQ({url:$});return Q.execute("PRAGMA foreign_keys = ON;"),Q.execute("PRAGMA busy_timeout = 5000;"),EQ(Q,{schema:IQ})}var L5=globalThis,_5=L5.dzDefault??R9(_Q);L5.dzDefault=_5;var s0=L5.dzByUrl??=new Map;function LQ($){let Q=s0.get($);if(!Q)Q=R9($),s0.set($,Q);return Q}function $1($){let Q=s0.get($);s0.delete($);try{Q?.$client?.close?.()}catch{}}function yQ(){if(process.env.BEACON_REPO)return _5;let $=E5()??j0();if(!$)return _5;return LQ(R5($))}var xQ=new Proxy({},{get($,Q){let Z=yQ(),Y=Z[Q];return typeof Y==="function"?Y.bind(Z):Y}});var SQ=["frontend","backend","fullstack"],fQ={fe:"frontend",front:"frontend",be:"backend",back:"backend",fs:"fullstack","full-stack":"fullstack","full stack":"fullstack"};function n0($){let Q=($??"").trim().toLowerCase();if(!Q)return null;if(SQ.includes(Q))return Q;return fQ[Q]??null}import{forceCenter as V1,forceCollide as X1,forceLink as H1,forceManyBody as G1,forceSimulation as j1}from"d3-force";var A9=R.object({title:R.string().trim().min(1),role:R.string().nullish(),plain:R.string().nullish(),cluster:R.string().nullish(),category:R.string().nullish(),domain:R.string().nullish(),priority:R.number().nullish(),kind:R.string().nullish(),layer:R.string().nullish(),dependsOn:R.array(R.string()).nullish()}).transform(({category:$,domain:Q,priority:Z,kind:Y,layer:V,...H})=>({...H,cluster:H.cluster??$??Q??null,priority:Z==null?null:Math.max(0,Math.min(3,Math.round(Z))),kind:Y?.trim().toUpperCase()==="BUG"?"BUG":"FEATURE",layer:n0(V)})),F1=R.object({features:R.array(A9).default([])});var uQ=/(\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 E9($){return!!$&&uQ.test($)}function T9($,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 gQ($){return $.cluster??$.category??$.domain??null}function I9($,Q){let Z=Q?.requireLayer??!1,Y=$.map((H)=>{let G=[],W=gQ(H);if(!W||!W.trim())G.push("category");if(H.priority==null)G.push("priority");if(Z&&!n0(H.layer))G.push("layer");return G.length?` \u2022 "${H.title?.trim()||"(untitled)"}" \u2014 missing ${G.join(" + ")}`:null}).filter((H)=>H!==null);if(Y.length===0)return null;let V=Z?" This workspace has a frontend surface, so every feature must also carry `layer`: "+'"frontend" | "backend" | "fullstack" \u2014 which side of the stack the work lands on.':"";return"\u26D4 Every roadmap feature needs a category AND a priority \u2014 they drive grouping and ordering "+"on the board, and the user shouldn't have to add them by hand."+V+` Missing:
351
+ ${a5}
352
+ `});var X9={};$0(X9,{provisionDb:()=>z$});import{createClient as I$}from"@libsql/client";import{drizzle as k$}from"drizzle-orm/libsql";import{migrate as _$}from"drizzle-orm/libsql/migrator";import{readMigrationFiles as L$}from"drizzle-orm/migrator";import{dirname as P5,join as y$}from"path";import{fileURLToPath as x$}from"url";async function b0($,Q){return(await $.execute({sql:"SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?",args:[Q]})).rows.length>0}async function g$($,Q){let Z=await $.execute(`PRAGMA table_info("${Q}")`);return new Set(Z.rows.map((Y)=>String(Y.name)))}async function V9($){if(!await b0($,"__drizzle_migrations"))return 0;let Q=await $.execute('SELECT count(*) AS n FROM "__drizzle_migrations"');return Number(Q.rows[0]?.n??0)}async function h$($){for(let[Q,Z]of Object.entries(u$)){if(!await b0($,Q))continue;let Y=await g$($,Q);for(let V of Z){if(!Y.has(V))continue;await $.execute(`UPDATE "${Q}" SET "${V}" = CAST((julianday("${V}") - 2440587.5) * 86400000 AS INTEGER) WHERE typeof("${V}") = 'text'`)}}}async function z$($,Q=f$){let Z=I$({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 b0(Z,"__drizzle_migrations"),V=await b0(Z,"Node"),H=!1;if(V&&!Y){let W=L$({migrationsFolder:Q})[0];if(W)await Z.execute('CREATE TABLE IF NOT EXISTS "__drizzle_migrations" (id SERIAL PRIMARY KEY, hash text NOT NULL, created_at numeric)'),await Z.execute({sql:'INSERT INTO "__drizzle_migrations" ("hash", "created_at") VALUES (?, ?)',args:[W.hash,W.folderMillis]}),H=!0}let G=await V9(Z);if(await _$(k$(Z),{migrationsFolder:Q}),await V9(Z)>G)H=!0;return await h$(Z),{migrated:H}}finally{Z.close()}}var S$,f$,u$;var H9=i(async()=>{S$=P5(P5(P5(x$(import.meta.url)))),f$=process.env.BEACON_MIGRATIONS_DIR||y$(S$,"drizzle"),u$={Node:["createdAt","updatedAt"],Note:["createdAt","updatedAt"],DbTable:["createdAt","updatedAt"],Endpoint:["createdAt","updatedAt"],DraftTable:["createdAt"],SyncState:["codeGraphSyncedAt","updatedAt"],AppSetting:["updatedAt"],ProjectMeta:["updatedAt"],CodeFile:["updatedAt"]}});H5();import{existsSync as N$}from"fs";import{homedir as q$}from"os";import{join as h0}from"path";function P$(){return process.env.HOME||process.env.USERPROFILE||q$()}var z0=()=>h0(P$(),".claude"),B5=()=>h0(z0(),"skills"),K5=()=>h0(z0(),"settings.json"),M5=()=>h0(z0(),"CLAUDE.md"),N5="<!-- beacon:global:start -->",Q9="<!-- beacon:global:end -->";var C$=R0,q5=[{event:"PreToolUse",matcher:"Edit|Write|MultiEdit",command:"beacon guard",description:"Gate edits against the active plan's scope contract: in-scope \u2192 allow, off-scope \u2192 ask the user to authorize. Fail-open when there's no active contract."},{event:"PostToolUse",matcher:"Edit|Write|MultiEdit",command:"beacon hook",description:"Report file edits to Beacon's active feature so the map stays fresh."},{event:"PermissionRequest",matcher:"ExitPlanMode",command:"beacon plan",description:"Pipe the agent's plan markdown into Beacon's /plan canvas for review."},{event:"PreToolUse",matcher:"AskUserQuestion",command:"beacon ask",description:"Surface the agent's AskUserQuestion in Beacon's modal; your pick flows back as the answer (falls through to the terminal if Beacon isn't open)."},{event:"PermissionRequest",matcher:"Edit|Write|MultiEdit|Bash|NotebookEdit",command:"beacon ask",description:"Surface edit/create/run approvals in Beacon's modal; your allow/deny flows back (falls through to the terminal prompt if Beacon isn't open)."},{event:"UserPromptSubmit",matcher:"*",command:"beacon prompt",description:"On feature-y prompts in a Beacon-wired repo, remind the agent to run the context\u2192propose\u2192describe loop (no-op otherwise)."},{event:"Stop",matcher:"*",command:"beacon stop-hook",description:"When the agent ends a turn asking for plan approval in prose (instead of presenting it), nudge it to present the plan on Beacon's /plan canvas. Bounded by stop_hook_active \u2014 at most one nudge."}];function w$($,Q){return _0(B5(),$,Q)}function Z9($){return J0(B5(),$)}function F$($){return L0(B5(),$)}function v$($){return A0(K5(),$)}function D$($){return E0(K5(),$)}function O$($){return T0(K5(),$)}function R$($){I0(M5(),N5,Q9,$)}function J9(){return Z0(M5(),N5)}function A$(){return k0(M5(),N5,Q9)}function BZ(){let $={};for(let Z of u)$[Z]=Z9(Z);let Q={};for(let Z of q5)Q[Z.event]=D$({event:Z.event,command:Z.command});return{homeExists:N$(z0()),skills:$,hooks:Q,claudeMdBlock:J9()}}async function E$(){let{INIT_SKILL:$,REFRESH_SKILL:Q,PLAN_SKILL:Z,EXPLAIN_SKILL:Y}=await Promise.resolve().then(() => (Y5(),J5)),V={"beacon-init":$,"beacon-refresh":Q,"beacon-plan":Z,"beacon-explain":Y},H=[];for(let j of u){if(!Z9(j))H.push(j);w$(j,V[j])}let G=0;for(let j of q5)if(v$({event:j.event,matcher:j.matcher,command:j.command}))G++;let W=J9();return R$(C$),{skillsAdded:H,hooksAdded:G,claudeMdBlockTouched:!W}}async function Y9(){if(m5())return{ok:!0,skipped:"plugin",skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1};let $;if(c5()){try{T$()}catch{}$={ok:!0,skipped:"plugin-present",skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1}}else try{$={ok:!0,...await E$()}}catch(Q){$={ok:!1,error:Q instanceof Error?Q.message:String(Q),skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1}}try{let Q=await Promise.resolve().then(() => ($9(),e5));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 T$(){let $=[];for(let Y of u)if(F$(Y))$.push(Y);let Q=0;for(let Y of q5)if(O$(Y))Q++;let Z=A$();return{skillsRemoved:$,hooksRemoved:Q,claudeMdBlockRemoved:Z}}import{AsyncLocalStorage as b$}from"async_hooks";import{spawnSync as m$}from"child_process";import{createHash as p$}from"crypto";import{existsSync as j9,mkdirSync as H0,readFileSync as w5,writeFileSync as F5}from"fs";import{homedir as U9}from"os";import{basename as c$,join as g,parse as l$,resolve as G9}from"path";function L(){return process.env.BEACON_HOME||g(U9(),".beacon")}function v5(){return g(L(),"workspaces.json")}function p($){return p$("sha256").update($).digest("hex").slice(0,12)}function D5($=process.cwd()){let Q=m$("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 m0($){let Q=G9($);return Q!==G9(U9())&&Q!==l$(Q).root}function W9(){return g(L(),"deleted.json")}function O5(){try{let $=JSON.parse(w5(W9(),"utf8"));return Array.isArray($)?$:[]}catch{return[]}}function B9($){H0(L(),{recursive:!0}),F5(W9(),JSON.stringify($,null,2))}function p0($){return O5().includes($)}function EZ($){let Q=O5();if(!Q.includes($))B9([...Q,$])}function d$($){let Q=O5();if(Q.includes($))B9(Q.filter((Z)=>Z!==$))}function c0($){return g(L(),$)}function R5($){return`file:${g(c0($),"db.sqlite")}`}function G0(){try{let $=JSON.parse(w5(v5(),"utf8"));return Array.isArray($)?$:[]}catch{return[]}}function A5($){H0(L(),{recursive:!0}),F5(v5(),JSON.stringify($,null,2))}function l0(){return G0().sort(($,Q)=>Q.lastOpenedAt.localeCompare($.lastOpenedAt))}function c($){return G0().find((Q)=>Q.id===$)??null}function d0($,Q,Z=new Date().toISOString()){if(!m0($))throw Error(`beacon: refusing to register a non-repo path as a workspace: ${$}`);let Y=p($);if(p0(Y))throw Error(`beacon: workspace ${Y} (${$}) was deleted \u2014 run \`beacon\` or /beacon-init to re-add it`);let V=G0(),H=V.find((j)=>j.id===Y),G={id:Y,path:$,name:Q||H?.name||c$($),lastOpenedAt:Z},W=[G,...V.filter((j)=>j.id!==Y)];return H0(c0(Y),{recursive:!0}),A5(W),G}function TZ($,Q){return d$(p($)),d0($,Q)}function IZ($,Q=new Date().toISOString()){let Z=G0(),Y=Z.find((V)=>V.id===$);if(!Y)return;Y.lastOpenedAt=Q,A5(Z)}function kZ($){if(A5(G0().filter((Q)=>Q.id!==$)),j0()===$)o$(l0()[0]?.id??null)}function K9(){return g(L(),"active")}function j0(){try{return w5(K9(),"utf8").trim()||null}catch{return null}}function o$($){H0(L(),{recursive:!0}),F5(K9(),$??"")}function _Z(){let $=j0();return $?c($):null}function LZ(){let $=E5()??j0();return $?c($):null}function yZ($){return c($)?.path??null}function xZ(){return j9(v5())}var M9="beacon_ws";function N9($,Q){let Z=$.headers.get("cookie");if(!Z)return null;for(let Y of Z.split(";")){let V=Y.indexOf("=");if(V===-1)continue;if(Y.slice(0,V).trim()===Q)return decodeURIComponent(Y.slice(V+1).trim())}return null}function SZ($){let Q=$.headers.get("x-beacon-workspace");if(Q&&c(Q))return Q;let Z=N9($,M9);if(Z&&c(Z))return Z;return s$()}function s$(){let $=l0();return $.length===1?$[0].id:null}var o0="x-beacon-workspace-path";function fZ($=process.cwd()){let Q=D5($);return{"x-beacon-workspace":p(Q),[o0]:Q}}async function uZ($){let Q=$.headers.get("x-beacon-workspace");if(Q&&c(Q))return Q;let Z=$.headers.get(o0);if(Z&&m0(Z)&&!p0(p(Z))&&(!Q||p(Z)===Q)){let V=d0(Z);return await T5(V.id),V.id}let Y=N9($,M9);if(Y&&c(Y))return Y;return null}var q9=new b$;function n$($,Q){return $?q9.run($,Q):Q()}function E5(){return q9.getStore()??null}var C5=new Set;function gZ($){C5.delete(g(c0($),"db.sqlite"))}async function T5($){let Q=c0($),Z=g(Q,"db.sqlite"),Y=j9(Z);if(Y&&C5.has(Z))return{ok:!0,created:!1,migrated:!1};try{H0(Q,{recursive:!0});let{provisionDb:V}=await H9().then(() => X9),H=await V(R5($));return C5.add(Z),{ok:!0,created:!Y,migrated:Y&&H.migrated}}catch(V){return{ok:!1,created:!1,migrated:!1,error:V instanceof Error?V.message:String(V)}}}import{connect as i$}from"net";var P9=4319;function a$($,Q,Z=400){return new Promise((Y)=>{let V=i$({host:$,port:Q}),H=!1,G=(W)=>{if(H)return;H=!0,V.destroy(),Y(W)};V.once("connect",()=>G(!0)),V.once("error",()=>G(!1)),V.setTimeout(Z,()=>G(!1))})}async function r$($){for(let Q of["127.0.0.1","::1"])if(await a$(Q,$))return!1;return!0}async function bZ($,Q=20){for(let Z=$;Z<$+Q;Z++)if(await r$(Z))return Z;return $}import{McpServer as pQ,ResourceTemplate as x5}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as cQ}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as J}from"zod";import{z as K}from"zod";var t$=new Set(["GET","HEAD","OPTIONS"]);function C9($){return t$.has($.trim().toUpperCase())?"read":"write"}var e$=K.preprocess(($)=>{if(typeof $==="string"){let[Q,...Z]=$.trim().split(/\s+/);return{name:Q,type:Z.join(" ")||"text"}}return $},K.object({name:K.string().trim().min(1),type:K.string().trim().min(1),isPk:K.boolean().optional(),isFk:K.boolean().optional(),nullable:K.boolean().optional(),note:K.string().nullish()})),w9=K.object({name:K.string().trim().min(1),domain:K.string().nullish(),description:K.string().nullish(),columns:K.array(e$).default([])}),F9=K.object({fromTable:K.string(),fromColumn:K.string(),toTable:K.string(),toColumn:K.string(),label:K.string().nullish()}),v9=K.object({method:K.string().trim().min(1),path:K.string().trim().min(1),domain:K.string().nullish(),description:K.string().nullish(),uses:K.array(K.object({table:K.string().trim().min(1),access:K.string().optional()})).default([])}).transform(($)=>({...$,uses:$.uses.map((Q)=>({...Q,access:Q.access??C9($.method)}))})),dZ=K.object({tables:K.array(w9).default([]),relations:K.array(F9).default([]),endpoints:K.array(v9).default([])});import{z as R}from"zod";import{and as M1,eq as N1,inArray as q1}from"drizzle-orm";import{drizzle as AQ}from"drizzle-orm/libsql";import{createClient as EQ}from"@libsql/client";var I5={};$0(I5,{workspaceFlag:()=>HQ,tag:()=>t,syncState:()=>YQ,projectMeta:()=>XQ,planContract:()=>GQ,note:()=>ZQ,nodeTags:()=>l,nodeFile:()=>U0,node:()=>q,endpointTable:()=>o,endpoint:()=>e,edge:()=>h,draftTable:()=>I,draftRelation:()=>s,draftColumn:()=>K0,dbTable:()=>D,dbRelation:()=>d,dbColumn:()=>B0,codeFileEdge:()=>n,codeFile:()=>y,bugFlag:()=>W0,boardAnnotation:()=>JQ,appSetting:()=>VQ});import{sqliteTable as P,index as N,foreignKey as $Q,text as X,integer as U,real as O,uniqueIndex as k,primaryKey as QQ}from"drizzle-orm/sqlite-core";import{createId as w}from"@paralleldrive/cuid2";var q=P("Node",{id:X().primaryKey().$defaultFn(()=>w()),view:X().notNull(),kind:X().default("FEATURE").notNull(),cluster:X(),layer:X(),title:X().notNull(),role:X(),plain:X(),status:X().default("PENDING").notNull(),priority:U().default(2).notNull(),progress:U().default(0).notNull(),x:O().default(0).notNull(),y:O().default(0).notNull(),sourceRef:X(),externalId:X(),source:X().default("MANUAL").notNull(),planId:X(),parentId:X(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[N("Node_cluster_idx").on($.cluster),N("Node_parentId_idx").on($.parentId),N("Node_view_idx").on($.view),$Q(()=>({columns:[$.parentId],foreignColumns:[$.id],name:"Node_parentId_Node_id_fk"})).onUpdate("cascade").onDelete("cascade")]),U0=P("NodeFile",{id:X().primaryKey().$defaultFn(()=>w()),nodeId:X().notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),path:X().notNull()},($)=>[k("NodeFile_nodeId_path_key").on($.nodeId,$.path),N("NodeFile_nodeId_idx").on($.nodeId)]),t=P("Tag",{id:X().primaryKey().$defaultFn(()=>w()),label:X().notNull(),color:X()},($)=>[k("Tag_label_key").on($.label)]),h=P("Edge",{id:X().primaryKey().$defaultFn(()=>w()),fromId:X().notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),toId:X().notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),kind:X().default("DEPENDS").notNull(),label:X(),sourceHandle:X(),targetHandle:X()},($)=>[k("Edge_fromId_toId_kind_key").on($.fromId,$.toId,$.kind),N("Edge_toId_idx").on($.toId),N("Edge_fromId_idx").on($.fromId)]),l=P("_NodeTags",{a:X("A").notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),b:X("B").notNull().references(()=>t.id,{onDelete:"cascade",onUpdate:"cascade"})},($)=>[k("_NodeTags_AB_unique").on($.a,$.b),N("_NodeTags_B_index").on($.b)]),ZQ=P("Note",{id:X().primaryKey().$defaultFn(()=>w()),title:X().default("Untitled").notNull(),body:X().default("").notNull(),ord:O().default(0).notNull(),pinned:U({mode:"boolean"}).default(!1).notNull(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[N("Note_updatedAt_idx").on($.updatedAt)]),JQ=P("BoardAnnotation",{id:X().primaryKey().$defaultFn(()=>w()),targetKind:X().notNull(),targetId:X().notNull(),columnName:X(),body:X().default("").notNull(),x:O(),y:O(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[N("BoardAnnotation_target_idx").on($.targetId)]),W0=P("BugFlag",{id:X().primaryKey().$defaultFn(()=>w()),nodeId:X().notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),by:X().notNull(),note:X().notNull(),resolvedAt:U({mode:"timestamp_ms"}),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date)},($)=>[N("BugFlag_nodeId_idx").on($.nodeId)]),D=P("DbTable",{id:X().primaryKey().$defaultFn(()=>w()),name:X().notNull(),domain:X(),description:X(),source:X().default("MANUAL").notNull(),planId:X(),x:O().default(0).notNull(),y:O().default(0).notNull(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[N("DbTable_domain_idx").on($.domain),k("DbTable_name_key").on($.name)]),B0=P("DbColumn",{id:X().primaryKey().$defaultFn(()=>w()),tableId:X().notNull().references(()=>D.id,{onDelete:"cascade",onUpdate:"cascade"}),name:X().notNull(),type:X().notNull(),isPk:U({mode:"boolean"}).default(!1).notNull(),isFk:U({mode:"boolean"}).default(!1).notNull(),nullable:U({mode:"boolean"}).default(!0).notNull(),note:X(),ord:U().default(0).notNull()},($)=>[k("DbColumn_tableId_name_key").on($.tableId,$.name),N("DbColumn_tableId_idx").on($.tableId)]),d=P("DbRelation",{id:X().primaryKey().$defaultFn(()=>w()),fromTableId:X().notNull().references(()=>D.id,{onDelete:"cascade",onUpdate:"cascade"}),toTableId:X().notNull().references(()=>D.id,{onDelete:"cascade",onUpdate:"cascade"}),fromColumn:X().notNull(),toColumn:X().notNull(),label:X()},($)=>[N("DbRelation_toTableId_idx").on($.toTableId),N("DbRelation_fromTableId_idx").on($.fromTableId)]),e=P("Endpoint",{id:X().primaryKey().$defaultFn(()=>w()),method:X().notNull(),path:X().notNull(),domain:X(),description:X(),source:X().default("MANUAL").notNull(),planId:X(),x:O().default(0).notNull(),y:O().default(0).notNull(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[k("Endpoint_method_path_key").on($.method,$.path),N("Endpoint_domain_idx").on($.domain)]),o=P("EndpointTable",{id:X().primaryKey().$defaultFn(()=>w()),endpointId:X().notNull().references(()=>e.id,{onDelete:"cascade",onUpdate:"cascade"}),tableId:X().notNull().references(()=>D.id,{onDelete:"cascade",onUpdate:"cascade"}),access:X().default("read").notNull()},($)=>[k("EndpointTable_endpointId_tableId_key").on($.endpointId,$.tableId),N("EndpointTable_tableId_idx").on($.tableId)]),I=P("DraftTable",{id:X().primaryKey().$defaultFn(()=>w()),name:X().notNull(),domain:X(),description:X(),x:O().default(0).notNull(),y:O().default(0).notNull(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date)},($)=>[k("DraftTable_name_key").on($.name)]),K0=P("DraftColumn",{id:X().primaryKey().$defaultFn(()=>w()),tableId:X().notNull().references(()=>I.id,{onDelete:"cascade",onUpdate:"cascade"}),name:X().notNull(),type:X().notNull(),isPk:U({mode:"boolean"}).default(!1).notNull(),isFk:U({mode:"boolean"}).default(!1).notNull(),nullable:U({mode:"boolean"}).default(!0).notNull(),note:X(),ord:U().default(0).notNull()},($)=>[N("DraftColumn_tableId_idx").on($.tableId)]),s=P("DraftRelation",{id:X().primaryKey().$defaultFn(()=>w()),fromTableId:X().notNull().references(()=>I.id,{onDelete:"cascade",onUpdate:"cascade"}),toTableId:X().notNull().references(()=>I.id,{onDelete:"cascade",onUpdate:"cascade"}),fromColumn:X().notNull(),toColumn:X().notNull(),label:X()},($)=>[N("DraftRelation_toTableId_idx").on($.toTableId),N("DraftRelation_fromTableId_idx").on($.fromTableId)]),y=P("CodeFile",{path:X().primaryKey(),root:X(),lang:X(),x:O().default(0).notNull(),y:O().default(0).notNull(),mtimeMs:O(),size:U(),inDegree:U().default(0).notNull(),outDegree:U().default(0).notNull(),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),n=P("CodeFileEdge",{fromPath:X().notNull().references(()=>y.path,{onDelete:"cascade",onUpdate:"cascade"}),toPath:X().notNull().references(()=>y.path,{onDelete:"cascade",onUpdate:"cascade"}),circular:U({mode:"boolean"}).default(!1).notNull()},($)=>[N("CodeFileEdge_circular_idx").on($.circular),N("CodeFileEdge_toPath_idx").on($.toPath),N("CodeFileEdge_fromPath_idx").on($.fromPath),QQ({columns:[$.fromPath,$.toPath],name:"CodeFileEdge_fromPath_toPath_pk"})]),YQ=P("SyncState",{id:X().primaryKey().default("singleton"),version:U().default(0).notNull(),codeGraphSyncedAt:U({mode:"timestamp_ms"}),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),VQ=P("AppSetting",{id:X().primaryKey().default("singleton"),editor:X().default("auto").notNull(),currentFeatureId:X(),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),XQ=P("ProjectMeta",{id:X().primaryKey().default("singleton"),overview:X(),conventions:X().default("[]").notNull(),hasFrontend:U({mode:"boolean"}),classificationRoots:X().default("[]").notNull(),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),HQ=P("WorkspaceFlag",{id:X().primaryKey().$defaultFn(()=>w()),key:X().notNull(),enabled:U({mode:"boolean"}).default(!1).notNull(),config:X(),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[k("WorkspaceFlag_key_key").on($.key)]),GQ=P("PlanContract",{id:X().primaryKey().$defaultFn(()=>w()),planId:X().notNull(),declaredFiles:X().default("[]").notNull(),authorizedExtras:X().default("[]").notNull(),active:U({mode:"boolean"}).default(!1).notNull(),createdAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:U({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[k("PlanContract_planId_key").on($.planId),N("PlanContract_active_idx").on($.active)]);var k5={};$0(k5,{tagRelations:()=>BQ,nodeTagsRelations:()=>KQ,nodeRelations:()=>jQ,nodeFileRelations:()=>UQ,endpointTableRelations:()=>wQ,endpointRelations:()=>CQ,edgeRelations:()=>MQ,draftTableRelations:()=>FQ,draftRelationRelations:()=>DQ,draftColumnRelations:()=>vQ,dbTableRelations:()=>NQ,dbRelationRelations:()=>PQ,dbColumnRelations:()=>qQ,codeFileRelations:()=>OQ,codeFileEdgeRelations:()=>RQ,bugFlagRelations:()=>WQ});import{relations as F}from"drizzle-orm";var jQ=F(q,({one:$,many:Q})=>({files:Q(U0),bugFlags:Q(W0),nodeTags:Q(l),edgesOut:Q(h,{relationName:"EdgeFrom"}),edgesIn:Q(h,{relationName:"EdgeTo"}),parent:$(q,{fields:[q.parentId],references:[q.id],relationName:"NodeTree"}),children:Q(q,{relationName:"NodeTree"})})),UQ=F(U0,({one:$})=>({node:$(q,{fields:[U0.nodeId],references:[q.id]})})),WQ=F(W0,({one:$})=>({node:$(q,{fields:[W0.nodeId],references:[q.id]})})),BQ=F(t,({many:$})=>({nodeTags:$(l)})),KQ=F(l,({one:$})=>({node:$(q,{fields:[l.a],references:[q.id]}),tag:$(t,{fields:[l.b],references:[t.id]})})),MQ=F(h,({one:$})=>({from:$(q,{fields:[h.fromId],references:[q.id],relationName:"EdgeFrom"}),to:$(q,{fields:[h.toId],references:[q.id],relationName:"EdgeTo"})})),NQ=F(D,({many:$})=>({columns:$(B0),fksOut:$(d,{relationName:"FkFrom"}),fksIn:$(d,{relationName:"FkTo"}),usages:$(o)})),qQ=F(B0,({one:$})=>({table:$(D,{fields:[B0.tableId],references:[D.id]})})),PQ=F(d,({one:$})=>({fromTable:$(D,{fields:[d.fromTableId],references:[D.id],relationName:"FkFrom"}),toTable:$(D,{fields:[d.toTableId],references:[D.id],relationName:"FkTo"})})),CQ=F(e,({many:$})=>({tables:$(o)})),wQ=F(o,({one:$})=>({endpoint:$(e,{fields:[o.endpointId],references:[e.id]}),table:$(D,{fields:[o.tableId],references:[D.id]})})),FQ=F(I,({many:$})=>({columns:$(K0),fksOut:$(s,{relationName:"DraftFkFrom"}),fksIn:$(s,{relationName:"DraftFkTo"})})),vQ=F(K0,({one:$})=>({table:$(I,{fields:[K0.tableId],references:[I.id]})})),DQ=F(s,({one:$})=>({fromTable:$(I,{fields:[s.fromTableId],references:[I.id],relationName:"DraftFkFrom"}),toTable:$(I,{fields:[s.toTableId],references:[I.id],relationName:"DraftFkTo"})})),OQ=F(y,({many:$})=>({edgesOut:$(n,{relationName:"CFEFrom"}),edgesIn:$(n,{relationName:"CFETo"})})),RQ=F(n,({one:$})=>({fromFile:$(y,{fields:[n.fromPath],references:[y.path],relationName:"CFEFrom"}),toFile:$(y,{fields:[n.toPath],references:[y.path],relationName:"CFETo"})}));var TQ={...I5,...k5};function IQ(){let $=process.env.DATABASE_URL;if($&&/^(file:|libsql:|wss?:|https?:|:memory:)/i.test($))return $;return"file:./dev.db"}var kQ=IQ();function _Q($){let Q=EQ({url:$});return Q.execute("PRAGMA foreign_keys = ON;"),Q.execute("PRAGMA busy_timeout = 5000;"),AQ(Q,{schema:TQ})}var LQ=globalThis,s0=LQ.dzByUrl??=new Map;function D9(){return O9(kQ)}function O9($){let Q=s0.get($);if(!Q)Q=_Q($),s0.set($,Q);return Q}function $1($){let Q=s0.get($);s0.delete($);try{Q?.$client?.close?.()}catch{}}function yQ(){if(process.env.BEACON_REPO)return D9();let $=E5()??j0();if(!$)return D9();return O9(R5($))}var xQ=new Proxy({},{get($,Q){let Z=yQ(),Y=Z[Q];return typeof Y==="function"?Y.bind(Z):Y}});var SQ=["frontend","backend","fullstack"],fQ={fe:"frontend",front:"frontend",be:"backend",back:"backend",fs:"fullstack","full-stack":"fullstack","full stack":"fullstack"};function n0($){let Q=($??"").trim().toLowerCase();if(!Q)return null;if(SQ.includes(Q))return Q;return fQ[Q]??null}import{forceCenter as V1,forceCollide as X1,forceLink as H1,forceManyBody as G1,forceSimulation as j1}from"d3-force";var R9=R.object({title:R.string().trim().min(1),role:R.string().nullish(),plain:R.string().nullish(),cluster:R.string().nullish(),category:R.string().nullish(),domain:R.string().nullish(),priority:R.number().nullish(),kind:R.string().nullish(),layer:R.string().nullish(),dependsOn:R.array(R.string()).nullish()}).transform(({category:$,domain:Q,priority:Z,kind:Y,layer:V,...H})=>({...H,cluster:H.cluster??$??Q??null,priority:Z==null?null:Math.max(0,Math.min(3,Math.round(Z))),kind:Y?.trim().toUpperCase()==="BUG"?"BUG":"FEATURE",layer:n0(V)})),v1=R.object({features:R.array(R9).default([])});var uQ=/(\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 A9($){return!!$&&uQ.test($)}function E9($,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 gQ($){return $.cluster??$.category??$.domain??null}function T9($,Q){let Z=Q?.requireLayer??!1,Y=$.map((H)=>{let G=[],W=gQ(H);if(!W||!W.trim())G.push("category");if(H.priority==null)G.push("priority");if(Z&&!n0(H.layer))G.push("layer");return G.length?` \u2022 "${H.title?.trim()||"(untitled)"}" \u2014 missing ${G.join(" + ")}`:null}).filter((H)=>H!==null);if(Y.length===0)return null;let V=Z?" This workspace has a frontend surface, so every feature must also carry `layer`: "+'"frontend" | "backend" | "fullstack" \u2014 which side of the stack the work lands on.':"";return"\u26D4 Every roadmap feature needs a category AND a priority \u2014 they drive grouping and ordering "+"on the board, and the user shouldn't have to add them by hand."+V+` Missing:
353
353
  `+Y.join(`
354
- `)+"\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 y5($){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`
354
+ `)+"\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 _5($){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`
355
355
 
356
356
  This plan created these roadmap feature(s):
357
357
  `+Q.join(`
358
- `)+'\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 hQ}from"fs";import{join as zQ}from"path";function bQ(){try{return JSON.parse(hQ(zQ(L(),"server.json"),"utf8"))}catch{return null}}function z(){if(process.env.BEACON_URL)return process.env.BEACON_URL;return`http://localhost:${bQ()?.port||process.env.PORT||w9}`}import{execSync as mQ}from"child_process";import{platform as k9}from"os";function x5($){if(process.env.BEACON_NO_OPEN)return;let Q=k9()==="darwin"?"open":k9()==="win32"?"start":"xdg-open";try{mQ(`${Q} "${$}"`,{stdio:"ignore"})}catch{}}async function S5($,Q){if(await fetch(`${$}/api/plan/presence`,{headers:{"x-beacon-workspace":Q}}).then((V)=>V.json()).then((V)=>!!V?.live).catch(()=>!1))return;let Y=encodeURIComponent(`/plan?ws=${Q}`);x5(`${$}/api/workspace/activate?id=${Q}&redirect=${Y}`)}async function _9($,Q){if(await fetch(`${$}/api/lesson/presence`,{headers:{"x-beacon-workspace":Q}}).then((V)=>V.json()).then((V)=>!!V?.live).catch(()=>!1))return;let Y=encodeURIComponent(`/learn?ws=${Q}`);x5(`${$}/api/workspace/activate?id=${Q}&redirect=${Y}`)}var L9=["imports","calls","persists to","reads from","writes to","routes to","depends on","emits","returns","contains","extends"];t0();function M0($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036F]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50)||"item"}function y9($){return`${M0($.title)}-${$.id.slice(-6)}`}function x9($){return{resources:$.map((Q)=>({uri:`note://${y9(Q)}`,name:Q.title||"Untitled",description:`${Q.title||"Untitled"}${Q.pinned?" \xB7 pinned":""} \xB7 note`,mimeType:"text/markdown"}))}}function S9($,Q){return $.find((Z)=>y9(Z)===Q)}function f9($){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(`
359
- `)}await X9();var b=D5(),x=p(b);if(!m0(b)){let $=l0();if($.length===1)console.error(`[beacon mcp] cwd ${b} isn't a registered repo \u2014 falling back to your only Beacon workspace "${$[0].name}".`);else if($.length>1)console.error(`[beacon mcp] cwd ${b} 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 ${b} \u2014 home/non-repo dir.`)}else if(p0(x))console.error(`[beacon mcp] not registering ${b} \u2014 workspace was deleted; run /beacon-init to re-add it.`);else try{d0(b);let $=await T5(x);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",x),Z.set(o0,b);let Y=await fetch(`${z()}${$}`,{...Q,headers:Z}),V=await Y.text();if(!Y.ok)throw Error(`Beacon ${$} -> ${Y.status} ${V}`);return V?JSON.parse(V):null}function N0($,Q){return E($,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Q)})}function u5($){let Q=$ instanceof Error?$.message:String($),Z=Q.match(/\{[\s\S]*\}$/);if(Z)try{let Y=JSON.parse(Z[0]);if(Y?.error)return{content:[{type:"text",text:Y.error}],isError:!0}}catch{}return{content:[{type:"text",text:Q}],isError:!0}}var A=new pQ({name:"beacon",version:"0.1.0"});A.registerTool("beacon_map",{description:"List the roadmap: every feature + its sub-tasks with `category`, `priority`, `layer`, `kind`, and `status`. Call this BEFORE creating anything with `beacon_feature` \u2014 it's the cheap way to learn which categories already exist (reuse one instead of inventing a synonym) and whether a card already exists. You do NOT need `beacon_entities` just to see categories."},async()=>{let $=await E("/api/map");return{content:[{type:"text",text:JSON.stringify($)}]}});var u9=J.array(J.object({title:J.string().describe("real component/subsystem name (e.g. 'Plan review loop') \u2014 NEVER a file"),domain:J.string().describe("uppercase lane: PLAN | DATA | UI | MCP | INTEL | \u2026"),role:J.string().optional().describe("one-line technical role"),plain:J.string().optional().describe("one plain-language sentence"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack the component lives on (only when the repo has a frontend); omitting it on an update keeps the prior value"),status:J.enum(["KEEP","REBUILD","REPLACE","DROP"]).optional(),files:J.array(J.string()).optional(),depends:J.array(J.string()).optional().describe("titles of components this one depends on"),bugs:J.array(J.object({note:J.string().describe("what was found / worth investigating")})).optional().describe("bugs or things worth investigating you found in this component's code \u2014 flagged on the node (by=agent); identical open flags are not duplicated")})).optional().describe("Only when the feature adds/changes a REAL architectural component \u2014 upserts curated nodes, never one-per-file");A.registerTool("beacon_feature",{description:'Manage a roadmap feature\'s whole lifecycle in ONE tool \u2014 no approval gate (that\'s `beacon_propose_plan`/`beacon_present_plan`). `action:"add"` puts a card on the board, defaulting to BACKLOG/PENDING (pass `status:"active"` to start it now); `"start"` marks an existing card IN_PROGRESS (create-or-flag); `"subtasks"` adds child tasks under a card; `"done"` completes feature(s) and registers the files/architecture touched (marks DONE + cascades to sub-tasks). A NEW card REQUIRES `category` + `priority` (and `layer` when the workspace has a frontend). Call `beacon_map` FIRST \u2014 it lists every card\'s category/priority/layer/status, so reuse a category and avoid an EXACT duplicate (same title + category + layer) \u2014 a same-named card in a different category, or on a different layer (FE/BE/FS), is allowed as its own card. `add` never activates an existing match \u2014 it returns `exists` so you can reuse it.',inputSchema:{action:J.enum(["add","start","subtasks","done"]).describe("add = put a card on the board (defaults to BACKLOG/PENDING); start = mark an existing card IN_PROGRESS; subtasks = add child tasks under a card; done = complete feature(s) + register files/architecture."),title:J.string().optional().describe("card title (add/start); for done's single form, the feature title (id preferred)."),id:J.string().optional().describe("node id from beacon_map (preferred over title) \u2014 start/done, or add to reference a known card."),category:J.string().optional().describe("REQUIRED for a NEW card (add/start): domain lane \u2014 AUTH | SEARCH | DATA | INTEL | BILLING | INFRA | UI | \u2026 Reuse one from beacon_map; ignored when matching an existing card or nesting under a `front`."),priority:J.number().int().min(0).max(3).optional().describe("priority of a NEW card (add/start): 0=P0 critical .. 3=P3 low. Defaults to P2."),front:J.string().optional().describe("title of an EXISTING parent feature to nest a NEW card under (add/start). NOT a domain tag (use `category`); a `front` matching nothing is REJECTED."),detail:J.string().optional().describe("one-line plain-language description shown on the card (add/start)."),kind:J.enum(["FEATURE","BUG"]).optional().describe("BUG renders a typed bug card; defaults to FEATURE (add/start)."),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack a NEW card lands on (add/start). REQUIRED when the workspace has a frontend; a card nested under a `front` inherits the parent's. Omit in pure-backend repos."),status:J.enum(["backlog","active"]).optional().describe(`add only: "backlog" (default) creates a PENDING card you're not working on yet; "active" creates it IN_PROGRESS.`),parentId:J.string().optional().describe("subtasks: node id of the parent card (preferred)."),parentTitle:J.string().optional().describe("subtasks: fuzzy title of the parent card; ignored if parentId is given."),items:J.array(J.object({title:J.string().describe("short sub-task title"),plain:J.string().optional().describe("one-paragraph description / why / acceptance hint"),kind:J.enum(["FEATURE","BUG"]).optional().describe("BUG for a bug discovered during work; defaults to FEATURE"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack the sub-task lands on; defaults to the parent's layer")})).optional().describe("subtasks: the child tasks to add under the parent."),features:J.array(J.object({id:J.string().optional().describe("node id from plan approval / beacon_map (preferred over title)"),title:J.string().optional().describe("feature title (fuzzy-matched if no id)"),description:J.string().describe("Markdown: ### Overview ... ### Files - `path` \u2014 what it does"),files:J.array(J.string()).optional().describe("repo-relative files this feature touches"),architecture:u9})).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:u9}},async($)=>{try{let{path:Q,body:Z}=T9($.action,$),Y=await N0(Q,Z);return{content:[{type:"text",text:JSON.stringify(Y)}]}}catch(Q){return u5(Q)}});A.registerTool("beacon_init_persist",{description:"Use ONLY inside the `beacon-init` skill. After YOU (Claude Code) have read the repo and built the architecture analysis, call this once to persist it into Beacon. Replaces any prior init-derived map. Same DB shape as `beacon_propose_plan` for tables/endpoints, but it commits directly (no /plan review step) because the user explicitly invoked init.",inputSchema:{overview:J.string().optional().describe("one-paragraph summary of the project \u2014 written to ProjectMeta + AGENTS.md"),conventions:J.array(J.string()).optional().describe("3-8 concrete conventions/gotchas a contributor must follow"),hasFrontend:J.boolean().optional().describe("Whether this repo has a frontend surface (UI code) \u2014 you just read the repo, so you know. Gates the per-item `layer` requirement + the layer UI on the boards. Set it explicitly (true or false); omitting leaves Beacon to detect it from the code graph."),classificationRoots:J.array(J.string()).optional().describe("Top-level dirs whose immediate children are the meaningful groups on the Files canvas \u2014 e.g. ['frontend','backend/app']. The canvas groups files ONE level below each (so 'frontend' \u2192 'frontend/components', 'frontend/app', \u2026). Pick the dir sitting directly ABOVE the real package dirs (use 'frontend/src' if there's a src/ wrapper). Not every dir \u2014 just where grouping should start. Omit for a simple single-root repo (the canvas auto-groups)."),components:J.array(J.object({title:J.string(),domain:J.string().describe("short UPPERCASE area: AUTH, API, DATA, UI, JOBS, INFRA, \u2026"),role:J.string().optional().describe("one-line technical role"),plain:J.string().optional().describe("one plain-language sentence"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack the component lives on \u2014 set it when hasFrontend is true"),files:J.array(J.string()).optional().describe("repo-relative key files"),depends:J.array(J.string()).optional().describe("titles of other components it depends on"),bugs:J.array(J.object({note:J.string().describe("what was found / worth investigating")})).optional().describe("bugs or things worth investigating you found while examining this component \u2014 flagged on the node (by=agent)")})).describe("8-25 main building blocks, not every file"),roadmap:J.array(J.object({title:J.string(),why:J.string().optional(),category:J.string().optional().describe("category for the board (AUTH | SEARCH | DATA | INTEL | \u2026) \u2014 set it so the item isn't category-less"),priority:J.number().int().min(0).max(3).optional().describe("0=P0 critical .. 3=P3 low"),kind:J.enum(["FEATURE","BUG"]).optional().describe("BUG when the survey found a concrete bug to fix \u2014 renders as a typed bug card; defaults to FEATURE"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack the item lands on \u2014 set it when hasFrontend is true")})).optional().describe("3-6 broad strategic directions (NOT detailed tasks); each with a `category` + `priority`. Re-runs DEDUPE roadmap features by title, so re-persisting won't double up existing ones."),snapshot:J.object({tables:J.array(J.object({name:J.string(),domain:J.string().optional(),description:J.string().optional(),columns:J.array(J.object({name:J.string(),type:J.string(),isPk:J.boolean().optional(),isFk:J.boolean().optional(),nullable:J.boolean().optional(),note:J.string().optional()}))})).optional(),relations:J.array(J.object({fromTable:J.string(),fromColumn:J.string(),toTable:J.string(),toColumn:J.string(),label:J.string().optional()})).optional(),endpoints:J.array(J.object({method:J.string(),path:J.string(),domain:J.string().optional(),description:J.string().optional(),uses:J.array(J.object({table:J.string(),access:J.string().optional()})).optional()})).optional()}).optional().describe("optional: also seed /db with the schema you discovered from prisma/SQLAlchemy/etc.")}},async($)=>{let Q=await N0("/api/init",$);return{content:[{type:"text",text:JSON.stringify(Q)}]}});A.registerTool("beacon_context_for_feature",{description:"Use BEFORE Glob/Grep/Read when starting work on a feature. Returns a single bundle of everything Beacon knows about it: attached files, what those files import + what imports them (1-hop blast radius from the live code graph), endpoints in the feature's domain + the tables each touches, those tables' FK relations, sibling architecture components, and the project's conventions. Saves an entire discovery-phase round of file reads. Match by id (preferred), exact title, or a natural-language query.",inputSchema:{id:J.string().optional().describe("node id from beacon_map (preferred)"),title:J.string().optional().describe("feature title (case-insensitive contains)"),query:J.string().optional().describe("natural-language phrase \u2014 OR-matched against title + plain description")}},async({id:$,title:Q,query:Z})=>{let Y=new URLSearchParams;if($)Y.set("id",$);if(Q)Y.set("title",Q);if(Z)Y.set("query",Z);let V=await E(`/api/context/feature?${Y.toString()}`);return{content:[{type:"text",text:JSON.stringify(V)}]}});A.registerTool("beacon_blast_radius",{description:"For 'if I change this file, what else cares?' \u2014 returns the file's 1-hop imports + importedBy, the TRANSITIVE blast radius both directions (downstream = who depends on it, upstream = what it depends on, grouped by depth), hub/centrality scoring (inDegree/outDegree + isHub), and every feature/component that has the file attached. Use mid-feature when deciding the impact of a change, or before refactoring a hub file.",inputSchema:{path:J.string().describe("repo-relative POSIX file path"),depth:J.number().optional().describe("how far to walk the transitive graph (default 2, capped at 5)")}},async({path:$,depth:Q})=>{let Z=new URLSearchParams({path:$});if(Q!=null)Z.set("depth",String(Q));let Y=await E(`/api/context/file?${Z.toString()}`);return{content:[{type:"text",text:JSON.stringify(Y)}]}});A.registerTool("beacon_entities",{description:"Read raw planning data: `features` (roadmap), `architecture` (components), `tables`/`endpoints` (DB map). Descriptions are truncated to ~160 chars by default to stay within the tool-result limit \u2014 pass `full:true` for complete text and `limit` to cap rows. For just titles + categories + status, prefer the lighter `beacon_map`.",inputSchema:{kind:J.enum(["features","architecture","tables","endpoints"]),full:J.boolean().optional().describe("return complete descriptions instead of the truncated default (features/architecture)"),limit:J.number().int().positive().optional().describe("cap the number of rows returned")}},async({kind:$,full:Q,limit:Z})=>{let Y=new URLSearchParams({kind:$});if(Q)Y.set("full","1");if(Z)Y.set("limit",String(Z));let V=await E(`/api/entities?${Y.toString()}`);return{content:[{type:"text",text:JSON.stringify(V)}]}});A.registerTool("beacon_propose_plan",{description:"BLOCKS until the user reviews. Pushes a feature plan (top-level roadmap features + DB tables + endpoints) to Beacon's /plan page. Use when the user asks you to plan a feature. EVERY feature MUST include `cluster` (its category) and `priority` (0=P0 critical .. 3=P3 low) \u2014 and, when the workspace has a frontend, `layer` (frontend | backend | fullstack). The tool REJECTS a plan whose features omit any required field, so set them on every feature. Do not implement code or migrations until this returns approval. If it returns inline feedback, revise and call again.",inputSchema:{description:J.string().describe("Short summary the user will see in the review header. In any prose (here or a feature's `plain`), write file references as repo-relative paths in `backticks` \u2014 on /plan, paths matching a REAL repo file render clickable to open in the user's editor."),features:J.array(J.object({title:J.string(),role:J.string().optional().describe("one-line technical role"),plain:J.string().optional().describe("one plain-language sentence for the user"),category:J.string().optional().describe("REQUIRED category for the board (AUTH | SEARCH | BILLING | DATA | INTEL | \u2026)"),cluster:J.string().optional().describe("alias for `category`"),domain:J.string().optional().describe("alias for `category`"),priority:J.number().int().min(0).max(3).optional().describe("REQUIRED priority: 0=P0 critical, 1=P1 high, 2=P2 medium, 3=P3 low"),dependsOn:J.array(J.string()).optional().describe("titles of other features in THIS plan that must ship first \u2014 drawn as 'depends on' links so the board shows the dependency chain, not loose cards"),kind:J.enum(["FEATURE","BUG"]).optional().describe("BUG when this roadmap item is a bug to fix \u2014 renders as a typed bug card; defaults to FEATURE"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("Which side of the stack the work lands on. REQUIRED on every feature when the workspace has a frontend (the tool rejects the plan otherwise); omit in pure-backend repos.")})).optional().describe("the top-level roadmap features this plan adds"),tables:J.array(J.object({name:J.string(),domain:J.string().optional(),description:J.string().optional(),columns:J.array(J.object({name:J.string(),type:J.string(),isPk:J.boolean().optional(),isFk:J.boolean().optional(),nullable:J.boolean().optional(),note:J.string().optional()}))})).optional(),relations:J.array(J.object({fromTable:J.string(),fromColumn:J.string(),toTable:J.string(),toColumn:J.string(),label:J.string().optional()})).optional(),endpoints:J.array(J.object({method:J.string().describe("GET|POST|PUT|PATCH|DELETE"),path:J.string(),domain:J.string().optional(),description:J.string().optional(),uses:J.array(J.object({table:J.string(),access:J.string().optional()})).optional()})).optional(),contract:J.array(J.string()).optional().describe("Repo-relative files THIS plan will touch \u2014 the scope contract. Frozen at approval; you're held to them while implementing: editing an undeclared file pauses for the user's authorization (which adds it to the contract), and the /plan Changes view groups your edits On-plan vs Strayed against this set. Always list the files you genuinely expect to edit \u2014 if omitted, the scope is inferred from the files you name in backticks.")}},async({description:$,features:Q,tables:Z,relations:Y,endpoints:V,contract:H})=>{let G=(C)=>new Promise((q0)=>setTimeout(q0,C)),W=(C)=>({content:[{type:"text",text:C}]}),j=(Z?.length??0)>0,B=(Q??[]).map((C)=>`${C.title} ${C.role??""} ${C.plain??""}`).join(`
360
- `),m=(V?.length??0)>0||E9(`${$}
361
- ${B}`);if(!j&&m)return W("\u26D4 This plan touches the database \u2014 it declares endpoints and/or its text describes "+"models/tables/migrations \u2014 but you passed NO `tables`. Beacon's schema board renders "+"ONLY from structured `tables`; prose is never parsed, so the /db tab would be empty and nothing would persist on approve.\n\nRe-call `beacon_propose_plan` with every table in `tables` (each with its `columns`), the `relations` (FKs), and keep the `endpoints` (each with `uses:[{table,access}]`). Mirror EVERY database entity your plan mentions into the structured fields.");if(Q?.length){let C=await E("/api/project-meta").then((m9)=>!!m9?.hasFrontend).catch(()=>!1),q0=I9(Q,{requireLayer:C});if(q0)return W(q0)}let F=(Z?.length??0)+(V?.length??0)>0;try{await N0("/api/plan",{description:$,draft:F?{tables:Z??[],relations:Y??[],endpoints:V??[]}:void 0,features:Q?.length?Q:void 0,contract:H?.length?H:void 0})}catch(C){return u5(C)}await fetch(`${z()}/api/workspace/activate?id=${x}`).catch(()=>{}),await S5(z(),x);let r0=Date.now()+C0;while(Date.now()<r0){await G(P0);let C=await E("/api/plan/verdict").catch(()=>null);if(!C)continue;if(C.kind==="feedback")return W("\uD83D\uDCAC The user left feedback on the plan in Beacon \u2014 text comments and/or edits they "+"made directly on the /map and /db boards. Read everything below, revise the plan accordingly (matching the board changes verbatim), and call `beacon_propose_plan` "+`again with the revised version \u2014 DO NOT implement yet:
358
+ `)+'\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 hQ}from"fs";import{join as zQ}from"path";function bQ(){try{return JSON.parse(hQ(zQ(L(),"server.json"),"utf8"))}catch{return null}}function z(){if(process.env.BEACON_URL)return process.env.BEACON_URL;return`http://localhost:${bQ()?.port||process.env.PORT||P9}`}import{execSync as mQ}from"child_process";import{platform as I9}from"os";function L5($){if(process.env.BEACON_NO_OPEN)return;let Q=I9()==="darwin"?"open":I9()==="win32"?"start":"xdg-open";try{mQ(`${Q} "${$}"`,{stdio:"ignore"})}catch{}}async function y5($,Q){if(await fetch(`${$}/api/plan/presence`,{headers:{"x-beacon-workspace":Q}}).then((V)=>V.json()).then((V)=>!!V?.live).catch(()=>!1))return;let Y=encodeURIComponent(`/plan?ws=${Q}`);L5(`${$}/api/workspace/activate?id=${Q}&redirect=${Y}`)}async function k9($,Q){if(await fetch(`${$}/api/lesson/presence`,{headers:{"x-beacon-workspace":Q}}).then((V)=>V.json()).then((V)=>!!V?.live).catch(()=>!1))return;let Y=encodeURIComponent(`/learn?ws=${Q}`);L5(`${$}/api/workspace/activate?id=${Q}&redirect=${Y}`)}var _9=["imports","calls","persists to","reads from","writes to","routes to","depends on","emits","returns","contains","extends"];t0();function M0($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036F]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50)||"item"}function L9($){return`${M0($.title)}-${$.id.slice(-6)}`}function y9($){return{resources:$.map((Q)=>({uri:`note://${L9(Q)}`,name:Q.title||"Untitled",description:`${Q.title||"Untitled"}${Q.pinned?" \xB7 pinned":""} \xB7 note`,mimeType:"text/markdown"}))}}function x9($,Q){return $.find((Z)=>L9(Z)===Q)}function S9($){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(`
359
+ `)}await Y9();var b=D5(),x=p(b);if(!m0(b)){let $=l0();if($.length===1)console.error(`[beacon mcp] cwd ${b} isn't a registered repo \u2014 falling back to your only Beacon workspace "${$[0].name}".`);else if($.length>1)console.error(`[beacon mcp] cwd ${b} 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 ${b} \u2014 home/non-repo dir.`)}else if(p0(x))console.error(`[beacon mcp] not registering ${b} \u2014 workspace was deleted; run /beacon-init to re-add it.`);else try{d0(b);let $=await T5(x);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",x),Z.set(o0,b);let Y=await fetch(`${z()}${$}`,{...Q,headers:Z}),V=await Y.text();if(!Y.ok)throw Error(`Beacon ${$} -> ${Y.status} ${V}`);return V?JSON.parse(V):null}function N0($,Q){return E($,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Q)})}function S5($){let Q=$ instanceof Error?$.message:String($),Z=Q.match(/\{[\s\S]*\}$/);if(Z)try{let Y=JSON.parse(Z[0]);if(Y?.error)return{content:[{type:"text",text:Y.error}],isError:!0}}catch{}return{content:[{type:"text",text:Q}],isError:!0}}var A=new pQ({name:"beacon",version:"0.1.0"});A.registerTool("beacon_map",{description:"List the roadmap: every feature + its sub-tasks with `category`, `priority`, `layer`, `kind`, and `status`. Call this BEFORE creating anything with `beacon_feature` \u2014 it's the cheap way to learn which categories already exist (reuse one instead of inventing a synonym) and whether a card already exists. You do NOT need `beacon_entities` just to see categories."},async()=>{let $=await E("/api/map");return{content:[{type:"text",text:JSON.stringify($)}]}});var f9=J.array(J.object({title:J.string().describe("real component/subsystem name (e.g. 'Plan review loop') \u2014 NEVER a file"),domain:J.string().describe("uppercase lane: PLAN | DATA | UI | MCP | INTEL | \u2026"),role:J.string().optional().describe("one-line technical role"),plain:J.string().optional().describe("one plain-language sentence"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack the component lives on (only when the repo has a frontend); omitting it on an update keeps the prior value"),status:J.enum(["KEEP","REBUILD","REPLACE","DROP"]).optional(),files:J.array(J.string()).optional(),depends:J.array(J.string()).optional().describe("titles of components this one depends on"),bugs:J.array(J.object({note:J.string().describe("what was found / worth investigating")})).optional().describe("bugs or things worth investigating you found in this component's code \u2014 flagged on the node (by=agent); identical open flags are not duplicated")})).optional().describe("Only when the feature adds/changes a REAL architectural component \u2014 upserts curated nodes, never one-per-file");A.registerTool("beacon_feature",{description:'Manage a roadmap feature\'s whole lifecycle in ONE tool \u2014 no approval gate (that\'s `beacon_propose_plan`/`beacon_present_plan`). `action:"add"` puts a card on the board, defaulting to BACKLOG/PENDING (pass `status:"active"` to start it now); `"start"` marks an existing card IN_PROGRESS (create-or-flag); `"subtasks"` adds child tasks under a card; `"done"` completes feature(s) and registers the files/architecture touched (marks DONE + cascades to sub-tasks). A NEW card REQUIRES `category` + `priority` (and `layer` when the workspace has a frontend). Call `beacon_map` FIRST \u2014 it lists every card\'s category/priority/layer/status, so reuse a category and avoid an EXACT duplicate (same title + category + layer) \u2014 a same-named card in a different category, or on a different layer (FE/BE/FS), is allowed as its own card. `add` never activates an existing match \u2014 it returns `exists` so you can reuse it.',inputSchema:{action:J.enum(["add","start","subtasks","done"]).describe("add = put a card on the board (defaults to BACKLOG/PENDING); start = mark an existing card IN_PROGRESS; subtasks = add child tasks under a card; done = complete feature(s) + register files/architecture."),title:J.string().optional().describe("card title (add/start); for done's single form, the feature title (id preferred)."),id:J.string().optional().describe("node id from beacon_map (preferred over title) \u2014 start/done, or add to reference a known card."),category:J.string().optional().describe("REQUIRED for a NEW card (add/start): domain lane \u2014 AUTH | SEARCH | DATA | INTEL | BILLING | INFRA | UI | \u2026 Reuse one from beacon_map; ignored when matching an existing card or nesting under a `front`."),priority:J.number().int().min(0).max(3).optional().describe("priority of a NEW card (add/start): 0=P0 critical .. 3=P3 low. Defaults to P2."),front:J.string().optional().describe("title of an EXISTING parent feature to nest a NEW card under (add/start). NOT a domain tag (use `category`); a `front` matching nothing is REJECTED."),detail:J.string().optional().describe("one-line plain-language description shown on the card (add/start)."),kind:J.enum(["FEATURE","BUG"]).optional().describe("BUG renders a typed bug card; defaults to FEATURE (add/start)."),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack a NEW card lands on (add/start). REQUIRED when the workspace has a frontend; a card nested under a `front` inherits the parent's. Omit in pure-backend repos."),status:J.enum(["backlog","active"]).optional().describe(`add only: "backlog" (default) creates a PENDING card you're not working on yet; "active" creates it IN_PROGRESS.`),parentId:J.string().optional().describe("subtasks: node id of the parent card (preferred)."),parentTitle:J.string().optional().describe("subtasks: fuzzy title of the parent card; ignored if parentId is given."),items:J.array(J.object({title:J.string().describe("short sub-task title"),plain:J.string().optional().describe("one-paragraph description / why / acceptance hint"),kind:J.enum(["FEATURE","BUG"]).optional().describe("BUG for a bug discovered during work; defaults to FEATURE"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack the sub-task lands on; defaults to the parent's layer")})).optional().describe("subtasks: the child tasks to add under the parent."),features:J.array(J.object({id:J.string().optional().describe("node id from plan approval / beacon_map (preferred over title)"),title:J.string().optional().describe("feature title (fuzzy-matched if no id)"),description:J.string().describe("Markdown: ### Overview ... ### Files - `path` \u2014 what it does"),files:J.array(J.string()).optional().describe("repo-relative files this feature touches"),architecture:f9})).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:f9}},async($)=>{try{let{path:Q,body:Z}=E9($.action,$),Y=await N0(Q,Z);return{content:[{type:"text",text:JSON.stringify(Y)}]}}catch(Q){return S5(Q)}});A.registerTool("beacon_init_persist",{description:"Use ONLY inside the `beacon-init` skill. After YOU (Claude Code) have read the repo and built the architecture analysis, call this once to persist it into Beacon. Replaces any prior init-derived map. Same DB shape as `beacon_propose_plan` for tables/endpoints, but it commits directly (no /plan review step) because the user explicitly invoked init.",inputSchema:{overview:J.string().optional().describe("one-paragraph summary of the project \u2014 written to ProjectMeta + AGENTS.md"),conventions:J.array(J.string()).optional().describe("3-8 concrete conventions/gotchas a contributor must follow"),hasFrontend:J.boolean().optional().describe("Whether this repo has a frontend surface (UI code) \u2014 you just read the repo, so you know. Gates the per-item `layer` requirement + the layer UI on the boards. Set it explicitly (true or false); omitting leaves Beacon to detect it from the code graph."),classificationRoots:J.array(J.string()).optional().describe("Top-level dirs whose immediate children are the meaningful groups on the Files canvas \u2014 e.g. ['frontend','backend/app']. The canvas groups files ONE level below each (so 'frontend' \u2192 'frontend/components', 'frontend/app', \u2026). Pick the dir sitting directly ABOVE the real package dirs (use 'frontend/src' if there's a src/ wrapper). Not every dir \u2014 just where grouping should start. Omit for a simple single-root repo (the canvas auto-groups)."),components:J.array(J.object({title:J.string(),domain:J.string().describe("short UPPERCASE area: AUTH, API, DATA, UI, JOBS, INFRA, \u2026"),role:J.string().optional().describe("one-line technical role"),plain:J.string().optional().describe("one plain-language sentence"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack the component lives on \u2014 set it when hasFrontend is true"),files:J.array(J.string()).optional().describe("repo-relative key files"),depends:J.array(J.string()).optional().describe("titles of other components it depends on"),bugs:J.array(J.object({note:J.string().describe("what was found / worth investigating")})).optional().describe("bugs or things worth investigating you found while examining this component \u2014 flagged on the node (by=agent)")})).describe("8-25 main building blocks, not every file"),roadmap:J.array(J.object({title:J.string(),why:J.string().optional(),category:J.string().optional().describe("category for the board (AUTH | SEARCH | DATA | INTEL | \u2026) \u2014 set it so the item isn't category-less"),priority:J.number().int().min(0).max(3).optional().describe("0=P0 critical .. 3=P3 low"),kind:J.enum(["FEATURE","BUG"]).optional().describe("BUG when the survey found a concrete bug to fix \u2014 renders as a typed bug card; defaults to FEATURE"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("which side of the stack the item lands on \u2014 set it when hasFrontend is true")})).optional().describe("3-6 broad strategic directions (NOT detailed tasks); each with a `category` + `priority`. Re-runs DEDUPE roadmap features by title, so re-persisting won't double up existing ones."),snapshot:J.object({tables:J.array(J.object({name:J.string(),domain:J.string().optional(),description:J.string().optional(),columns:J.array(J.object({name:J.string(),type:J.string(),isPk:J.boolean().optional(),isFk:J.boolean().optional(),nullable:J.boolean().optional(),note:J.string().optional()}))})).optional(),relations:J.array(J.object({fromTable:J.string(),fromColumn:J.string(),toTable:J.string(),toColumn:J.string(),label:J.string().optional()})).optional(),endpoints:J.array(J.object({method:J.string(),path:J.string(),domain:J.string().optional(),description:J.string().optional(),uses:J.array(J.object({table:J.string(),access:J.string().optional()})).optional()})).optional()}).optional().describe("optional: also seed /db with the schema you discovered from prisma/SQLAlchemy/etc.")}},async($)=>{let Q=await N0("/api/init",$);return{content:[{type:"text",text:JSON.stringify(Q)}]}});A.registerTool("beacon_context_for_feature",{description:"Use BEFORE Glob/Grep/Read when starting work on a feature. Returns a single bundle of everything Beacon knows about it: attached files, what those files import + what imports them (1-hop blast radius from the live code graph), endpoints in the feature's domain + the tables each touches, those tables' FK relations, sibling architecture components, and the project's conventions. Saves an entire discovery-phase round of file reads. Match by id (preferred), exact title, or a natural-language query.",inputSchema:{id:J.string().optional().describe("node id from beacon_map (preferred)"),title:J.string().optional().describe("feature title (case-insensitive contains)"),query:J.string().optional().describe("natural-language phrase \u2014 OR-matched against title + plain description")}},async({id:$,title:Q,query:Z})=>{let Y=new URLSearchParams;if($)Y.set("id",$);if(Q)Y.set("title",Q);if(Z)Y.set("query",Z);let V=await E(`/api/context/feature?${Y.toString()}`);return{content:[{type:"text",text:JSON.stringify(V)}]}});A.registerTool("beacon_blast_radius",{description:"For 'if I change this file, what else cares?' \u2014 returns the file's 1-hop imports + importedBy, the TRANSITIVE blast radius both directions (downstream = who depends on it, upstream = what it depends on, grouped by depth), hub/centrality scoring (inDegree/outDegree + isHub), and every feature/component that has the file attached. Use mid-feature when deciding the impact of a change, or before refactoring a hub file.",inputSchema:{path:J.string().describe("repo-relative POSIX file path"),depth:J.number().optional().describe("how far to walk the transitive graph (default 2, capped at 5)")}},async({path:$,depth:Q})=>{let Z=new URLSearchParams({path:$});if(Q!=null)Z.set("depth",String(Q));let Y=await E(`/api/context/file?${Z.toString()}`);return{content:[{type:"text",text:JSON.stringify(Y)}]}});A.registerTool("beacon_entities",{description:"Read raw planning data: `features` (roadmap), `architecture` (components), `tables`/`endpoints` (DB map). Descriptions are truncated to ~160 chars by default to stay within the tool-result limit \u2014 pass `full:true` for complete text and `limit` to cap rows. For just titles + categories + status, prefer the lighter `beacon_map`.",inputSchema:{kind:J.enum(["features","architecture","tables","endpoints"]),full:J.boolean().optional().describe("return complete descriptions instead of the truncated default (features/architecture)"),limit:J.number().int().positive().optional().describe("cap the number of rows returned")}},async({kind:$,full:Q,limit:Z})=>{let Y=new URLSearchParams({kind:$});if(Q)Y.set("full","1");if(Z)Y.set("limit",String(Z));let V=await E(`/api/entities?${Y.toString()}`);return{content:[{type:"text",text:JSON.stringify(V)}]}});A.registerTool("beacon_propose_plan",{description:"BLOCKS until the user reviews. Pushes a feature plan (top-level roadmap features + DB tables + endpoints) to Beacon's /plan page. Use when the user asks you to plan a feature. EVERY feature MUST include `cluster` (its category) and `priority` (0=P0 critical .. 3=P3 low) \u2014 and, when the workspace has a frontend, `layer` (frontend | backend | fullstack). The tool REJECTS a plan whose features omit any required field, so set them on every feature. Do not implement code or migrations until this returns approval. If it returns inline feedback, revise and call again.",inputSchema:{description:J.string().describe("Short summary the user will see in the review header. In any prose (here or a feature's `plain`), write file references as repo-relative paths in `backticks` \u2014 on /plan, paths matching a REAL repo file render clickable to open in the user's editor."),features:J.array(J.object({title:J.string(),role:J.string().optional().describe("one-line technical role"),plain:J.string().optional().describe("one plain-language sentence for the user"),category:J.string().optional().describe("REQUIRED category for the board (AUTH | SEARCH | BILLING | DATA | INTEL | \u2026)"),cluster:J.string().optional().describe("alias for `category`"),domain:J.string().optional().describe("alias for `category`"),priority:J.number().int().min(0).max(3).optional().describe("REQUIRED priority: 0=P0 critical, 1=P1 high, 2=P2 medium, 3=P3 low"),dependsOn:J.array(J.string()).optional().describe("titles of other features in THIS plan that must ship first \u2014 drawn as 'depends on' links so the board shows the dependency chain, not loose cards"),kind:J.enum(["FEATURE","BUG"]).optional().describe("BUG when this roadmap item is a bug to fix \u2014 renders as a typed bug card; defaults to FEATURE"),layer:J.enum(["frontend","backend","fullstack"]).optional().describe("Which side of the stack the work lands on. REQUIRED on every feature when the workspace has a frontend (the tool rejects the plan otherwise); omit in pure-backend repos.")})).optional().describe("the top-level roadmap features this plan adds"),tables:J.array(J.object({name:J.string(),domain:J.string().optional(),description:J.string().optional(),columns:J.array(J.object({name:J.string(),type:J.string(),isPk:J.boolean().optional(),isFk:J.boolean().optional(),nullable:J.boolean().optional(),note:J.string().optional()}))})).optional(),relations:J.array(J.object({fromTable:J.string(),fromColumn:J.string(),toTable:J.string(),toColumn:J.string(),label:J.string().optional()})).optional(),endpoints:J.array(J.object({method:J.string().describe("GET|POST|PUT|PATCH|DELETE"),path:J.string(),domain:J.string().optional(),description:J.string().optional(),uses:J.array(J.object({table:J.string(),access:J.string().optional()})).optional()})).optional(),contract:J.array(J.string()).optional().describe("Repo-relative files THIS plan will touch \u2014 the scope contract. Frozen at approval; you're held to them while implementing: editing an undeclared file pauses for the user's authorization (which adds it to the contract), and the /plan Changes view groups your edits On-plan vs Strayed against this set. Always list the files you genuinely expect to edit \u2014 if omitted, the scope is inferred from the files you name in backticks.")}},async({description:$,features:Q,tables:Z,relations:Y,endpoints:V,contract:H})=>{let G=(C)=>new Promise((q0)=>setTimeout(q0,C)),W=(C)=>({content:[{type:"text",text:C}]}),j=(Z?.length??0)>0,B=(Q??[]).map((C)=>`${C.title} ${C.role??""} ${C.plain??""}`).join(`
360
+ `),m=(V?.length??0)>0||A9(`${$}
361
+ ${B}`);if(!j&&m)return W("\u26D4 This plan touches the database \u2014 it declares endpoints and/or its text describes "+"models/tables/migrations \u2014 but you passed NO `tables`. Beacon's schema board renders "+"ONLY from structured `tables`; prose is never parsed, so the /db tab would be empty and nothing would persist on approve.\n\nRe-call `beacon_propose_plan` with every table in `tables` (each with its `columns`), the `relations` (FKs), and keep the `endpoints` (each with `uses:[{table,access}]`). Mirror EVERY database entity your plan mentions into the structured fields.");if(Q?.length){let C=await E("/api/project-meta").then((b9)=>!!b9?.hasFrontend).catch(()=>!1),q0=T9(Q,{requireLayer:C});if(q0)return W(q0)}let v=(Z?.length??0)+(V?.length??0)>0;try{await N0("/api/plan",{description:$,draft:v?{tables:Z??[],relations:Y??[],endpoints:V??[]}:void 0,features:Q?.length?Q:void 0,contract:H?.length?H:void 0})}catch(C){return S5(C)}await fetch(`${z()}/api/workspace/activate?id=${x}`).catch(()=>{}),await y5(z(),x);let r0=Date.now()+C0;while(Date.now()<r0){await G(P0);let C=await E("/api/plan/verdict").catch(()=>null);if(!C)continue;if(C.kind==="feedback")return W("\uD83D\uDCAC The user left feedback on the plan in Beacon \u2014 text comments and/or edits they "+"made directly on the /map and /db boards. Read everything below, revise the plan accordingly (matching the board changes verbatim), and call `beacon_propose_plan` "+`again with the revised version \u2014 DO NOT implement yet:
362
362
 
363
363
  `+C.feedback);if(C.kind==="approved")return W(`\u2705 Plan approved by the user. ${C.summary}`+(C.detail?`
364
364
 
365
365
  Implement EXACTLY the schema below (migrations + code) \u2014 the user may have `+`edited columns on the canvas:
366
366
 
367
- `+C.detail:"")+y5(C.features));if(C.kind==="discarded")return W(`\u274C The user discarded the plan in Beacon. ${C.summary} Ask what they want to adjust before proposing again.`)}return W("Still waiting for the user to review in Beacon. Your plan is preserved \u2014 call "+"`beacon_propose_plan` again with the SAME plan to resume (the verdict is picked up immediately if they've since decided), or ask whether they've reviewed it.")});A.registerTool("beacon_explain",{description:"BLOCKS until the user is done learning. Use when the user asks you to EXPLAIN / TEACH / walk "+"them through part of the codebase (architecture, a category, how X works) \u2014 NOT to plan a "+"build (that's beacon_propose_plan). Pushes an interactive Lesson to Beacon's /learn page: a curated concept map (nodes + verb-labeled arrows) beside a plain-English narrative. The user highlights text to ask questions and drops question notes; this returns their questions so you ANSWER them and call beacon_explain AGAIN with the same lesson plus `answers:[{questionId,answer}]`, looping until they Save.\n\nWrite like a great teacher (the house style): open each component with the PROBLEM it solves and a concrete scenario; give a numbered step-by-step flow naming every real identifier in `backticks` (files become clickable on /learn); add 'Why X?' sections that explain why the alternative is worse; include a worked example with a small data table; use **bold** for decisions, *italic* for concepts. Map every piece you name to a node, "+"and every 'A does X to B' to a labeled edge. Plain English throughout \u2014 define terms inline.",inputSchema:{title:J.string().describe("the lesson title, e.g. 'How a plan flows to /plan'"),topic:J.string().optional().describe("the user's request, verbatim (shown in the library)"),narrative:J.string().describe("The house-style explanation as markdown (problem-first \u2192 numbered flow \u2192 'Why X?' \u2192 worked example). Write file references as repo-relative paths in `backticks` \u2014 they render clickable on /learn."),nodes:J.array(J.object({id:J.string().describe("a short stable id you assign (e.g. 'n1') \u2014 edges reference it"),title:J.string(),summary:J.string().optional().describe("one-line plain-English summary shown on the node face"),detail:J.string().optional().describe("fuller plain-English explanation, markdown, shown on click"),files:J.array(J.string()).optional().describe("real repo-relative paths this node maps to \u2014 clickable chips"),group:J.string().optional().describe("optional cluster label for landmark regions"),x:J.number().optional(),y:J.number().optional()})).optional().describe("the curated concept-map boxes \u2014 keep the resting set small (~4-7 per view)"),edges:J.array(J.object({fromId:J.string(),toId:J.string(),verb:J.enum(L9).describe("the relationship \u2014 a labeled directional arrow, never a bare line")})).optional(),tables:J.array(J.object({id:J.string().describe("a short stable id you assign (e.g. 't1') \u2014 edges + fkTo reference it"),name:J.string(),domain:J.string().optional(),note:J.string().optional().describe("one plain-English line: why this table exists"),group:J.string().optional(),columns:J.array(J.object({name:J.string(),type:J.string().optional(),isPk:J.boolean().optional(),isFk:J.boolean().optional(),fkTo:J.string().optional().describe("id of the table this column references \u2014 draws an FK link"),note:J.string().optional().describe("plain-English: what this column is for")})).optional(),sample:J.array(J.record(J.string(),J.string())).optional().describe("worked-example rows (column name \u2192 value) shown when the card is expanded")})).optional().describe("database tables the lesson teaches \u2014 rendered as annotated schema cards on the SAME board. Connect a concept to a table with an edge whose toId is the table id (verb 'persists to' / 'reads from'); give key columns isPk, FKs an fkTo, and EVERY column a plain-English note. Add a sample row."),steps:J.array(J.object({title:J.string(),summary:J.string().optional(),focusIds:J.array(J.string()).optional().describe("node/table ids to spotlight this step; omit/[] = whole-board overview"),narrativeAnchor:J.string().optional()})).optional().describe("the guided-walkthrough order \u2014 reveal one node/step at a time; first step should be the overview"),answers:J.array(J.object({questionId:J.string(),answer:J.string()})).optional().describe("on a re-push: your answers to the user's questions, keyed by the [q:ID] they came with")}},async({title:$,topic:Q,narrative:Z,nodes:Y,edges:V,tables:H,steps:G,answers:W})=>{let j=(F)=>new Promise((r0)=>setTimeout(r0,F)),B=(F)=>({content:[{type:"text",text:F}]});try{await N0("/api/lesson",{title:$,topic:Q,narrative:Z,nodes:Y,edges:V,tables:H,steps:G,answers:W})}catch(F){return u5(F)}await fetch(`${z()}/api/workspace/activate?id=${x}`).catch(()=>{}),await _9(z(),x);let m=Date.now()+C0;while(Date.now()<m){await j(P0);let F=await E("/api/lesson/verdict").catch(()=>null);if(!F)continue;if(F.kind==="questions")return B("\uD83D\uDCAC The user asked questions about the lesson in Beacon. Answer each one, then call "+"`beacon_explain` AGAIN with the SAME lesson plus `answers:[{questionId,answer}]` (keyed by the [q:ID] below). Expand the narrative or add nodes where it helps the explanation. "+`Keep looping until the user saves \u2014 DO NOT stop after one round:
367
+ `+C.detail:"")+_5(C.features));if(C.kind==="discarded")return W(`\u274C The user discarded the plan in Beacon. ${C.summary} Ask what they want to adjust before proposing again.`)}return W("Still waiting for the user to review in Beacon. Your plan is preserved \u2014 call "+"`beacon_propose_plan` again with the SAME plan to resume (the verdict is picked up immediately if they've since decided), or ask whether they've reviewed it.")});A.registerTool("beacon_explain",{description:"BLOCKS until the user is done learning. Use when the user asks you to EXPLAIN / TEACH / walk "+"them through part of the codebase (architecture, a category, how X works) \u2014 NOT to plan a "+"build (that's beacon_propose_plan). Pushes an interactive Lesson to Beacon's /learn page: a curated concept map (nodes + verb-labeled arrows) beside a plain-English narrative. The user highlights text to ask questions and drops question notes; this returns their questions so you ANSWER them and call beacon_explain AGAIN with the same lesson plus `answers:[{questionId,answer}]`, looping until they Save.\n\nWrite like a great teacher (the house style): open each component with the PROBLEM it solves and a concrete scenario; give a numbered step-by-step flow naming every real identifier in `backticks` (files become clickable on /learn); add 'Why X?' sections that explain why the alternative is worse; include a worked example with a small data table; use **bold** for decisions, *italic* for concepts. Map every piece you name to a node, "+"and every 'A does X to B' to a labeled edge. Plain English throughout \u2014 define terms inline.",inputSchema:{title:J.string().describe("the lesson title, e.g. 'How a plan flows to /plan'"),topic:J.string().optional().describe("the user's request, verbatim (shown in the library)"),narrative:J.string().describe("The house-style explanation as markdown (problem-first \u2192 numbered flow \u2192 'Why X?' \u2192 worked example). Write file references as repo-relative paths in `backticks` \u2014 they render clickable on /learn."),nodes:J.array(J.object({id:J.string().describe("a short stable id you assign (e.g. 'n1') \u2014 edges reference it"),title:J.string(),summary:J.string().optional().describe("one-line plain-English summary shown on the node face"),detail:J.string().optional().describe("fuller plain-English explanation, markdown, shown on click"),files:J.array(J.string()).optional().describe("real repo-relative paths this node maps to \u2014 clickable chips"),group:J.string().optional().describe("optional cluster label for landmark regions"),x:J.number().optional(),y:J.number().optional()})).optional().describe("the curated concept-map boxes \u2014 keep the resting set small (~4-7 per view)"),edges:J.array(J.object({fromId:J.string(),toId:J.string(),verb:J.enum(_9).describe("the relationship \u2014 a labeled directional arrow, never a bare line")})).optional(),tables:J.array(J.object({id:J.string().describe("a short stable id you assign (e.g. 't1') \u2014 edges + fkTo reference it"),name:J.string(),domain:J.string().optional(),note:J.string().optional().describe("one plain-English line: why this table exists"),group:J.string().optional(),columns:J.array(J.object({name:J.string(),type:J.string().optional(),isPk:J.boolean().optional(),isFk:J.boolean().optional(),fkTo:J.string().optional().describe("id of the table this column references \u2014 draws an FK link"),note:J.string().optional().describe("plain-English: what this column is for")})).optional(),sample:J.array(J.record(J.string(),J.string())).optional().describe("worked-example rows (column name \u2192 value) shown when the card is expanded")})).optional().describe("database tables the lesson teaches \u2014 rendered as annotated schema cards on the SAME board. Connect a concept to a table with an edge whose toId is the table id (verb 'persists to' / 'reads from'); give key columns isPk, FKs an fkTo, and EVERY column a plain-English note. Add a sample row."),steps:J.array(J.object({title:J.string(),summary:J.string().optional(),focusIds:J.array(J.string()).optional().describe("node/table ids to spotlight this step; omit/[] = whole-board overview"),narrativeAnchor:J.string().optional()})).optional().describe("the guided-walkthrough order \u2014 reveal one node/step at a time; first step should be the overview"),answers:J.array(J.object({questionId:J.string(),answer:J.string()})).optional().describe("on a re-push: your answers to the user's questions, keyed by the [q:ID] they came with")}},async({title:$,topic:Q,narrative:Z,nodes:Y,edges:V,tables:H,steps:G,answers:W})=>{let j=(v)=>new Promise((r0)=>setTimeout(r0,v)),B=(v)=>({content:[{type:"text",text:v}]});try{await N0("/api/lesson",{title:$,topic:Q,narrative:Z,nodes:Y,edges:V,tables:H,steps:G,answers:W})}catch(v){return S5(v)}await fetch(`${z()}/api/workspace/activate?id=${x}`).catch(()=>{}),await k9(z(),x);let m=Date.now()+C0;while(Date.now()<m){await j(P0);let v=await E("/api/lesson/verdict").catch(()=>null);if(!v)continue;if(v.kind==="questions")return B("\uD83D\uDCAC The user asked questions about the lesson in Beacon. Answer each one, then call "+"`beacon_explain` AGAIN with the SAME lesson plus `answers:[{questionId,answer}]` (keyed by the [q:ID] below). Expand the narrative or add nodes where it helps the explanation. "+`Keep looping until the user saves \u2014 DO NOT stop after one round:
368
368
 
369
- `+(F.rendered??""));if(F.kind==="saved")return B(`\u2705 The user saved the lesson to their library. ${F.summary} You're done explaining \u2014 `+"they can reopen it anytime from /learn.");if(F.kind==="closed")return B(`The user closed the lesson without saving. ${F.summary} Stop here; ask if they'd like a different explanation.`)}return B("Still waiting for the user to finish the lesson in Beacon. It's preserved \u2014 call "+"`beacon_explain` again with the SAME lesson to resume.")});A.registerTool("beacon_present_plan",{description:"BLOCKS until the user reviews. Pushes ANY plan (as markdown) to Beacon's /plan page so the user reviews it on the canvas instead of in the terminal \u2014 use this whenever you'd otherwise end a turn asking 'does this look right / should I proceed?'. Embed ONE fenced ```beacon block of JSON ({tables,relations,endpoints,features}) for any DB/roadmap entities so they render as an editable board. Returns the verdict (approved / discarded / feedback). Do NOT implement until it returns approval; on feedback, revise and call again. (For a pure schema+features plan, beacon_propose_plan is the structured alternative.)",inputSchema:{description:J.string().describe("One-line summary shown in the review header"),markdown:J.string().describe("The full plan as markdown. Embed a ```beacon block for tables/endpoints/features. Write file references as repo-relative paths in `backticks` (e.g. `app/api/plan/route.ts`) \u2014 on /plan, paths matching a REAL repo file render clickable to open in the user's editor.")}},async({description:$,markdown:Q})=>{let Z=(H)=>new Promise((G)=>setTimeout(G,H)),Y=(H)=>({content:[{type:"text",text:H}]});await N0("/api/plan",{description:$,markdown:Q}),await fetch(`${z()}/api/workspace/activate?id=${x}`).catch(()=>{}),await S5(z(),x);let V=Date.now()+C0;while(Date.now()<V){await Z(P0);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:
369
+ `+(v.rendered??""));if(v.kind==="saved")return B(`\u2705 The user saved the lesson to their library. ${v.summary} You're done explaining \u2014 `+"they can reopen it anytime from /learn.");if(v.kind==="closed")return B(`The user closed the lesson without saving. ${v.summary} Stop here; ask if they'd like a different explanation.`)}return B("Still waiting for the user to finish the lesson in Beacon. It's preserved \u2014 call "+"`beacon_explain` again with the SAME lesson to resume.")});A.registerTool("beacon_present_plan",{description:"BLOCKS until the user reviews. Pushes ANY plan (as markdown) to Beacon's /plan page so the user reviews it on the canvas instead of in the terminal \u2014 use this whenever you'd otherwise end a turn asking 'does this look right / should I proceed?'. Embed ONE fenced ```beacon block of JSON ({tables,relations,endpoints,features}) for any DB/roadmap entities so they render as an editable board. Returns the verdict (approved / discarded / feedback). Do NOT implement until it returns approval; on feedback, revise and call again. (For a pure schema+features plan, beacon_propose_plan is the structured alternative.)",inputSchema:{description:J.string().describe("One-line summary shown in the review header"),markdown:J.string().describe("The full plan as markdown. Embed a ```beacon block for tables/endpoints/features. Write file references as repo-relative paths in `backticks` (e.g. `app/api/plan/route.ts`) \u2014 on /plan, paths matching a REAL repo file render clickable to open in the user's editor.")}},async({description:$,markdown:Q})=>{let Z=(H)=>new Promise((G)=>setTimeout(G,H)),Y=(H)=>({content:[{type:"text",text:H}]});await N0("/api/plan",{description:$,markdown:Q}),await fetch(`${z()}/api/workspace/activate?id=${x}`).catch(()=>{}),await y5(z(),x);let V=Date.now()+C0;while(Date.now()<V){await Z(P0);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:
370
370
 
371
371
  `+H.feedback);if(H.kind==="approved")return Y(`\u2705 Plan approved by the user. ${H.summary??""}`.trim()+(H.detail?`
372
372
 
373
373
  Implement exactly what's on the board:
374
374
 
375
- ${H.detail}`:"")+y5(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 h9=($)=>Array.isArray($)?$[0]:$;async function a0($){return(await E(`/api/entities?kind=${$}&full=1`)).items}function z9($,Q){return{resources:$.map((Z)=>({uri:`${Q}${M0(Z.title)}`,name:Z.title,description:`${Z.title}${Z.cluster?` \xB7 ${Z.cluster}`:""} \xB7 ${Z.status}`,mimeType:"text/markdown"}))}}async function b9($,Q,Z){let Y=(await a0(Z)).find((W)=>M0(W.title)===h9(Q));if(!Y)return{contents:[{uri:$.href,mimeType:"text/markdown",text:"(not found)"}]};let H=((await E("/api/entities?kind=tables")).items??[]).map((W)=>W.name),G=[`# ${Y.title}`];if(Y.cluster)G.push(`*Domain:* \`${Y.cluster}\``);if(Y.status)G.push(`*Status:* \`${Y.status}\``);if(G.push(""),G.push(Y.plain?.trim()||"(this node has no description yet \u2014 add one on Beacon's /map page)"),G.push("","## Existing DB tables in this project"),G.push(H.length?H.join(", "):"(none yet)"),Z==="features"){let W=await a0("features"),j=[...new Set(W.map((B)=>B.cluster?.trim()).filter((B)=>!!B))].sort();G.push("","## Existing feature categories \u2014 reuse one before inventing a new one"),G.push(j.length?j.join(", "):"(none yet)"),G.push("","## Beacon feature loop \u2014 follow IN ORDER (do not jump to Glob/Grep/Read)","1. **Load context FIRST.** Call `beacon_context_for_feature({ title })` for this feature BEFORE any Glob/Grep/Read. It returns the attached files, 1-hop import blast radius, the domain's endpoints + tables + FK relations, sibling components, and the project conventions \u2014 and marks this feature active so your edits attach to it. That bundle replaces the discovery phase; Glob is a last resort.","2. **Design data before code.** Identify the tables this feature needs. If ANY are missing from the list above, design the schema and call `beacon_propose_plan` (tables + relations + endpoints, each endpoint with `uses:[{table,access}]`). It BLOCKS until the user approves on /plan \u2014 do NOT write migrations or code until it returns approval.","3. **Register at the end \u2014 in ONE call.** When the work is done, call `beacon_feature({ action: \"done\" })` ONCE with a `features` array (one entry per feature the plan created, each keyed by the `id` you got back at approval, with the files you touched + a short markdown summary). Don't make one call per feature, and don't register only the umbrella \u2014 that leaves the rest Pending.")}return{contents:[{uri:$.href,mimeType:"text/markdown",text:G.join(`
376
- `)}]}}A.registerResource("beacon-feature",new f5("feature://{slug}",{list:async()=>z9(await a0("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})=>b9($,Q,"features"));A.registerResource("beacon-component",new f5("component://{slug}",{list:async()=>z9(await a0("architecture"),"component://")}),{title:"Beacon: architecture",description:"Architecture components \u2014 picking one imports 'what the agent sees'.",mimeType:"text/markdown"},($,{slug:Q})=>b9($,Q,"architecture"));async function g9(){return await E("/api/notes")}A.registerResource("beacon-note",new f5("note://{slug}",{list:async()=>x9(await g9())}),{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=S9(await g9(),h9(Q)),Y=Z?f9(Z):"(not found)";return{contents:[{uri:$.href,mimeType:"text/markdown",text:Y}]}});await A.connect(new cQ);var i0=-1;setInterval(async()=>{try{let{version:$}=await E("/api/version");if(i0===-1)i0=$;else if($!==i0)i0=$,A.sendResourceListChanged()}catch{}},g5);
375
+ ${H.detail}`:"")+_5(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 g9=($)=>Array.isArray($)?$[0]:$;async function a0($){return(await E(`/api/entities?kind=${$}&full=1`)).items}function h9($,Q){return{resources:$.map((Z)=>({uri:`${Q}${M0(Z.title)}`,name:Z.title,description:`${Z.title}${Z.cluster?` \xB7 ${Z.cluster}`:""} \xB7 ${Z.status}`,mimeType:"text/markdown"}))}}async function z9($,Q,Z){let Y=(await a0(Z)).find((W)=>M0(W.title)===g9(Q));if(!Y)return{contents:[{uri:$.href,mimeType:"text/markdown",text:"(not found)"}]};let H=((await E("/api/entities?kind=tables")).items??[]).map((W)=>W.name),G=[`# ${Y.title}`];if(Y.cluster)G.push(`*Domain:* \`${Y.cluster}\``);if(Y.status)G.push(`*Status:* \`${Y.status}\``);if(G.push(""),G.push(Y.plain?.trim()||"(this node has no description yet \u2014 add one on Beacon's /map page)"),G.push("","## Existing DB tables in this project"),G.push(H.length?H.join(", "):"(none yet)"),Z==="features"){let W=await a0("features"),j=[...new Set(W.map((B)=>B.cluster?.trim()).filter((B)=>!!B))].sort();G.push("","## Existing feature categories \u2014 reuse one before inventing a new one"),G.push(j.length?j.join(", "):"(none yet)"),G.push("","## Beacon feature loop \u2014 follow IN ORDER (do not jump to Glob/Grep/Read)","1. **Load context FIRST.** Call `beacon_context_for_feature({ title })` for this feature BEFORE any Glob/Grep/Read. It returns the attached files, 1-hop import blast radius, the domain's endpoints + tables + FK relations, sibling components, and the project conventions \u2014 and marks this feature active so your edits attach to it. That bundle replaces the discovery phase; Glob is a last resort.","2. **Design data before code.** Identify the tables this feature needs. If ANY are missing from the list above, design the schema and call `beacon_propose_plan` (tables + relations + endpoints, each endpoint with `uses:[{table,access}]`). It BLOCKS until the user approves on /plan \u2014 do NOT write migrations or code until it returns approval.","3. **Register at the end \u2014 in ONE call.** When the work is done, call `beacon_feature({ action: \"done\" })` ONCE with a `features` array (one entry per feature the plan created, each keyed by the `id` you got back at approval, with the files you touched + a short markdown summary). Don't make one call per feature, and don't register only the umbrella \u2014 that leaves the rest Pending.")}return{contents:[{uri:$.href,mimeType:"text/markdown",text:G.join(`
376
+ `)}]}}A.registerResource("beacon-feature",new x5("feature://{slug}",{list:async()=>h9(await a0("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})=>z9($,Q,"features"));A.registerResource("beacon-component",new x5("component://{slug}",{list:async()=>h9(await a0("architecture"),"component://")}),{title:"Beacon: architecture",description:"Architecture components \u2014 picking one imports 'what the agent sees'.",mimeType:"text/markdown"},($,{slug:Q})=>z9($,Q,"architecture"));async function u9(){return await E("/api/notes")}A.registerResource("beacon-note",new x5("note://{slug}",{list:async()=>y9(await u9())}),{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=x9(await u9(),g9(Q)),Y=Z?S9(Z):"(not found)";return{contents:[{uri:$.href,mimeType:"text/markdown",text:Y}]}});await A.connect(new cQ);var i0=-1;setInterval(async()=>{try{let{version:$}=await E("/api/version");if(i0===-1)i0=$;else if($!==i0)i0=$,A.sendResourceListChanged()}catch{}},f5);
@@ -1,4 +1,8 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{execSync as X}from"child_process";import{existsSync as Y,readFileSync as Z}from"fs";import{join as $}from"path";function D(){process.exit(0)}function f(q){let G=q;try{G=X("git rev-parse --show-toplevel",{cwd:q,stdio:["ignore","pipe","ignore"]}).toString().trim()||q}catch{}for(let Q of new Set([G,q])){let H=$(Q,".mcp.json");try{if(Y(H)&&Z(H,"utf8").includes("beacon"))return!0}catch{}}return!1}var g=/@beacon:feature/i,j=/\b(feature|sub-?tasks?)\b/i,B=/\b(implement|build|add|create|design|develop|work on|wire up|ship|refactor)\b/i,J="";try{for await(let q of process.stdin)J+=q}catch{D()}var z="",P=process.cwd();try{let q=JSON.parse(J||"{}");if(typeof q.prompt==="string")z=q.prompt;if(typeof q.cwd==="string"&&q.cwd)P=q.cwd}catch{D()}var C=g.test(z)||j.test(z)&&B.test(z);if(!z||!C||!f(P))D();var I=["[Beacon] This looks like feature work. Follow Beacon's loop IN ORDER \u2014 do not start blind codebase searches:","1. Call beacon_context_for_feature({ id | title | query }) FIRST. It returns the attached files, 1-hop import blast radius, the domain's endpoints + tables + FK relations, sibling components, and conventions \u2014 and marks the feature active. That replaces the discovery phase.","2. Design data before code: if the feature needs tables that don't exist yet, call beacon_propose_plan (tables + relations + endpoints) and WAIT for approval on /plan before writing migrations or code.",'3. When done, call beacon_feature({ action: "done" }) with the files you touched + a short markdown summary so the map and AGENTS.md stay accurate.'].join(`
4
- `);process.stdout.write(JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:I}}));process.exit(0);
3
+ var r=Object.defineProperty;var i=(Q)=>Q;function e(Q,X){this[Q]=i.bind(null,X)}var QQ=(Q,X)=>{for(var Z in X)r(Q,Z,{get:X[Z],enumerable:!0,configurable:!0,set:e.bind(X,Z)})};var XQ=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X);var S={};QQ(S,{provisionDb:()=>jQ});import{createClient as ZQ}from"@libsql/client";import{drizzle as $Q}from"drizzle-orm/libsql";import{migrate as JQ}from"drizzle-orm/libsql/migrator";import{readMigrationFiles as YQ}from"drizzle-orm/migrator";import{dirname as T,join as GQ}from"path";import{fileURLToPath as VQ}from"url";async function U(Q,X){return(await Q.execute({sql:"SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?",args:[X]})).rows.length>0}async function zQ(Q,X){let Z=await Q.execute(`PRAGMA table_info("${X}")`);return new Set(Z.rows.map(($)=>String($.name)))}async function E(Q){if(!await U(Q,"__drizzle_migrations"))return 0;let X=await Q.execute('SELECT count(*) AS n FROM "__drizzle_migrations"');return Number(X.rows[0]?.n??0)}async function LQ(Q){for(let[X,Z]of Object.entries(MQ)){if(!await U(Q,X))continue;let $=await zQ(Q,X);for(let J of Z){if(!$.has(J))continue;await Q.execute(`UPDATE "${X}" SET "${J}" = CAST((julianday("${J}") - 2440587.5) * 86400000 AS INTEGER) WHERE typeof("${J}") = 'text'`)}}}async function jQ(Q,X=BQ){let Z=ZQ({url:Q});try{await Z.execute("PRAGMA journal_mode = WAL;"),await Z.execute("PRAGMA foreign_keys = ON;"),await Z.execute("PRAGMA busy_timeout = 5000;");let $=await U(Z,"__drizzle_migrations"),J=await U(Z,"Node"),Y=!1;if(J&&!$){let B=YQ({migrationsFolder:X})[0];if(B)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:[B.hash,B.folderMillis]}),Y=!0}let V=await E(Z);if(await JQ($Q(Z),{migrationsFolder:X}),await E(Z)>V)Y=!0;return await LQ(Z),{migrated:Y}}finally{Z.close()}}var KQ,BQ,MQ;var W=XQ(async()=>{KQ=T(T(T(VQ(import.meta.url)))),BQ=process.env.BEACON_MIGRATIONS_DIR||GQ(KQ,"drizzle"),MQ={Node:["createdAt","updatedAt"],Note:["createdAt","updatedAt"],DbTable:["createdAt","updatedAt"],Endpoint:["createdAt","updatedAt"],DraftTable:["createdAt"],SyncState:["codeGraphSyncedAt","updatedAt"],AppSetting:["updatedAt"],ProjectMeta:["updatedAt"],CodeFile:["updatedAt"]}});import{AsyncLocalStorage as NQ}from"async_hooks";import{spawnSync as UQ}from"child_process";import{createHash as CQ}from"crypto";import{existsSync as F,mkdirSync as L,readFileSync as _,writeFileSync as x}from"fs";import{homedir as P}from"os";import{basename as HQ,join as K,parse as OQ,resolve as f}from"path";function G(){return process.env.BEACON_HOME||K(P(),".beacon")}function I(){return K(G(),"workspaces.json")}function z(Q){return CQ("sha256").update(Q).digest("hex").slice(0,12)}function qQ(Q=process.cwd()){let X=UQ("git",["rev-parse","--show-toplevel"],{cwd:Q,stdio:["ignore","pipe","ignore"]});if(X.status===0){let Z=X.stdout?.toString().trim();if(Z)return Z}return Q}function y(Q){let X=f(Q);return X!==f(P())&&X!==OQ(X).root}function g(){return K(G(),"deleted.json")}function A(){try{let Q=JSON.parse(_(g(),"utf8"));return Array.isArray(Q)?Q:[]}catch{return[]}}function b(Q){L(G(),{recursive:!0}),x(g(),JSON.stringify(Q,null,2))}function k(Q){return A().includes(Q)}function QX(Q){let X=A();if(!X.includes(Q))b([...X,Q])}function TQ(Q){let X=A();if(X.includes(Q))b(X.filter((Z)=>Z!==Q))}function C(Q){return K(G(),Q)}function uQ(Q){return`file:${K(C(Q),"db.sqlite")}`}function j(){try{let Q=JSON.parse(_(I(),"utf8"));return Array.isArray(Q)?Q:[]}catch{return[]}}function D(Q){L(G(),{recursive:!0}),x(I(),JSON.stringify(Q,null,2))}function m(){return j().sort((Q,X)=>X.lastOpenedAt.localeCompare(Q.lastOpenedAt))}function M(Q){return j().find((X)=>X.id===Q)??null}function w(Q,X,Z=new Date().toISOString()){if(!y(Q))throw Error(`beacon: refusing to register a non-repo path as a workspace: ${Q}`);let $=z(Q);if(k($))throw Error(`beacon: workspace ${$} (${Q}) was deleted \u2014 run \`beacon\` or /beacon-init to re-add it`);let J=j(),Y=J.find((q)=>q.id===$),V={id:$,path:Q,name:X||Y?.name||HQ(Q),lastOpenedAt:Z},B=[V,...J.filter((q)=>q.id!==$)];return L(C($),{recursive:!0}),D(B),V}function XX(Q,X){return TQ(z(Q)),w(Q,X)}function ZX(Q,X=new Date().toISOString()){let Z=j(),$=Z.find((J)=>J.id===Q);if(!$)return;$.lastOpenedAt=X,D(Z)}function $X(Q){if(D(j().filter((X)=>X.id!==Q)),R()===Q)_Q(m()[0]?.id??null)}function h(){return K(G(),"active")}function R(){try{return _(h(),"utf8").trim()||null}catch{return null}}function _Q(Q){L(G(),{recursive:!0}),x(h(),Q??"")}function JX(){let Q=R();return Q?M(Q):null}function YX(){let Q=IQ()??R();return Q?M(Q):null}function GX(Q){return M(Q)?.path??null}function VX(){return F(I())}var p="beacon_ws";function l(Q,X){let Z=Q.headers.get("cookie");if(!Z)return null;for(let $ of Z.split(";")){let J=$.indexOf("=");if(J===-1)continue;if($.slice(0,J).trim()===X)return decodeURIComponent($.slice(J+1).trim())}return null}function KX(Q){let X=Q.headers.get("x-beacon-workspace");if(X&&M(X))return X;let Z=l(Q,p);if(Z&&M(Z))return Z;return xQ()}function xQ(){let Q=m();return Q.length===1?Q[0].id:null}var c="x-beacon-workspace-path";function n(Q=process.cwd()){let X=qQ(Q);return{"x-beacon-workspace":z(X),[c]:X}}async function BX(Q){let X=Q.headers.get("x-beacon-workspace");if(X&&M(X))return X;let Z=Q.headers.get(c);if(Z&&y(Z)&&!k(z(Z))&&(!X||z(Z)===X)){let J=w(Z);return await AQ(J.id),J.id}let $=l(Q,p);if($&&M($))return $;return null}var s=new NQ;function MX(Q,X){return Q?s.run(Q,X):X()}function IQ(){return s.getStore()??null}var u=new Set;function zX(Q){u.delete(K(C(Q),"db.sqlite"))}async function AQ(Q){let X=C(Q),Z=K(X,"db.sqlite"),$=F(Z);if($&&u.has(Z))return{ok:!0,created:!1,migrated:!1};try{L(X,{recursive:!0});let{provisionDb:J}=await W().then(() => S),Y=await J(uQ(Q));return u.add(Z),{ok:!0,created:!$,migrated:$&&Y.migrated}}catch(J){return{ok:!1,created:!1,migrated:!1,error:J instanceof Error?J.message:String(J)}}}import{connect as DQ}from"net";var d=4319;function RQ(Q,X,Z=400){return new Promise(($)=>{let J=DQ({host:Q,port:X}),Y=!1,V=(B)=>{if(Y)return;Y=!0,J.destroy(),$(B)};J.once("connect",()=>V(!0)),J.once("error",()=>V(!1)),J.setTimeout(Z,()=>V(!1))})}async function vQ(Q){for(let X of["127.0.0.1","::1"])if(await RQ(X,Q))return!1;return!0}async function NX(Q,X=20){for(let Z=Q;Z<Q+X;Z++)if(await vQ(Z))return Z;return Q}import{execSync as fQ}from"child_process";import{existsSync as FQ,readFileSync as PQ}from"fs";import{join as yQ}from"path";import{readFileSync as EQ}from"fs";import{join as SQ}from"path";function WQ(){try{return JSON.parse(EQ(SQ(G(),"server.json"),"utf8"))}catch{return null}}function o(){if(process.env.BEACON_URL)return process.env.BEACON_URL;return`http://localhost:${WQ()?.port||process.env.PORT||d}`}function H(){process.exit(0)}function gQ(Q){let X=Q;try{X=fQ("git rev-parse --show-toplevel",{cwd:Q,stdio:["ignore","pipe","ignore"]}).toString().trim()||Q}catch{}for(let Z of new Set([X,Q])){let $=yQ(Z,".mcp.json");try{if(FQ($)&&PQ($,"utf8").includes("beacon"))return!0}catch{}}return!1}var bQ=/@beacon:feature/i,kQ=/\b(feature|sub-?tasks?)\b/i,mQ=/\b(implement|build|add|create|design|develop|work on|wire up|ship|refactor)\b/i,a="";try{for await(let Q of process.stdin)a+=Q}catch{H()}var N="",v=process.cwd(),t="";try{let Q=JSON.parse(a||"{}");if(typeof Q.prompt==="string")N=Q.prompt;if(typeof Q.cwd==="string"&&Q.cwd)v=Q.cwd;if(typeof Q.session_id==="string")t=Q.session_id}catch{H()}if(!gQ(v))H();var O=[];try{let Q=await fetch(`${o()}/api/changes/comment/claim?session=${encodeURIComponent(t)}`,{method:"POST",headers:n(v),signal:AbortSignal.timeout(2500)}).catch(()=>null),X=Q?.ok?(await Q.json().catch(()=>null))?.additionalContext:"";if(X&&X.trim())O.push(X)}catch{}var wQ=bQ.test(N)||kQ.test(N)&&mQ.test(N);if(N&&wQ)O.push(["[Beacon] This looks like feature work. Follow Beacon's loop IN ORDER \u2014 do not start blind codebase searches:","1. Call beacon_context_for_feature({ id | title | query }) FIRST. It returns the attached files, 1-hop import blast radius, the domain's endpoints + tables + FK relations, sibling components, and conventions \u2014 and marks the feature active. That replaces the discovery phase.","2. Design data before code: if the feature needs tables that don't exist yet, call beacon_propose_plan (tables + relations + endpoints) and WAIT for approval on /plan before writing migrations or code.",'3. When done, call beacon_feature({ action: "done" }) with the files you touched + a short markdown summary so the map and AGENTS.md stay accurate.'].join(`
4
+ `));if(!O.length)H();process.stdout.write(JSON.stringify({hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:O.join(`
5
+
6
+ ---
7
+
8
+ `)}}));process.exit(0);