#!/usr/bin/env bun
// @bun
var xZ=Object.defineProperty;var GZ=(Q)=>Q;function KZ(Q,Z){this[Q]=GZ.bind(null,Z)}var ZQ=(Q,Z)=>{for(var $ in Z)xZ(Q,$,{get:Z[$],enumerable:!0,configurable:!0,set:KZ.bind(Z,$)})};var T=(Q,Z)=>()=>(Q&&(Z=Q(Q=0)),Z);var VQ={};ZQ(VQ,{removeRepoAssets:()=>uZ,installRefreshSkill:()=>vZ,installPlanSkill:()=>CZ,installInitSkill:()=>NZ,installCodexRepoSkills:()=>TZ,ensureWorkflowDoc:()=>gZ,ensureMcp:()=>wZ,auditRepo:()=>FZ,REFRESH_SKILL:()=>YQ,PLAN_SKILL:()=>fQ,INIT_SKILL:()=>$Q});import{existsSync as N,mkdirSync as D,readFileSync as P,rmSync as b,writeFileSync as H}from"fs";import{join as W}from"path";function NZ(Q){let Z=W(Q,".claude","skills","beacon-init");D(Z,{recursive:!0});let $=W(Z,"SKILL.md");return H($,$Q),$}function vZ(Q){let Z=W(Q,".claude","skills","beacon-refresh");D(Z,{recursive:!0});let $=W(Z,"SKILL.md");return H($,YQ),$}function CZ(Q){let Z=W(Q,".claude","skills","beacon-plan");D(Z,{recursive:!0});let $=W(Z,"SKILL.md");return H($,fQ),$}function TZ(Q){let Z=[];for(let $ of MZ){let Y=W(Q,".agents","skills",$.name);D(Y,{recursive:!0});let J=W(Y,"SKILL.md");H(J,$.body()),Z.push(J)}return Z}function gZ(Q){let Z=W(Q,"AGENTS.md"),$="";try{$=P(Z,"utf8")}catch{}let Y=new RegExp(`${I}[\\s\\S]*?${JQ}`);$=Y.test($)?$.replace(Y,RQ):`${$.trim()}

${RQ}
`.trimStart(),H(Z,$.endsWith(`
`)?$:`${$}
`);let J=W(Q,"CLAUDE.md"),V="";try{V=P(J,"utf8")}catch{}if(!/@AGENTS\.md/.test(V))H(J,`${V?`${V.trim()}

`:""}@AGENTS.md
`)}function wZ(Q){let Z=W(Q,".mcp.json"),$={};try{$=JSON.parse(P(Z,"utf8"))}catch{}if($.mcpServers=$.mcpServers??{},$.mcpServers.beacon)return{path:Z,added:!1};return $.mcpServers.beacon={command:"beacon",args:["mcp"]},H(Z,JSON.stringify($,null,2)+`
`),{path:Z,added:!0}}function FZ(Q){let Z=W(Q,".mcp.json"),$=!1;try{$=!!JSON.parse(P(Z,"utf8")).mcpServers?.beacon}catch{}let Y=!1;try{Y=P(W(Q,"AGENTS.md"),"utf8").includes(I)}catch{}let J=!1;try{J=/@AGENTS\.md/.test(P(W(Q,"CLAUDE.md"),"utf8"))}catch{}return{repo:Q,mcpRegistered:$,agentsMdBlock:Y,claudeMdImport:J,skills:{"beacon-init":N(W(Q,".claude","skills","beacon-init","SKILL.md")),"beacon-refresh":N(W(Q,".claude","skills","beacon-refresh","SKILL.md"))},codexSkills:{"beacon-init":N(W(Q,".agents","skills","beacon-init","SKILL.md")),"beacon-refresh":N(W(Q,".agents","skills","beacon-refresh","SKILL.md"))}}}function uZ(Q){let Z=[];for(let z of["beacon-init","beacon-refresh","beacon-db-design"]){let U=W(Q,".claude","skills",z);if(N(U))b(U,{recursive:!0,force:!0}),Z.push(z)}for(let z of["beacon-init","beacon-refresh"]){let U=W(Q,".agents","skills",z);if(N(U))b(U,{recursive:!0,force:!0}),Z.push(`codex:${z}`)}let $=!1,Y=W(Q,".mcp.json");try{let z=JSON.parse(P(Y,"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(Y,{force:!0});else H(Y,JSON.stringify(z,null,2)+`
`)}}catch{}let J=!1,V=W(Q,"AGENTS.md");try{let z=P(V,"utf8"),U=new RegExp(`\\n?${I}[\\s\\S]*?${JQ}\\n?`);if(U.test(z)){let M=z.replace(U,`
`).replace(/\n{3,}/g,`

`).trimStart();H(V,M.endsWith(`
`)?M:`${M}
`),J=!0}}catch{}let X=!1,q=W(Q,"CLAUDE.md");try{let z=P(q,"utf8"),U=z.replace(/^[ \t]*@AGENTS\.md[ \t]*\n?/m,"");if(U!==z){if(!U.trim())b(q,{force:!0});else H(q,U);X=!0}}catch{}return{skillsRemoved:Z,mcpUnregistered:$,agentsBlockRemoved:J,claudeImportRemoved:X}}var $Q=`---
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.
`,YQ=`---
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.
`,fQ=`---
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.
`,MZ,I="<!-- beacon:workflow:start -->",JQ="<!-- beacon:workflow:end -->",RQ;var zQ=T(()=>{MZ=[{name:"beacon-init",body:()=>$Q},{name:"beacon-refresh",body:()=>YQ}];RQ=`${I}
## 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).
${JQ}`});import{existsSync as bQ,mkdirSync as qQ,readFileSync as E,rmSync as RZ,writeFileSync as O}from"fs";import{dirname as DQ,join as A}from"path";function XQ(Q){try{return JSON.parse(E(Q,"utf8"))}catch{return{}}}function IQ(Q,Z){qQ(DQ(Q),{recursive:!0}),O(Q,JSON.stringify(Z,null,2)+`
`)}function k(Q,Z){let $=XQ(Q);$.hooks=$.hooks??{},$.hooks[Z.event]=$.hooks[Z.event]??[];let Y=$.hooks[Z.event];if(Y.some((V)=>V.matcher===Z.matcher&&V.hooks?.some((X)=>X.command===Z.command)))return!1;return Y.push({matcher:Z.matcher,hooks:[{type:"command",command:Z.command}]}),IQ(Q,$),!0}function L(Q,Z){return(XQ(Q).hooks?.[Z.event]??[]).some((J)=>J.hooks?.some((V)=>V.command===Z.command))}function _(Q,Z){let $=XQ(Q),Y=$.hooks?.[Z.event];if(!Y)return!1;let J=!1,V=Y.map((X)=>{let q=X.hooks?.length??0,z=(X.hooks??[]).filter((U)=>U.command!==Z.command);if(z.length!==q)J=!0;return{...X,hooks:z}}).filter((X)=>(X.hooks??[]).length>0);if(!J)return!1;if(V.length)$.hooks[Z.event]=V;else delete $.hooks[Z.event];if($.hooks&&Object.keys($.hooks).length===0)delete $.hooks;return IQ(Q,$),!0}function h(Q,Z,$,Y){let J=`${Z}
${Y.trim()}
${$}`,V="";try{V=E(Q,"utf8")}catch{}let X=new RegExp(`${Z}[\\s\\S]*?${$}`);V=X.test(V)?V.replace(X,J):V.trim()?`${V.trim()}

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

`).trimStart();return O(Q,V),!0}function m(Q,Z,$){let Y=A(Q,Z);qQ(Y,{recursive:!0});let J=A(Y,"SKILL.md");return O(J,$),J}function w(Q,Z){return bQ(A(Q,Z,"SKILL.md"))}function p(Q,Z){let $=A(Q,Z);if(!bQ($))return!1;return RZ($,{recursive:!0,force:!0}),!0}var j,y=`## 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 WQ=T(()=>{j=["beacon-init","beacon-refresh","beacon-plan"]});import{mkdirSync as fZ,renameSync as bZ,rmSync as DZ,writeFileSync as IZ}from"fs";import{dirname as AZ}from"path";function UQ(Q,Z){fZ(AZ(Q),{recursive:!0});let $=`${Q}.tmp`;try{IZ($,Z),bZ($,Q)}catch(Y){throw DZ($,{force:!0}),Y}}var AQ=()=>{};var SQ={};ZQ(SQ,{setupCodexAssets:()=>kZ,removeCodexMcp:()=>hQ,removeCodexArtifacts:()=>_Z,hasCodexMcp:()=>jQ,ensureCodexMcp:()=>_Q,codexMcpProblem:()=>yZ,codexDetected:()=>yQ,auditCodex:()=>LZ,CODEX_HOOKS:()=>n});import{readFileSync as a}from"fs";import{homedir as EZ}from"os";import{join as R}from"path";function EQ(){return process.env.HOME||process.env.USERPROFILE||EZ()}function yQ(){if(process.env.BEACON_CODEX==="1")return!0;if(process.env.BEACON_CODEX==="0")return!1;if(BQ===void 0)BQ=Bun.which("codex")!==null;return BQ}function u(Q){try{return Bun.TOML.parse(Q)}catch{return null}}function jQ(){try{return Boolean(u(a(v(),"utf8"))?.mcp_servers?.beacon)}catch{return!1}}function yZ(){let Q="";try{Q=a(v(),"utf8")}catch{return null}let Z=u(Q);if(!Z)return`~/.codex/config.toml does not parse \u2014 ${F}`;if(Z.mcp_servers?.beacon)return null;if(/^\s*mcp_servers\s*=/m.test(Q))return`mcp_servers is an inline table \u2014 ${F}`;return null}function _Q(){let Q="",Z=!1;try{Q=a(v(),"utf8"),Z=!0}catch{}if(Z){let V=u(Q);if(!V)return{added:!1,error:`~/.codex/config.toml does not parse \u2014 ${F}`};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 ${F}`}}let $=!Q?"":Q.endsWith(`
`)?`
`:`

`,Y=Q+$+OZ;if(u(Y)?.mcp_servers?.beacon?.command!=="beacon")return{added:!1,error:`could not safely append [mcp_servers.beacon] \u2014 ${F}`};return UQ(v(),Y),{added:!0}}function hQ(){let Q="";try{Q=a(v(),"utf8")}catch{return{removed:!1}}let Z=Q.split(`
`),$=Z.indexOf(kQ);if($===-1)return{removed:!1,skipped:jQ()};let Y=Z.indexOf(LQ,$);if(Y===-1)return{removed:!1,skipped:!0};Z.splice($,Y-$+1);let J=Z.join(`
`).replace(/\n{3,}/g,`

`).replace(/^\n+/,"");if(u(J)===null)return{removed:!1,skipped:!0};return UQ(v(),J),{removed:!0}}async function kZ(){let{INIT_SKILL:Q,REFRESH_SKILL:Z,PLAN_SKILL:$}=await Promise.resolve().then(() => (zQ(),VQ)),Y={"beacon-init":Q,"beacon-refresh":Z,"beacon-plan":$},J=[];for(let z of j){if(!w(d(),z))J.push(z);m(d(),z,Y[z])}let V=0;for(let z of n)if(k(PQ(),{event:z.event,matcher:z.matcher,command:z.command}))V++;let X=g(c(),l);h(c(),l,OQ,y);let q=_Q();return{skillsAdded:J,hooksAdded:V,agentsMdBlockTouched:!X,mcp:q}}function LZ(){let Q={};for(let $ of j)Q[$]=w(d(),$);let Z={};for(let $ of n)Z[$.event]=L(PQ(),{event:$.event,command:$.command});return{detected:yQ(),skills:Q,hooks:Z,agentsMdBlock:g(c(),l),mcp:jQ()}}function _Z(){let Q=[];for(let J of j)if(p(d(),J))Q.push(J);let Z=0;for(let J of n)if(_(PQ(),{event:J.event,command:J.command}))Z++;let $=S(c(),l,OQ),Y=hQ();return{skillsRemoved:Q,hooksRemoved:Z,agentsMdBlockRemoved:$,mcpRemoved:Y.removed,mcpSkipped:Y.skipped}}var HQ=()=>R(EQ(),".codex"),PQ=()=>R(HQ(),"hooks.json"),v=()=>R(HQ(),"config.toml"),c=()=>R(HQ(),"AGENTS.md"),d=()=>R(EQ(),".agents","skills"),l="<!-- beacon:global:start -->",OQ="<!-- beacon:global:end -->",n,BQ,kQ="# beacon:start (managed by Beacon \u2014 `beacon uninstall` removes this block)",LQ="# beacon:end",OZ,F="add it manually: codex mcp add beacon -- beacon mcp";var mQ=T(()=>{WQ();AQ();n=[{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."}];OZ=`${kQ}
[mcp_servers.beacon]
command = "beacon"
args = ["mcp"]
${LQ}
`});var nQ={};ZQ(nQ,{provisionDb:()=>X0});import{createClient as oZ}from"@libsql/client";import{drizzle as iZ}from"drizzle-orm/libsql";import{migrate as eZ}from"drizzle-orm/libsql/migrator";import{readMigrationFiles as Q0}from"drizzle-orm/migrator";import{dirname as CQ,join as Z0}from"path";import{fileURLToPath as $0}from"url";async function r(Q,Z){return(await Q.execute({sql:"SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?",args:[Z]})).rows.length>0}async function z0(Q,Z){let $=await Q.execute(`PRAGMA table_info("${Z}")`);return new Set($.rows.map((Y)=>String(Y.name)))}async function aQ(Q){if(!await r(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 q0(Q){for(let[Z,$]of Object.entries(V0)){if(!await r(Q,Z))continue;let Y=await z0(Q,Z);for(let J of $){if(!Y.has(J))continue;await Q.execute(`UPDATE "${Z}" SET "${J}" = CAST((julianday("${J}") - 2440587.5) * 86400000 AS INTEGER) WHERE typeof("${J}") = 'text'`)}}}async function X0(Q,Z=J0){let $=oZ({url:Q});try{await $.execute("PRAGMA journal_mode = WAL;"),await $.execute("PRAGMA foreign_keys = ON;");let Y=await r($,"__drizzle_migrations"),J=await r($,"Node"),V=!1;if(J&&!Y){let q=Q0({migrationsFolder:Z})[0];if(q)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:[q.hash,q.folderMillis]}),V=!0}let X=await aQ($);if(await eZ(iZ($),{migrationsFolder:Z}),await aQ($)>X)V=!0;return await q0($),{migrated:V}}finally{$.close()}}var Y0,J0,V0;var tQ=T(async()=>{Y0=CQ(CQ(CQ($0(import.meta.url)))),J0=process.env.BEACON_MIGRATIONS_DIR||Z0(Y0,"drizzle"),V0={Node:["createdAt","updatedAt"],Note:["createdAt","updatedAt"],DbTable:["createdAt","updatedAt"],Endpoint:["createdAt","updatedAt"],DraftTable:["createdAt"],SyncState:["codeGraphSyncedAt","updatedAt"],AppSetting:["updatedAt"],ProjectMeta:["updatedAt"],CodeFile:["updatedAt"]}});WQ();import{existsSync as hZ}from"fs";import{homedir as SZ}from"os";import{join as t}from"path";function mZ(){return process.env.HOME||process.env.USERPROFILE||SZ()}var s=()=>t(mZ(),".claude"),xQ=()=>t(s(),"skills"),GQ=()=>t(s(),"settings.json"),KQ=()=>t(s(),"CLAUDE.md"),NQ="<!-- beacon:global:start -->",pQ="<!-- beacon:global:end -->";var pZ=y,vQ=[{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 cZ(Q,Z){return m(xQ(),Q,Z)}function cQ(Q){return w(xQ(),Q)}function dZ(Q){return p(xQ(),Q)}function lZ(Q){return k(GQ(),Q)}function aZ(Q){return L(GQ(),Q)}function nZ(Q){return _(GQ(),Q)}function tZ(Q){h(KQ(),NQ,pQ,Q)}function dQ(){return g(KQ(),NQ)}function sZ(){return S(KQ(),NQ,pQ)}function X1(){let Q={};for(let $ of j)Q[$]=cQ($);let Z={};for(let $ of vQ)Z[$.event]=aZ({event:$.event,command:$.command});return{homeExists:hZ(s()),skills:Q,hooks:Z,claudeMdBlock:dQ()}}async function rZ(){let{INIT_SKILL:Q,REFRESH_SKILL:Z,PLAN_SKILL:$}=await Promise.resolve().then(() => (zQ(),VQ)),Y={"beacon-init":Q,"beacon-refresh":Z,"beacon-plan":$},J=[];for(let q of j){if(!cQ(q))J.push(q);cZ(q,Y[q])}let V=0;for(let q of vQ)if(lZ({event:q.event,matcher:q.matcher,command:q.command}))V++;let X=dQ();return tZ(pZ),{skillsAdded:J,hooksAdded:V,claudeMdBlockTouched:!X}}async function lQ(){let Q;try{Q={ok:!0,...await rZ()}}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(() => (mQ(),SQ));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 W1(){let Q=[];for(let Y of j)if(dZ(Y))Q.push(Y);let Z=0;for(let Y of vQ)if(nZ(Y))Z++;let $=sZ();return{skillsRemoved:Q,hooksRemoved:Z,claudeMdBlockRemoved:$}}import{AsyncLocalStorage as W0}from"async_hooks";import{spawnSync as U0}from"child_process";import{createHash as B0}from"crypto";import{existsSync as rQ,mkdirSync as o,readFileSync as oQ,writeFileSync as iQ}from"fs";import{homedir as H0}from"os";import{basename as P0,join as C}from"path";function G(){return process.env.BEACON_HOME||C(H0(),".beacon")}function MQ(){return C(G(),"workspaces.json")}function eQ(Q){return B0("sha256").update(Q).digest("hex").slice(0,12)}function g1(Q=process.cwd()){let Z=U0("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 TQ(Q){return C(G(),Q)}function j0(Q){return`file:${C(TQ(Q),"db.sqlite")}`}function f(){try{let Q=JSON.parse(oQ(MQ(),"utf8"));return Array.isArray(Q)?Q:[]}catch{return[]}}function gQ(Q){o(G(),{recursive:!0}),iQ(MQ(),JSON.stringify(Q,null,2))}function x0(){return f().sort((Q,Z)=>Z.lastOpenedAt.localeCompare(Q.lastOpenedAt))}function x(Q){return f().find((Z)=>Z.id===Q)??null}function G0(Q,Z,$=new Date().toISOString()){let Y=eQ(Q),J=f(),V=J.find((z)=>z.id===Y),X={id:Y,path:Q,name:Z||V?.name||P0(Q),lastOpenedAt:$},q=[X,...J.filter((z)=>z.id!==Y)];return o(TQ(Y),{recursive:!0}),gQ(q),X}function w1(Q,Z=new Date().toISOString()){let $=f(),Y=$.find((J)=>J.id===Q);if(!Y)return;Y.lastOpenedAt=Z,gQ($)}function F1(Q){if(gQ(f().filter((Z)=>Z.id!==Q)),wQ()===Q)K0(x0()[0]?.id??null)}function QZ(){return C(G(),"active")}function wQ(){try{return oQ(QZ(),"utf8").trim()||null}catch{return null}}function K0(Q){o(G(),{recursive:!0}),iQ(QZ(),Q??"")}function u1(){let Q=wQ();return Q?x(Q):null}function R1(){let Q=v0()??wQ();return Q?x(Q):null}function f1(Q){return x(Q)?.path??null}function b1(){return rQ(MQ())}var ZZ="beacon_ws";function $Z(Q,Z){let $=Q.headers.get("cookie");if(!$)return null;for(let Y of $.split(";")){let J=Y.indexOf("=");if(J===-1)continue;if(Y.slice(0,J).trim()===Z)return decodeURIComponent(Y.slice(J+1).trim())}return null}function D1(Q){let Z=Q.headers.get("x-beacon-workspace");if(Z&&x(Z))return Z;let $=$Z(Q,ZZ);if($&&x($))return $;return null}var N0="x-beacon-workspace-path";async function I1(Q){let Z=Q.headers.get("x-beacon-workspace");if(Z&&x(Z))return Z;let $=Q.headers.get(N0);if($&&(!Z||eQ($)===Z)){let J=G0($);return await C0(J.id),J.id}let Y=$Z(Q,ZZ);if(Y&&x(Y))return Y;return null}var YZ=new W0;function A1(Q,Z){return Q?YZ.run(Q,Z):Z()}function v0(){return YZ.getStore()??null}var sQ=new Set;async function C0(Q){let Z=TQ(Q),$=C(Z,"db.sqlite"),Y=rQ($);if(Y&&sQ.has($))return{ok:!0,created:!1,migrated:!1};try{o(Z,{recursive:!0});let{provisionDb:J}=await tQ().then(() => nQ),V=await J(j0(Q));return sQ.add($),{ok:!0,created:!Y,migrated:Y&&V.migrated}}catch(J){return{ok:!1,created:!1,migrated:!1,error:J instanceof Error?J.message:String(J)}}}import{execSync as HZ,spawn as F0}from"child_process";import{mkdirSync as u0,openSync as R0,readFileSync as f0,writeFileSync as b0}from"fs";import{homedir as D0,platform as UZ}from"os";import{dirname as I0,join as e}from"path";import{fileURLToPath as A0}from"url";import{createHash as E0}from"crypto";var JZ=1500,VZ=345600000,O1=1800000,y1=3000;import{mkdirSync as h1,readFileSync as T0,writeFileSync as S1}from"fs";import{join as g0}from"path";var M0=["default","acceptEdits","bypassPermissions","auto"];function zZ(Q){return typeof Q==="string"&&M0.includes(Q)}function qZ(Q,Z){let $={behavior:"allow"};if(Q)$.updatedPermissions=[{type:"setMode",mode:Q,destination:"session"}];let Y={hookEventName:"PermissionRequest",decision:$};if(Z?.trim())Y.additionalContext=Z;return{hookSpecificOutput:Y}}function w0(){return g0(G(),"preferences.json")}function XZ(){try{let Q=JSON.parse(T0(w0(),"utf8"));return{planApprovalMode:zZ(Q.planApprovalMode)?Q.planApprovalMode:void 0,planApprovalModeConfigured:Q.planApprovalModeConfigured===!0}}catch{return{}}}function WZ(Q){if(!Q?.length)return"";let Z=Q.map((Y)=>Y.id?`  \u2022 ${Y.title} \u2014 id: ${Y.id}`:`  \u2022 ${Y.title}`),$=Q.some((Y)=>Y.id);return`

This plan created these roadmap feature(s):
`+Z.join(`
`)+"\n\nWhen the work ships, register them in ONE call: `beacon_describe_feature` with a "+"`features` array \u2014 one entry per feature"+($?", 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."}var O0=e(I0(A0(import.meta.url)),".."),uQ=process.env.BEACON_HOME||e(D0(),".beacon"),PZ=e(uQ,"server.json"),BZ=process.env.PORT||"4319";function y0(Q){try{return process.kill(Q,0),!0}catch{return!1}}function k0(Q){try{return JSON.parse(f0(Q,"utf8"))}catch{return null}}async function jZ(Q){try{return(await fetch(Q)).ok}catch{return!1}}async function L0(Q,Z=60){for(let $=0;$<Z;$++){if(await jZ(Q))return!0;await new Promise((Y)=>setTimeout(Y,500))}return!1}function _0(){u0(uQ,{recursive:!0});let Q=R0(e(uQ,"server.log"),"a"),Z={...process.env,PORT:BZ,BEACON_NO_OPEN:"1"};delete Z.BEACON_REPO,delete Z.BEACON_DATA_DIR,delete Z.DATABASE_URL;let $=F0("bun",["run","dev"],{cwd:O0,env:Z,detached:!0,stdio:["ignore",Q,Q]});$.unref();let Y={pid:$.pid??0,port:BZ};return b0(PZ,JSON.stringify(Y)),Y}async function h0(){let Q=k0(PZ);if(Q&&y0(Q.pid)&&await jZ(`http://localhost:${Q.port}/api/workspace`))return Q.port;let{port:Z}=_0();return await L0(`http://localhost:${Z}/api/workspace`),Z}function S0(Q){if(process.env.BEACON_NO_OPEN)return;let Z=UZ()==="darwin"?"open":UZ()==="win32"?"start":"xdg-open";try{HZ(`${Z} "${Q}"`,{stdio:"ignore"})}catch{}}function m0(){try{return HZ("git rev-parse --show-toplevel",{cwd:process.cwd(),stdio:["ignore","pipe","ignore"]}).toString().trim()}catch{return""}}function p0(Q){return E0("sha256").update(Q).digest("hex").slice(0,12)}async function c0(){if(process.stdin.isTTY)return null;let Q=[];for await(let $ of process.stdin)Q.push($);let Z=Buffer.concat(Q).toString("utf8").trim();if(!Z)return null;try{return JSON.parse(Z)}catch{return null}}function FQ(Q,Z){return qZ(Q,Z)}function i(Q){return{hookSpecificOutput:{hookEventName:"PermissionRequest",decision:{behavior:"deny",message:Q}}}}function K(Q){process.stdout.write(JSON.stringify(Q)),process.exit(0)}(async()=>{await lQ();let Z=(await c0())?.tool_input?.plan;if(!Z||!Z.trim())K(FQ());let Y=`http://localhost:${await h0()}`,J=m0()||process.cwd(),V=p0(J);await fetch(`${Y}/api/workspace/activate?id=${V}`).catch(()=>{});let X=Z.split(`
`,1)[0]?.replace(/^#+\s*/,"").slice(0,160)||"Plan review",q=await fetch(`${Y}/api/plan`,{method:"POST",headers:{"content-type":"application/json","x-beacon-workspace":V},body:JSON.stringify({description:X,markdown:Z})});if(q.status===422){let B=await q.json().catch(()=>({}));K(i(B.error??"Beacon rejected the plan: every roadmap feature needs a category and a priority. Add them and re-present."))}if(!q.ok)K(FQ());if(!await fetch(`${Y}/api/plan/presence`,{headers:{"x-beacon-workspace":V}}).then((B)=>B.json()).then((B)=>!!B?.live).catch(()=>!1)){let B=encodeURIComponent(`/plan?ws=${V}`);S0(`${Y}/api/workspace/activate?id=${V}&redirect=${B}`)}let U=Date.now()+VZ,M=(B)=>new Promise((QQ)=>setTimeout(QQ,B));while(Date.now()<U){await M(JZ);let B=await fetch(`${Y}/api/plan/verdict`,{headers:{"x-beacon-workspace":V}}).then((QQ)=>QQ.json()).catch(()=>null);if(!B)continue;if(B.kind==="approved")K(FQ(XZ().planApprovalMode,WZ(B.features)));if(B.kind==="discarded")K(i("The user discarded the plan in Beacon. Ask what they want to adjust before re-presenting."));if(B.kind==="feedback")K(i(`The user left feedback on the plan in Beacon (inline comments and/or edits on the /map and /db boards). Revise the plan based on the feedback below, then re-present (call ExitPlanMode again):

`+B.feedback))}K(i("Beacon plan review timed out without a verdict. Re-present the plan and ask the user to review it."))})();
