trybeacon 0.1.66 → 0.1.67
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.
- package/.claude-plugin/plugin.json +1 -1
- package/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +8 -8
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +11 -11
- package/.next/server/app/_not-found.segments/_full.segment.rsc +11 -11
- package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_index.segment.rsc +11 -11
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/api/lesson/close/route.js +1 -1
- package/.next/server/app/api/lesson/questions/route.js +1 -1
- package/.next/server/app/api/lesson/route.js +1 -1
- package/.next/server/app/api/lesson/save/route.js +1 -1
- package/.next/server/app/api/lesson/verdict/route.js +1 -1
- package/.next/server/app/docs/page_client-reference-manifest.js +1 -1
- package/.next/server/app/docs.html +1 -1
- package/.next/server/app/docs.rsc +11 -11
- package/.next/server/app/docs.segments/_full.segment.rsc +11 -11
- package/.next/server/app/docs.segments/_head.segment.rsc +1 -1
- package/.next/server/app/docs.segments/_index.segment.rsc +11 -11
- package/.next/server/app/docs.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/docs.segments/docs/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/docs.segments/docs.segment.rsc +1 -1
- package/.next/server/app/feedback/page_client-reference-manifest.js +1 -1
- package/.next/server/app/feedback.html +1 -1
- package/.next/server/app/feedback.rsc +11 -11
- package/.next/server/app/feedback.segments/_full.segment.rsc +11 -11
- package/.next/server/app/feedback.segments/_head.segment.rsc +1 -1
- package/.next/server/app/feedback.segments/_index.segment.rsc +11 -11
- package/.next/server/app/feedback.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/feedback.segments/feedback/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/feedback.segments/feedback.segment.rsc +1 -1
- package/.next/server/app/help/page_client-reference-manifest.js +1 -1
- package/.next/server/app/help.html +1 -1
- package/.next/server/app/help.rsc +11 -11
- package/.next/server/app/help.segments/_full.segment.rsc +11 -11
- package/.next/server/app/help.segments/_head.segment.rsc +1 -1
- package/.next/server/app/help.segments/_index.segment.rsc +11 -11
- package/.next/server/app/help.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/help.segments/help/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/help.segments/help.segment.rsc +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +12 -12
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
- package/.next/server/app/index.segments/_full.segment.rsc +12 -12
- package/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/.next/server/app/index.segments/_index.segment.rsc +11 -11
- package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/learn/page.js +5 -3
- package/.next/server/app/learn/page.js.nft.json +1 -1
- package/.next/server/app/learn/page_client-reference-manifest.js +1 -1
- package/.next/server/app/map/page.js +2 -2
- package/.next/server/app/map/page.js.nft.json +1 -1
- package/.next/server/app/map/page_client-reference-manifest.js +1 -1
- package/.next/server/app/page.js +2 -2
- package/.next/server/app/page.js.nft.json +1 -1
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app/plan/page.js +2 -2
- package/.next/server/app/plan/page.js.nft.json +1 -1
- package/.next/server/app/plan/page_client-reference-manifest.js +1 -1
- package/.next/server/app/s/[token]/page.js +2 -2
- package/.next/server/app/s/[token]/page.js.nft.json +1 -1
- package/.next/server/app/s/[token]/page_client-reference-manifest.js +1 -1
- package/.next/server/app/settings/page.js +1 -1
- package/.next/server/app/settings/page.js.nft.json +1 -1
- package/.next/server/app/settings/page_client-reference-manifest.js +1 -1
- package/.next/server/app-paths-manifest.json +8 -8
- package/.next/server/chunks/2025.js +1 -0
- package/.next/server/chunks/2994.js +2 -0
- package/.next/server/chunks/4046.js +3 -3
- package/.next/server/chunks/5683.js +1 -0
- package/.next/server/chunks/5719.js +1 -0
- package/.next/server/chunks/7720.js +154 -0
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.js +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/1276-b84f61ec9c0df862.js +1 -0
- package/.next/static/chunks/1a258343-954e0e6619585d3c.js +2 -0
- package/.next/static/chunks/2059-fba06ba63ba64522.js +62 -0
- package/.next/static/chunks/4607-a668ea431c41e60e.js +1 -0
- package/.next/static/chunks/4853-6dc402b4ce452fa5.js +1 -0
- package/.next/static/chunks/{7043-254590cf9891391f.js → 4888-911c0da3c2d785d2.js} +1 -1
- package/.next/static/chunks/5957-83f611fcd5a08b45.js +1 -0
- package/.next/static/chunks/766-242213d211df0afd.js +1 -0
- package/.next/static/chunks/8997-78a359d0d238622e.js +1 -0
- package/.next/static/chunks/app/{layout-0c993f55d3a798f4.js → layout-9f0f4d8e4534a62e.js} +1 -1
- package/.next/static/chunks/app/learn/page-03acad0a37068966.js +7 -0
- package/.next/static/chunks/app/map/page-5cfad64d5feea695.js +1 -0
- package/.next/static/chunks/app/page-d08947a671077569.js +1 -0
- package/.next/static/chunks/app/plan/page-5eacb6b83bd4873d.js +1 -0
- package/.next/static/chunks/app/s/[token]/page-1a350cf50a45500c.js +1 -0
- package/.next/static/chunks/app/settings/page-7e176d120b1effa9.js +1 -0
- package/.next/static/css/63986592e2be7d62.css +1 -0
- package/.next/trace +43 -43
- package/.next/trace-build +1 -1
- package/dist/bin/beacon.js +14 -12
- package/dist/bin/doctor.js +22 -15
- package/dist/bin/hook.js +18 -11
- package/dist/bin/mcp.js +41 -34
- package/dist/bin/plan.js +21 -14
- package/dist/bin/uninstall.js +26 -19
- package/dist/lib/assets.js +7 -0
- package/dist/lib/codex-install.js +28 -21
- package/dist/lib/global-install.js +27 -20
- package/package.json +1 -1
- package/plugin/skills/beacon-explain/SKILL.md +7 -0
- package/.next/server/chunks/3584.js +0 -154
- package/.next/server/chunks/6024.js +0 -2
- package/.next/server/chunks/7187.js +0 -1
- package/.next/server/chunks/8035.js +0 -1
- package/.next/static/chunks/1936-7fea5225b5bfcfda.js +0 -1
- package/.next/static/chunks/1a258343-6baccd9e573fdfaf.js +0 -2
- package/.next/static/chunks/2019-3be80edc82176878.js +0 -1
- package/.next/static/chunks/3845-6fe7e66d4bf82eb5.js +0 -1
- package/.next/static/chunks/4549-591415d55ca009a3.js +0 -62
- package/.next/static/chunks/6638-4e53879181b1df75.js +0 -1
- package/.next/static/chunks/7643-6c7ff4b9400f68fc.js +0 -1
- package/.next/static/chunks/app/learn/page-797d74e02b98fa88.js +0 -5
- package/.next/static/chunks/app/map/page-634b6d5d98e921b3.js +0 -1
- package/.next/static/chunks/app/page-84dc684d45002cfb.js +0 -1
- package/.next/static/chunks/app/plan/page-df829b2054c40611.js +0 -1
- package/.next/static/chunks/app/s/[token]/page-f97dec75856a7952.js +0 -1
- package/.next/static/chunks/app/settings/page-59d90685cd17fc1f.js +0 -1
- package/.next/static/css/b3d3212da726bbfb.css +0 -1
- /package/.next/static/{P3uXQySdS-m6_bxuiezYe → hkOIw5DQW9WSwBwZrD8_9}/_buildManifest.js +0 -0
- /package/.next/static/{P3uXQySdS-m6_bxuiezYe → hkOIw5DQW9WSwBwZrD8_9}/_ssgManifest.js +0 -0
package/dist/bin/mcp.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var b9=Object.defineProperty;var m9=($)=>$;function p9($,Q){this[$]=m9.bind(null,Q)}var
|
|
3
|
+
var b9=Object.defineProperty;var m9=($)=>$;function p9($,Q){this[$]=m9.bind(null,Q)}var $0=($,Q)=>{for(var Z in Q)b9($,Z,{get:Q[Z],enumerable:!0,configurable:!0,set:p9.bind(Q,Z)})};var s=($,Q)=>()=>($&&(Q=$($=0)),Q);var P0=1500,cQ=480000,C0=1800000,w0=3600000,f5=3000;var a0=()=>{};var Q5={};$0(Q5,{removeRepoAssets:()=>t9,installRefreshSkill:()=>l9,installPlanSkill:()=>d9,installInitSkill:()=>c9,installExplainSkill:()=>o9,installCodexRepoSkills:()=>n9,ensureWorkflowDoc:()=>i9,ensureMcp:()=>r9,auditRepo:()=>a9,REFRESH_SKILL:()=>e0,PLAN_SKILL:()=>u5,INIT_SKILL:()=>t0,EXPLAIN_SKILL:()=>g5});import{existsSync as n,mkdirSync as Q0,readFileSync as _,rmSync as v0,writeFileSync as T}from"fs";import{join as N}from"path";function c9($){let Q=N($,".claude","skills","beacon-init");Q0(Q,{recursive:!0});let Z=N(Q,"SKILL.md");return T(Z,t0),Z}function l9($){let Q=N($,".claude","skills","beacon-refresh");Q0(Q,{recursive:!0});let Z=N(Q,"SKILL.md");return T(Z,e0),Z}function d9($){let Q=N($,".claude","skills","beacon-plan");Q0(Q,{recursive:!0});let Z=N(Q,"SKILL.md");return T(Z,u5),Z}function o9($){let Q=N($,".claude","skills","beacon-explain");Q0(Q,{recursive:!0});let Z=N(Q,"SKILL.md");return T(Z,g5),Z}function n9($){let Q=[];for(let Z of s9){let Y=N($,".agents","skills",Z.name);Q0(Y,{recursive:!0});let X=N(Y,"SKILL.md");T(X,Z.body()),Q.push(X)}return Q}function i9($){let Q=N($,"AGENTS.md"),Z="";try{Z=_(Q,"utf8")}catch{}let Y=new RegExp(`${F0}[\\s\\S]*?${$5}`);Z=Y.test(Z)?Z.replace(Y,h5):`${Z.trim()}
|
|
4
4
|
|
|
5
|
-
${
|
|
5
|
+
${h5}
|
|
6
6
|
`.trimStart(),T(Q,Z.endsWith(`
|
|
7
7
|
`)?Z:`${Z}
|
|
8
8
|
`);let X=N($,"CLAUDE.md"),H="";try{H=_(X,"utf8")}catch{}if(!/@AGENTS\.md/.test(H))T(X,`${H?`${H.trim()}
|
|
9
9
|
|
|
10
10
|
`:""}@AGENTS.md
|
|
11
|
-
`)}function r9($){let Q=N($,".mcp.json"),Z={};try{Z=JSON.parse(_(Q,"utf8"))}catch{}Z.mcpServers=Z.mcpServers??{};let Y=Z.mcpServers.beacon;if(Y){if(!Y.timeout||Y.timeout<
|
|
12
|
-
`),{path:Q,added:!1,updated:!0};return{path:Q,added:!1,updated:!1}}return Z.mcpServers.beacon={command:"beacon",args:["mcp"],timeout:
|
|
13
|
-
`),{path:Q,added:!0,updated:!1}}function a9($){let Q=N($,".mcp.json"),Z=!1;try{Z=!!JSON.parse(_(Q,"utf8")).mcpServers?.beacon}catch{}let Y=!1;try{Y=_(N($,"AGENTS.md"),"utf8").includes(F0)}catch{}let X=!1;try{X=/@AGENTS\.md/.test(_(N($,"CLAUDE.md"),"utf8"))}catch{}return{repo:$,mcpRegistered:Z,agentsMdBlock:Y,claudeMdImport:X,skills:{"beacon-init":
|
|
14
|
-
`)}}catch{}let X=!1,H=N($,"AGENTS.md");try{let j=_(H,"utf8"),
|
|
11
|
+
`)}function r9($){let Q=N($,".mcp.json"),Z={};try{Z=JSON.parse(_(Q,"utf8"))}catch{}Z.mcpServers=Z.mcpServers??{};let Y=Z.mcpServers.beacon;if(Y){if(!Y.timeout||Y.timeout<w0)return Y.timeout=w0,T(Q,JSON.stringify(Z,null,2)+`
|
|
12
|
+
`),{path:Q,added:!1,updated:!0};return{path:Q,added:!1,updated:!1}}return Z.mcpServers.beacon={command:"beacon",args:["mcp"],timeout:w0},T(Q,JSON.stringify(Z,null,2)+`
|
|
13
|
+
`),{path:Q,added:!0,updated:!1}}function a9($){let Q=N($,".mcp.json"),Z=!1;try{Z=!!JSON.parse(_(Q,"utf8")).mcpServers?.beacon}catch{}let Y=!1;try{Y=_(N($,"AGENTS.md"),"utf8").includes(F0)}catch{}let X=!1;try{X=/@AGENTS\.md/.test(_(N($,"CLAUDE.md"),"utf8"))}catch{}return{repo:$,mcpRegistered:Z,agentsMdBlock:Y,claudeMdImport:X,skills:{"beacon-init":n(N($,".claude","skills","beacon-init","SKILL.md")),"beacon-refresh":n(N($,".claude","skills","beacon-refresh","SKILL.md"))},codexSkills:{"beacon-init":n(N($,".agents","skills","beacon-init","SKILL.md")),"beacon-refresh":n(N($,".agents","skills","beacon-refresh","SKILL.md"))}}}function t9($){let Q=[];for(let j of["beacon-init","beacon-refresh","beacon-db-design"]){let B=N($,".claude","skills",j);if(n(B))v0(B,{recursive:!0,force:!0}),Q.push(j)}for(let j of["beacon-init","beacon-refresh"]){let B=N($,".agents","skills",j);if(n(B))v0(B,{recursive:!0,force:!0}),Q.push(`codex:${j}`)}let Z=!1,Y=N($,".mcp.json");try{let j=JSON.parse(_(Y,"utf8"));if(j.mcpServers?.beacon){if(delete j.mcpServers.beacon,Z=!0,j.mcpServers&&Object.keys(j.mcpServers).length===0)delete j.mcpServers;if(Object.keys(j).length===0)v0(Y,{force:!0});else T(Y,JSON.stringify(j,null,2)+`
|
|
14
|
+
`)}}catch{}let X=!1,H=N($,"AGENTS.md");try{let j=_(H,"utf8"),B=new RegExp(`\\n?${F0}[\\s\\S]*?${$5}\\n?`);if(B.test(j)){let b=j.replace(B,`
|
|
15
15
|
`).replace(/\n{3,}/g,`
|
|
16
16
|
|
|
17
|
-
`).trimStart();T(H,
|
|
18
|
-
`)?
|
|
19
|
-
`),X=!0}}catch{}let G=!1,U=N($,"CLAUDE.md");try{let j=_(U,"utf8"),
|
|
17
|
+
`).trimStart();T(H,b.endsWith(`
|
|
18
|
+
`)?b:`${b}
|
|
19
|
+
`),X=!0}}catch{}let G=!1,U=N($,"CLAUDE.md");try{let j=_(U,"utf8"),B=j.replace(/^[ \t]*@AGENTS\.md[ \t]*\n?/m,"");if(B!==j){if(!B.trim())v0(U,{force:!0});else T(U,B);G=!0}}catch{}return{skillsRemoved:Q,mcpUnregistered:Z,agentsBlockRemoved:X,claudeImportRemoved:G}}var t0=`---
|
|
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
|
---
|
|
@@ -63,7 +63,7 @@ beacon init-persist /tmp/beacon-init.json # or: beacon init-persist < /tmp/bea
|
|
|
63
63
|
That one command wires the repo (writes \`.mcp.json\` + skills so your NEXT session gets the \`beacon_*\` tools natively, heals the global install), starts the Beacon daemon if it isn't running, registers + provisions this workspace, and POSTs your analysis to the same \`/api/init\` endpoint the MCP tool uses \u2014 so init completes in THIS session. Read the counts it prints and report them.
|
|
64
64
|
|
|
65
65
|
After the tool (or \`beacon init-persist\`) returns, tell the user the counts (components / roadmap / tables / endpoints) and point them at the running Beacon panel.
|
|
66
|
-
`,
|
|
66
|
+
`,e0=`---
|
|
67
67
|
name: beacon-refresh
|
|
68
68
|
description: Re-survey the repo and update Beacon's architecture / schema / endpoints map after /beacon-init was already run \u2014 picks up new components, removed ones, schema changes, and new routes. Use when the user runs /beacon-refresh or asks to "refresh", "update", "re-sync", or "bring Beacon up to date" with the current code.
|
|
69
69
|
---
|
|
@@ -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
|
-
`,
|
|
113
|
+
`,u5=`---
|
|
114
114
|
name: beacon-plan
|
|
115
115
|
description: Present your current plan or approach to the user on Beacon's /plan canvas for review \u2014 instead of asking for approval in prose. Use when the user says "present the plan", "show me the plan", "let me see it / the plan", or whenever you are about to end a turn asking whether to proceed with a plan, design, or approach.
|
|
116
116
|
---
|
|
@@ -158,7 +158,7 @@ If it returns feedback, revise and call it again.
|
|
|
158
158
|
If \`beacon_present_plan\` isn't available, the panel isn't wired here \u2014 fall back to ExitPlanMode
|
|
159
159
|
with the same \`\`\`beacon block (Claude Code only; Codex has no ExitPlanMode), or tell the user to
|
|
160
160
|
run \`beacon\` in this repo once.
|
|
161
|
-
`,
|
|
161
|
+
`,g5=`---
|
|
162
162
|
name: beacon-explain
|
|
163
163
|
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".
|
|
164
164
|
---
|
|
@@ -214,6 +214,13 @@ push depth into \`detail\`, not the node face. Supply \`steps\` for the guided w
|
|
|
214
214
|
is the overview (empty \`focusIds\`), then teach one node (or a few) per step in order, each with its
|
|
215
215
|
\`focusIds\`.
|
|
216
216
|
|
|
217
|
+
When the topic involves DATABASE tables, pass them in \`tables\` (they render as annotated schema cards
|
|
218
|
+
on the SAME board, not just raw schemas). For each table give a one-line \`note\` (why it exists), mark
|
|
219
|
+
the key columns \`isPk\`, point FKs at another table with \`fkTo: "<that table's id>"\`, give EVERY column a
|
|
220
|
+
short plain-English \`note\`, and add a \`sample\` row or two (the worked example, made concrete). Connect a
|
|
221
|
+
concept to its table with an \`edge\` (e.g. \`persists to\` / \`reads from\`) whose \`toId\` is the table's id \u2014
|
|
222
|
+
so the learner sees the table IN CONTEXT, wired to the code that uses it.
|
|
223
|
+
|
|
217
224
|
## 4. Answer in the loop \u2014 don't stop after one round
|
|
218
225
|
|
|
219
226
|
\`beacon_explain\` returns the user's questions, each tagged \`[q:ID]\`. Answer EACH by calling
|
|
@@ -221,7 +228,7 @@ is the overview (empty \`focusIds\`), then teach one node (or a few) per step in
|
|
|
221
228
|
Every answer must ADD understanding (rationale, trade-off) \u2014 never just restate the question. Expand
|
|
222
229
|
the narrative or add nodes where it helps. Keep looping until the tool reports the user saved or closed
|
|
223
230
|
the lesson.
|
|
224
|
-
`,s9,F0="<!-- beacon:workflow:start -->"
|
|
231
|
+
`,s9,F0="<!-- beacon:workflow:start -->",$5="<!-- beacon:workflow:end -->",h5;var Z5=s(()=>{a0();s9=[{name:"beacon-init",body:()=>t0},{name:"beacon-refresh",body:()=>e0}];h5=`${F0}
|
|
225
232
|
## Beacon \u2014 feature workflow
|
|
226
233
|
|
|
227
234
|
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:
|
|
@@ -293,18 +300,18 @@ Register them all in that single batched call. If a plan added five features, th
|
|
|
293
300
|
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.
|
|
294
301
|
|
|
295
302
|
Pull raw planning data anytime with \`beacon_entities\` (features / architecture / tables / endpoints).
|
|
296
|
-
${
|
|
297
|
-
`)}function
|
|
303
|
+
${$5}`});import{existsSync as D0,mkdirSync as J5,readdirSync as e9,readFileSync as i,rmSync as $$,writeFileSync as O0}from"fs";import{dirname as z5,join as S}from"path";function b5(){return!!process.env.CLAUDE_PLUGIN_ROOT}function m5($=process.env.HOME||process.env.USERPROFILE||""){if(!$)return null;let Q=S($,".claude","plugins");if(!D0(Q))return null;let Z=[Q];for(let Y=0;Y<3&&Z.length;Y++){let X=[];for(let H of Z){let G=S(H,".claude-plugin","plugin.json");try{if(D0(G)&&JSON.parse(i(G,"utf8")).name==="beacon")return H}catch{}try{for(let U of e9(H,{withFileTypes:!0}))if(U.isDirectory())X.push(S(H,U.name))}catch{}}Z=X}return null}function p5($){return m5($)!==null}function Q$($){return/[\\/]\.claude[\\/]plugins[\\/]/.test($)}function Z$($=process.env.HOME||process.env.USERPROFILE||""){if(!$)return null;try{let Q=JSON.parse(i(S($,".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 Y5($){try{return JSON.parse(i($,"utf8"))}catch{return{}}}function c5($,Q){J5(z5($),{recursive:!0}),O0($,JSON.stringify(Q,null,2)+`
|
|
304
|
+
`)}function A0($,Q){let Z=Y5($);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}]}),c5($,Z),!0}function E0($,Q){return(Y5($).hooks?.[Q.event]??[]).some((X)=>X.hooks?.some((H)=>H.command===Q.command))}function T0($,Q){let Z=Y5($),Y=Z.hooks?.[Q.event];if(!Y)return!1;let X=!1,H=Y.map((G)=>{let U=G.hooks?.length??0,j=(G.hooks??[]).filter((B)=>B.command!==Q.command);if(j.length!==U)X=!0;return{...G,hooks:j}}).filter((G)=>(G.hooks??[]).length>0);if(!X)return!1;if(H.length)Z.hooks[Q.event]=H;else delete Z.hooks[Q.event];if(Z.hooks&&Object.keys(Z.hooks).length===0)delete Z.hooks;return c5($,Z),!0}function I0($,Q,Z,Y){let X=`${Q}
|
|
298
305
|
${Y.trim()}
|
|
299
|
-
${Z}`,H="";try{H
|
|
306
|
+
${Z}`,H="";try{H=i($,"utf8")}catch{}let G=new RegExp(`${Q}[\\s\\S]*?${Z}`);H=G.test(H)?H.replace(G,X):H.trim()?`${H.trim()}
|
|
300
307
|
|
|
301
308
|
${X}
|
|
302
309
|
`:`${X}
|
|
303
|
-
`,
|
|
310
|
+
`,J5(z5($),{recursive:!0}),O0($,H.endsWith(`
|
|
304
311
|
`)?H:`${H}
|
|
305
|
-
`)}function
|
|
312
|
+
`)}function Z0($,Q){try{return i($,"utf8").includes(Q)}catch{return!1}}function k0($,Q,Z){let Y="";try{Y=i($,"utf8")}catch{return!1}let X=new RegExp(`${Q}[\\s\\S]*?${Z}\\n?`);if(!X.test(Y))return!1;let H=Y.replace(X,"").replace(/\n{3,}/g,`
|
|
306
313
|
|
|
307
|
-
`).trimStart();return
|
|
314
|
+
`).trimStart();return O0($,H),!0}function _0($,Q,Z){let Y=S($,Q);J5(Y,{recursive:!0});let X=S(Y,"SKILL.md");return O0(X,Z),X}function J0($,Q){return D0(S($,Q,"SKILL.md"))}function L0($,Q){let Z=S($,Q);if(!D0(Z))return!1;return $$(Z,{recursive:!0,force:!0}),!0}var f,R0=`## Beacon (visual planning panel)
|
|
308
315
|
|
|
309
316
|
This machine has Beacon installed \u2014 a local visual planning surface for the terminal-side
|
|
310
317
|
agent. Beacon proposes feature plans (roadmap features + DB schema + endpoints) via MCP,
|
|
@@ -328,41 +335,41 @@ the user reviews on a canvas at /plan, and feedback flows back as the next round
|
|
|
328
335
|
Feedback bundles inline annotations on the markdown PLUS any edits the user made directly
|
|
329
336
|
on the /map and /db boards (added features, attached subtasks, edited columns, new
|
|
330
337
|
endpoints). Treat board edits as the user's revision intent \u2014 re-propose matching them
|
|
331
|
-
verbatim. Do NOT implement until the tool returns approval.`;var
|
|
338
|
+
verbatim. Do NOT implement until the tool returns approval.`;var V5=s(()=>{f=["beacon-init","beacon-refresh","beacon-plan","beacon-explain"]});import{mkdirSync as J$,renameSync as Y$,rmSync as V$,writeFileSync as X$}from"fs";import{dirname as H$}from"path";function y0($,Q){J$(H$($),{recursive:!0});let Z=`${$}.tmp`;try{X$(Z,Q),Y$(Z,$)}catch(Y){throw V$(Z,{force:!0}),Y}}function eQ($,Q,Z=!1){y0($,JSON.stringify(Q,null,Z?2:void 0))}var l5=()=>{};var t5={};$0(t5,{setupCodexAssets:()=>U$,removeCodexMcp:()=>a5,removeCodexArtifacts:()=>K$,hasCodexMcp:()=>j5,ensureCodexMcp:()=>r5,codexMcpProblem:()=>W$,codexDetected:()=>s5,auditCodex:()=>B$,CODEX_HOOKS:()=>u0});import{readFileSync as h0}from"fs";import{homedir as G$}from"os";import{join as X0}from"path";function d5(){return process.env.HOME||process.env.USERPROFILE||G$()}function s5(){if(process.env.BEACON_CODEX==="1")return!0;if(process.env.BEACON_CODEX==="0")return!1;if(X5===void 0)X5=Bun.which("codex")!==null;return X5}function V0($){try{return Bun.TOML.parse($)}catch{return null}}function j5(){try{return Boolean(V0(h0(r(),"utf8"))?.mcp_servers?.beacon)}catch{return!1}}function W$(){let $="";try{$=h0(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{$=h0(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(`
|
|
332
339
|
`)?`
|
|
333
340
|
`:`
|
|
334
341
|
|
|
335
|
-
`,Y=$+Z+
|
|
336
|
-
`),Z=Q.indexOf(
|
|
342
|
+
`,Y=$+Z+j$;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 a5(){let $="";try{$=h0(r(),"utf8")}catch{return{removed:!1}}let Q=$.split(`
|
|
343
|
+
`),Z=Q.indexOf(n5);if(Z===-1)return{removed:!1,skipped:j5()};let Y=Q.indexOf(i5,Z);if(Y===-1)return{removed:!1,skipped:!0};Q.splice(Z,Y-Z+1);let X=Q.join(`
|
|
337
344
|
`).replace(/\n{3,}/g,`
|
|
338
345
|
|
|
339
|
-
`).replace(/^\n+/,"");if(
|
|
346
|
+
`).replace(/^\n+/,"");if(V0(X)===null)return{removed:!1,skipped:!0};return y0(r(),X),{removed:!0}}async function U$(){let{INIT_SKILL:$,REFRESH_SKILL:Q,PLAN_SKILL:Z,EXPLAIN_SKILL:Y}=await Promise.resolve().then(() => (Z5(),Q5)),X={"beacon-init":$,"beacon-refresh":Q,"beacon-plan":Z,"beacon-explain":Y},H=[];for(let B of f){if(!J0(S0(),B))H.push(B);_0(S0(),B,X[B])}let G=0;for(let B of u0)if(A0(G5(),{event:B.event,matcher:B.matcher,command:B.command}))G++;let U=Z0(x0(),f0);I0(x0(),f0,o5,R0);let j=r5();return{skillsAdded:H,hooksAdded:G,agentsMdBlockTouched:!U,mcp:j}}function B$(){let $={};for(let Z of f)$[Z]=J0(S0(),Z);let Q={};for(let Z of u0)Q[Z.event]=E0(G5(),{event:Z.event,command:Z.command});return{detected:s5(),skills:$,hooks:Q,agentsMdBlock:Z0(x0(),f0),mcp:j5()}}function K$(){let $=[];for(let X of f)if(L0(S0(),X))$.push(X);let Q=0;for(let X of u0)if(T0(G5(),{event:X.event,command:X.command}))Q++;let Z=k0(x0(),f0,o5),Y=a5();return{skillsRemoved:$,hooksRemoved:Q,agentsMdBlockRemoved:Z,mcpRemoved:Y.removed,mcpSkipped:Y.skipped}}var H5=()=>X0(d5(),".codex"),G5=()=>X0(H5(),"hooks.json"),r=()=>X0(H5(),"config.toml"),x0=()=>X0(H5(),"AGENTS.md"),S0=()=>X0(d5(),".agents","skills"),f0="<!-- beacon:global:start -->",o5="<!-- beacon:global:end -->",u0,X5,n5="# beacon:start (managed by Beacon \u2014 `beacon uninstall` removes this block)",i5="# beacon:end",j$,Y0="add it manually: codex mcp add beacon -- beacon mcp";var e5=s(()=>{V5();l5();u0=[{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."}];j$=`${n5}
|
|
340
347
|
[mcp_servers.beacon]
|
|
341
348
|
command = "beacon"
|
|
342
349
|
args = ["mcp"]
|
|
343
|
-
${
|
|
344
|
-
`});var Y9={};t(Y9,{provisionDb:()=>f$});import{createClient as A$}from"@libsql/client";import{drizzle as E$}from"drizzle-orm/libsql";import{migrate as T$}from"drizzle-orm/libsql/migrator";import{readMigrationFiles as I$}from"drizzle-orm/migrator";import{dirname as N5,join as k$}from"path";import{fileURLToPath as _$}from"url";async function g0($,Q){return(await $.execute({sql:"SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?",args:[Q]})).rows.length>0}async function S$($,Q){let Z=await $.execute(`PRAGMA table_info("${Q}")`);return new Set(Z.rows.map((Y)=>String(Y.name)))}async function J9($){if(!await g0($,"__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(x$)){if(!await g0($,Q))continue;let Y=await S$($,Q);for(let X of Z){if(!Y.has(X))continue;await $.execute(`UPDATE "${Q}" SET "${X}" = CAST((julianday("${X}") - 2440587.5) * 86400000 AS INTEGER) WHERE typeof("${X}") = 'text'`)}}}async function f$($,Q=y$){let Z=A$({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 g0(Z,"__drizzle_migrations"),X=await g0(Z,"Node"),H=!1;if(X&&!Y){let U=I$({migrationsFolder:Q})[0];if(U)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:[U.hash,U.folderMillis]}),H=!0}let G=await J9(Z);if(await T$(E$(Z),{migrationsFolder:Q}),await J9(Z)>G)H=!0;return await z$(Z),{migrated:H}}finally{Z.close()}}var L$,y$,x$;var V9=o(async()=>{L$=N5(N5(N5(_$(import.meta.url)))),y$=process.env.BEACON_MIGRATIONS_DIR||k$(L$,"drizzle"),x$={Node:["createdAt","updatedAt"],Note:["createdAt","updatedAt"],DbTable:["createdAt","updatedAt"],Endpoint:["createdAt","updatedAt"],DraftTable:["createdAt"],SyncState:["codeGraphSyncedAt","updatedAt"],AppSetting:["updatedAt"],ProjectMeta:["updatedAt"],CodeFile:["updatedAt"]}});Y5();import{existsSync as B$}from"fs";import{homedir as K$}from"os";import{join as h0}from"path";function N$(){return process.env.HOME||process.env.USERPROFILE||K$()}var u0=()=>h0(N$(),".claude"),j5=()=>h0(u0(),"skills"),W5=()=>h0(u0(),"settings.json"),U5=()=>h0(u0(),"CLAUDE.md"),B5="<!-- beacon:global:start -->",e5="<!-- beacon:global:end -->";var M$=O0,K5=[{event:"PreToolUse",matcher:"Edit|Write|MultiEdit",command:"beacon guard",description:"Gate edits against the active plan's scope contract (when the scope-guard flag is on): in-scope \u2192 allow, off-scope \u2192 ask the user to authorize. No-op + fail-open otherwise."},{event:"PostToolUse",matcher:"Edit|Write|MultiEdit",command:"beacon hook",description:"Report file edits to Beacon's active feature so the map stays fresh."},{event:"PermissionRequest",matcher:"ExitPlanMode",command:"beacon plan",description:"Pipe the agent's plan markdown into Beacon's /plan canvas for review."},{event:"UserPromptSubmit",matcher:"*",command:"beacon prompt",description:"On feature-y prompts in a Beacon-wired repo, remind the agent to run the context\u2192propose\u2192describe loop (no-op otherwise)."},{event:"Stop",matcher:"*",command:"beacon stop-hook",description:"When the agent ends a turn asking for plan approval in prose (instead of presenting it), nudge it to present the plan on Beacon's /plan canvas. Bounded by stop_hook_active \u2014 at most one nudge."}];function q$($,Q){return k0(j5(),$,Q)}function $9($){return Z0(j5(),$)}function P$($){return _0(j5(),$)}function C$($){return R0(W5(),$)}function w$($){return A0(W5(),$)}function F$($){return E0(W5(),$)}function v$($){T0(U5(),B5,e5,$)}function Q9(){return Q0(U5(),B5)}function D$(){return I0(U5(),B5,e5)}function GZ(){let $={};for(let Z of S)$[Z]=$9(Z);let Q={};for(let Z of K5)Q[Z.event]=w$({event:Z.event,command:Z.command});return{homeExists:B$(u0()),skills:$,hooks:Q,claudeMdBlock:Q9()}}async function O$(){let{INIT_SKILL:$,REFRESH_SKILL:Q,PLAN_SKILL:Z,EXPLAIN_SKILL:Y}=await Promise.resolve().then(() => (Q5(),$5)),X={"beacon-init":$,"beacon-refresh":Q,"beacon-plan":Z,"beacon-explain":Y},H=[];for(let j of S){if(!$9(j))H.push(j);q$(j,X[j])}let G=0;for(let j of K5)if(C$({event:j.event,matcher:j.matcher,command:j.command}))G++;let U=Q9();return v$(M$),{skillsAdded:H,hooksAdded:G,claudeMdBlockTouched:!U}}async function Z9(){if(g5())return{ok:!0,skipped:"plugin",skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1};let $;if(m5()){try{R$()}catch{}$={ok:!0,skipped:"plugin-present",skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1}}else try{$={ok:!0,...await O$()}}catch(Q){$={ok:!1,error:Q instanceof Error?Q.message:String(Q),skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1}}try{let Q=await Promise.resolve().then(() => (t5(),a5));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 R$(){let $=[];for(let Y of S)if(P$(Y))$.push(Y);let Q=0;for(let Y of K5)if(F$(Y))Q++;let Z=D$();return{skillsRemoved:$,hooksRemoved:Q,claudeMdBlockRemoved:Z}}import{AsyncLocalStorage as h$}from"async_hooks";import{spawnSync as u$}from"child_process";import{createHash as g$}from"crypto";import{existsSync as H9,mkdirSync as X0,readFileSync as q5,writeFileSync as P5}from"fs";import{homedir as G9}from"os";import{basename as b$,join as z,parse as m$,resolve as X9}from"path";function L(){return process.env.BEACON_HOME||z(G9(),".beacon")}function C5(){return z(L(),"workspaces.json")}function i($){return g$("sha256").update($).digest("hex").slice(0,12)}function j9($=process.cwd()){let Q=u$("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 b0($){let Q=X9($);return Q!==X9(G9())&&Q!==m$(Q).root}function W9(){return z(L(),"deleted.json")}function w5(){try{let $=JSON.parse(q5(W9(),"utf8"));return Array.isArray($)?$:[]}catch{return[]}}function U9($){X0(L(),{recursive:!0}),P5(W9(),JSON.stringify($,null,2))}function m0($){return w5().includes($)}function DZ($){let Q=w5();if(!Q.includes($))U9([...Q,$])}function p$($){let Q=w5();if(Q.includes($))U9(Q.filter((Z)=>Z!==$))}function p0($){return z(L(),$)}function F5($){return`file:${z(p0($),"db.sqlite")}`}function H0(){try{let $=JSON.parse(q5(C5(),"utf8"));return Array.isArray($)?$:[]}catch{return[]}}function v5($){X0(L(),{recursive:!0}),P5(C5(),JSON.stringify($,null,2))}function c0(){return H0().sort(($,Q)=>Q.lastOpenedAt.localeCompare($.lastOpenedAt))}function b($){return H0().find((Q)=>Q.id===$)??null}function l0($,Q,Z=new Date().toISOString()){if(!b0($))throw Error(`beacon: refusing to register a non-repo path as a workspace: ${$}`);let Y=i($);if(m0(Y))throw Error(`beacon: workspace ${Y} (${$}) was deleted \u2014 run \`beacon\` or /beacon-init to re-add it`);let X=H0(),H=X.find((j)=>j.id===Y),G={id:Y,path:$,name:Q||H?.name||b$($),lastOpenedAt:Z},U=[G,...X.filter((j)=>j.id!==Y)];return X0(p0(Y),{recursive:!0}),v5(U),G}function OZ($,Q){return p$(i($)),l0($,Q)}function RZ($,Q=new Date().toISOString()){let Z=H0(),Y=Z.find((X)=>X.id===$);if(!Y)return;Y.lastOpenedAt=Q,v5(Z)}function AZ($){if(v5(H0().filter((Q)=>Q.id!==$)),G0()===$)c$(c0()[0]?.id??null)}function B9(){return z(L(),"active")}function G0(){try{return q5(B9(),"utf8").trim()||null}catch{return null}}function c$($){X0(L(),{recursive:!0}),P5(B9(),$??"")}function EZ(){let $=G0();return $?b($):null}function TZ(){let $=O5()??G0();return $?b($):null}function IZ($){return b($)?.path??null}function kZ(){return H9(C5())}var K9="beacon_ws";function N9($,Q){let Z=$.headers.get("cookie");if(!Z)return null;for(let Y of Z.split(";")){let X=Y.indexOf("=");if(X===-1)continue;if(Y.slice(0,X).trim()===Q)return decodeURIComponent(Y.slice(X+1).trim())}return null}function _Z($){let Q=$.headers.get("x-beacon-workspace");if(Q&&b(Q))return Q;let Z=N9($,K9);if(Z&&b(Z))return Z;return l$()}function l$(){let $=c0();return $.length===1?$[0].id:null}var D5="x-beacon-workspace-path";async function LZ($){let Q=$.headers.get("x-beacon-workspace");if(Q&&b(Q))return Q;let Z=$.headers.get(D5);if(Z&&b0(Z)&&!m0(i(Z))&&(!Q||i(Z)===Q)){let X=l0(Z);return await R5(X.id),X.id}let Y=N9($,K9);if(Y&&b(Y))return Y;return null}var M9=new h$;function d$($,Q){return $?M9.run($,Q):Q()}function O5(){return M9.getStore()??null}var M5=new Set;function yZ($){M5.delete(z(p0($),"db.sqlite"))}async function R5($){let Q=p0($),Z=z(Q,"db.sqlite"),Y=H9(Z);if(Y&&M5.has(Z))return{ok:!0,created:!1,migrated:!1};try{X0(Q,{recursive:!0});let{provisionDb:X}=await V9().then(() => Y9),H=await X(F5($));return M5.add(Z),{ok:!0,created:!Y,migrated:Y&&H.migrated}}catch(X){return{ok:!1,created:!1,migrated:!1,error:X instanceof Error?X.message:String(X)}}}import{connect as o$}from"net";var q9=4319;function s$($,Q,Z=400){return new Promise((Y)=>{let X=o$({host:$,port:Q}),H=!1,G=(U)=>{if(H)return;H=!0,X.destroy(),Y(U)};X.once("connect",()=>G(!0)),X.once("error",()=>G(!1)),X.setTimeout(Z,()=>G(!1))})}async function n$($){for(let Q of["127.0.0.1","::1"])if(await s$(Q,$))return!1;return!0}async function zZ($,Q=20){for(let Z=$;Z<$+Q;Z++)if(await n$(Z))return Z;return $}import{McpServer as uQ,ResourceTemplate as y5}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as gQ}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as J}from"zod";import{z as B}from"zod";var i$=new Set(["GET","HEAD","OPTIONS"]);function P9($){return i$.has($.trim().toUpperCase())?"read":"write"}var r$=B.preprocess(($)=>{if(typeof $==="string"){let[Q,...Z]=$.trim().split(/\s+/);return{name:Q,type:Z.join(" ")||"text"}}return $},B.object({name:B.string().trim().min(1),type:B.string().trim().min(1),isPk:B.boolean().optional(),isFk:B.boolean().optional(),nullable:B.boolean().optional(),note:B.string().nullish()})),C9=B.object({name:B.string().trim().min(1),domain:B.string().nullish(),description:B.string().nullish(),columns:B.array(r$).default([])}),w9=B.object({fromTable:B.string(),fromColumn:B.string(),toTable:B.string(),toColumn:B.string(),label:B.string().nullish()}),F9=B.object({method:B.string().trim().min(1),path:B.string().trim().min(1),domain:B.string().nullish(),description:B.string().nullish(),uses:B.array(B.object({table:B.string().trim().min(1),access:B.string().optional()})).default([])}).transform(($)=>({...$,uses:$.uses.map((Q)=>({...Q,access:Q.access??P9($.method)}))})),bZ=B.object({tables:B.array(C9).default([]),relations:B.array(w9).default([]),endpoints:B.array(F9).default([])});import{z as R}from"zod";import{and as j1,eq as W1,inArray as U1}from"drizzle-orm";import{drizzle as DQ}from"drizzle-orm/libsql";import{createClient as OQ}from"@libsql/client";var A5={};t(A5,{workspaceFlag:()=>YQ,tag:()=>r,syncState:()=>QQ,projectMeta:()=>JQ,planContract:()=>VQ,note:()=>e$,nodeTags:()=>m,nodeFile:()=>j0,node:()=>q,endpointTable:()=>c,endpoint:()=>a,edge:()=>f,draftTable:()=>I,draftRelation:()=>l,draftColumn:()=>B0,dbTable:()=>D,dbRelation:()=>p,dbColumn:()=>U0,codeFileEdge:()=>d,codeFile:()=>y,bugFlag:()=>W0,boardAnnotation:()=>$Q,appSetting:()=>ZQ});import{sqliteTable as P,index as M,foreignKey as a$,text as V,integer as W,real as O,uniqueIndex as k,primaryKey as t$}from"drizzle-orm/sqlite-core";import{createId as F}from"@paralleldrive/cuid2";var q=P("Node",{id:V().primaryKey().$defaultFn(()=>F()),view:V().notNull(),kind:V().default("FEATURE").notNull(),cluster:V(),layer:V(),title:V().notNull(),role:V(),plain:V(),status:V().default("PENDING").notNull(),priority:W().default(2).notNull(),progress:W().default(0).notNull(),x:O().default(0).notNull(),y:O().default(0).notNull(),sourceRef:V(),externalId:V(),source:V().default("MANUAL").notNull(),planId:V(),parentId:V(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[M("Node_cluster_idx").on($.cluster),M("Node_parentId_idx").on($.parentId),M("Node_view_idx").on($.view),a$(()=>({columns:[$.parentId],foreignColumns:[$.id],name:"Node_parentId_Node_id_fk"})).onUpdate("cascade").onDelete("cascade")]),j0=P("NodeFile",{id:V().primaryKey().$defaultFn(()=>F()),nodeId:V().notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),path:V().notNull()},($)=>[k("NodeFile_nodeId_path_key").on($.nodeId,$.path),M("NodeFile_nodeId_idx").on($.nodeId)]),r=P("Tag",{id:V().primaryKey().$defaultFn(()=>F()),label:V().notNull(),color:V()},($)=>[k("Tag_label_key").on($.label)]),f=P("Edge",{id:V().primaryKey().$defaultFn(()=>F()),fromId:V().notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),toId:V().notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),kind:V().default("DEPENDS").notNull(),label:V(),sourceHandle:V(),targetHandle:V()},($)=>[k("Edge_fromId_toId_kind_key").on($.fromId,$.toId,$.kind),M("Edge_toId_idx").on($.toId),M("Edge_fromId_idx").on($.fromId)]),m=P("_NodeTags",{a:V("A").notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),b:V("B").notNull().references(()=>r.id,{onDelete:"cascade",onUpdate:"cascade"})},($)=>[k("_NodeTags_AB_unique").on($.a,$.b),M("_NodeTags_B_index").on($.b)]),e$=P("Note",{id:V().primaryKey().$defaultFn(()=>F()),title:V().default("Untitled").notNull(),body:V().default("").notNull(),ord:O().default(0).notNull(),pinned:W({mode:"boolean"}).default(!1).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[M("Note_updatedAt_idx").on($.updatedAt)]),$Q=P("BoardAnnotation",{id:V().primaryKey().$defaultFn(()=>F()),targetKind:V().notNull(),targetId:V().notNull(),columnName:V(),body:V().default("").notNull(),x:O(),y:O(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[M("BoardAnnotation_target_idx").on($.targetId)]),W0=P("BugFlag",{id:V().primaryKey().$defaultFn(()=>F()),nodeId:V().notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),by:V().notNull(),note:V().notNull(),resolvedAt:W({mode:"timestamp_ms"}),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date)},($)=>[M("BugFlag_nodeId_idx").on($.nodeId)]),D=P("DbTable",{id:V().primaryKey().$defaultFn(()=>F()),name:V().notNull(),domain:V(),description:V(),source:V().default("MANUAL").notNull(),planId:V(),x:O().default(0).notNull(),y:O().default(0).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[M("DbTable_domain_idx").on($.domain),k("DbTable_name_key").on($.name)]),U0=P("DbColumn",{id:V().primaryKey().$defaultFn(()=>F()),tableId:V().notNull().references(()=>D.id,{onDelete:"cascade",onUpdate:"cascade"}),name:V().notNull(),type:V().notNull(),isPk:W({mode:"boolean"}).default(!1).notNull(),isFk:W({mode:"boolean"}).default(!1).notNull(),nullable:W({mode:"boolean"}).default(!0).notNull(),note:V(),ord:W().default(0).notNull()},($)=>[k("DbColumn_tableId_name_key").on($.tableId,$.name),M("DbColumn_tableId_idx").on($.tableId)]),p=P("DbRelation",{id:V().primaryKey().$defaultFn(()=>F()),fromTableId:V().notNull().references(()=>D.id,{onDelete:"cascade",onUpdate:"cascade"}),toTableId:V().notNull().references(()=>D.id,{onDelete:"cascade",onUpdate:"cascade"}),fromColumn:V().notNull(),toColumn:V().notNull(),label:V()},($)=>[M("DbRelation_toTableId_idx").on($.toTableId),M("DbRelation_fromTableId_idx").on($.fromTableId)]),a=P("Endpoint",{id:V().primaryKey().$defaultFn(()=>F()),method:V().notNull(),path:V().notNull(),domain:V(),description:V(),source:V().default("MANUAL").notNull(),planId:V(),x:O().default(0).notNull(),y:O().default(0).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[k("Endpoint_method_path_key").on($.method,$.path),M("Endpoint_domain_idx").on($.domain)]),c=P("EndpointTable",{id:V().primaryKey().$defaultFn(()=>F()),endpointId:V().notNull().references(()=>a.id,{onDelete:"cascade",onUpdate:"cascade"}),tableId:V().notNull().references(()=>D.id,{onDelete:"cascade",onUpdate:"cascade"}),access:V().default("read").notNull()},($)=>[k("EndpointTable_endpointId_tableId_key").on($.endpointId,$.tableId),M("EndpointTable_tableId_idx").on($.tableId)]),I=P("DraftTable",{id:V().primaryKey().$defaultFn(()=>F()),name:V().notNull(),domain:V(),description:V(),x:O().default(0).notNull(),y:O().default(0).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date)},($)=>[k("DraftTable_name_key").on($.name)]),B0=P("DraftColumn",{id:V().primaryKey().$defaultFn(()=>F()),tableId:V().notNull().references(()=>I.id,{onDelete:"cascade",onUpdate:"cascade"}),name:V().notNull(),type:V().notNull(),isPk:W({mode:"boolean"}).default(!1).notNull(),isFk:W({mode:"boolean"}).default(!1).notNull(),nullable:W({mode:"boolean"}).default(!0).notNull(),note:V(),ord:W().default(0).notNull()},($)=>[M("DraftColumn_tableId_idx").on($.tableId)]),l=P("DraftRelation",{id:V().primaryKey().$defaultFn(()=>F()),fromTableId:V().notNull().references(()=>I.id,{onDelete:"cascade",onUpdate:"cascade"}),toTableId:V().notNull().references(()=>I.id,{onDelete:"cascade",onUpdate:"cascade"}),fromColumn:V().notNull(),toColumn:V().notNull(),label:V()},($)=>[M("DraftRelation_toTableId_idx").on($.toTableId),M("DraftRelation_fromTableId_idx").on($.fromTableId)]),y=P("CodeFile",{path:V().primaryKey(),root:V(),lang:V(),x:O().default(0).notNull(),y:O().default(0).notNull(),mtimeMs:O(),size:W(),inDegree:W().default(0).notNull(),outDegree:W().default(0).notNull(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),d=P("CodeFileEdge",{fromPath:V().notNull().references(()=>y.path,{onDelete:"cascade",onUpdate:"cascade"}),toPath:V().notNull().references(()=>y.path,{onDelete:"cascade",onUpdate:"cascade"}),circular:W({mode:"boolean"}).default(!1).notNull()},($)=>[M("CodeFileEdge_circular_idx").on($.circular),M("CodeFileEdge_toPath_idx").on($.toPath),M("CodeFileEdge_fromPath_idx").on($.fromPath),t$({columns:[$.fromPath,$.toPath],name:"CodeFileEdge_fromPath_toPath_pk"})]),QQ=P("SyncState",{id:V().primaryKey().default("singleton"),version:W().default(0).notNull(),codeGraphSyncedAt:W({mode:"timestamp_ms"}),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),ZQ=P("AppSetting",{id:V().primaryKey().default("singleton"),editor:V().default("auto").notNull(),currentFeatureId:V(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),JQ=P("ProjectMeta",{id:V().primaryKey().default("singleton"),overview:V(),conventions:V().default("[]").notNull(),hasFrontend:W({mode:"boolean"}),classificationRoots:V().default("[]").notNull(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),YQ=P("WorkspaceFlag",{id:V().primaryKey().$defaultFn(()=>F()),key:V().notNull(),enabled:W({mode:"boolean"}).default(!1).notNull(),config:V(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[k("WorkspaceFlag_key_key").on($.key)]),VQ=P("PlanContract",{id:V().primaryKey().$defaultFn(()=>F()),planId:V().notNull(),declaredFiles:V().default("[]").notNull(),authorizedExtras:V().default("[]").notNull(),active:W({mode:"boolean"}).default(!1).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[k("PlanContract_planId_key").on($.planId),M("PlanContract_active_idx").on($.active)]);var E5={};t(E5,{tagRelations:()=>jQ,nodeTagsRelations:()=>WQ,nodeRelations:()=>XQ,nodeFileRelations:()=>HQ,endpointTableRelations:()=>qQ,endpointRelations:()=>MQ,edgeRelations:()=>UQ,draftTableRelations:()=>PQ,draftRelationRelations:()=>wQ,draftColumnRelations:()=>CQ,dbTableRelations:()=>BQ,dbRelationRelations:()=>NQ,dbColumnRelations:()=>KQ,codeFileRelations:()=>FQ,codeFileEdgeRelations:()=>vQ,bugFlagRelations:()=>GQ});import{relations as v}from"drizzle-orm";var XQ=v(q,({one:$,many:Q})=>({files:Q(j0),bugFlags:Q(W0),nodeTags:Q(m),edgesOut:Q(f,{relationName:"EdgeFrom"}),edgesIn:Q(f,{relationName:"EdgeTo"}),parent:$(q,{fields:[q.parentId],references:[q.id],relationName:"NodeTree"}),children:Q(q,{relationName:"NodeTree"})})),HQ=v(j0,({one:$})=>({node:$(q,{fields:[j0.nodeId],references:[q.id]})})),GQ=v(W0,({one:$})=>({node:$(q,{fields:[W0.nodeId],references:[q.id]})})),jQ=v(r,({many:$})=>({nodeTags:$(m)})),WQ=v(m,({one:$})=>({node:$(q,{fields:[m.a],references:[q.id]}),tag:$(r,{fields:[m.b],references:[r.id]})})),UQ=v(f,({one:$})=>({from:$(q,{fields:[f.fromId],references:[q.id],relationName:"EdgeFrom"}),to:$(q,{fields:[f.toId],references:[q.id],relationName:"EdgeTo"})})),BQ=v(D,({many:$})=>({columns:$(U0),fksOut:$(p,{relationName:"FkFrom"}),fksIn:$(p,{relationName:"FkTo"}),usages:$(c)})),KQ=v(U0,({one:$})=>({table:$(D,{fields:[U0.tableId],references:[D.id]})})),NQ=v(p,({one:$})=>({fromTable:$(D,{fields:[p.fromTableId],references:[D.id],relationName:"FkFrom"}),toTable:$(D,{fields:[p.toTableId],references:[D.id],relationName:"FkTo"})})),MQ=v(a,({many:$})=>({tables:$(c)})),qQ=v(c,({one:$})=>({endpoint:$(a,{fields:[c.endpointId],references:[a.id]}),table:$(D,{fields:[c.tableId],references:[D.id]})})),PQ=v(I,({many:$})=>({columns:$(B0),fksOut:$(l,{relationName:"DraftFkFrom"}),fksIn:$(l,{relationName:"DraftFkTo"})})),CQ=v(B0,({one:$})=>({table:$(I,{fields:[B0.tableId],references:[I.id]})})),wQ=v(l,({one:$})=>({fromTable:$(I,{fields:[l.fromTableId],references:[I.id],relationName:"DraftFkFrom"}),toTable:$(I,{fields:[l.toTableId],references:[I.id],relationName:"DraftFkTo"})})),FQ=v(y,({many:$})=>({edgesOut:$(d,{relationName:"CFEFrom"}),edgesIn:$(d,{relationName:"CFETo"})})),vQ=v(d,({one:$})=>({fromFile:$(y,{fields:[d.fromPath],references:[y.path],relationName:"CFEFrom"}),toFile:$(y,{fields:[d.toPath],references:[y.path],relationName:"CFETo"})}));var RQ={...A5,...E5};function AQ(){let $=process.env.DATABASE_URL;if($&&/^(file:|libsql:|wss?:|https?:|:memory:)/i.test($))return $;return"file:./dev.db"}var EQ=AQ();function v9($){let Q=OQ({url:$});return Q.execute("PRAGMA foreign_keys = ON;"),Q.execute("PRAGMA busy_timeout = 5000;"),DQ(Q,{schema:RQ})}var I5=globalThis,T5=I5.dzDefault??v9(EQ);I5.dzDefault=T5;var d0=I5.dzByUrl??=new Map;function TQ($){let Q=d0.get($);if(!Q)Q=v9($),d0.set($,Q);return Q}function iZ($){let Q=d0.get($);d0.delete($);try{Q?.$client?.close?.()}catch{}}function IQ(){if(process.env.BEACON_REPO)return T5;let $=O5()??G0();if(!$)return T5;return TQ(F5($))}var kQ=new Proxy({},{get($,Q){let Z=IQ(),Y=Z[Q];return typeof Y==="function"?Y.bind(Z):Y}});var _Q=["frontend","backend","fullstack"],LQ={fe:"frontend",front:"frontend",be:"backend",back:"backend",fs:"fullstack","full-stack":"fullstack","full stack":"fullstack"};function o0($){let Q=($??"").trim().toLowerCase();if(!Q)return null;if(_Q.includes(Q))return Q;return LQ[Q]??null}import{forceCenter as $1,forceCollide as Q1,forceLink as Z1,forceManyBody as J1,forceSimulation as Y1}from"d3-force";var D9=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:X,...H})=>({...H,cluster:H.cluster??$??Q??null,priority:Z==null?null:Math.max(0,Math.min(3,Math.round(Z))),kind:Y?.trim().toUpperCase()==="BUG"?"BUG":"FEATURE",layer:o0(X)})),q1=R.object({features:R.array(D9).default([])});var yQ=/(\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 O9($){return!!$&&yQ.test($)}function R9($,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 xQ($){return $.cluster??$.category??$.domain??null}function A9($,Q){let Z=Q?.requireLayer??!1,Y=$.map((H)=>{let G=[],U=xQ(H);if(!U||!U.trim())G.push("category");if(H.priority==null)G.push("priority");if(Z&&!o0(H.layer))G.push("layer");return G.length?` \u2022 "${H.title?.trim()||"(untitled)"}" \u2014 missing ${G.join(" + ")}`:null}).filter((H)=>H!==null);if(Y.length===0)return null;let X=Z?" This workspace has a frontend surface, so every feature must also carry `layer`: "+'"frontend" | "backend" | "fullstack" \u2014 which side of the stack the work lands on.':"";return"\u26D4 Every roadmap feature needs a category AND a priority \u2014 they drive grouping and ordering "+"on the board, and the user shouldn't have to add them by hand."+X+` Missing:
|
|
350
|
+
${i5}
|
|
351
|
+
`});var V9={};$0(V9,{provisionDb:()=>g$});import{createClient as T$}from"@libsql/client";import{drizzle as I$}from"drizzle-orm/libsql";import{migrate as k$}from"drizzle-orm/libsql/migrator";import{readMigrationFiles as _$}from"drizzle-orm/migrator";import{dirname as M5,join as L$}from"path";import{fileURLToPath as y$}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 Y9($){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 u$($){for(let[Q,Z]of Object.entries(f$)){if(!await b0($,Q))continue;let Y=await h$($,Q);for(let X of Z){if(!Y.has(X))continue;await $.execute(`UPDATE "${Q}" SET "${X}" = CAST((julianday("${X}") - 2440587.5) * 86400000 AS INTEGER) WHERE typeof("${X}") = 'text'`)}}}async function g$($,Q=S$){let Z=T$({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"),X=await b0(Z,"Node"),H=!1;if(X&&!Y){let U=_$({migrationsFolder:Q})[0];if(U)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:[U.hash,U.folderMillis]}),H=!0}let G=await Y9(Z);if(await k$(I$(Z),{migrationsFolder:Q}),await Y9(Z)>G)H=!0;return await u$(Z),{migrated:H}}finally{Z.close()}}var x$,S$,f$;var X9=s(async()=>{x$=M5(M5(M5(y$(import.meta.url)))),S$=process.env.BEACON_MIGRATIONS_DIR||L$(x$,"drizzle"),f$={Node:["createdAt","updatedAt"],Note:["createdAt","updatedAt"],DbTable:["createdAt","updatedAt"],Endpoint:["createdAt","updatedAt"],DraftTable:["createdAt"],SyncState:["codeGraphSyncedAt","updatedAt"],AppSetting:["updatedAt"],ProjectMeta:["updatedAt"],CodeFile:["updatedAt"]}});V5();import{existsSync as N$}from"fs";import{homedir as M$}from"os";import{join as g0}from"path";function q$(){return process.env.HOME||process.env.USERPROFILE||M$()}var z0=()=>g0(q$(),".claude"),W5=()=>g0(z0(),"skills"),U5=()=>g0(z0(),"settings.json"),B5=()=>g0(z0(),"CLAUDE.md"),K5="<!-- beacon:global:start -->",$9="<!-- beacon:global:end -->";var P$=R0,N5=[{event:"PreToolUse",matcher:"Edit|Write|MultiEdit",command:"beacon guard",description:"Gate edits against the active plan's scope contract (when the scope-guard flag is on): in-scope \u2192 allow, off-scope \u2192 ask the user to authorize. No-op + fail-open otherwise."},{event:"PostToolUse",matcher:"Edit|Write|MultiEdit",command:"beacon hook",description:"Report file edits to Beacon's active feature so the map stays fresh."},{event:"PermissionRequest",matcher:"ExitPlanMode",command:"beacon plan",description:"Pipe the agent's plan markdown into Beacon's /plan canvas for review."},{event:"UserPromptSubmit",matcher:"*",command:"beacon prompt",description:"On feature-y prompts in a Beacon-wired repo, remind the agent to run the context\u2192propose\u2192describe loop (no-op otherwise)."},{event:"Stop",matcher:"*",command:"beacon stop-hook",description:"When the agent ends a turn asking for plan approval in prose (instead of presenting it), nudge it to present the plan on Beacon's /plan canvas. Bounded by stop_hook_active \u2014 at most one nudge."}];function C$($,Q){return _0(W5(),$,Q)}function Q9($){return J0(W5(),$)}function w$($){return L0(W5(),$)}function v$($){return A0(U5(),$)}function F$($){return E0(U5(),$)}function D$($){return T0(U5(),$)}function O$($){I0(B5(),K5,$9,$)}function Z9(){return Z0(B5(),K5)}function R$(){return k0(B5(),K5,$9)}function WZ(){let $={};for(let Z of f)$[Z]=Q9(Z);let Q={};for(let Z of N5)Q[Z.event]=F$({event:Z.event,command:Z.command});return{homeExists:N$(z0()),skills:$,hooks:Q,claudeMdBlock:Z9()}}async function A$(){let{INIT_SKILL:$,REFRESH_SKILL:Q,PLAN_SKILL:Z,EXPLAIN_SKILL:Y}=await Promise.resolve().then(() => (Z5(),Q5)),X={"beacon-init":$,"beacon-refresh":Q,"beacon-plan":Z,"beacon-explain":Y},H=[];for(let j of f){if(!Q9(j))H.push(j);C$(j,X[j])}let G=0;for(let j of N5)if(v$({event:j.event,matcher:j.matcher,command:j.command}))G++;let U=Z9();return O$(P$),{skillsAdded:H,hooksAdded:G,claudeMdBlockTouched:!U}}async function J9(){if(b5())return{ok:!0,skipped:"plugin",skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1};let $;if(p5()){try{E$()}catch{}$={ok:!0,skipped:"plugin-present",skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1}}else try{$={ok:!0,...await A$()}}catch(Q){$={ok:!1,error:Q instanceof Error?Q.message:String(Q),skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1}}try{let Q=await Promise.resolve().then(() => (e5(),t5));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 E$(){let $=[];for(let Y of f)if(w$(Y))$.push(Y);let Q=0;for(let Y of N5)if(D$(Y))Q++;let Z=R$();return{skillsRemoved:$,hooksRemoved:Q,claudeMdBlockRemoved:Z}}import{AsyncLocalStorage as z$}from"async_hooks";import{spawnSync as b$}from"child_process";import{createHash as m$}from"crypto";import{existsSync as G9,mkdirSync as H0,readFileSync as P5,writeFileSync as C5}from"fs";import{homedir as j9}from"os";import{basename as p$,join as h,parse as c$,resolve as H9}from"path";function L(){return process.env.BEACON_HOME||h(j9(),".beacon")}function w5(){return h(L(),"workspaces.json")}function a($){return m$("sha256").update($).digest("hex").slice(0,12)}function W9($=process.cwd()){let Q=b$("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=H9($);return Q!==H9(j9())&&Q!==c$(Q).root}function U9(){return h(L(),"deleted.json")}function v5(){try{let $=JSON.parse(P5(U9(),"utf8"));return Array.isArray($)?$:[]}catch{return[]}}function B9($){H0(L(),{recursive:!0}),C5(U9(),JSON.stringify($,null,2))}function p0($){return v5().includes($)}function RZ($){let Q=v5();if(!Q.includes($))B9([...Q,$])}function l$($){let Q=v5();if(Q.includes($))B9(Q.filter((Z)=>Z!==$))}function c0($){return h(L(),$)}function F5($){return`file:${h(c0($),"db.sqlite")}`}function G0(){try{let $=JSON.parse(P5(w5(),"utf8"));return Array.isArray($)?$:[]}catch{return[]}}function D5($){H0(L(),{recursive:!0}),C5(w5(),JSON.stringify($,null,2))}function l0(){return G0().sort(($,Q)=>Q.lastOpenedAt.localeCompare($.lastOpenedAt))}function m($){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=a($);if(p0(Y))throw Error(`beacon: workspace ${Y} (${$}) was deleted \u2014 run \`beacon\` or /beacon-init to re-add it`);let X=G0(),H=X.find((j)=>j.id===Y),G={id:Y,path:$,name:Q||H?.name||p$($),lastOpenedAt:Z},U=[G,...X.filter((j)=>j.id!==Y)];return H0(c0(Y),{recursive:!0}),D5(U),G}function AZ($,Q){return l$(a($)),d0($,Q)}function EZ($,Q=new Date().toISOString()){let Z=G0(),Y=Z.find((X)=>X.id===$);if(!Y)return;Y.lastOpenedAt=Q,D5(Z)}function TZ($){if(D5(G0().filter((Q)=>Q.id!==$)),j0()===$)d$(l0()[0]?.id??null)}function K9(){return h(L(),"active")}function j0(){try{return P5(K9(),"utf8").trim()||null}catch{return null}}function d$($){H0(L(),{recursive:!0}),C5(K9(),$??"")}function IZ(){let $=j0();return $?m($):null}function kZ(){let $=R5()??j0();return $?m($):null}function _Z($){return m($)?.path??null}function LZ(){return G9(w5())}var N9="beacon_ws";function M9($,Q){let Z=$.headers.get("cookie");if(!Z)return null;for(let Y of Z.split(";")){let X=Y.indexOf("=");if(X===-1)continue;if(Y.slice(0,X).trim()===Q)return decodeURIComponent(Y.slice(X+1).trim())}return null}function yZ($){let Q=$.headers.get("x-beacon-workspace");if(Q&&m(Q))return Q;let Z=M9($,N9);if(Z&&m(Z))return Z;return o$()}function o$(){let $=l0();return $.length===1?$[0].id:null}var O5="x-beacon-workspace-path";async function xZ($){let Q=$.headers.get("x-beacon-workspace");if(Q&&m(Q))return Q;let Z=$.headers.get(O5);if(Z&&m0(Z)&&!p0(a(Z))&&(!Q||a(Z)===Q)){let X=d0(Z);return await A5(X.id),X.id}let Y=M9($,N9);if(Y&&m(Y))return Y;return null}var q9=new z$;function s$($,Q){return $?q9.run($,Q):Q()}function R5(){return q9.getStore()??null}var q5=new Set;function SZ($){q5.delete(h(c0($),"db.sqlite"))}async function A5($){let Q=c0($),Z=h(Q,"db.sqlite"),Y=G9(Z);if(Y&&q5.has(Z))return{ok:!0,created:!1,migrated:!1};try{H0(Q,{recursive:!0});let{provisionDb:X}=await X9().then(() => V9),H=await X(F5($));return q5.add(Z),{ok:!0,created:!Y,migrated:Y&&H.migrated}}catch(X){return{ok:!1,created:!1,migrated:!1,error:X instanceof Error?X.message:String(X)}}}import{connect as n$}from"net";var P9=4319;function i$($,Q,Z=400){return new Promise((Y)=>{let X=n$({host:$,port:Q}),H=!1,G=(U)=>{if(H)return;H=!0,X.destroy(),Y(U)};X.once("connect",()=>G(!0)),X.once("error",()=>G(!1)),X.setTimeout(Z,()=>G(!1))})}async function r$($){for(let Q of["127.0.0.1","::1"])if(await i$(Q,$))return!1;return!0}async function uZ($,Q=20){for(let Z=$;Z<$+Q;Z++)if(await r$(Z))return Z;return $}import{McpServer as bQ,ResourceTemplate as x5}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as mQ}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as J}from"zod";import{z as K}from"zod";var a$=new Set(["GET","HEAD","OPTIONS"]);function C9($){return a$.has($.trim().toUpperCase())?"read":"write"}var t$=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(t$).default([])}),v9=K.object({fromTable:K.string(),fromColumn:K.string(),toTable:K.string(),toColumn:K.string(),label:K.string().nullish()}),F9=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)}))})),pZ=K.object({tables:K.array(w9).default([]),relations:K.array(v9).default([]),endpoints:K.array(F9).default([])});import{z as R}from"zod";import{and as U1,eq as B1,inArray as K1}from"drizzle-orm";import{drizzle as RQ}from"drizzle-orm/libsql";import{createClient as AQ}from"@libsql/client";var E5={};$0(E5,{workspaceFlag:()=>XQ,tag:()=>t,syncState:()=>JQ,projectMeta:()=>VQ,planContract:()=>HQ,note:()=>QQ,nodeTags:()=>p,nodeFile:()=>W0,node:()=>q,endpointTable:()=>l,endpoint:()=>e,edge:()=>u,draftTable:()=>I,draftRelation:()=>d,draftColumn:()=>K0,dbTable:()=>D,dbRelation:()=>c,dbColumn:()=>B0,codeFileEdge:()=>o,codeFile:()=>y,bugFlag:()=>U0,boardAnnotation:()=>ZQ,appSetting:()=>YQ});import{sqliteTable as P,index as M,foreignKey as e$,text as V,integer as W,real as O,uniqueIndex as k,primaryKey as $Q}from"drizzle-orm/sqlite-core";import{createId as w}from"@paralleldrive/cuid2";var q=P("Node",{id:V().primaryKey().$defaultFn(()=>w()),view:V().notNull(),kind:V().default("FEATURE").notNull(),cluster:V(),layer:V(),title:V().notNull(),role:V(),plain:V(),status:V().default("PENDING").notNull(),priority:W().default(2).notNull(),progress:W().default(0).notNull(),x:O().default(0).notNull(),y:O().default(0).notNull(),sourceRef:V(),externalId:V(),source:V().default("MANUAL").notNull(),planId:V(),parentId:V(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[M("Node_cluster_idx").on($.cluster),M("Node_parentId_idx").on($.parentId),M("Node_view_idx").on($.view),e$(()=>({columns:[$.parentId],foreignColumns:[$.id],name:"Node_parentId_Node_id_fk"})).onUpdate("cascade").onDelete("cascade")]),W0=P("NodeFile",{id:V().primaryKey().$defaultFn(()=>w()),nodeId:V().notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),path:V().notNull()},($)=>[k("NodeFile_nodeId_path_key").on($.nodeId,$.path),M("NodeFile_nodeId_idx").on($.nodeId)]),t=P("Tag",{id:V().primaryKey().$defaultFn(()=>w()),label:V().notNull(),color:V()},($)=>[k("Tag_label_key").on($.label)]),u=P("Edge",{id:V().primaryKey().$defaultFn(()=>w()),fromId:V().notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),toId:V().notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),kind:V().default("DEPENDS").notNull(),label:V(),sourceHandle:V(),targetHandle:V()},($)=>[k("Edge_fromId_toId_kind_key").on($.fromId,$.toId,$.kind),M("Edge_toId_idx").on($.toId),M("Edge_fromId_idx").on($.fromId)]),p=P("_NodeTags",{a:V("A").notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),b:V("B").notNull().references(()=>t.id,{onDelete:"cascade",onUpdate:"cascade"})},($)=>[k("_NodeTags_AB_unique").on($.a,$.b),M("_NodeTags_B_index").on($.b)]),QQ=P("Note",{id:V().primaryKey().$defaultFn(()=>w()),title:V().default("Untitled").notNull(),body:V().default("").notNull(),ord:O().default(0).notNull(),pinned:W({mode:"boolean"}).default(!1).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[M("Note_updatedAt_idx").on($.updatedAt)]),ZQ=P("BoardAnnotation",{id:V().primaryKey().$defaultFn(()=>w()),targetKind:V().notNull(),targetId:V().notNull(),columnName:V(),body:V().default("").notNull(),x:O(),y:O(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[M("BoardAnnotation_target_idx").on($.targetId)]),U0=P("BugFlag",{id:V().primaryKey().$defaultFn(()=>w()),nodeId:V().notNull().references(()=>q.id,{onDelete:"cascade",onUpdate:"cascade"}),by:V().notNull(),note:V().notNull(),resolvedAt:W({mode:"timestamp_ms"}),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date)},($)=>[M("BugFlag_nodeId_idx").on($.nodeId)]),D=P("DbTable",{id:V().primaryKey().$defaultFn(()=>w()),name:V().notNull(),domain:V(),description:V(),source:V().default("MANUAL").notNull(),planId:V(),x:O().default(0).notNull(),y:O().default(0).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[M("DbTable_domain_idx").on($.domain),k("DbTable_name_key").on($.name)]),B0=P("DbColumn",{id:V().primaryKey().$defaultFn(()=>w()),tableId:V().notNull().references(()=>D.id,{onDelete:"cascade",onUpdate:"cascade"}),name:V().notNull(),type:V().notNull(),isPk:W({mode:"boolean"}).default(!1).notNull(),isFk:W({mode:"boolean"}).default(!1).notNull(),nullable:W({mode:"boolean"}).default(!0).notNull(),note:V(),ord:W().default(0).notNull()},($)=>[k("DbColumn_tableId_name_key").on($.tableId,$.name),M("DbColumn_tableId_idx").on($.tableId)]),c=P("DbRelation",{id:V().primaryKey().$defaultFn(()=>w()),fromTableId:V().notNull().references(()=>D.id,{onDelete:"cascade",onUpdate:"cascade"}),toTableId:V().notNull().references(()=>D.id,{onDelete:"cascade",onUpdate:"cascade"}),fromColumn:V().notNull(),toColumn:V().notNull(),label:V()},($)=>[M("DbRelation_toTableId_idx").on($.toTableId),M("DbRelation_fromTableId_idx").on($.fromTableId)]),e=P("Endpoint",{id:V().primaryKey().$defaultFn(()=>w()),method:V().notNull(),path:V().notNull(),domain:V(),description:V(),source:V().default("MANUAL").notNull(),planId:V(),x:O().default(0).notNull(),y:O().default(0).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[k("Endpoint_method_path_key").on($.method,$.path),M("Endpoint_domain_idx").on($.domain)]),l=P("EndpointTable",{id:V().primaryKey().$defaultFn(()=>w()),endpointId:V().notNull().references(()=>e.id,{onDelete:"cascade",onUpdate:"cascade"}),tableId:V().notNull().references(()=>D.id,{onDelete:"cascade",onUpdate:"cascade"}),access:V().default("read").notNull()},($)=>[k("EndpointTable_endpointId_tableId_key").on($.endpointId,$.tableId),M("EndpointTable_tableId_idx").on($.tableId)]),I=P("DraftTable",{id:V().primaryKey().$defaultFn(()=>w()),name:V().notNull(),domain:V(),description:V(),x:O().default(0).notNull(),y:O().default(0).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date)},($)=>[k("DraftTable_name_key").on($.name)]),K0=P("DraftColumn",{id:V().primaryKey().$defaultFn(()=>w()),tableId:V().notNull().references(()=>I.id,{onDelete:"cascade",onUpdate:"cascade"}),name:V().notNull(),type:V().notNull(),isPk:W({mode:"boolean"}).default(!1).notNull(),isFk:W({mode:"boolean"}).default(!1).notNull(),nullable:W({mode:"boolean"}).default(!0).notNull(),note:V(),ord:W().default(0).notNull()},($)=>[M("DraftColumn_tableId_idx").on($.tableId)]),d=P("DraftRelation",{id:V().primaryKey().$defaultFn(()=>w()),fromTableId:V().notNull().references(()=>I.id,{onDelete:"cascade",onUpdate:"cascade"}),toTableId:V().notNull().references(()=>I.id,{onDelete:"cascade",onUpdate:"cascade"}),fromColumn:V().notNull(),toColumn:V().notNull(),label:V()},($)=>[M("DraftRelation_toTableId_idx").on($.toTableId),M("DraftRelation_fromTableId_idx").on($.fromTableId)]),y=P("CodeFile",{path:V().primaryKey(),root:V(),lang:V(),x:O().default(0).notNull(),y:O().default(0).notNull(),mtimeMs:O(),size:W(),inDegree:W().default(0).notNull(),outDegree:W().default(0).notNull(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),o=P("CodeFileEdge",{fromPath:V().notNull().references(()=>y.path,{onDelete:"cascade",onUpdate:"cascade"}),toPath:V().notNull().references(()=>y.path,{onDelete:"cascade",onUpdate:"cascade"}),circular:W({mode:"boolean"}).default(!1).notNull()},($)=>[M("CodeFileEdge_circular_idx").on($.circular),M("CodeFileEdge_toPath_idx").on($.toPath),M("CodeFileEdge_fromPath_idx").on($.fromPath),$Q({columns:[$.fromPath,$.toPath],name:"CodeFileEdge_fromPath_toPath_pk"})]),JQ=P("SyncState",{id:V().primaryKey().default("singleton"),version:W().default(0).notNull(),codeGraphSyncedAt:W({mode:"timestamp_ms"}),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),YQ=P("AppSetting",{id:V().primaryKey().default("singleton"),editor:V().default("auto").notNull(),currentFeatureId:V(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),VQ=P("ProjectMeta",{id:V().primaryKey().default("singleton"),overview:V(),conventions:V().default("[]").notNull(),hasFrontend:W({mode:"boolean"}),classificationRoots:V().default("[]").notNull(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)}),XQ=P("WorkspaceFlag",{id:V().primaryKey().$defaultFn(()=>w()),key:V().notNull(),enabled:W({mode:"boolean"}).default(!1).notNull(),config:V(),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[k("WorkspaceFlag_key_key").on($.key)]),HQ=P("PlanContract",{id:V().primaryKey().$defaultFn(()=>w()),planId:V().notNull(),declaredFiles:V().default("[]").notNull(),authorizedExtras:V().default("[]").notNull(),active:W({mode:"boolean"}).default(!1).notNull(),createdAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date),updatedAt:W({mode:"timestamp_ms"}).notNull().$defaultFn(()=>new Date).$onUpdate(()=>new Date)},($)=>[k("PlanContract_planId_key").on($.planId),M("PlanContract_active_idx").on($.active)]);var T5={};$0(T5,{tagRelations:()=>UQ,nodeTagsRelations:()=>BQ,nodeRelations:()=>GQ,nodeFileRelations:()=>jQ,endpointTableRelations:()=>CQ,endpointRelations:()=>PQ,edgeRelations:()=>KQ,draftTableRelations:()=>wQ,draftRelationRelations:()=>FQ,draftColumnRelations:()=>vQ,dbTableRelations:()=>NQ,dbRelationRelations:()=>qQ,dbColumnRelations:()=>MQ,codeFileRelations:()=>DQ,codeFileEdgeRelations:()=>OQ,bugFlagRelations:()=>WQ});import{relations as v}from"drizzle-orm";var GQ=v(q,({one:$,many:Q})=>({files:Q(W0),bugFlags:Q(U0),nodeTags:Q(p),edgesOut:Q(u,{relationName:"EdgeFrom"}),edgesIn:Q(u,{relationName:"EdgeTo"}),parent:$(q,{fields:[q.parentId],references:[q.id],relationName:"NodeTree"}),children:Q(q,{relationName:"NodeTree"})})),jQ=v(W0,({one:$})=>({node:$(q,{fields:[W0.nodeId],references:[q.id]})})),WQ=v(U0,({one:$})=>({node:$(q,{fields:[U0.nodeId],references:[q.id]})})),UQ=v(t,({many:$})=>({nodeTags:$(p)})),BQ=v(p,({one:$})=>({node:$(q,{fields:[p.a],references:[q.id]}),tag:$(t,{fields:[p.b],references:[t.id]})})),KQ=v(u,({one:$})=>({from:$(q,{fields:[u.fromId],references:[q.id],relationName:"EdgeFrom"}),to:$(q,{fields:[u.toId],references:[q.id],relationName:"EdgeTo"})})),NQ=v(D,({many:$})=>({columns:$(B0),fksOut:$(c,{relationName:"FkFrom"}),fksIn:$(c,{relationName:"FkTo"}),usages:$(l)})),MQ=v(B0,({one:$})=>({table:$(D,{fields:[B0.tableId],references:[D.id]})})),qQ=v(c,({one:$})=>({fromTable:$(D,{fields:[c.fromTableId],references:[D.id],relationName:"FkFrom"}),toTable:$(D,{fields:[c.toTableId],references:[D.id],relationName:"FkTo"})})),PQ=v(e,({many:$})=>({tables:$(l)})),CQ=v(l,({one:$})=>({endpoint:$(e,{fields:[l.endpointId],references:[e.id]}),table:$(D,{fields:[l.tableId],references:[D.id]})})),wQ=v(I,({many:$})=>({columns:$(K0),fksOut:$(d,{relationName:"DraftFkFrom"}),fksIn:$(d,{relationName:"DraftFkTo"})})),vQ=v(K0,({one:$})=>({table:$(I,{fields:[K0.tableId],references:[I.id]})})),FQ=v(d,({one:$})=>({fromTable:$(I,{fields:[d.fromTableId],references:[I.id],relationName:"DraftFkFrom"}),toTable:$(I,{fields:[d.toTableId],references:[I.id],relationName:"DraftFkTo"})})),DQ=v(y,({many:$})=>({edgesOut:$(o,{relationName:"CFEFrom"}),edgesIn:$(o,{relationName:"CFETo"})})),OQ=v(o,({one:$})=>({fromFile:$(y,{fields:[o.fromPath],references:[y.path],relationName:"CFEFrom"}),toFile:$(y,{fields:[o.toPath],references:[y.path],relationName:"CFETo"})}));var EQ={...E5,...T5};function TQ(){let $=process.env.DATABASE_URL;if($&&/^(file:|libsql:|wss?:|https?:|:memory:)/i.test($))return $;return"file:./dev.db"}var IQ=TQ();function D9($){let Q=AQ({url:$});return Q.execute("PRAGMA foreign_keys = ON;"),Q.execute("PRAGMA busy_timeout = 5000;"),RQ(Q,{schema:EQ})}var k5=globalThis,I5=k5.dzDefault??D9(IQ);k5.dzDefault=I5;var o0=k5.dzByUrl??=new Map;function kQ($){let Q=o0.get($);if(!Q)Q=D9($),o0.set($,Q);return Q}function aZ($){let Q=o0.get($);o0.delete($);try{Q?.$client?.close?.()}catch{}}function _Q(){if(process.env.BEACON_REPO)return I5;let $=R5()??j0();if(!$)return I5;return kQ(F5($))}var LQ=new Proxy({},{get($,Q){let Z=_Q(),Y=Z[Q];return typeof Y==="function"?Y.bind(Z):Y}});var yQ=["frontend","backend","fullstack"],xQ={fe:"frontend",front:"frontend",be:"backend",back:"backend",fs:"fullstack","full-stack":"fullstack","full stack":"fullstack"};function s0($){let Q=($??"").trim().toLowerCase();if(!Q)return null;if(yQ.includes(Q))return Q;return xQ[Q]??null}import{forceCenter as Z1,forceCollide as J1,forceLink as Y1,forceManyBody as V1,forceSimulation as X1}from"d3-force";var O9=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:X,...H})=>({...H,cluster:H.cluster??$??Q??null,priority:Z==null?null:Math.max(0,Math.min(3,Math.round(Z))),kind:Y?.trim().toUpperCase()==="BUG"?"BUG":"FEATURE",layer:s0(X)})),C1=R.object({features:R.array(O9).default([])});var SQ=/(\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 R9($){return!!$&&SQ.test($)}function A9($,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 fQ($){return $.cluster??$.category??$.domain??null}function E9($,Q){let Z=Q?.requireLayer??!1,Y=$.map((H)=>{let G=[],U=fQ(H);if(!U||!U.trim())G.push("category");if(H.priority==null)G.push("priority");if(Z&&!s0(H.layer))G.push("layer");return G.length?` \u2022 "${H.title?.trim()||"(untitled)"}" \u2014 missing ${G.join(" + ")}`:null}).filter((H)=>H!==null);if(Y.length===0)return null;let X=Z?" This workspace has a frontend surface, so every feature must also carry `layer`: "+'"frontend" | "backend" | "fullstack" \u2014 which side of the stack the work lands on.':"";return"\u26D4 Every roadmap feature needs a category AND a priority \u2014 they drive grouping and ordering "+"on the board, and the user shouldn't have to add them by hand."+X+` Missing:
|
|
345
352
|
`+Y.join(`
|
|
346
|
-
`)+"\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
|
|
353
|
+
`)+"\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`
|
|
347
354
|
|
|
348
355
|
This plan created these roadmap feature(s):
|
|
349
356
|
`+Q.join(`
|
|
350
|
-
`)+'\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
|
|
351
|
-
`)}await Z9();var u=j9(),x=i(u);if(!b0(u)){let $=c0();if($.length===1)console.error(`[beacon mcp] cwd ${u} isn't a registered repo \u2014 falling back to your only Beacon workspace "${$[0].name}".`);else if($.length>1)console.error(`[beacon mcp] cwd ${u} 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 ${u} \u2014 home/non-repo dir.`)}else if(m0(x))console.error(`[beacon mcp] not registering ${u} \u2014 workspace was deleted; run /beacon-init to re-add it.`);else try{l0(u);let $=await R5(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(D5,u);let Y=await fetch(`${h()}${$}`,{...Q,headers:Z}),X=await Y.text();if(!Y.ok)throw Error(`Beacon ${$} -> ${Y.status} ${X}`);return X?JSON.parse(X):null}function N0($,Q){return E($,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Q)})}function x5($){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 uQ({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 x9=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:x9})).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:x9}},async($)=>{try{let{path:Q,body:Z}=R9($.action,$),Y=await N0(Q,Z);return{content:[{type:"text",text:JSON.stringify(Y)}]}}catch(Q){return x5(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 X=await E(`/api/context/feature?${Y.toString()}`);return{content:[{type:"text",text:JSON.stringify(X)}]}});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 X=await E(`/api/entities?${Y.toString()}`);return{content:[{type:"text",text:JSON.stringify(X)}]}});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. When the user has the plan scope-guard enabled, these are frozen at approval and you are held to them while implementing: editing an undeclared file pauses for the user's authorization (which adds it to the contract). Safe to always include; ignored when the guard is off.")}},async({description:$,features:Q,tables:Z,relations:Y,endpoints:X,contract:H})=>{let G=(C)=>new Promise((M0)=>setTimeout(M0,C)),U=(C)=>({content:[{type:"text",text:C}]}),j=(Z?.length??0)>0,K=(Q??[]).map((C)=>`${C.title} ${C.role??""} ${C.plain??""}`).join(`
|
|
352
|
-
`),
|
|
353
|
-
${
|
|
357
|
+
`)+'\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 uQ}from"path";function gQ(){try{return JSON.parse(hQ(uQ(L(),"server.json"),"utf8"))}catch{return null}}function g(){if(process.env.BEACON_URL)return process.env.BEACON_URL;return`http://localhost:${gQ()?.port||process.env.PORT||P9}`}import{execSync as zQ}from"child_process";import{platform as T9}from"os";function L5($){if(process.env.BEACON_NO_OPEN)return;let Q=T9()==="darwin"?"open":T9()==="win32"?"start":"xdg-open";try{zQ(`${Q} "${$}"`,{stdio:"ignore"})}catch{}}async function y5($,Q){if(await fetch(`${$}/api/plan/presence`,{headers:{"x-beacon-workspace":Q}}).then((X)=>X.json()).then((X)=>!!X?.live).catch(()=>!1))return;let Y=encodeURIComponent(`/plan?ws=${Q}`);L5(`${$}/api/workspace/activate?id=${Q}&redirect=${Y}`)}async function I9($,Q){if(await fetch(`${$}/api/lesson/presence`,{headers:{"x-beacon-workspace":Q}}).then((X)=>X.json()).then((X)=>!!X?.live).catch(()=>!1))return;let Y=encodeURIComponent(`/learn?ws=${Q}`);L5(`${$}/api/workspace/activate?id=${Q}&redirect=${Y}`)}var k9=["imports","calls","persists to","reads from","writes to","routes to","depends on","emits","returns","contains","extends"];a0();function N0($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036F]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50)||"item"}function _9($){return`${N0($.title)}-${$.id.slice(-6)}`}function L9($){return{resources:$.map((Q)=>({uri:`note://${_9(Q)}`,name:Q.title||"Untitled",description:`${Q.title||"Untitled"}${Q.pinned?" \xB7 pinned":""} \xB7 note`,mimeType:"text/markdown"}))}}function y9($,Q){return $.find((Z)=>_9(Z)===Q)}function x9($){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(`
|
|
358
|
+
`)}await J9();var z=W9(),x=a(z);if(!m0(z)){let $=l0();if($.length===1)console.error(`[beacon mcp] cwd ${z} isn't a registered repo \u2014 falling back to your only Beacon workspace "${$[0].name}".`);else if($.length>1)console.error(`[beacon mcp] cwd ${z} 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 ${z} \u2014 home/non-repo dir.`)}else if(p0(x))console.error(`[beacon mcp] not registering ${z} \u2014 workspace was deleted; run /beacon-init to re-add it.`);else try{d0(z);let $=await A5(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(O5,z);let Y=await fetch(`${g()}${$}`,{...Q,headers:Z}),X=await Y.text();if(!Y.ok)throw Error(`Beacon ${$} -> ${Y.status} ${X}`);return X?JSON.parse(X):null}function M0($,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 bQ({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 S9=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:S9})).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:S9}},async($)=>{try{let{path:Q,body:Z}=A9($.action,$),Y=await M0(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 M0("/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 X=await E(`/api/context/feature?${Y.toString()}`);return{content:[{type:"text",text:JSON.stringify(X)}]}});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 X=await E(`/api/entities?${Y.toString()}`);return{content:[{type:"text",text:JSON.stringify(X)}]}});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. When the user has the plan scope-guard enabled, these are frozen at approval and you are held to them while implementing: editing an undeclared file pauses for the user's authorization (which adds it to the contract). Safe to always include; ignored when the guard is off.")}},async({description:$,features:Q,tables:Z,relations:Y,endpoints:X,contract:H})=>{let G=(C)=>new Promise((q0)=>setTimeout(q0,C)),U=(C)=>({content:[{type:"text",text:C}]}),j=(Z?.length??0)>0,B=(Q??[]).map((C)=>`${C.title} ${C.role??""} ${C.plain??""}`).join(`
|
|
359
|
+
`),b=(X?.length??0)>0||R9(`${$}
|
|
360
|
+
${B}`);if(!j&&b)return U("\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((z9)=>!!z9?.hasFrontend).catch(()=>!1),q0=E9(Q,{requireLayer:C});if(q0)return U(q0)}let F=(Z?.length??0)+(X?.length??0)>0;try{await M0("/api/plan",{description:$,draft:F?{tables:Z??[],relations:Y??[],endpoints:X??[]}:void 0,features:Q?.length?Q:void 0,contract:H?.length?H:void 0})}catch(C){return S5(C)}await fetch(`${g()}/api/workspace/activate?id=${x}`).catch(()=>{}),await y5(g(),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 U("\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:
|
|
354
361
|
|
|
355
362
|
`+C.feedback);if(C.kind==="approved")return U(`\u2705 Plan approved by the user. ${C.summary}`+(C.detail?`
|
|
356
363
|
|
|
357
364
|
Implement EXACTLY the schema below (migrations + code) \u2014 the user may have `+`edited columns on the canvas:
|
|
358
365
|
|
|
359
|
-
`+C.detail:"")+
|
|
366
|
+
`+C.detail:"")+_5(C.features));if(C.kind==="discarded")return U(`\u274C The user discarded the plan in Beacon. ${C.summary} Ask what they want to adjust before proposing again.`)}return U("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(k9).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:X,tables:H,steps:G,answers:U})=>{let j=(F)=>new Promise((r0)=>setTimeout(r0,F)),B=(F)=>({content:[{type:"text",text:F}]});try{await M0("/api/lesson",{title:$,topic:Q,narrative:Z,nodes:Y,edges:X,tables:H,steps:G,answers:U})}catch(F){return S5(F)}await fetch(`${g()}/api/workspace/activate?id=${x}`).catch(()=>{}),await I9(g(),x);let b=Date.now()+C0;while(Date.now()<b){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:
|
|
360
367
|
|
|
361
|
-
`+(
|
|
368
|
+
`+(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 M0("/api/plan",{description:$,markdown:Q}),await fetch(`${g()}/api/workspace/activate?id=${x}`).catch(()=>{}),await y5(g(),x);let X=Date.now()+C0;while(Date.now()<X){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:
|
|
362
369
|
|
|
363
370
|
`+H.feedback);if(H.kind==="approved")return Y(`\u2705 Plan approved by the user. ${H.summary??""}`.trim()+(H.detail?`
|
|
364
371
|
|
|
365
372
|
Implement exactly what's on the board:
|
|
366
373
|
|
|
367
|
-
${H.detail}`:"")+
|
|
368
|
-
`)}]}}A.registerResource("beacon-feature",new
|
|
374
|
+
${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 h9=($)=>Array.isArray($)?$[0]:$;async function i0($){return(await E(`/api/entities?kind=${$}&full=1`)).items}function u9($,Q){return{resources:$.map((Z)=>({uri:`${Q}${N0(Z.title)}`,name:Z.title,description:`${Z.title}${Z.cluster?` \xB7 ${Z.cluster}`:""} \xB7 ${Z.status}`,mimeType:"text/markdown"}))}}async function g9($,Q,Z){let Y=(await i0(Z)).find((U)=>N0(U.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((U)=>U.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 U=await i0("features"),j=[...new Set(U.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(`
|
|
375
|
+
`)}]}}A.registerResource("beacon-feature",new x5("feature://{slug}",{list:async()=>u9(await i0("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})=>g9($,Q,"features"));A.registerResource("beacon-component",new x5("component://{slug}",{list:async()=>u9(await i0("architecture"),"component://")}),{title:"Beacon: architecture",description:"Architecture components \u2014 picking one imports 'what the agent sees'.",mimeType:"text/markdown"},($,{slug:Q})=>g9($,Q,"architecture"));async function f9(){return await E("/api/notes")}A.registerResource("beacon-note",new x5("note://{slug}",{list:async()=>L9(await f9())}),{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=y9(await f9(),h9(Q)),Y=Z?x9(Z):"(not found)";return{contents:[{uri:$.href,mimeType:"text/markdown",text:Y}]}});await A.connect(new mQ);var n0=-1;setInterval(async()=>{try{let{version:$}=await E("/api/version");if(n0===-1)n0=$;else if($!==n0)n0=$,A.sendResourceListChanged()}catch{}},f5);
|