#!/usr/bin/env bun
// @bun
var HZ=Object.defineProperty;var jZ=(Q)=>Q;function vZ(Q,Z){this[Q]=jZ.bind(null,Z)}var qQ=(Q,Z)=>{for(var $ in Z)HZ(Q,$,{get:Z[$],enumerable:!0,configurable:!0,set:vZ.bind(Z,$)})};var g=(Q,Z)=>()=>(Q&&(Z=Q(Q=0)),Z);var HQ={};qQ(HQ,{removeRepoAssets:()=>fZ,installRefreshSkill:()=>NZ,installPlanSkill:()=>xZ,installInitSkill:()=>BZ,installCodexRepoSkills:()=>KZ,ensureWorkflowDoc:()=>CZ,ensureMcp:()=>MZ,auditRepo:()=>PQ,REFRESH_SKILL:()=>UQ,PLAN_SKILL:()=>bQ,INIT_SKILL:()=>XQ});import{existsSync as f,mkdirSync as _,readFileSync as x,rmSync as b,writeFileSync as N}from"fs";import{join as q}from"path";function BZ(Q){let Z=q(Q,".claude","skills","beacon-init");_(Z,{recursive:!0});let $=q(Z,"SKILL.md");return N($,XQ),$}function NZ(Q){let Z=q(Q,".claude","skills","beacon-refresh");_(Z,{recursive:!0});let $=q(Z,"SKILL.md");return N($,UQ),$}function xZ(Q){let Z=q(Q,".claude","skills","beacon-plan");_(Z,{recursive:!0});let $=q(Z,"SKILL.md");return N($,bQ),$}function KZ(Q){let Z=[];for(let $ of GZ){let J=q(Q,".agents","skills",$.name);_(J,{recursive:!0});let Y=q(J,"SKILL.md");N(Y,$.body()),Z.push(Y)}return Z}function CZ(Q){let Z=q(Q,"AGENTS.md"),$="";try{$=x(Z,"utf8")}catch{}let J=new RegExp(`${k}[\\s\\S]*?${WQ}`);$=J.test($)?$.replace(J,AQ):`${$.trim()}

${AQ}
`.trimStart(),N(Z,$.endsWith(`
`)?$:`${$}
`);let Y=q(Q,"CLAUDE.md"),V="";try{V=x(Y,"utf8")}catch{}if(!/@AGENTS\.md/.test(V))N(Y,`${V?`${V.trim()}

`:""}@AGENTS.md
`)}function MZ(Q){let Z=q(Q,".mcp.json"),$={};try{$=JSON.parse(x(Z,"utf8"))}catch{}if($.mcpServers=$.mcpServers??{},$.mcpServers.beacon)return{path:Z,added:!1};return $.mcpServers.beacon={command:"beacon",args:["mcp"]},N(Z,JSON.stringify($,null,2)+`
`),{path:Z,added:!0}}function PQ(Q){let Z=q(Q,".mcp.json"),$=!1;try{$=!!JSON.parse(x(Z,"utf8")).mcpServers?.beacon}catch{}let J=!1;try{J=x(q(Q,"AGENTS.md"),"utf8").includes(k)}catch{}let Y=!1;try{Y=/@AGENTS\.md/.test(x(q(Q,"CLAUDE.md"),"utf8"))}catch{}return{repo:Q,mcpRegistered:$,agentsMdBlock:J,claudeMdImport:Y,skills:{"beacon-init":f(q(Q,".claude","skills","beacon-init","SKILL.md")),"beacon-refresh":f(q(Q,".claude","skills","beacon-refresh","SKILL.md"))},codexSkills:{"beacon-init":f(q(Q,".agents","skills","beacon-init","SKILL.md")),"beacon-refresh":f(q(Q,".agents","skills","beacon-refresh","SKILL.md"))}}}function fZ(Q){let Z=[];for(let z of["beacon-init","beacon-refresh","beacon-db-design"]){let j=q(Q,".claude","skills",z);if(f(j))b(j,{recursive:!0,force:!0}),Z.push(z)}for(let z of["beacon-init","beacon-refresh"]){let j=q(Q,".agents","skills",z);if(f(j))b(j,{recursive:!0,force:!0}),Z.push(`codex:${z}`)}let $=!1,J=q(Q,".mcp.json");try{let z=JSON.parse(x(J,"utf8"));if(z.mcpServers?.beacon){if(delete z.mcpServers.beacon,$=!0,z.mcpServers&&Object.keys(z.mcpServers).length===0)delete z.mcpServers;if(Object.keys(z).length===0)b(J,{force:!0});else N(J,JSON.stringify(z,null,2)+`
`)}}catch{}let Y=!1,V=q(Q,"AGENTS.md");try{let z=x(V,"utf8"),j=new RegExp(`\\n?${k}[\\s\\S]*?${WQ}\\n?`);if(j.test(z)){let zQ=z.replace(j,`
`).replace(/\n{3,}/g,`

`).trimStart();N(V,zQ.endsWith(`
`)?zQ:`${zQ}
`),Y=!0}}catch{}let X=!1,U=q(Q,"CLAUDE.md");try{let z=x(U,"utf8"),j=z.replace(/^[ \t]*@AGENTS\.md[ \t]*\n?/m,"");if(j!==z){if(!j.trim())b(U,{force:!0});else N(U,j);X=!0}}catch{}return{skillsRemoved:Z,mcpUnregistered:$,agentsBlockRemoved:Y,claudeImportRemoved:X}}var XQ=`---
name: beacon-init
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.
---

# Map this repo into Beacon (/beacon-init)

The user already has Beacon running. You're going to map this repository's architecture into it \u2014 what used to be \`beacon init\`. **You** do the analysis (your session already has the codebase context); Beacon just persists what you send.

## What you produce

A single \`beacon_init_persist\` MCP tool call with:

- **components**: 8\u201325 main building blocks of this codebase. NOT every file. Group them by \`domain\` (short UPPERCASE: AUTH, API, DATA, UI, JOBS, INFRA, BILLING, SEARCH, \u2026). For each: a one-line technical \`role\`, a one-sentence plain-language \`plain\`, the few \`files\` that implement it (repo-relative), and \`depends\` listing other component titles it relies on. Use the dependency graph you can see in the source \u2014 files that import each other heavily usually belong together. If you spot a bug or something worth investigating while reading a component's code, add \`bugs: [{ note }]\` to that component \u2014 it renders as a bug flag on the node (attributed to the agent). Only flag what you actually saw in the code; don't speculate.
- **roadmap**: 3\u20136 BROAD strategic directions. Big-picture themes only \u2014 "Harden auth & security", "Add observability", "Scale the data layer", "Pay down test-coverage debt". NOT detailed tasks. NOT file-level. Each gets a short title and one-line \`why\`. If one of them is a concrete BUG to fix (something broken you saw in the code), add \`kind: "BUG"\` so it renders as a typed bug card.
- **overview**: one paragraph describing what this project is and its stack. This lands in AGENTS.md as the project intro.
- **conventions**: 3\u20138 concrete rules a contributor MUST follow \u2014 build/test commands, where code goes, patterns, things easy to get wrong. Infer from actual files, not assumptions.
- **snapshot** (optional but encouraged): \`{ tables, relations, endpoints }\` for the existing database. If the project uses Prisma, read \`prisma/schema.prisma\`. If SQLAlchemy, read the model files. If Django, read \`models.py\`. If you find no obvious schema source, skip the snapshot \u2014 don't fabricate.

## How to do it

1. **Survey**. Use \`LS\` / \`Glob\` to see the top-level structure. Read \`README.md\` and the manifest (\`package.json\` / \`pyproject.toml\` / \`go.mod\` / \`Cargo.toml\` / \`pom.xml\`).
2. **Sample the source.** Read 15\u201330 representative files \u2014 one per cluster you can identify. Don't read everything; pick by name (route files, model files, main entrypoints, key services). The goal is to identify boundaries, not memorize every line.
3. **Identify the schema** if any. \`prisma/schema.prisma\` \u2192 translate each model into a \`tables\` entry. \`alembic\`/SQLAlchemy \u2192 read the latest models. Django \u2192 read \`models.py\`. Skip the snapshot if the source-of-truth isn't obvious.
4. **Identify endpoints** if any. Look for routes \u2014 Next.js \`app/api/*\` files, FastAPI \`@router.*\` / \`@app.*\`, Express \`app.get\`/etc. For each endpoint try to fill \`uses: [{ table, access }]\` so the canvas can draw which endpoint touches which table.
5. **Call \`beacon_init_persist\`** ONCE with the whole analysis. It replaces any prior init-derived map (idempotent) and regenerates \`AGENTS.md\`.

## What you should NOT do

- Don't propose detailed tasks in \`roadmap\` \u2014 that's what \`beacon_propose_plan\` is for. Init roadmap is strategic only.
- Don't list every file as a \`component\`. Aim for ~15. If you have 40, you're listing files, not components.
- Don't fabricate tables/endpoints. If you can't find the schema source, omit \`snapshot\`.
- Don't ask the user to confirm before persisting. The user invoked /beacon-init \u2014 that's the confirmation.

If \`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-init.

After the tool returns, tell the user the counts (components / roadmap / tables / endpoints) and point them at the running Beacon panel.
`,UQ=`---
name: beacon-refresh
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.
---

# Refresh Beacon's map (/beacon-refresh)

Beacon was already initialized in this repo (\`/beacon-init\` ran at some point). The codebase has moved since then \u2014 new modules, removed ones, schema changes, new routes. Your job is to re-survey the current code, show the user what changed, then persist the refreshed map.

## How it differs from /beacon-init

- **Init is a cold start** \u2014 no prior map, you survey everything fresh.
- **Refresh is incremental** \u2014 the map already exists. Read what's there first, then diff against the source so you can tell the user what actually changed. The user gets to see "+ 3 new components, \u2212 1 removed, ~ 2 changed roles" instead of an opaque re-run.

## What gets preserved vs replaced

The \`beacon_init_persist\` tool **replaces only init-derived nodes** (\`source=INIT\`). Anything the user added manually on the canvas \u2014 manually-created components, hand-edited tables, custom positions, notes, draft feature plans \u2014 survives the refresh untouched. So you can re-run this freely; nothing the user curated by hand is at risk.

The one caveat: if the user manually edited an INIT-source node on the canvas (e.g., renamed it, rewrote its role), that edit IS overwritten when you re-persist. If the user mentions hand-curated INIT nodes, ask whether they want those carried into the new analysis verbatim.

## How to do it

1. **Read the current map.** Call \`beacon_entities\` with \`{ kind: "architecture" }\`, \`{ kind: "roadmap" }\`, \`{ kind: "tables" }\`, \`{ kind: "endpoints" }\`. This is what Beacon has now.
2. **Survey the source like init.** Same approach as \`/beacon-init\`: \`LS\` / \`Glob\` for top-level structure, read \`README.md\` and the manifest, sample 15\u201330 representative files. Focus on areas likely to have changed \u2014 diff your memory against what \`beacon_entities\` returned.
3. **Build the diff in your head.** For each entity kind:
   - **components**: which titles in the current map no longer match any cluster you'd produce? Which clusters you'd produce don't appear in the current map?
   - **tables**: any added / removed since? Any model files you can see that aren't in the snapshot?
   - **endpoints**: walk the route directories \u2014 any new routes, any deleted ones?
   - **roadmap**: usually stable, but a strategic theme can finish or new ones can emerge.
4. **Surface the diff to the user, briefly, BEFORE persisting.** Something like:
   - **+ added**: NEW_COMPONENT_1, NEW_COMPONENT_2 (with one-line reason each)
   - **\u2212 removed**: STALE_COMPONENT (file no longer exists)
   - **~ changed**: COMPONENT_X (role expanded to cover Y)
   - **schema**: + 2 new tables (TableA, TableB); + 3 new endpoints; \u2212 1 deprecated endpoint
   No need to wait for confirmation \u2014 just show the diff so the user sees what's about to land.
5. **Call \`beacon_init_persist\`** ONCE with the refreshed full analysis (same shape as init: \`components\`, \`roadmap\`, \`overview\`, \`conventions\`, \`snapshot\`). It replaces all init-source nodes and regenerates \`AGENTS.md\`. Bug flags already on a component survive the refresh (they're carried over by title); add \`bugs: [{ note }]\` for anything NEW you found worth investigating \u2014 identical open flags are not duplicated.

## What you should NOT do

- Don't ask "should I refresh?" \u2014 the user invoked /beacon-refresh, that's the answer.
- Don't preserve stale components for sentimental reasons. If the underlying files are gone or merged into another component, drop it from the new \`components\` list.
- Don't pad with file-level granularity. Refresh maintains the same ~15-component altitude as init.
- Don't fabricate changes. If the codebase hasn't materially moved since the last init, say so and persist the current state anyway (re-runs are cheap; it's fine).

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.

After the tool returns, report the final counts plus a one-line summary of the diff you surfaced.
`,bQ=`---
name: beacon-plan
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.
---

# Present a plan on Beacon (/beacon-plan)

Beacon reviews plans on a canvas at /plan \u2014 never as a wall of text in the terminal. So do NOT
end a turn with "here's my plan\u2026 should I proceed?" in prose. Present it through Beacon and let the
tool BLOCK until the user decides.

## How to present

Call the **\`beacon_present_plan\`** MCP tool with your plan as markdown:

- \`description\`: a one-line summary shown in the review header.
- \`markdown\`: the full plan as markdown (headings, lists, code).
- If the plan proposes DB tables / relations / endpoints or roadmap features, embed ONE fenced
  \`\`\`beacon JSON block in the markdown \u2014 the same shapes \`beacon_propose_plan\` accepts:

\`\`\`beacon
{ "tables": [...], "relations": [...], "endpoints": [...], "features": [...] }
\`\`\`

Beacon extracts that block deterministically, strips it from the prose, and renders an editable
board on /plan. The board is built ONLY from the block \u2014 prose is never parsed \u2014 so mirror EVERY
table/endpoint/feature you mention in the prose into the block, or that board will be empty.

\`beacon_present_plan\` opens /plan and BLOCKS until the user clicks Approve / Discard / submits
feedback, then returns their verdict. Implement code or migrations ONLY after it returns approval.
If it returns feedback, revise and call it again.

## Which tool

- **Pure schema/feature plan** (tables + endpoints + roadmap features, little prose) \u2192 you may use
  \`beacon_propose_plan\` with the structured fields instead; it's the same review loop.
- **Anything else** (a code-change plan, a mixed plan, a "how should I approach X") \u2192 use
  \`beacon_present_plan\` with markdown so the full reasoning shows on /plan.

If \`beacon_present_plan\` isn't available, the panel isn't wired here \u2014 fall back to ExitPlanMode
with the same \`\`\`beacon block (Claude Code only; Codex has no ExitPlanMode), or tell the user to
run \`beacon\` in this repo once.
`,GZ,k="<!-- beacon:workflow:start -->",WQ="<!-- beacon:workflow:end -->",AQ;var L=g(()=>{GZ=[{name:"beacon-init",body:()=>XQ},{name:"beacon-refresh",body:()=>UQ}];AQ=`${k}
## Beacon \u2014 feature workflow

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:

### 1. Load context FIRST \u2014 do NOT Glob/Grep the codebase blind

Call \`beacon_context_for_feature({ id | title | query })\` BEFORE reading files. It returns, in one round-trip:
- the files the feature is attached to,
- what those files import + what imports them (live code-graph blast radius),
- endpoints in the feature's domain + the tables each touches + those tables' FK relations,
- sibling architecture components and the project's conventions.

That bundle replaces the discovery phase. Read only the files it returns plus whatever those imports lead you to. If the feature has no files attached yet, the bundle still gives you the domain map \u2014 Glob is a last resort.

Mid-feature, when deciding whether a change is safe, call \`beacon_blast_radius({ path })\` for the file you're about to edit \u2014 same code-graph data, file-centric.

### 2. Design the data BEFORE writing code

Determine the database tables the feature needs. If any don't exist yet, design the schema and call \`beacon_propose_plan\` (tables + relations + endpoints). This renders an **editable draft on the /plan page** for the user to review. The tool BLOCKS until the user clicks Approve / Discard / submits feedback. Implement migrations + code ONLY after it returns approval.

When listing endpoints, give each \`uses: [{ table, access }]\` so the endpoint\u2192table links draw on /db.

EVERY feature MUST carry \`category\` (e.g. AUTH | SEARCH | DATA | INTEL | BILLING | \u2026; \`cluster\` is accepted as an alias) and \`priority\` (0 = P0 critical, 1 = P1 high, 2 = P2 medium, 3 = P3 low). Beacon REJECTS a plan whose features omit either \u2014 \`beacon_propose_plan\` returns the list of what's missing, and an ExitPlanMode \`\`\`beacon block is denied \u2014 so set both on every feature instead of relying on defaults.

REUSE before you create. Call \`beacon_map\` to see the features + categories that already exist. Beacon HARD-BLOCKS a feature that duplicates an existing one (it returns the existing feature to use instead) and one created without a category \u2014 so don't re-create work that's already on the board, and reuse an existing category rather than a near-synonym. \`category\` is the ONLY domain field. \`front\` (in \`beacon_start_feature\`) nests a feature UNDER an existing parent feature \u2014 it is NOT a domain tag; a \`front\` that matches no real feature is rejected.

When listing features, give each \`dependsOn: ["Other feature title", \u2026]\` for any feature that must ship after another in the same plan. Beacon draws these as "depends on" links so the roadmap shows the dependency chain instead of loose, disconnected cards.

A roadmap item that is a BUG to fix (not a feature to build) should carry \`kind: "BUG"\` \u2014 it renders as a typed bug card. This works everywhere roadmap cards are created: \`beacon_propose_plan\` features, the \`\`\`beacon block, \`beacon_start_feature\` (when the user says they're starting on a bug), \`beacon_add_subtasks\` items (a bug discovered mid-work), and \`beacon_init_persist\` roadmap items. Default is FEATURE.

### 2b. Presenting a plan in plan mode (ExitPlanMode)

In Codex (which has no ExitPlanMode), always present plans via \`beacon_present_plan\` / \`beacon_propose_plan\` instead \u2014 this section applies to Claude Code's plan mode only.

When you present a plan via ExitPlanMode (not \`beacon_propose_plan\`) and it proposes DB tables/relations/endpoints or roadmap features, embed ONE fenced \`\`\`beacon code block of JSON in the plan \u2014 the same shapes \`beacon_propose_plan\` accepts:

\`\`\`beacon
{ "tables": [...], "relations": [...], "endpoints": [...], "features": [...] }
\`\`\`

Beacon extracts it deterministically and **strips the block from the prose** (it's never shown in the annotation panel), then renders the tables + features as an **editable board** on /plan so the user can edit them and have those edits flow back as feedback. Omit the block for pure code-change plans.

**The board is built ONLY from the block \u2014 prose is NOT parsed.** If your plan describes ANY database models/tables/columns in the prose (e.g. "Model \`legal_precedent.py\` \u2014 natural key (court, \u2026)"), you MUST also put them in the block's \`tables\` array (with \`columns\`), or the /db tab will be empty for that plan. Same for endpoints (\`endpoints\` with \`uses:[{table,access}]\`) and features (\`features\`). A plan that lists five tables in prose but ships a block with only \`features\` renders an empty database board \u2014 exactly the "I described models but the DB tab is empty" failure. Mirror every DB entity you mention into the block.

### 3. At the end, register the work \u2014 in ONE call

Call \`beacon_describe_feature\` **ONCE** with a \`features\` array \u2014 one entry per feature the plan created \u2014 each with the files you touched and a short markdown description. This flips each one to **Done** \u2014 including its sub-tasks (the cascade completes every PENDING/IN_PROGRESS child; a sub-task you did NOT finish must be set BLOCKED or CANCELLED before registering, so it survives visibly) \u2014 and keeps \`beacon_context_for_feature\` accurate for the next session.

Key each entry by its node \`id\`: the ids are handed back to you when the plan is approved (in the approval message / additionalContext), so you don't fuzzy-match titles or pay a disambiguation round-trip. If you don't have an id, \`title\` still works.

Register them all in that single batched call. If a plan added five features, that's ONE \`beacon_describe_feature\` call with five entries \u2014 NOT five calls, and NOT just an umbrella ("Harden auth"), which leaves the individual features stuck on **Pending**.

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.

Pull raw planning data anytime with \`beacon_entities\` (features / architecture / tables / endpoints).
${WQ}`});import{existsSync as _Q,mkdirSync as jQ,readFileSync as S,rmSync as wZ,writeFileSync as m}from"fs";import{dirname as kQ,join as h}from"path";function vQ(Q){try{return JSON.parse(S(Q,"utf8"))}catch{return{}}}function LQ(Q,Z){jQ(kQ(Q),{recursive:!0}),m(Q,JSON.stringify(Z,null,2)+`
`)}function c(Q,Z){let $=vQ(Q);$.hooks=$.hooks??{},$.hooks[Z.event]=$.hooks[Z.event]??[];let J=$.hooks[Z.event];if(J.some((V)=>V.matcher===Z.matcher&&V.hooks?.some((X)=>X.command===Z.command)))return!1;return J.push({matcher:Z.matcher,hooks:[{type:"command",command:Z.command}]}),LQ(Q,$),!0}function l(Q,Z){return(vQ(Q).hooks?.[Z.event]??[]).some((Y)=>Y.hooks?.some((V)=>V.command===Z.command))}function n(Q,Z){let $=vQ(Q),J=$.hooks?.[Z.event];if(!J)return!1;let Y=!1,V=J.map((X)=>{let U=X.hooks?.length??0,z=(X.hooks??[]).filter((j)=>j.command!==Z.command);if(z.length!==U)Y=!0;return{...X,hooks:z}}).filter((X)=>(X.hooks??[]).length>0);if(!Y)return!1;if(V.length)$.hooks[Z.event]=V;else delete $.hooks[Z.event];if($.hooks&&Object.keys($.hooks).length===0)delete $.hooks;return LQ(Q,$),!0}function t(Q,Z,$,J){let Y=`${Z}
${J.trim()}
${$}`,V="";try{V=S(Q,"utf8")}catch{}let X=new RegExp(`${Z}[\\s\\S]*?${$}`);V=X.test(V)?V.replace(X,Y):V.trim()?`${V.trim()}

${Y}
`:`${Y}
`,jQ(kQ(Q),{recursive:!0}),m(Q,V.endsWith(`
`)?V:`${V}
`)}function R(Q,Z){try{return S(Q,"utf8").includes(Z)}catch{return!1}}function s(Q,Z,$){let J="";try{J=S(Q,"utf8")}catch{return!1}let Y=new RegExp(`${Z}[\\s\\S]*?${$}\\n?`);if(!Y.test(J))return!1;let V=J.replace(Y,"").replace(/\n{3,}/g,`

`).trimStart();return m(Q,V),!0}function a(Q,Z,$){let J=h(Q,Z);jQ(J,{recursive:!0});let Y=h(J,"SKILL.md");return m(Y,$),Y}function E(Q,Z){return _Q(h(Q,Z,"SKILL.md"))}function d(Q,Z){let $=h(Q,Z);if(!_Q($))return!1;return wZ($,{recursive:!0,force:!0}),!0}var v,p=`## Beacon (visual planning panel)

This machine has Beacon installed \u2014 a local visual planning surface for the terminal-side
agent. Beacon proposes feature plans (roadmap features + DB schema + endpoints) via MCP,
the user reviews on a canvas at /plan, and feedback flows back as the next round.

**When to invoke**
- User asks to "plan a feature" / "design a schema" \u2192 if the \`beacon_propose_plan\`
  MCP tool is available, design the plan and call it. If it is NOT available, the panel
  isn't wired in this repo \u2014 run \`beacon\` here once, then retry.
- User asks to "set up Beacon" / "map this repo" \u2192 invoke the \`beacon-init\` skill.
- User asks to "refresh Beacon" / "update the map" / "bring Beacon up to date" \u2192 invoke
  the \`beacon-refresh\` skill. Re-surveys the repo and updates init-derived nodes while
  preserving anything the user added by hand.
- Run \`beacon doctor\` to audit what's wired (global hooks, repo's .mcp.json, AGENTS.md block).

**The plan feedback loop**
\`beacon_propose_plan\` BLOCKS until the user clicks Approve / Discard / submits feedback.
Feedback bundles inline annotations on the markdown PLUS any edits the user made directly
on the /map and /db boards (added features, attached subtasks, edited columns, new
endpoints). Treat board edits as the user's revision intent \u2014 re-propose matching them
verbatim. Do NOT implement until the tool returns approval.`;var BQ=g(()=>{v=["beacon-init","beacon-refresh","beacon-plan"]});import{mkdirSync as uZ,renameSync as TZ,rmSync as FZ,writeFileSync as gZ}from"fs";import{dirname as RZ}from"path";function NQ(Q,Z){uZ(RZ(Q),{recursive:!0});let $=`${Q}.tmp`;try{gZ($,Z),TZ($,Q)}catch(J){throw FZ($,{force:!0}),J}}var hQ=()=>{};var tQ={};qQ(tQ,{setupCodexAssets:()=>IZ,removeCodexMcp:()=>nQ,removeCodexArtifacts:()=>OZ,hasCodexMcp:()=>CQ,ensureCodexMcp:()=>lQ,codexMcpProblem:()=>MQ,codexDetected:()=>QQ,auditCodex:()=>fQ,CODEX_HOOKS:()=>K});import{readFileSync as e}from"fs";import{homedir as EZ}from"os";import{join as O}from"path";function SQ(){return process.env.HOME||process.env.USERPROFILE||EZ()}function QQ(){if(process.env.BEACON_CODEX==="1")return!0;if(process.env.BEACON_CODEX==="0")return!1;if(xQ===void 0)xQ=Bun.which("codex")!==null;return xQ}function I(Q){try{return Bun.TOML.parse(Q)}catch{return null}}function CQ(){try{return Boolean(I(e(w(),"utf8"))?.mcp_servers?.beacon)}catch{return!1}}function MQ(){let Q="";try{Q=e(w(),"utf8")}catch{return null}let Z=I(Q);if(!Z)return`~/.codex/config.toml does not parse \u2014 ${D}`;if(Z.mcp_servers?.beacon)return null;if(/^\s*mcp_servers\s*=/m.test(Q))return`mcp_servers is an inline table \u2014 ${D}`;return null}function lQ(){let Q="",Z=!1;try{Q=e(w(),"utf8"),Z=!0}catch{}if(Z){let V=I(Q);if(!V)return{added:!1,error:`~/.codex/config.toml does not parse \u2014 ${D}`};if(V.mcp_servers?.beacon)return{added:!1};if(/^\s*mcp_servers\s*=/m.test(Q))return{added:!1,error:`mcp_servers is an inline table \u2014 ${D}`}}let $=!Q?"":Q.endsWith(`
`)?`
`:`

`,J=Q+$+DZ;if(I(J)?.mcp_servers?.beacon?.command!=="beacon")return{added:!1,error:`could not safely append [mcp_servers.beacon] \u2014 ${D}`};return NQ(w(),J),{added:!0}}function nQ(){let Q="";try{Q=e(w(),"utf8")}catch{return{removed:!1}}let Z=Q.split(`
`),$=Z.indexOf(pQ);if($===-1)return{removed:!1,skipped:CQ()};let J=Z.indexOf(cQ,$);if(J===-1)return{removed:!1,skipped:!0};Z.splice($,J-$+1);let Y=Z.join(`
`).replace(/\n{3,}/g,`

`).replace(/^\n+/,"");if(I(Y)===null)return{removed:!1,skipped:!0};return NQ(w(),Y),{removed:!0}}async function IZ(){let{INIT_SKILL:Q,REFRESH_SKILL:Z,PLAN_SKILL:$}=await Promise.resolve().then(() => (L(),HQ)),J={"beacon-init":Q,"beacon-refresh":Z,"beacon-plan":$},Y=[];for(let z of v){if(!E(i(),z))Y.push(z);a(i(),z,J[z])}let V=0;for(let z of K)if(c(KQ(),{event:z.event,matcher:z.matcher,command:z.command}))V++;let X=R(r(),o);t(r(),o,mQ,p);let U=lQ();return{skillsAdded:Y,hooksAdded:V,agentsMdBlockTouched:!X,mcp:U}}function fQ(){let Q={};for(let $ of v)Q[$]=E(i(),$);let Z={};for(let $ of K)Z[$.event]=l(KQ(),{event:$.event,command:$.command});return{detected:QQ(),skills:Q,hooks:Z,agentsMdBlock:R(r(),o),mcp:CQ()}}function OZ(){let Q=[];for(let Y of v)if(d(i(),Y))Q.push(Y);let Z=0;for(let Y of K)if(n(KQ(),{event:Y.event,command:Y.command}))Z++;let $=s(r(),o,mQ),J=nQ();return{skillsRemoved:Q,hooksRemoved:Z,agentsMdBlockRemoved:$,mcpRemoved:J.removed,mcpSkipped:J.skipped}}var GQ=()=>O(SQ(),".codex"),KQ=()=>O(GQ(),"hooks.json"),w=()=>O(GQ(),"config.toml"),r=()=>O(GQ(),"AGENTS.md"),i=()=>O(SQ(),".agents","skills"),o="<!-- beacon:global:start -->",mQ="<!-- beacon:global:end -->",K,xQ,pQ="# beacon:start (managed by Beacon \u2014 `beacon uninstall` removes this block)",cQ="# beacon:end",DZ,D="add it manually: codex mcp add beacon -- beacon mcp";var wQ=g(()=>{BQ();hQ();K=[{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."}];DZ=`${pQ}
[mcp_servers.beacon]
command = "beacon"
args = ["mcp"]
${cQ}
`});var oQ={};qQ(oQ,{provisionDb:()=>$0});import{createClient as nZ}from"@libsql/client";import{drizzle as tZ}from"drizzle-orm/libsql";import{migrate as sZ}from"drizzle-orm/libsql/migrator";import{readMigrationFiles as aZ}from"drizzle-orm/migrator";import{dirname as RQ,join as dZ}from"path";import{fileURLToPath as rZ}from"url";async function JQ(Q,Z){return(await Q.execute({sql:"SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?",args:[Z]})).rows.length>0}async function Q0(Q,Z){let $=await Q.execute(`PRAGMA table_info("${Z}")`);return new Set($.rows.map((J)=>String(J.name)))}async function iQ(Q){if(!await JQ(Q,"__drizzle_migrations"))return 0;let Z=await Q.execute('SELECT count(*) AS n FROM "__drizzle_migrations"');return Number(Z.rows[0]?.n??0)}async function Z0(Q){for(let[Z,$]of Object.entries(eZ)){if(!await JQ(Q,Z))continue;let J=await Q0(Q,Z);for(let Y of $){if(!J.has(Y))continue;await Q.execute(`UPDATE "${Z}" SET "${Y}" = CAST((julianday("${Y}") - 2440587.5) * 86400000 AS INTEGER) WHERE typeof("${Y}") = 'text'`)}}}async function $0(Q,Z=oZ){let $=nZ({url:Q});try{await $.execute("PRAGMA journal_mode = WAL;"),await $.execute("PRAGMA foreign_keys = ON;");let J=await JQ($,"__drizzle_migrations"),Y=await JQ($,"Node"),V=!1;if(Y&&!J){let U=aZ({migrationsFolder:Z})[0];if(U)await $.execute('CREATE TABLE IF NOT EXISTS "__drizzle_migrations" (id SERIAL PRIMARY KEY, hash text NOT NULL, created_at numeric)'),await $.execute({sql:'INSERT INTO "__drizzle_migrations" ("hash", "created_at") VALUES (?, ?)',args:[U.hash,U.folderMillis]}),V=!0}let X=await iQ($);if(await sZ(tZ($),{migrationsFolder:Z}),await iQ($)>X)V=!0;return await Z0($),{migrated:V}}finally{$.close()}}var iZ,oZ,eZ;var eQ=g(async()=>{iZ=RQ(RQ(RQ(rZ(import.meta.url)))),oZ=process.env.BEACON_MIGRATIONS_DIR||dZ(iZ,"drizzle"),eZ={Node:["createdAt","updatedAt"],Note:["createdAt","updatedAt"],DbTable:["createdAt","updatedAt"],Endpoint:["createdAt","updatedAt"],DraftTable:["createdAt"],SyncState:["codeGraphSyncedAt","updatedAt"],AppSetting:["updatedAt"],ProjectMeta:["updatedAt"],CodeFile:["updatedAt"]}});BQ();import{existsSync as yZ}from"fs";import{homedir as AZ}from"os";import{join as ZQ}from"path";function bZ(){return process.env.HOME||process.env.USERPROFILE||AZ()}var $Q=()=>ZQ(bZ(),".claude"),uQ=()=>ZQ($Q(),"skills"),TQ=()=>ZQ($Q(),"settings.json"),FQ=()=>ZQ($Q(),"CLAUDE.md"),gQ="<!-- beacon:global:start -->",sQ="<!-- beacon:global:end -->";var _Z=p,u=[{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 kZ(Q,Z){return a(uQ(),Q,Z)}function aQ(Q){return E(uQ(),Q)}function LZ(Q){return d(uQ(),Q)}function hZ(Q){return c(TQ(),Q)}function SZ(Q){return l(TQ(),Q)}function mZ(Q){return n(TQ(),Q)}function pZ(Q){t(FQ(),gQ,sQ,Q)}function dQ(){return R(FQ(),gQ)}function cZ(){return s(FQ(),gQ,sQ)}function rQ(){let Q={};for(let $ of v)Q[$]=aQ($);let Z={};for(let $ of u)Z[$.event]=SZ({event:$.event,command:$.command});return{homeExists:yZ($Q()),skills:Q,hooks:Z,claudeMdBlock:dQ()}}async function lZ(){let{INIT_SKILL:Q,REFRESH_SKILL:Z,PLAN_SKILL:$}=await Promise.resolve().then(() => (L(),HQ)),J={"beacon-init":Q,"beacon-refresh":Z,"beacon-plan":$},Y=[];for(let U of v){if(!aQ(U))Y.push(U);kZ(U,J[U])}let V=0;for(let U of u)if(hZ({event:U.event,matcher:U.matcher,command:U.command}))V++;let X=dQ();return pZ(_Z),{skillsAdded:Y,hooksAdded:V,claudeMdBlockTouched:!X}}async function m0(){let Q;try{Q={ok:!0,...await lZ()}}catch(Z){Q={ok:!1,error:Z instanceof Error?Z.message:String(Z),skillsAdded:[],hooksAdded:0,claudeMdBlockTouched:!1}}try{let Z=await Promise.resolve().then(() => (wQ(),tQ));if(Z.codexDetected())Q.codex={ok:!0,...await Z.setupCodexAssets()}}catch(Z){Q.codex={ok:!1,error:Z instanceof Error?Z.message:String(Z),skillsAdded:[],hooksAdded:0,agentsMdBlockTouched:!1,mcp:{added:!1}}}return Q}function p0(){let Q=[];for(let J of v)if(LZ(J))Q.push(J);let Z=0;for(let J of u)if(mZ(J))Z++;let $=cZ();return{skillsRemoved:Q,hooksRemoved:Z,claudeMdBlockRemoved:$}}import{AsyncLocalStorage as J0}from"async_hooks";import{spawnSync as Y0}from"child_process";import{createHash as V0}from"crypto";import{existsSync as ZZ,mkdirSync as YQ,readFileSync as $Z,writeFileSync as JZ}from"fs";import{homedir as z0}from"os";import{basename as q0,join as T}from"path";function G(){return process.env.BEACON_HOME||T(z0(),".beacon")}function EQ(){return T(G(),"workspaces.json")}function YZ(Q){return V0("sha256").update(Q).digest("hex").slice(0,12)}function $1(Q=process.cwd()){let Z=Y0("git",["rev-parse","--show-toplevel"],{cwd:Q,stdio:["ignore","pipe","ignore"]});if(Z.status===0){let $=Z.stdout?.toString().trim();if($)return $}return Q}function DQ(Q){return T(G(),Q)}function X0(Q){return`file:${T(DQ(Q),"db.sqlite")}`}function y(){try{let Q=JSON.parse($Z(EQ(),"utf8"));return Array.isArray(Q)?Q:[]}catch{return[]}}function IQ(Q){YQ(G(),{recursive:!0}),JZ(EQ(),JSON.stringify(Q,null,2))}function OQ(){return y().sort((Q,Z)=>Z.lastOpenedAt.localeCompare(Q.lastOpenedAt))}function C(Q){return y().find((Z)=>Z.id===Q)??null}function U0(Q,Z,$=new Date().toISOString()){let J=YZ(Q),Y=y(),V=Y.find((z)=>z.id===J),X={id:J,path:Q,name:Z||V?.name||q0(Q),lastOpenedAt:$},U=[X,...Y.filter((z)=>z.id!==J)];return YQ(DQ(J),{recursive:!0}),IQ(U),X}function J1(Q,Z=new Date().toISOString()){let $=y(),J=$.find((Y)=>Y.id===Q);if(!J)return;J.lastOpenedAt=Z,IQ($)}function Y1(Q){if(IQ(y().filter((Z)=>Z.id!==Q)),yQ()===Q)W0(OQ()[0]?.id??null)}function VZ(){return T(G(),"active")}function yQ(){try{return $Z(VZ(),"utf8").trim()||null}catch{return null}}function W0(Q){YQ(G(),{recursive:!0}),JZ(VZ(),Q??"")}function V1(){let Q=yQ();return Q?C(Q):null}function z1(){let Q=H0()??yQ();return Q?C(Q):null}function q1(Q){return C(Q)?.path??null}function X1(){return ZZ(EQ())}var zZ="beacon_ws";function qZ(Q,Z){let $=Q.headers.get("cookie");if(!$)return null;for(let J of $.split(";")){let Y=J.indexOf("=");if(Y===-1)continue;if(J.slice(0,Y).trim()===Z)return decodeURIComponent(J.slice(Y+1).trim())}return null}function U1(Q){let Z=Q.headers.get("x-beacon-workspace");if(Z&&C(Z))return Z;let $=qZ(Q,zZ);if($&&C($))return $;return null}var P0="x-beacon-workspace-path";async function W1(Q){let Z=Q.headers.get("x-beacon-workspace");if(Z&&C(Z))return Z;let $=Q.headers.get(P0);if($&&(!Z||YZ($)===Z)){let Y=U0($);return await j0(Y.id),Y.id}let J=qZ(Q,zZ);if(J&&C(J))return J;return null}var XZ=new J0;function P1(Q,Z){return Q?XZ.run(Q,Z):Z()}function H0(){return XZ.getStore()??null}var QZ=new Set;async function j0(Q){let Z=DQ(Q),$=T(Z,"db.sqlite"),J=ZZ($);if(J&&QZ.has($))return{ok:!0,created:!1,migrated:!1};try{YQ(Z,{recursive:!0});let{provisionDb:Y}=await eQ().then(() => oQ),V=await Y(X0(Q));return QZ.add($),{ok:!0,created:!J,migrated:J&&V.migrated}}catch(Y){return{ok:!1,created:!1,migrated:!1,error:Y instanceof Error?Y.message:String(Y)}}}L();wQ();import{execSync as v0,spawnSync as UZ}from"child_process";import{existsSync as B0,readFileSync as N0}from"fs";import{join as WZ}from"path";var W=(Q)=>`\x1B[32m\u2713\x1B[0m ${Q}`,P=(Q)=>`\x1B[31m\u2717\x1B[0m ${Q}`,M=(Q)=>`\x1B[2m${Q}\x1B[0m`,A=(Q)=>`
\x1B[1m${Q}\x1B[0m`;function x0(){try{return v0("git rev-parse --show-toplevel",{cwd:process.cwd(),stdio:["ignore","pipe","ignore"]}).toString().trim()}catch{return""}}function G0(){let Q=WZ(G(),"server.json");try{let Z=JSON.parse(N0(Q,"utf8"));if(!Z.pid)return P("daemon: no server.json yet");try{return process.kill(Z.pid,0),W(`daemon running (pid ${Z.pid}, port ${Z.port??"?"})`)}catch{return P(`daemon NOT running (server.json stale: pid ${Z.pid})`)}}catch{return P("daemon: no server.json (never started)")}}function K0(){let Q=UZ("bun",["--version"],{stdio:["ignore","pipe","ignore"]});if(Q.status===0)return W(`bun ${Q.stdout.toString().trim()}`);return P("bun NOT found on PATH (required to run Beacon)")}function C0(){return x0()||process.cwd()}var VQ=C0(),F=rQ(),PZ=OQ(),M0=PZ.some((Q)=>Q.path===VQ),H=M0||B0(WZ(VQ,".mcp.json"))?PQ(VQ):null;console.log(A("Beacon \xB7 doctor"));console.log(A("Runtime"));console.log(`  ${K0()}`);console.log(`  ${G0()}`);console.log(`  ${W(`home: ${G()}`)}`);console.log(`  ${W(`workspaces registered: ${PZ.length}`)}`);console.log(A("Global (~/.claude/)"));for(let Q of v)console.log(`  ${F.skills[Q]?W(`skill ${Q}`):P(`skill ${Q} \u2014 missing`)}`);for(let Q of u)console.log(`  ${F.hooks[Q.event]?W(`hook ${Q.event} \u2192 ${Q.command}`):P(`hook ${Q.event} \u2192 ${Q.command} \u2014 missing`)}   ${M(Q.description)}`);console.log(`  ${F.claudeMdBlock?W("global CLAUDE.md block"):P("global CLAUDE.md block \u2014 missing (every Claude session won't auto-discover Beacon)")}`);console.log(A("Codex (~/.codex/ + ~/.agents/)"));var B=QQ()?fQ():null;if(!B)console.log(`  ${M("codex not on PATH \u2014 Codex integration inactive (wires automatically once codex is installed)")}`);else{let Q=UZ("codex",["--version"],{stdio:["ignore","pipe","ignore"]});console.log(`  ${Q.status===0?W(`codex ${Q.stdout.toString().trim()}`):M("codex version unavailable (BEACON_CODEX override?)")}`);for(let $ of v)console.log(`  ${B.skills[$]?W(`skill ${$} (~/.agents/skills)`):P(`skill ${$} (~/.agents/skills) \u2014 missing`)}`);for(let $ of K)console.log(`  ${B.hooks[$.event]?W(`hook ${$.event} \u2192 ${$.command}`):P(`hook ${$.event} \u2192 ${$.command} \u2014 missing`)}   ${M($.description)}`);console.log(`  ${B.agentsMdBlock?W("global ~/.codex/AGENTS.md block"):P("global ~/.codex/AGENTS.md block \u2014 missing")}`);let Z=MQ();console.log(`  ${B.mcp?W("config.toml has [mcp_servers.beacon]"):P(`config.toml missing [mcp_servers.beacon]${Z?` \u2014 ${Z}`:""}`)}`)}console.log(A(`Current repo (${VQ})`));if(!H)console.log(`  ${M("not registered with Beacon and no .mcp.json \u2014 run `beacon` here to wire it.")}`);else if(console.log(`  ${H.mcpRegistered?W(".mcp.json has beacon entry"):P(".mcp.json missing beacon entry")}`),console.log(`  ${H.agentsMdBlock?W("AGENTS.md has Beacon workflow block"):P("AGENTS.md missing Beacon workflow block")}`),console.log(`  ${H.claudeMdImport?W("CLAUDE.md @-imports AGENTS.md"):P("CLAUDE.md does NOT @-import AGENTS.md")}`),console.log(`  ${H.skills["beacon-init"]?W("skill beacon-init (repo)"):P("skill beacon-init (repo) \u2014 missing")}`),console.log(`  ${H.skills["beacon-refresh"]?W("skill beacon-refresh (repo)"):P("skill beacon-refresh (repo) \u2014 missing")}`),B)console.log(`  ${H.codexSkills["beacon-init"]?W("skill beacon-init (.agents/skills)"):P("skill beacon-init (.agents/skills) \u2014 missing")}`),console.log(`  ${H.codexSkills["beacon-refresh"]?W("skill beacon-refresh (.agents/skills)"):P("skill beacon-refresh (.agents/skills) \u2014 missing")}`);var f0=v.some((Q)=>!F.skills[Q])||u.some((Q)=>!F.hooks[Q.event])||!F.claudeMdBlock||(B?v.some((Q)=>!B.skills[Q])||K.some((Q)=>!B.hooks[Q.event])||!B.agentsMdBlock||!B.mcp:!1)||(H?!H.mcpRegistered||!H.agentsMdBlock||!H.claudeMdImport||!H.skills["beacon-init"]||!H.skills["beacon-refresh"]||(B?!H.codexSkills["beacon-init"]||!H.codexSkills["beacon-refresh"]:!1):!1);if(f0)console.log(`
${M("Fix everything marked \u2717 by running")} \x1B[1mbeacon\x1B[0m ${M("in this repo.")}`);console.log();
