#!/usr/bin/env bun
// @bun
var QZ=Object.defineProperty;var ZZ=(Q)=>Q;function $Z(Q,Z){this[Q]=ZZ.bind(null,Z)}var o=(Q,Z)=>{for(var $ in Z)QZ(Q,$,{get:Z[$],enumerable:!0,configurable:!0,set:$Z.bind(Z,$)})};var K=(Q,Z)=>()=>(Q&&(Z=Q(Q=0)),Z);var ZQ={};o(ZQ,{removeRepoAssets:()=>PZ,installRefreshSkill:()=>YZ,installPlanSkill:()=>VZ,installInitSkill:()=>JZ,installCodexRepoSkills:()=>qZ,ensureWorkflowDoc:()=>XZ,ensureMcp:()=>UZ,auditRepo:()=>WZ,REFRESH_SKILL:()=>e,PLAN_SKILL:()=>MQ,INIT_SKILL:()=>i});import{existsSync as B,mkdirSync as f,readFileSync as x,rmSync as F,writeFileSync as P}from"fs";import{join as X}from"path";function JZ(Q){let Z=X(Q,".claude","skills","beacon-init");f(Z,{recursive:!0});let $=X(Z,"SKILL.md");return P($,i),$}function YZ(Q){let Z=X(Q,".claude","skills","beacon-refresh");f(Z,{recursive:!0});let $=X(Z,"SKILL.md");return P($,e),$}function VZ(Q){let Z=X(Q,".claude","skills","beacon-plan");f(Z,{recursive:!0});let $=X(Z,"SKILL.md");return P($,MQ),$}function qZ(Q){let Z=[];for(let $ of zZ){let J=X(Q,".agents","skills",$.name);f(J,{recursive:!0});let Y=X(J,"SKILL.md");P(Y,$.body()),Z.push(Y)}return Z}function XZ(Q){let Z=X(Q,"AGENTS.md"),$="";try{$=x(Z,"utf8")}catch{}let J=new RegExp(`${R}[\\s\\S]*?${QQ}`);$=J.test($)?$.replace(J,CQ):`${$.trim()}

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

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

`).trimStart();P(V,r.endsWith(`
`)?r:`${r}
`),Y=!0}}catch{}let q=!1,U=X(Q,"CLAUDE.md");try{let z=x(U,"utf8"),W=z.replace(/^[ \t]*@AGENTS\.md[ \t]*\n?/m,"");if(W!==z){if(!W.trim())F(U,{force:!0});else P(U,W);q=!0}}catch{}return{skillsRemoved:Z,mcpUnregistered:$,agentsBlockRemoved:Y,claudeImportRemoved:q}}var i=`---
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.
`,e=`---
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.
`,MQ=`---
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.
`,zZ,R="<!-- beacon:workflow:start -->",QQ="<!-- beacon:workflow:end -->",CQ;var $Q=K(()=>{zZ=[{name:"beacon-init",body:()=>i},{name:"beacon-refresh",body:()=>e}];CQ=`${R}
## 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).
${QQ}`});import{existsSync as wQ,mkdirSync as JQ,readFileSync as D,rmSync as xZ,writeFileSync as I}from"fs";import{dirname as gQ,join as b}from"path";function YQ(Q){try{return JSON.parse(D(Q,"utf8"))}catch{return{}}}function TQ(Q,Z){JQ(gQ(Q),{recursive:!0}),I(Q,JSON.stringify(Z,null,2)+`
`)}function E(Q,Z){let $=YQ(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((q)=>q.command===Z.command)))return!1;return J.push({matcher:Z.matcher,hooks:[{type:"command",command:Z.command}]}),TQ(Q,$),!0}function A(Q,Z){return(YQ(Q).hooks?.[Z.event]??[]).some((Y)=>Y.hooks?.some((V)=>V.command===Z.command))}function y(Q,Z){let $=YQ(Q),J=$.hooks?.[Z.event];if(!J)return!1;let Y=!1,V=J.map((q)=>{let U=q.hooks?.length??0,z=(q.hooks??[]).filter((W)=>W.command!==Z.command);if(z.length!==U)Y=!0;return{...q,hooks:z}}).filter((q)=>(q.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 TQ(Q,$),!0}function k(Q,Z,$,J){let Y=`${Z}
${J.trim()}
${$}`,V="";try{V=D(Q,"utf8")}catch{}let q=new RegExp(`${Z}[\\s\\S]*?${$}`);V=q.test(V)?V.replace(q,Y):V.trim()?`${V.trim()}

${Y}
`:`${Y}
`,JQ(gQ(Q),{recursive:!0}),I(Q,V.endsWith(`
`)?V:`${V}
`)}function u(Q,Z){try{return D(Q,"utf8").includes(Z)}catch{return!1}}function L(Q,Z,$){let J="";try{J=D(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 I(Q,V),!0}function _(Q,Z,$){let J=b(Q,Z);JQ(J,{recursive:!0});let Y=b(J,"SKILL.md");return I(Y,$),Y}function v(Q,Z){return wQ(b(Q,Z,"SKILL.md"))}function h(Q,Z){let $=b(Q,Z);if(!wQ($))return!1;return xZ($,{recursive:!0,force:!0}),!0}var H,O=`## 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 VQ=K(()=>{H=["beacon-init","beacon-refresh","beacon-plan"]});import{mkdirSync as HZ,renameSync as jZ,rmSync as BZ,writeFileSync as GZ}from"fs";import{dirname as NZ}from"path";function zQ(Q,Z){HZ(NZ(Q),{recursive:!0});let $=`${Q}.tmp`;try{GZ($,Z),jZ($,Q)}catch(J){throw BZ($,{force:!0}),J}}var FQ=()=>{};var AQ={};o(AQ,{setupCodexAssets:()=>CZ,removeCodexMcp:()=>EQ,removeCodexArtifacts:()=>wZ,hasCodexMcp:()=>WQ,ensureCodexMcp:()=>OQ,codexMcpProblem:()=>vZ,codexDetected:()=>bQ,auditCodex:()=>MZ,CODEX_HOOKS:()=>n});import{readFileSync as c}from"fs";import{homedir as KZ}from"os";import{join as w}from"path";function fQ(){return process.env.HOME||process.env.USERPROFILE||KZ()}function bQ(){if(process.env.BEACON_CODEX==="1")return!0;if(process.env.BEACON_CODEX==="0")return!1;if(qQ===void 0)qQ=Bun.which("codex")!==null;return qQ}function M(Q){try{return Bun.TOML.parse(Q)}catch{return null}}function WQ(){try{return Boolean(M(c(G(),"utf8"))?.mcp_servers?.beacon)}catch{return!1}}function vZ(){let Q="";try{Q=c(G(),"utf8")}catch{return null}let Z=M(Q);if(!Z)return`~/.codex/config.toml does not parse \u2014 ${C}`;if(Z.mcp_servers?.beacon)return null;if(/^\s*mcp_servers\s*=/m.test(Q))return`mcp_servers is an inline table \u2014 ${C}`;return null}function OQ(){let Q="",Z=!1;try{Q=c(G(),"utf8"),Z=!0}catch{}if(Z){let V=M(Q);if(!V)return{added:!1,error:`~/.codex/config.toml does not parse \u2014 ${C}`};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 ${C}`}}let $=!Q?"":Q.endsWith(`
`)?`
`:`

`,J=Q+$+uZ;if(M(J)?.mcp_servers?.beacon?.command!=="beacon")return{added:!1,error:`could not safely append [mcp_servers.beacon] \u2014 ${C}`};return zQ(G(),J),{added:!0}}function EQ(){let Q="";try{Q=c(G(),"utf8")}catch{return{removed:!1}}let Z=Q.split(`
`),$=Z.indexOf(DQ);if($===-1)return{removed:!1,skipped:WQ()};let J=Z.indexOf(IQ,$);if(J===-1)return{removed:!1,skipped:!0};Z.splice($,J-$+1);let Y=Z.join(`
`).replace(/\n{3,}/g,`

`).replace(/^\n+/,"");if(M(Y)===null)return{removed:!1,skipped:!0};return zQ(G(),Y),{removed:!0}}async function CZ(){let{INIT_SKILL:Q,REFRESH_SKILL:Z,PLAN_SKILL:$}=await Promise.resolve().then(() => ($Q(),ZQ)),J={"beacon-init":Q,"beacon-refresh":Z,"beacon-plan":$},Y=[];for(let z of H){if(!v(m(),z))Y.push(z);_(m(),z,J[z])}let V=0;for(let z of n)if(E(UQ(),{event:z.event,matcher:z.matcher,command:z.command}))V++;let q=u(S(),p);k(S(),p,RQ,O);let U=OQ();return{skillsAdded:Y,hooksAdded:V,agentsMdBlockTouched:!q,mcp:U}}function MZ(){let Q={};for(let $ of H)Q[$]=v(m(),$);let Z={};for(let $ of n)Z[$.event]=A(UQ(),{event:$.event,command:$.command});return{detected:bQ(),skills:Q,hooks:Z,agentsMdBlock:u(S(),p),mcp:WQ()}}function wZ(){let Q=[];for(let Y of H)if(h(m(),Y))Q.push(Y);let Z=0;for(let Y of n)if(y(UQ(),{event:Y.event,command:Y.command}))Z++;let $=L(S(),p,RQ),J=EQ();return{skillsRemoved:Q,hooksRemoved:Z,agentsMdBlockRemoved:$,mcpRemoved:J.removed,mcpSkipped:J.skipped}}var XQ=()=>w(fQ(),".codex"),UQ=()=>w(XQ(),"hooks.json"),G=()=>w(XQ(),"config.toml"),S=()=>w(XQ(),"AGENTS.md"),m=()=>w(fQ(),".agents","skills"),p="<!-- beacon:global:start -->",RQ="<!-- beacon:global:end -->",n,qQ,DQ="# beacon:start (managed by Beacon \u2014 `beacon uninstall` removes this block)",IQ="# beacon:end",uZ,C="add it manually: codex mcp add beacon -- beacon mcp";var yQ=K(()=>{VQ();FQ();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."}];uZ=`${DQ}
[mcp_servers.beacon]
command = "beacon"
args = ["mcp"]
${IQ}
`});var mQ={};o(mQ,{provisionDb:()=>lZ});import{createClient as kZ}from"@libsql/client";import{drizzle as LZ}from"drizzle-orm/libsql";import{migrate as _Z}from"drizzle-orm/libsql/migrator";import{readMigrationFiles as hZ}from"drizzle-orm/migrator";import{dirname as GQ,join as SZ}from"path";import{fileURLToPath as mZ}from"url";async function l(Q,Z){return(await Q.execute({sql:"SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?",args:[Z]})).rows.length>0}async function aZ(Q,Z){let $=await Q.execute(`PRAGMA table_info("${Z}")`);return new Set($.rows.map((J)=>String(J.name)))}async function SQ(Q){if(!await l(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 dZ(Q){for(let[Z,$]of Object.entries(nZ)){if(!await l(Q,Z))continue;let J=await aZ(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 lZ(Q,Z=cZ){let $=kZ({url:Q});try{await $.execute("PRAGMA journal_mode = WAL;"),await $.execute("PRAGMA foreign_keys = ON;");let J=await l($,"__drizzle_migrations"),Y=await l($,"Node"),V=!1;if(Y&&!J){let U=hZ({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 q=await SQ($);if(await _Z(LZ($),{migrationsFolder:Z}),await SQ($)>q)V=!0;return await dZ($),{migrated:V}}finally{$.close()}}var pZ,cZ,nZ;var pQ=K(async()=>{pZ=GQ(GQ(GQ(mZ(import.meta.url)))),cZ=process.env.BEACON_MIGRATIONS_DIR||SZ(pZ,"drizzle"),nZ={Node:["createdAt","updatedAt"],Note:["createdAt","updatedAt"],DbTable:["createdAt","updatedAt"],Endpoint:["createdAt","updatedAt"],DraftTable:["createdAt"],SyncState:["codeGraphSyncedAt","updatedAt"],AppSetting:["updatedAt"],ProjectMeta:["updatedAt"],CodeFile:["updatedAt"]}});VQ();import{existsSync as gZ}from"fs";import{homedir as TZ}from"os";import{join as a}from"path";function FZ(){return process.env.HOME||process.env.USERPROFILE||TZ()}var d=()=>a(FZ(),".claude"),PQ=()=>a(d(),"skills"),xQ=()=>a(d(),"settings.json"),HQ=()=>a(d(),"CLAUDE.md"),jQ="<!-- beacon:global:start -->",kQ="<!-- beacon:global:end -->";var fZ=O,BQ=[{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 RZ(Q,Z){return _(PQ(),Q,Z)}function LQ(Q){return v(PQ(),Q)}function bZ(Q){return h(PQ(),Q)}function DZ(Q){return E(xQ(),Q)}function IZ(Q){return A(xQ(),Q)}function OZ(Q){return y(xQ(),Q)}function EZ(Q){k(HQ(),jQ,kQ,Q)}function _Q(){return u(HQ(),jQ)}function AZ(){return L(HQ(),jQ,kQ)}function b0(){let Q={};for(let $ of H)Q[$]=LQ($);let Z={};for(let $ of BQ)Z[$.event]=IZ({event:$.event,command:$.command});return{homeExists:gZ(d()),skills:Q,hooks:Z,claudeMdBlock:_Q()}}async function yZ(){let{INIT_SKILL:Q,REFRESH_SKILL:Z,PLAN_SKILL:$}=await Promise.resolve().then(() => ($Q(),ZQ)),J={"beacon-init":Q,"beacon-refresh":Z,"beacon-plan":$},Y=[];for(let U of H){if(!LQ(U))Y.push(U);RZ(U,J[U])}let V=0;for(let U of BQ)if(DZ({event:U.event,matcher:U.matcher,command:U.command}))V++;let q=_Q();return EZ(fZ),{skillsAdded:Y,hooksAdded:V,claudeMdBlockTouched:!q}}async function hQ(){let Q;try{Q={ok:!0,...await yZ()}}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(() => (yQ(),AQ));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 D0(){let Q=[];for(let J of H)if(bZ(J))Q.push(J);let Z=0;for(let J of BQ)if(OZ(J))Z++;let $=AZ();return{skillsRemoved:Q,hooksRemoved:Z,claudeMdBlockRemoved:$}}import{AsyncLocalStorage as sZ}from"async_hooks";import{spawnSync as tZ}from"child_process";import{createHash as rZ}from"crypto";import{existsSync as nQ,mkdirSync as s,readFileSync as aQ,writeFileSync as dQ}from"fs";import{homedir as oZ}from"os";import{basename as iZ,join as N}from"path";function g(){return process.env.BEACON_HOME||N(oZ(),".beacon")}function NQ(){return N(g(),"workspaces.json")}function t(Q){return rZ("sha256").update(Q).digest("hex").slice(0,12)}function lQ(Q=process.cwd()){let Z=tZ("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 KQ(Q){return N(g(),Q)}function eZ(Q){return`file:${N(KQ(Q),"db.sqlite")}`}function T(){try{let Q=JSON.parse(aQ(NQ(),"utf8"));return Array.isArray(Q)?Q:[]}catch{return[]}}function uQ(Q){s(g(),{recursive:!0}),dQ(NQ(),JSON.stringify(Q,null,2))}function Q0(){return T().sort((Q,Z)=>Z.lastOpenedAt.localeCompare(Q.lastOpenedAt))}function j(Q){return T().find((Z)=>Z.id===Q)??null}function Z0(Q,Z,$=new Date().toISOString()){let J=t(Q),Y=T(),V=Y.find((z)=>z.id===J),q={id:J,path:Q,name:Z||V?.name||iZ(Q),lastOpenedAt:$},U=[q,...Y.filter((z)=>z.id!==J)];return s(KQ(J),{recursive:!0}),uQ(U),q}function n0(Q,Z=new Date().toISOString()){let $=T(),J=$.find((Y)=>Y.id===Q);if(!J)return;J.lastOpenedAt=Z,uQ($)}function a0(Q){if(uQ(T().filter((Z)=>Z.id!==Q)),vQ()===Q)$0(Q0()[0]?.id??null)}function sQ(){return N(g(),"active")}function vQ(){try{return aQ(sQ(),"utf8").trim()||null}catch{return null}}function $0(Q){s(g(),{recursive:!0}),dQ(sQ(),Q??"")}function d0(){let Q=vQ();return Q?j(Q):null}function l0(){let Q=Y0()??vQ();return Q?j(Q):null}function s0(Q){return j(Q)?.path??null}function t0(){return nQ(NQ())}var tQ="beacon_ws";function rQ(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 r0(Q){let Z=Q.headers.get("x-beacon-workspace");if(Z&&j(Z))return Z;let $=rQ(Q,tQ);if($&&j($))return $;return null}var J0="x-beacon-workspace-path";async function o0(Q){let Z=Q.headers.get("x-beacon-workspace");if(Z&&j(Z))return Z;let $=Q.headers.get(J0);if($&&(!Z||t($)===Z)){let Y=Z0($);return await V0(Y.id),Y.id}let J=rQ(Q,tQ);if(J&&j(J))return J;return null}var oQ=new sZ;function i0(Q,Z){return Q?oQ.run(Q,Z):Z()}function Y0(){return oQ.getStore()??null}var cQ=new Set;async function V0(Q){let Z=KQ(Q),$=N(Z,"db.sqlite"),J=nQ($);if(J&&cQ.has($))return{ok:!0,created:!1,migrated:!1};try{s(Z,{recursive:!0});let{provisionDb:Y}=await pQ().then(() => mQ),V=await Y(eZ(Q));return cQ.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)}}}import{resolve as z0}from"path";var q0="*** Begin Patch",X0=/^\*\*\* (Update File|Add File|Move to): (.+)$/;function U0(Q){let Z=[];for(let $ of Q.split(`
`)){let J=X0.exec($.trim());if(!J)continue;let Y=J[2].trim();if(J[1]==="Move to")Z.pop();Z.push(Y)}return Z}function iQ(Q){let Z=Q.tool_input;if(Z===null||typeof Z!=="object")return[];let $=Z,J=[];if(typeof $.file_path==="string")J.push($.file_path);if(typeof $.path==="string")J.push($.path);if(Array.isArray($.files))for(let V of $.files){let q=V?.file_path;if(typeof q==="string")J.push(q)}if(J.length)return J;let Y=typeof Q.cwd==="string"?Q.cwd:process.cwd();for(let V of Object.values($)){if(typeof V!=="string"||!V.includes(q0))continue;return U0(V).map((q)=>z0(Y,q))}return[]}var W0=process.env.BEACON_URL||`http://localhost:${process.env.PORT||4319}`;await hQ();var eQ="";for await(let Q of process.stdin)eQ+=Q;try{let Q=JSON.parse(eQ||"{}"),Z=iQ(Q);if(Z.length){let $=t(lQ(typeof Q.cwd==="string"?Q.cwd:void 0));await fetch(`${W0}/api/map/touch-active`,{method:"POST",headers:{"content-type":"application/json","x-beacon-workspace":$},body:JSON.stringify({files:Z})}).catch(()=>{})}}catch{}process.exit(0);
