Skip to content

See how your app actually fits together. An interactive, plain-English map of your codebase, drawn by Claude or Codex.

Blueprints: a floorplan planned from a PRD, before any code exists

Hayden Smith340ebf221de2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b825e86..644d67d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,9 @@
# Changelog
+## Unreleased
+
+- **Blueprints: plan it before you build it.** Share a PRD, a spec or a description of something you want to build, and Floorplan draws the map of what it would take: every part, file, endpoint and screen, how they connect, and the outside services they rely on. It's marked as planned (dashed cards and a **Blueprint** label), Health becomes a design review of the plan (endpoints anyone could use, decisions the PRD leaves open, loose ends), and each part has **Build this with Claude** (or Codex), a ready request to build it as planned. Once the code exists, the map can switch to the real code.
+
## 0.2.2 (2026-10-28)
- **Light mode:** a new **Theme** button in the top bar cycles **Auto → Light → Dark**. Auto follows your device's light or dark setting and changes with it. Your choice is remembered on this device, and the map shows the right colours from the first moment, with no flash. The button is a 44 px target, works from the keyboard with a visible focus ring, and the change is instant (nothing animates, so Reduce Motion is respected). Dark looks exactly as before. Requested in #9 and built by @menachem-kurkus in #10.
diff --git a/README.md b/README.md
index 3d3281f..6673fd5 100644
--- a/README.md
+++ b/README.md
@@ -96,6 +96,14 @@ The cards your AI just changed light up green, each with a note on how the chang
**⚡ Stays current, stays yours**<br>
Updates re-read only what changed, and an open map reloads itself. Everything runs on your machine, and nothing is committed to git.
+</td>
+</tr>
+<tr>
+<td colspan="2" valign="top">
+
+**📐 Plan it before you build it**<br>
+No code yet? Share a PRD or describe what you want to build, and get a blueprint: the same map of every piece you'd need and how they fit together, with a review of what's still undecided and a ready request to build each part.
+
</td>
</tr>
</table>
@@ -186,6 +194,12 @@ When you've done more work, ask:
Only what changed is re-read, and what you just worked on lights up under **Recent work**.
+**Planning something new?** Ask:
+
+> Here's my PRD. Make me a floorplan of what we'd need to build.
+
+You get a blueprint of the planned system, marked as planned, and each part has **Build this with Claude** (or Codex) when you're ready to start.
+
### Things to try
| Ask Claude Code or Codex | Ask the map |
@@ -195,6 +209,7 @@ Only what changed is re-read, and what you just worked on lights up under **Rece
| "Fix the important issues from the floorplan's Health check" | "If I change the users table, what breaks?" |
| "Add a flow showing how a new user signs up" | "Which files handle login?" |
| "Rewrite the floorplan for developers" | "What did we change for refunds?" |
+| "Here's my PRD: make me a blueprint" | "What do I need to build for payments?" |
## How it works
diff --git a/docs/development.md b/docs/development.md
index b4be09b..19857de 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -19,9 +19,11 @@ skills/floorplan/
schema.md architecture.json and recent-work.json
choosing-boundaries.md how to carve a codebase into a good map
writing-descriptions.md plain-language names and descriptions
+ blueprint.md plan.json, for a map planned from a PRD
scripts/ Node.js, no dependencies; Claude runs these
status.mjs is there a map, and how stale is it (runs when the skill loads)
scan.mjs repos, files, imports, endpoints, requests → .cache/scan.json
+ plan.mjs a blueprint's plan.json → the same .cache/scan.json
build.mjs validate, assign files, connect, Health, screens → graph.json + index.html
describe.mjs worksheets for Claude to name and describe files and endpoints
refresh.mjs incremental update: re-scan, carry over, flag changes, rebuild
@@ -30,7 +32,7 @@ skills/floorplan/
lib/ extraction, import resolution, route matching, Health, screens, which agent is running, helpers
assets/
viewer.html the map (template the build fills in)
- ui/ viewer extensions: Theme button, glossary, Health, recent work, screens, tour, waitlist card
+ ui/ viewer extensions: Theme button, blueprints, glossary, Health, recent work, screens, tour, waitlist card
graph-query.js shared map lookups (viewer, query.mjs, Ask instructions)
serve.mjs copied into each project's floorplan/ folder; answers through Claude Code or Codex
query-cli.mjs becomes floorplan/query.mjs
@@ -78,6 +80,7 @@ The tests use Node's built-in test runner, so there's nothing to install (`npm t
| `secrets.test.mjs` | Health finds secrets, masks them, and ignores placeholders |
| `health.test.mjs` | which endpoints Health calls open to anyone (FastAPI sample in `fixtures/`) |
| `firebase.test.mjs` | Firebase Cloud Functions: callables and onRequest functions as endpoints, the website's calls to them, Screens, Health, background functions (React + Firebase sample in `fixtures/`) |
+| `blueprint.test.mjs` | a map planned from a PRD before any code exists: plan.json errors, endpoints and calls, Screens, the design review, refreshing and switching to the real code (sample PRD in `fixtures/`) |
| `sample-app.test.mjs` | a whole map of a two-repo shop: endpoints, cross-repo requests, Health, offline map, no secret values written, updates |
| `serve.test.mjs` | the map's server: 127.0.0.1 only, token and same-origin checks, nothing served from outside its folder |
| `ask.test.mjs` | asking through Claude Code or Codex: which one is used, read-only, follow-ups, sign-in errors (stand-in CLIs in `fixtures/fake-cli/`) |
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index d7ce21f..d9cb704 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -89,6 +89,19 @@ It then:
Then it rebuilds. The AI only has to describe what's new or flagged, and check the structure if the change was large. That's why updates are quick.
+## Blueprints
+
+A blueprint is a map of something that isn't built yet. The AI reads a PRD or a description and writes `floorplan/plan.json`: every file and endpoint the system would need, which screen calls which endpoint, which parts use outside services and the database, and who may use each endpoint. It also lists the stack it chose, its assumptions and the questions the PRD leaves open.
+
+`plan.mjs` turns the plan into the same scan `scan.mjs` makes from code, so the build, Screens, flows, the tour and Ask all work the same way. The differences:
+
+- cards have dashed outlines and the board a **Blueprint** label;
+- Health becomes a **design review** of the plan: endpoints anyone could use to change data, endpoints with no decision on who may use them, open questions, and pieces nothing connects to;
+- every part has **Build this with Claude** (or Codex): a request to build that part as planned, listing its files, endpoints and what it relies on;
+- Ask answers from the plan and the PRD, since there's no code to read.
+
+Updating a blueprint redraws it from `plan.json`. Once the code exists, `refresh.mjs --from-code` maps the real code instead, and `plan.json` stays.
+
## Asking questions
The map's server answers each question with the AI on your computer, in your project:
diff --git a/skills/floorplan/SKILL.md b/skills/floorplan/SKILL.md
index 0e3a7fa..59f0b77 100644
--- a/skills/floorplan/SKILL.md
+++ b/skills/floorplan/SKILL.md
@@ -1,6 +1,6 @@
---
name: floorplan
-description: Draw a floorplan of an app's codebase (one repo or several side by side), an interactive node-graph map where every subsystem, module, file and HTTP route has a human-readable name and a one-line description, connected by the imports and HTTP calls between them, at several zoom levels. It is saved as a self-contained floorplan/index.html in the codebase. Use whenever the user wants to visualize, map, diagram, document or get an architectural overview of a codebase, repo or monorepo, understand how their app works or is connected under the hood, onboard onto unfamiliar code, see how the frontend talks to the backend, or update an existing floorplan, even if they don't say "visualize".
+description: Draw a floorplan of an app's codebase (one repo or several side by side), an interactive node-graph map where every subsystem, module, file and HTTP route has a human-readable name and a one-line description, connected by the imports and HTTP calls between them, at several zoom levels. It is saved as a self-contained floorplan/index.html in the codebase. Use whenever the user wants to visualize, map, diagram, document or get an architectural overview of a codebase, repo or monorepo, understand how their app works or is connected under the hood, onboard onto unfamiliar code, see how the frontend talks to the backend, or update an existing floorplan, even if they don't say "visualize". Also use it before any code exists: when the user shares a PRD, a spec or a description of something they want to build and asks what pieces it needs or how they'd fit together, it draws a blueprint, the same map planned from the document.
argument-hint: "[path-to-codebase-root] [--refresh]"
allowed-tools: Bash(node ${CLAUDE_SKILL_DIR}/scripts/*)
---
@@ -19,6 +19,20 @@ Arguments: $ARGUMENTS
**In Codex** (or any agent that left the two lines above unfilled): `${CLAUDE_SKILL_DIR}` in every command here means this skill's folder, the one holding this SKILL.md, so use its path. Run `node <that folder>/scripts/status.mjs` from the codebase root yourself to see whether a map exists, and take the path and `--refresh` from the user's request. The scripts notice they're running under Codex, so the map's Ask bar and "Fix with" prompts use Codex.
+## Nothing built yet? Draw a blueprint
+
+If the user wants to plan something they haven't built ("here's my PRD", "I want to build an app that…", a long description of a system), make a **blueprint**: the same map, planned from their document instead of scanned from code. Use this path when there's no code for the system yet, even if the folder holds other things. If the code exists, make a normal map.
+
+1. **Read the input.** A PRD file, a pasted message, or a document they point you at. Ask 2–3 questions only if something fundamental is open (who uses it, web or mobile, does anyone sign in, does money change hands); otherwise decide and record it as an assumption.
+2. **Read [references/blueprint.md](references/blueprint.md)**, then [references/schema.md](references/schema.md) for architecture.json.
+3. **Write `floorplan/plan.json`**: every planned file and endpoint, what each screen calls, which outside services and data each part uses, who may use each endpoint, your assumptions and the open questions. If the PRD is only in the chat, save it as `docs/prd.md` and use that as `source`, so the map and later questions can refer back to it.
+4. **Run `node ${CLAUDE_SKILL_DIR}/scripts/plan.mjs <root>`.** Fix what it reports and run it again until it's clean.
+5. **Write `floorplan/architecture.json`** as for a code map (parts, external nodes, 1–3 flows for the PRD's main user stories, a tour), with globs covering the planned paths. Plain language for everyone, as in step 4 below.
+6. **Run build.mjs** (step 5 below), then **show it** with open.mjs (step 8). Skip describe.mjs and recent.mjs: names and descriptions come from plan.json.
+7. **Report:** the shape of the system in 3–5 lines, the stack you chose, your main assumptions, and the design review's questions and warnings. Tell them each part has **Build this with Claude** (or Codex) for a ready request to build just that part, and that they can ask you to change the plan.
+
+To change a blueprint, edit plan.json and architecture.json and run `refresh.mjs`, which redraws it from plan.json. Once the code exists and the user wants a map of it, run `refresh.mjs <root> --from-code`, then carry on as for a refresh. plan.json stays where it is.
+
## A map already exists? Refresh it instead
If the status above shows an existing map, don't start over. Run:
diff --git a/skills/floorplan/assets/graph-query.js b/skills/floorplan/assets/graph-query.js
index 7b160fe..5a874ff 100644
--- a/skills/floorplan/assets/graph-query.js
+++ b/skills/floorplan/assets/graph-query.js
@@ -216,15 +216,17 @@ function floorplanAskInstructions(G, engine) {
const tools = engine === 'cli'
? `Query the map from the shell: \`node floorplan/query.mjs overview\`, \`node floorplan/query.mjs find "<words>" [--kind module|file|endpoint|symbol]\`, \`node floorplan/query.mjs show <id>\`, \`node floorplan/query.mjs path <fromId> <toId>\`. Every result is JSON with ids. Start with the map; read or grep source files when you need specifics the map does not have.`
: `Use the tools find_items, get_item and dependency_path to explore the map. You cannot read source files, so answer from the map's names, descriptions, endpoints and connections, and say so when a question needs the code itself.`;
+ const bp = G.meta?.blueprint;
return [
`You answer questions about the codebase "${G.project.name}" for someone exploring an interactive architecture map of it.`,
`The map has cards for modules (ids n:...), files (f:<path>), HTTP endpoints (r:<number>) and exported symbols (s:<path>#<number>), each with a human-readable name and description, connected by imports and HTTP calls.`,
tools,
+ bp ? `This map is a blueprint: a plan of a system that hasn't been built yet, so its files don't exist.${engine === 'cli' ? ` Instead of source files, read floorplan/plan.json${bp.source ? ` and ${bp.source} (what it was planned from)` : ''} when you need more than the map.` : ''} Answer about what would be built and why, and say plainly when the plan doesn't cover something.` : '',
'Use a few lookups, not dozens. Then reply with JSON only: {"title", "answer", "items", "steps", "followups"}.',
'- answer: Markdown, at most ~180 words, plain and specific. Refer to map items inline as [[id]] (they become clickable).',
'- items: the 3-14 cards that best show the answer, most important first, each with a note (at most 15 words) on its role.',
'- steps: an ordered walkthrough when the answer is a sequence (a request path, a data flow); otherwise [].',
'- followups: 2-3 short follow-up questions.',
'Only use ids that the map gave you.',
- ].join('\n');
+ ].filter(Boolean).join('\n');
}
diff --git a/skills/floorplan/assets/ui/06-blueprint.js b/skills/floorplan/assets/ui/06-blueprint.js
new file mode 100644
index 0000000..56b544d
--- /dev/null
+++ b/skills/floorplan/assets/ui/06-blueprint.js
@@ -0,0 +1,91 @@
+// Blueprints: a map planned from a PRD or a description, before any code exists (graph.meta.blueprint,
+// from scripts/plan.mjs). Cards get a dashed outline and the project name a "Blueprint" pill, the
+// overview says what it was planned from, and every planned part offers "Build this with Claude": a
+// ready prompt to build just that part, following the plan. Talks to the viewer only through window.Floorplan.
+(() => {
+ const SC = window.Floorplan;
+ const BP = SC && SC.graph.meta.blueprint;
+ if (!BP) return;
+ const { h } = SC;
+ const A = SC.agent || { name: 'Claude', app: 'Claude Code' };
+ const G = SC.graph;
+
+ document.documentElement.classList.add('blueprint');
+ const style = document.createElement('style');
+ style.textContent = `
+ /* planned, not built: a dashed outline on every card */
+ html.blueprint .card:not(.connector)::after { content: ""; position: absolute; inset: 0; border-radius: inherit; border: 2.5px dashed rgba(var(--ink), .32); pointer-events: none; }
+ .bp-pill { display: inline-flex; align-items: center; height: 20px; padding: 0 8px; margin-left: 8px; border-radius: 999px; font-size: 11px; font-weight: 500; letter-spacing: .02em; color: var(--text-2); border: 1px dashed rgba(var(--ink), .35); flex: none; }
+ .bp-list { margin: 8px 0 0; padding-left: 18px; color: var(--text-2); font-size: 13px; line-height: 1.55; }
+ .bp-list li + li { margin-top: 4px; }
+ `;
+ document.head.appendChild(style);
+
+ // a "Blueprint" pill beside the board's title, which is redrawn on every move
+ const addPill = () => {
+ const k = document.querySelector('#context .k');
+ if (!k || k.querySelector('.bp-pill')) return;
+ k.insertAdjacentHTML('beforeend', '<span class="bp-pill" title="Planned, not built yet: every card is a part the system would need.">Blueprint</span>');
+ };
+ SC.on('render', addPill);
+ SC.on('ready', addPill);
+
+ const ACCESS = { public: 'anyone', 'signed-in': 'signed-in users', staff: 'staff', webhook: 'the service that sends it, which must prove it', internal: 'only our own services' };
+
+ SC.addPanelSection('overview', () => ({
+ html: `<div class="sec"><h3>Blueprint</h3>
+ <p class="pd">Planned${BP.source ? ` from <b>${h(BP.source)}</b>` : ''}, not built yet. Every dashed card is a part the system would need. Pick one and choose <b>Build this with ${h(A.name)}</b> to start on it.</p>
+ ${BP.stack?.length ? `<div class="tags" style="margin-top:10px">${BP.stack.map((s) => `<span class="tag">${h(s)}</span>`).join('')}</div>` : ''}
+ ${BP.assumptions?.length ? `<h3 style="margin-top:14px">Assumptions</h3><ul class="bp-list">${BP.assumptions.map((a) => `<li>${h(a)}</li>`).join('')}</ul>` : ''}
+ </div>`,
+ }));
+
+ /** The planned files inside an item (a part, a folder or one file). */
+ const filesIn = (id) => G.files.filter((f) => id === 'f:' + f.p || SC.chain('f:' + f.p).includes(id));
+ function buildPrompt(id) {
+ const i = SC.info(id);
+ const fl = filesIn(id);
+ const paths = new Set(fl.map((f) => 'f:' + f.p));
+ const eps = SC.routes.filter((r) => paths.has('f:' + r.f));
+ const deps = new Map();
+ for (const l of G.links) {
+ if (!paths.has(l.a) || paths.has(l.b)) continue;
+ const o = SC.info(l.b);
+ if (o) deps.set(l.b, `${o.name}${l.b.startsWith('f:') ? ` (${l.b.slice(2)})` : ''}`);
+ }
+ // open questions from the PRD that touch this part
+ const inside = (x) => x === id || paths.has(x) || (x.startsWith('r:') && paths.has('f:' + SC.routes[+x.slice(2)]?.f)) || (SC.exists(x) && SC.chain(x).includes(id));
+ const questions = (G.health?.issues || []).filter((q) => q.kind === 'question' && (q.items || []).some(inside)).map((q) => q.title);
+ return [
+ `Build "${i.name}" from the ${G.project.name} blueprint: floorplan/plan.json and floorplan/architecture.json${BP.source ? `, planned from ${BP.source}` : ''}.`,
+ i.desc ? `\nWhat it's for: ${i.desc}` : '',
+ BP.stack?.length ? `\nStack: ${BP.stack.join('; ')}.` : '',
+ `\nFiles to create:`,
+ ...fl.map((f) => `- ${f.p}: ${f.name}${f.d ? `. ${f.d}` : ''}`),
+ eps.length ? `\nEndpoints to create (keep the method, path and who may use them exactly as planned):` : '',
+ ...eps.map((r) => `- ${r.m} ${r.p} (${r.access ? `for ${ACCESS[r.access] || r.access}` : 'who may use it isn’t decided yet: ask me'}): ${r.name}${r.d ? `. ${r.d}` : ''}`),
+ deps.size ? `\nIt relies on: ${[...deps.values()].join('; ')}.` : '',
+ questions.length ? `\nStill undecided (ask me before building what depends on it):\n${questions.map((q) => `- ${q}`).join('\n')}` : '',
+ `\nBefore writing code, read these parts of plan.json, and check which of the things it relies on exist yet; if some don't, tell me and suggest what to build first. Keep the plan's file paths and names. If the plan looks wrong or incomplete for this part, tell me before changing it. When it's done, run it or its tests and tell me how to try it.`,
+ ].filter((x) => x !== '').join('\n');
+ }
+
+ SC.addPanelSection('item', (id) => {
+ if (!id || typeof id !== 'string') return '';
+ const i = SC.info(id);
+ if (!i || (i.type === 'node' && i.n.kind === 'external') || !filesIn(id).length) return '';
+ return {
+ html: `<div class="sec"><h3>Build it</h3><p class="pd">A ready request for ${h(A.app)} to build ${i.type === 'file' ? 'this file' : 'this part'} the way the plan describes.</p>
+ <div class="actions"><button class="btn soft" data-bp-build>${SC.iconI('spark')}Build this with ${h(A.name)}</button></div></div>`,
+ bind: (el) => el.querySelector('[data-bp-build]')?.addEventListener('click', (ev) => {
+ ev.stopPropagation();
+ const prompt = buildPrompt(id);
+ SC.modal({
+ title: `Build this with ${A.name}`,
+ html: `<p class="hc-hint">Copy this request and paste it into <b>${h(A.app)}</b>, opened in your project folder.</p><pre>${h(prompt)}</pre>`,
+ actions: [{ label: 'Copy prompt', primary: true, icon: 'copy', onClick: () => { SC.copy(prompt); SC.toast(`Copied. Paste it into ${A.app}.`); } }],
+ });
+ }),
+ };
+ });
+})();
diff --git a/skills/floorplan/assets/ui/20-health.js b/skills/floorplan/assets/ui/20-health.js
index 443548c..4d0a4cd 100644
--- a/skills/floorplan/assets/ui/20-health.js
+++ b/skills/floorplan/assets/ui/20-health.js
@@ -7,6 +7,9 @@
const { h } = SC;
const A = SC.agent || { name: 'Claude', app: 'Claude Code' };
const issues = (SC.graph.health && SC.graph.health.issues) || [];
+ // a blueprint (planned, not built) gets a design review of the plan instead of a code check
+ const PLAN = !!SC.graph.meta.blueprint;
+ const FIX = PLAN ? 'Resolve' : 'Fix';
const SEV = {
high: { color: 'var(--sev-high)', group: 'Fix these first', word: 'important' },
@@ -48,13 +51,13 @@
function closeList() { isOpen = false; SC.closePanel(); }
function showOnMap(issue) {
const items = (issue.items || []).filter((id) => SC.exists(id)).map((id) => ({ id, note: (issue.notes && issue.notes[id]) || '' }));
- if (!items.length) { SC.toast(`This one isn’t on the map. Use “Fix with ${A.name}” instead.`); return; }
+ if (!items.length) { SC.toast(`This one isn’t on the map. Use “${FIX} with ${A.name}” instead.`); return; }
if (isOpen) closeList();
SC.showBoard({ title: issue.title, question: issue.detail, items });
}
function fixWith(issue) {
SC.modal({
- title: `Fix with ${A.name}`,
+ title: `${FIX} with ${A.name}`,
html: `<p class="hc-hint">Copy this request and paste it into <b>${A.app}</b>, opened in your project folder. It explains what to change and asks before anything risky.</p><pre>${h(issue.fix)}</pre>`,
actions: [{ label: 'Copy prompt', primary: true, icon: 'copy', onClick: () => { SC.copy(issue.fix); SC.toast(`Copied. Paste it into ${A.app}.`); } }],
});
@@ -74,7 +77,7 @@
${locText(issue)}
<div class="hc-a">
${onMap(issue) ? `<button class="btn soft" data-hc-show="${idx}">${SC.iconI('search')}Show on map</button>` : ''}
- <button class="btn soft" data-hc-fix="${idx}">${SC.iconI('spark')}Fix with ${A.name}</button>
+ <button class="btn soft" data-hc-fix="${idx}">${SC.iconI('spark')}${FIX} with ${A.name}</button>
</div>
</div>`;
const bindIssues = (el) => {
@@ -86,17 +89,17 @@
function listHtml() {
const top = `<div class="sec">
- <div class="ph"><span class="ico" style="--c:${urgent ? SEV[count('high') ? 'high' : 'medium'].color : 'var(--ok)'}">${SC.icon('health')}</span><span class="kindlabel">Health check</span></div>
+ <div class="ph"><span class="ico" style="--c:${urgent ? SEV[count('high') ? 'high' : 'medium'].color : 'var(--ok)'}">${SC.icon('health')}</span><span class="kindlabel">${PLAN ? 'Design review' : 'Health check'}</span></div>
<h2 class="pt">${h(headline())}</h2>
- <p class="pd">We looked for passwords and keys left in the code, parts of your app anyone on the internet can use, leftover files and files too big to edit safely.</p>
- ${issues.length ? breakdown() : `<div class="hc-calm">Nothing stood out. This is a quick automatic check, not a full security review.</div>`}
+ <p class="pd">${PLAN ? 'We checked the plan for parts anyone on the internet could use, decisions the PRD leaves open, and pieces nothing connects to. Settling these now is cheaper than after it’s built.' : 'We looked for passwords and keys left in the code, parts of your app anyone on the internet can use, leftover files and files too big to edit safely.'}</p>
+ ${issues.length ? breakdown() : `<div class="hc-calm">Nothing stood out. This is a quick automatic check, not a full ${PLAN ? 'design' : 'security'} review.</div>`}
<div class="actions"><button class="btn soft" data-hc-back>${SC.iconI('left')}Back</button></div>
</div>`;
const groups = ORDER.map((sev) => {
const list = issues.map((i, idx) => [i, idx]).filter(([i]) => i.severity === sev);
return list.length ? `<div class="sec"><h3>${h(SEV[sev].group)} <span class="c">${list.length}</span></h3>${list.map(([i, idx]) => issueHtml(i, idx)).join('')}</div>` : '';
}).join('');
- const foot = issues.length ? `<div class="sec" style="color:var(--text-3);font-size:12px;line-height:1.6">These are automatic hints. “Fix with ${A.name}” gives you a request to paste into ${A.app}; it checks the code before changing anything.</div>` : '';
+ const foot = issues.length ? `<div class="sec" style="color:var(--text-3);font-size:12px;line-height:1.6">These are automatic hints. “${FIX} with ${A.name}” gives you a request to paste into ${A.app}; ${PLAN ? 'it explains the choice and updates the plan once you decide' : 'it checks the code before changing anything'}.</div>` : '';
return top + groups + foot;
}
function openList() {
@@ -110,8 +113,8 @@
// ---------- chrome ----------
const btn = SC.addHeaderButton({
- id: 'btn-health', label: 'Health', icon: urgent ? 'health' : 'check',
- title: urgent ? `Health check: ${headline()}` : 'Health check: nothing urgent',
+ id: 'btn-health', label: PLAN ? 'Review' : 'Health', icon: urgent ? 'health' : 'check',
+ title: `${PLAN ? 'Design review' : 'Health check'}: ${urgent ? headline() : 'nothing urgent'}`,
onClick: () => (isOpen ? closeList() : openList()),
});
if (urgent) {
@@ -127,9 +130,9 @@
SC.on('panel', () => { if (isOpen && openedAt && where() !== openedAt) { isOpen = false; SC.closePanel(); } });
SC.addPanelSection('overview', () => ({
- html: `<div class="sec"><h3>Health</h3><div class="list"><a class="row" data-hc-open>
+ html: `<div class="sec"><h3>${PLAN ? 'Design review' : 'Health'}</h3><div class="list"><a class="row" data-hc-open>
<span class="dot" style="background:${urgent ? SEV[count('high') ? 'high' : 'medium'].color : 'var(--ok)'}"></span>
- <span class="rt"><div class="rn">${h(headline())}</div><div class="rd">${issues.length ? ORDER.filter(count).map((s) => `${count(s)} ${SEV[s].word}`).join(' · ') : 'Quick automatic check of secrets, open endpoints and leftover files'}</div></span>
+ <span class="rt"><div class="rn">${h(headline())}</div><div class="rd">${issues.length ? ORDER.filter(count).map((s) => `${count(s)} ${SEV[s].word}`).join(' · ') : PLAN ? 'Quick automatic check of the plan' : 'Quick automatic check of secrets, open endpoints and leftover files'}</div></span>
<span class="rc">${SC.iconI('right')}</span></a></div></div>`,
bind: (el) => el.querySelector('[data-hc-open]')?.addEventListener('click', (ev) => { ev.preventDefault(); openList(); }),
}));
@@ -144,6 +147,6 @@
hits.push(issueHtml(issue, idx, exact || (inside.length > 1 || inside[0] !== itemId ? `Affects ${SC.plural(inside.length, 'place')} in here` : '')));
});
if (!hits.length) return '';
- return { html: `<div class="sec"><h3>Health <span class="c">${hits.length}</span></h3>${hits.slice(0, 6).join('')}${hits.length > 6 ? `<div class="more" data-hc-open style="cursor:pointer">+${hits.length - 6} more in the health check</div>` : ''}</div>`, bind: (el) => { bindIssues(el); el.querySelector('[data-hc-open]')?.addEventListener('click', openList); } };
+ return { html: `<div class="sec"><h3>${PLAN ? 'Design review' : 'Health'} <span class="c">${hits.length}</span></h3>${hits.slice(0, 6).join('')}${hits.length > 6 ? `<div class="more" data-hc-open style="cursor:pointer">+${hits.length - 6} more in the ${PLAN ? 'design review' : 'health check'}</div>` : ''}</div>`, bind: (el) => { bindIssues(el); el.querySelector('[data-hc-open]')?.addEventListener('click', openList); } };
});
})();
diff --git a/skills/floorplan/assets/viewer.html b/skills/floorplan/assets/viewer.html
index 09b856d..8cead66 100644
--- a/skills/floorplan/assets/viewer.html
+++ b/skills/floorplan/assets/viewer.html
@@ -528,6 +528,8 @@ const AGENT = (window.FLOORPLAN_SERVER?.engine || window.FLOORPLAN_SERVER?.want
signIn: 'Run <code>claude</code> in a terminal once to sign in, then ask again.' };
const Cap = (t) => t[0].toUpperCase() + t.slice(1);
if (!G) { document.body.innerHTML = '<p style="padding:2rem">No data. Run build.mjs.</p>'; return; }
+// a blueprint: planned from a PRD, so its files don't exist yet (no line counts, nothing to open in an editor)
+const PLAN = !!G.meta.blueprint;
if (typeof ELK === 'undefined') { document.body.innerHTML = '<p style="padding:2rem">Could not load the ELK layout engine. Rebuild the map with build.mjs.</p>'; return; }
const NS = 'http://www.w3.org/2000/svg';
@@ -885,7 +887,7 @@ function cardTip(id) {
const st = statsOf(id);
const kind = i.type === 'node' ? i.kind : i.type === 'route' ? 'endpoint' : i.type === 'symbol' ? i.symKind : i.type === 'module' ? 'file' : i.type;
const where = i.type === 'node' ? (i.n.paths || []).join('\n') : i.type === 'route' ? `${i.f.p}${i.r.h ? ` · ${i.r.h}()` : ''}` : i.path || '';
- const size = st?.files ? (i.type === 'file' || i.type === 'module' ? `${fmt(st.loc)} lines` : `${plural(st.files, 'file')} · ${fmt(st.loc)} lines`) : '';
+ const size = !st?.files ? '' : PLAN ? (i.type === 'file' || i.type === 'module' ? 'planned' : plural(st.files, 'planned file')) : i.type === 'file' || i.type === 'module' ? `${fmt(st.loc)} lines` : `${plural(st.files, 'file')} · ${fmt(st.loc)} lines`;
const hints = [drillable(id) && state.container !== id ? '<span><span class="kbd">2×click</span> open</span>' : '', '<span><span class="kbd">right-click</span> more</span>'].join('');
return `<div class="tt">${h(i.name)}</div><div class="td" style="text-transform:capitalize">${h(kind)}${size ? ` · ${size}` : ''}</div>${where ? `<div class="tp">${h(where)}</div>` : ''}${recentTip(id)}<div class="th">${hints}</div>`;
}
@@ -1321,7 +1323,7 @@ function renderLegend(view) {
}
// ======================= inspector =======================
-const editorUrl = (p, line = 1) => G.meta.root ? `vscode://file/${encodeURI(G.meta.root.replace(/\\/g, '/'))}/${encodeURI(p)}:${line}` : null;
+const editorUrl = (p, line = 1) => G.meta.root && !PLAN ? `vscode://file/${encodeURI(G.meta.root.replace(/\\/g, '/'))}/${encodeURI(p)}:${line}` : null;
const rowFor = (item, extra = '', dotColor) => {
const i = info(item);
return `<a class="row" data-go="${h(item)}" title="${h(i.path || '')}"><span class="dot" style="background:${dotColor || colorOf(i)}"></span><span class="rt"><div class="rn">${h(i.name)}</div>${i.desc ? `<div class="rd">${h(i.desc)}</div>` : ''}</span>${extra ? `<span class="rc">${extra}</span>` : ''}</a>`;
@@ -1395,7 +1397,7 @@ function systemsSection(tops) {
const parts = SYSTEM_GROUPS.map((g) => {
const items = tops.filter((t) => g.kinds.includes(info(t).kind));
items.forEach((t) => placed.add(t));
- return items.length ? `<div class="group-h">${h(g.label)}<span class="gd">${h(g.hint)}</span></div><div class="list">${items.map((t) => rowFor(t, info(t).kind === 'external' ? '' : technical() && statsOf(t)?.files ? fmt(statsOf(t).loc) + ' loc' : statsOf(t)?.files ? plural(statsOf(t).files, 'file') : '')).join('')}</div>` : '';
+ return items.length ? `<div class="group-h">${h(g.label)}<span class="gd">${h(g.hint)}</span></div><div class="list">${items.map((t) => rowFor(t, info(t).kind === 'external' ? '' : technical() && !PLAN && statsOf(t)?.files ? fmt(statsOf(t).loc) + ' loc' : statsOf(t)?.files ? plural(statsOf(t).files, 'file') : '')).join('')}</div>` : '';
});
const rest = tops.filter((t) => !placed.has(t));
if (rest.length) parts.push(`<div class="group-h">Other</div><div class="list">${rest.map((t) => rowFor(t)).join('')}</div>`);
@@ -1406,8 +1408,8 @@ function overviewPanel() {
const p = G.project;
const tops = kids.get('root') || [];
const undescribed = G.files.filter((f) => f.auto).length + routes.filter((r) => r.auto).length;
- return `<div class="sec"><div class="ph"><span class="ico" style="--c:var(--accent)">${icon('feature')}</span><span class="kind">Codebase</span></div><h2 class="pt">${h(p.name)}</h2>${p.summary ? `<p class="pd">${h(p.summary)}</p>` : ''}
- <div class="stats" style="margin-top:14px"><div><b>${fmt(G.meta.counts.files)}</b><span>files</span></div><div><b>${fmt(G.meta.counts.loc)}</b><span>lines</span></div><div><b>${fmt(routes.length)}</b><span>endpoints</span></div></div>
+ return `<div class="sec"><div class="ph"><span class="ico" style="--c:var(--accent)">${icon('feature')}</span><span class="kind">${PLAN ? 'Blueprint' : 'Codebase'}</span></div><h2 class="pt">${h(p.name)}</h2>${p.summary ? `<p class="pd">${h(p.summary)}</p>` : ''}
+ <div class="stats" style="margin-top:14px"><div><b>${fmt(G.meta.counts.files)}</b><span>${PLAN ? 'planned files' : 'files'}</span></div>${PLAN ? `<div><b>${fmt((G.screens || []).length)}</b><span>screens</span></div>` : `<div><b>${fmt(G.meta.counts.loc)}</b><span>lines</span></div>`}<div><b>${fmt(routes.length)}</b><span>endpoints</span></div></div>
${undescribed ? `<div class="callout">${undescribed} files and endpoints still use generated names. Run the skill again to describe them.</div>` : ''}</div>
${systemsSection(tops)}
${listSec('Guided flows', G.flows.map((f) => `<a class="row" data-flow="${h(f.id)}"><span class="dot" style="background:var(--accent)"></span><span class="rt"><div class="rn">${h(f.title)}</div>${f.description ? `<div class="rd">${h(f.description)}</div>` : ''}</span><span class="rc">${f.steps.length} steps</span></a>`))}
@@ -1451,15 +1453,15 @@ function itemPanel(item, viaConnector) {
const tot = langs.reduce((a, [, v]) => a + v, 0) || 1;
const palette = ['#a78bfa', '#38bdf8', '#34d399', '#fbbf24', '#f472b6'];
const nr = routes.filter((r) => chain('f:' + r.f).includes(item)).length;
- html += `<div class="sec"><div class="stats"><div><b>${fmt(s.files)}</b><span>files</span></div><div><b>${fmt(s.loc)}</b><span>lines</span></div><div><b>${nr}</b><span>endpoints</span></div></div>
- ${langs.length ? `<div class="bar">${langs.map(([, v], k) => `<span style="flex:${v};background:${palette[k]}"></span>`).join('')}</div><div class="legend-row">${langs.map(([l, v], k) => `<span><span class="dot" style="background:${palette[k]}"></span>${h(l)} ${Math.round((v / tot) * 100)}%</span>`).join('')}</div>` : ''}</div>`;
+ html += `<div class="sec"><div class="stats"><div><b>${fmt(s.files)}</b><span>${PLAN ? 'planned files' : 'files'}</span></div>${PLAN ? '' : `<div><b>${fmt(s.loc)}</b><span>lines</span></div>`}<div><b>${nr}</b><span>endpoints</span></div></div>
+ ${langs.length && !PLAN ? `<div class="bar">${langs.map(([, v], k) => `<span style="flex:${v};background:${palette[k]}"></span>`).join('')}</div><div class="legend-row">${langs.map(([l, v], k) => `<span><span class="dot" style="background:${palette[k]}"></span>${h(l)} ${Math.round((v / tot) * 100)}%</span>`).join('')}</div>` : ''}</div>`;
}
if (n?.packages?.length || n?.hosts?.length || n?.tags?.length) html += `<div class="sec"><h3>Matched by</h3><div class="tags">${[...n.packages.map((p) => 'pkg ' + p), ...n.hosts.map((p) => 'host ' + p), ...n.tags.map((t) => '#' + t)].map((t) => `<span class="tag">${h(t)}</span>`).join('')}</div></div>`;
html += listSec('Inside', (kids.get(item) || []).filter((k) => !k.startsWith('f:')).map((k) => rowFor(k)));
const c = connections(item);
html += listSec('Used by', c.inn) + listSec('Depends on', c.out);
const fl = (i.d ? i.d.files : G.files.filter((f) => chain('f:' + f.p).includes(item))).slice().sort((a, b) => b.loc - a.loc);
- html += listSec('Files', fl.map((f) => rowFor('f:' + f.p, fmt(f.loc))), fl.length, 25);
+ html += listSec(PLAN ? 'Planned files' : 'Files', fl.map((f) => rowFor('f:' + f.p, PLAN ? '' : fmt(f.loc))), fl.length, 25);
} else if (i.type === 'file' || i.type === 'module') {
const f = i.f, fid = 'f:' + f.p, url = editorUrl(f.p);
if (f.note) html += `<div class="callout">${h(f.note)}</div>`;
@@ -1467,7 +1469,7 @@ function itemPanel(item, viaConnector) {
if (url) actions.push(`<a class="btn soft" href="${url}">${iconI('open')}Open in editor</a>`);
if (actions.length) html += `<div class="actions">${actions.join('')}</div>`;
const owner = nodes.get(f.n);
- html += `</div><div class="sec"><div class="stats"><div><b>${fmt(f.loc)}</b><span>lines</span></div><div><b>${(routesByFile.get(f.p) || []).length}</b><span>endpoints</span></div><div><b>${technical() ? (f.s || []).length : fmt(G.links.filter((l) => l.b === 'f:' + f.p).length)}</b><span>${technical() ? 'exports' : 'used by'}</span></div></div>
+ html += `</div><div class="sec"><div class="stats">${PLAN ? `<div><b>${fmt(G.links.filter((l) => l.a === fid).length)}</b><span>uses</span></div>` : `<div><b>${fmt(f.loc)}</b><span>lines</span></div>`}<div><b>${(routesByFile.get(f.p) || []).length}</b><span>endpoints</span></div><div><b>${technical() ? (f.s || []).length : fmt(G.links.filter((l) => l.b === 'f:' + f.p).length)}</b><span>${technical() ? 'exports' : 'used by'}</span></div></div>
${owner ? `<div class="list" style="margin-top:12px">${rowFor('n:' + owner.id, 'module')}</div>` : ''}</div>`;
html += listSec('Endpoints', (routesByFile.get(f.p) || []).map((ri) => routeRow(ri)), undefined, 60);
const inL = G.links.filter((l) => l.b === fid), outL = G.links.filter((l) => l.a === fid);
diff --git a/skills/floorplan/references/blueprint.md b/skills/floorplan/references/blueprint.md
new file mode 100644
index 0000000..f29d727
--- /dev/null
+++ b/skills/floorplan/references/blueprint.md
@@ -0,0 +1,78 @@
+# Blueprints: a floorplan of a system that isn't built yet
+
+A blueprint is the same map, drawn from a plan instead of code. Someone has a PRD, a spec or just a long description of what they want to build, and the map shows every piece they'd need, how the pieces connect, what each screen relies on, and what still has to be decided.
+
+You write two files in `floorplan/`:
+- `plan.json`: the files, endpoints and connections the system would have (this file).
+- `architecture.json`: the parts, outside services, flows and tour, exactly as for a code map ([schema.md](schema.md)).
+
+`plan.mjs` turns `plan.json` into the scan `build.mjs` expects, so everything after that works as for real code. Cards are drawn with dashed outlines and a **Blueprint** label, Health becomes a **design review** of the plan, and every part has a **Build this with Claude** (or Codex) button with a ready request to build it.
+
+Contents: [Planning well](#planning-well) · [plan.json](#planjson) · [Checks](#what-the-design-review-checks)
+
+## Planning well
+
+- **Plan to the level of files and endpoints**, not just boxes. Screens, the design review and the build prompts all depend on it. A small product is typically 15–60 files and 10–40 endpoints. Don't plan every helper: one file per page, per group of endpoints, per outside service and per kind of saved data is about right.
+- **Pick a sensible, common stack** unless the PRD names one, and list it in `stack`. Prefer what a solo builder working with AI would choose: a Next.js or React website, a Node or Python server, Postgres, Stripe, a hosted email service. Use real, conventional paths for that stack (`web/app/checkout/page.tsx`, `api/src/routes/orders.ts`).
+- **Every screen the PRD describes is a file with a `screen` URL.** Give each screen `calls` for the endpoints it uses and `uses` for the parts it's built from.
+- **Every endpoint gets `access`.** Decide it from the PRD. If the PRD is silent and it matters, leave it out (the review will flag it) or add a question.
+- **Don't invent requirements.** Where the PRD doesn't say and you had to choose, write the choice in `assumptions`. Where the answer changes what gets built and you can't reasonably choose, add it to `questions` with the parts it affects. Ask the user 2–3 questions up front only if the PRD leaves something fundamental open (who uses it, web or mobile, does anyone sign in, does money change hands).
+- **Outside services and data stores are `external` nodes** in architecture.json (Stripe, the database, an email service). Files reach them through `services` and `data` in plan.json.
+- **Background work** (scheduled emails, nightly jobs, queue workers) gets its own files and a `worker` node.
+
+## plan.json
+
+```json
+{
+ "$schema": "floorplan/plan@1",
+ "source": "docs/prd.md",
+ "stack": ["Next.js website", "Node.js + Express server", "Postgres", "Stripe"],
+ "assumptions": ["Staff and customers share one sign-in, with staff marked as such."],
+ "questions": [{ "question": "Can customers cancel for free?", "about": ["POST /api/orders/:id/cancel"] }],
+ "files": [ { "path": "web/app/checkout/page.tsx", "name": "Checkout page", "description": "…", "screen": "/checkout", "uses": ["web/lib/api.ts"], "calls": ["POST /api/orders"] } ],
+ "endpoints": [ { "method": "POST", "path": "/api/orders", "file": "api/src/routes/orders.ts", "name": "Place an order", "description": "…", "access": "signed-in" } ]
+}
+```
+
+| field | meaning |
+|---|---|
+| `source` | what it was planned from: the PRD's path in the project, or a few words such as "a description in chat" |
+| `stack` | the technology choices, in plain words |
+| `assumptions` | choices you made where the PRD didn't say. Shown on the map's overview |
+| `questions` | `{ question, about }`: decisions the PRD leaves open. `about` lists node ids, file paths or `"METHOD /path"`. Each one shows in the design review until it's answered and removed |
+| `files` | every planned file (see below) |
+| `endpoints` | every planned endpoint (see below) |
+
+**files[]**
+
+| field | meaning |
+|---|---|
+| `path` | where it would live, relative to the project folder. Required, unique |
+| `name`, `description` | a human name and one plain sentence, written like a description of real code ([writing-descriptions.md](writing-descriptions.md)) |
+| `screen` | for a page people open: its URL (`/checkout`, `/orders/:id`). Makes it a screen in **Screens** |
+| `uses` | other planned files it is built from or calls directly (becomes "uses" connections) |
+| `calls` | endpoints it calls, as `"METHOD /path"`, exactly as in `endpoints` |
+| `services` | ids of `external` nodes it talks to (Stripe, an email service) |
+| `data` | ids of nodes for the data stores it reads or writes (usually the database) |
+
+**endpoints[]**
+
+| field | meaning |
+|---|---|
+| `method` | GET, POST, PUT, PATCH, DELETE, or CALL for a callable function (for example Firebase `onCall`) |
+| `path` | the URL, starting with `/`. Use `:name` for parts that change (`/api/orders/:id`) |
+| `file` | the planned file that handles it. Required |
+| `name`, `description` | as for files |
+| `access` | who may use it: `public` (anyone), `signed-in`, `staff`, `webhook` (another company's service, which must prove it's them) or `internal` (only your own services) |
+
+Node `paths` globs in architecture.json assign planned files to parts, the same as for code. Aim for no unassigned files.
+
+## What the design review checks
+
+- endpoints that change data and are open to anyone (worth a second look, though sign-up and guest checkout are legitimate);
+- endpoints with no `access` decided;
+- every open question, pointing at the parts it affects;
+- endpoints no planned screen or service calls;
+- planned files connected to nothing.
+
+Each has **Resolve with Claude/Codex**, a request to settle it and update the plan.
diff --git a/skills/floorplan/scripts/build.mjs b/skills/floorplan/scripts/build.mjs
index 5e55408..0c1a78b 100644
--- a/skills/floorplan/scripts/build.mjs
+++ b/skills/floorplan/scripts/build.mjs
@@ -10,6 +10,7 @@ import { fileURLToPath } from 'node:url';
import { compileGlob, parseArgs, fmtNum, mapDir, keepOutOfGit } from './lib/common.mjs';
import { fallbackFileName, fallbackRouteName, routeKey } from './lib/names.mjs';
import { buildHealth } from './lib/health.mjs';
+import { buildPlanHealth } from './lib/blueprint.mjs';
import { buildScreens } from './lib/screens.mjs';
import { writeClaudeMd } from './lib/claudemd.mjs';
import { detectAgent } from './lib/agent.mjs';
@@ -193,6 +194,13 @@ for (const h of scan.hosts) {
for (const pm of pkgMatchers) if (!pm.hits) warn(`node "${pm.id}" packages match nothing imported. Known: ${extIds.slice(0, 8).join(', ')}…`);
for (const hm of hostMatchers) if (!hm.hits) warn(`node "${hm.id}" hosts match no host called from code`);
+// a blueprint's planned links from files to outside services and data stores (plan.json "services"/"data")
+for (const e of scan.nodeLinks || []) {
+ if (!includedSet.has(e.from)) continue;
+ if (!byId.has(e.to)) { err(`plan.json: "${e.from}" names "${e.to}" in its ${e.kind === 'data' ? 'data' : 'services'}, which is not a node id in architecture.json${didYouMean(e.to, ids)}`); continue; }
+ addLink(`f:${e.from}`, `n:${e.to}`, EDGE_KINDS.includes(e.kind) ? e.kind : 'call', { label: e.label });
+}
+
archEdges.forEach((e, i) => {
const where = `edges[${i}]`;
if (!EDGE_KINDS.includes(e?.kind)) err(`${where}.kind "${e?.kind}" must be one of ${EDGE_KINDS.join(', ')}${didYouMean(String(e?.kind), EDGE_KINDS)}`);
@@ -342,7 +350,7 @@ report.push('');
report.push(`ASSIGNMENT ${included.length} files (${include.join('+')}), ${unassigned.length} unassigned (${pct.toFixed(1)}%)`);
for (const n of nodes.filter((n) => n?.id && !n.parent)) {
const s = stats.get(n.id);
- report.push(` ${n.id.padEnd(28)} ${String(s.files).padStart(5)} files ${fmtNum(s.loc).padStart(6)} loc [${n.kind}]`);
+ report.push(` ${n.id.padEnd(28)} ${String(s.files).padStart(5)} files ${scan.blueprint ? '' : `${fmtNum(s.loc).padStart(6)} loc `}[${n.kind}]`);
}
if (unassigned.length) {
const byDir = new Map();
@@ -353,8 +361,8 @@ if (unassigned.length) {
const byKind = {};
for (const l of links.values()) byKind[l.k] = (byKind[l.k] || 0) + 1;
report.push(`LINKS ${[...links.values()].length} (${Object.entries(byKind).map(([k, v]) => `${k} ${v}`).join(', ')})`);
-const describedFiles = included.filter((f) => fileDesc.get(f.path)?.d).length;
-const describedRoutes = routesIn.filter((r) => routeDesc.get(routeKey(r))?.d).length;
+const describedFiles = included.filter((f) => fileDesc.get(f.path)?.d || f.desc).length;
+const describedRoutes = routesIn.filter((r) => routeDesc.get(routeKey(r))?.d || r.desc).length;
const noSummary = nodes.filter((n) => n?.id && !isStr(n.summary)).map((n) => n.id);
const reviewCount = [...fileDesc.values(), ...routeDesc.values()].filter((d) => d.review).length;
report.push(`DESCRIPTIONS files ${describedFiles}/${included.length} · routes ${describedRoutes}/${routesIn.length} · modules ${nodes.length - noSummary.length}/${nodes.length}${reviewCount ? ` · ${reviewCount} need review (code changed)` : ''}`);
@@ -370,6 +378,7 @@ const graph = {
meta: {
generatedAt: new Date().toISOString(), scanAt: scan.generatedAt, rootName: scan.rootName, root: scan.root,
audience, agent,
+ ...(scan.blueprint ? { blueprint: { source: scan.blueprint.source, stack: scan.blueprint.stack, assumptions: scan.blueprint.assumptions } } : {}),
repos: scan.repos.map(({ path: p, name, branch, head, remote }) => ({ path: p, name, branch, head, remote })),
counts: { files: included.length, loc: included.reduce((s, f) => s + f.loc, 0), unassigned: unassigned.length },
},
@@ -386,7 +395,7 @@ const graph = {
const d = fileDesc.get(f.path);
return {
p: f.path, n: owner.get(f.path), r: f.repo, l: f.lang || f.category, loc: f.loc,
- name: d?.name || fallbackFileName(f.path), d: d?.d || f.doc || '', ...(d?.d ? {} : { auto: true }),
+ name: d?.name || f.name || fallbackFileName(f.path), d: d?.d || f.desc || f.doc || '', ...(d?.d || f.desc ? {} : { auto: true }),
...(f.doc ? { doc: f.doc } : {}),
...(d?.review ? { review: d.review } : {}),
...(f.h ? { h: f.h, sig: f.sig } : {}),
@@ -396,7 +405,7 @@ const graph = {
}),
routes: routesIn.map((r) => {
const d = routeDesc.get(routeKey(r));
- return { f: r.file, m: r.method, p: r.path, l: r.line, h: r.handler || null, name: d?.name || fallbackRouteName(r), d: d?.d || r.doc || '', ...(d?.d ? {} : { auto: true }), ...(d?.review ? { review: d.review } : {}), ...(r.doc ? { doc: r.doc } : {}) };
+ return { f: r.file, m: r.method, p: r.path, l: r.line, h: r.handler || null, name: d?.name || r.name || fallbackRouteName(r), d: d?.d || r.desc || r.doc || '', ...(d?.d || r.desc ? {} : { auto: true }), ...(d?.review ? { review: d.review } : {}), ...(r.doc ? { doc: r.doc } : {}), ...(r.access ? { access: r.access } : {}) };
}),
links: [...links.values()],
flows: outFlows,
@@ -404,8 +413,10 @@ const graph = {
...(outRecent?.items.length ? { recent: outRecent } : {}),
};
// extension hooks, computed from the finished graph plus the raw scan
-try { graph.health = buildHealth({ graph, scan, arch, root }); } catch (e) { warn(`health check failed: ${e.message}`); graph.health = { issues: [] }; }
+// a blueprint has no code to check, so its Health is a design review of the plan (computed after screens)
+if (!scan.blueprint) try { graph.health = buildHealth({ graph, scan, arch, root }); } catch (e) { warn(`health check failed: ${e.message}`); graph.health = { issues: [] }; }
try { graph.screens = buildScreens({ graph, scan, arch, root }); } catch (e) { warn(`screen detection failed: ${e.message}`); graph.screens = []; }
+if (scan.blueprint) try { graph.health = buildPlanHealth({ graph, scan }); } catch (e) { warn(`design review failed: ${e.message}`); graph.health = { issues: [] }; }
fs.mkdirSync(outDir, { recursive: true });
const trackedWarning = keepOutOfGit(outDir);
fs.writeFileSync(path.join(outDir, 'graph.json'), JSON.stringify(graph, null, 0));
@@ -449,7 +460,7 @@ function escapeHtml(s) { return s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<'
const hs = graph.health?.summary;
if (hs && (hs.high || hs.medium || hs.low)) {
- report.push(`HEALTH ${hs.high} important · ${hs.medium} worth fixing · ${hs.low} minor`);
+ report.push(`${scan.blueprint ? 'DESIGN REVIEW' : 'HEALTH'} ${hs.high} important · ${hs.medium} worth fixing · ${hs.low} minor`);
for (const i of graph.health.issues.filter((x) => x.severity !== 'low').slice(0, 8)) report.push(` [${i.severity}] ${i.title}`);
}
if (graph.screens?.length) report.push(`SCREENS ${graph.screens.length} detected`);
@@ -459,6 +470,7 @@ report.push(graph.recent
// point future Claude Code sessions in this project at the map. Codex has no personal, uncommitted
// equivalent (AGENTS.md is shared with the team), so a map built by Codex leaves the project's notes alone.
if (agent === 'codex') report.push('AGENT Codex: questions on the map run through Codex');
+else if (scan.blueprint) report.push('BLUEPRINT planned, not built yet: drawn from floorplan/plan.json');
else if (!args['no-claude-md']) report.push(`CLAUDE.LOCAL.MD ${writeClaudeMd(root, outDir)}`);
report.push(trackedWarning ? `GIT ! ${trackedWarning}` : 'GIT floorplan/ is kept out of git (it ignores itself)');
report.push('');
diff --git a/skills/floorplan/scripts/lib/blueprint.mjs b/skills/floorplan/scripts/lib/blueprint.mjs
new file mode 100644
index 0000000..83c0f23
--- /dev/null
+++ b/skills/floorplan/scripts/lib/blueprint.mjs
@@ -0,0 +1,216 @@
+// Blueprints: a floorplan of a system that hasn't been built yet, planned from a PRD or a description.
+//
+// planToScan(plan, root) — turns floorplan/plan.json (the planned files, endpoints and calls, written by
+// the agent) into the same scan.json shape scan.mjs writes for real code, so
+// build.mjs and the viewer work unchanged. Returns { scan, errors, warnings }.
+// buildPlanHealth(ctx) — called by build.mjs instead of buildHealth for a blueprint: a design review of
+// the plan (who may call each endpoint, loose ends, open questions) in the same
+// { summary, issues } shape, so the Health panel shows it.
+
+import path from 'node:path';
+import { classify, toPosix } from './common.mjs';
+import { matchCalls } from './routes.mjs';
+
+export const ACCESS = ['public', 'signed-in', 'staff', 'webhook', 'internal'];
+const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'CALL', 'ANY'];
+const WRITE = new Set(['POST', 'PUT', 'PATCH', 'DELETE', 'CALL']);
+const isStr = (v) => typeof v === 'string' && v.trim().length > 0;
+const strArr = (v) => (Array.isArray(v) ? v.filter(isStr) : []);
+const routeKey = (m, p) => `${m} ${p}`;
+
+/** "POST /api/orders" -> { method, path }, or null. */
+export function parseCall(s) {
+ const m = /^\s*([A-Za-z]+)\s+(\/\S*)\s*$/.exec(String(s || ''));
+ return m && METHODS.includes(m[1].toUpperCase()) ? { method: m[1].toUpperCase(), path: m[2] } : null;
+}
+
+export function planToScan(plan, root) {
+ const errors = [], warnings = [];
+ const err = (m) => errors.push(m), warn = (m) => warnings.push(m);
+ if (!plan || typeof plan !== 'object') return { scan: null, errors: ['plan.json must be an object'], warnings };
+ const files = Array.isArray(plan.files) ? plan.files : [];
+ const endpoints = Array.isArray(plan.endpoints) ? plan.endpoints : [];
+ if (!files.length) err('files must be a non-empty array of the files the system would have');
+
+ const byPath = new Map();
+ files.forEach((f, i) => {
+ const where = `files[${i}]${f?.path ? ` ("${f.path}")` : ''}`;
+ if (!isStr(f?.path)) return err(`${where}.path is required`);
+ const p = toPosix(f.path.trim()).replace(/^\.\//, '');
+ if (p.startsWith('/') || p.includes('..')) return err(`${where}.path must be relative to the project folder`);
+ if (byPath.has(p)) return err(`${where}.path duplicates an earlier file`);
+ if (!isStr(f.description)) warn(`${where} has no description`);
+ byPath.set(p, f);
+ });
+ const known = [...byPath.keys()];
+ const near = (p) => { const base = p.split('/').pop(); const hit = known.find((k) => k.split('/').pop() === base); return hit ? ` (did you mean "${hit}"?)` : ''; };
+
+ // endpoints, keyed by "METHOD /path"
+ const routes = [], access = {}, seen = new Set();
+ endpoints.forEach((e, i) => {
+ const where = `endpoints[${i}]${e?.method && e?.path ? ` ("${e.method} ${e.path}")` : ''}`;
+ const method = String(e?.method || '').toUpperCase();
+ if (!METHODS.includes(method)) return err(`${where}.method must be one of ${METHODS.join(', ')}`);
+ if (!isStr(e.path) || !e.path.startsWith('/')) return err(`${where}.path must start with "/"`);
+ if (!isStr(e.file)) return err(`${where}.file is required: the planned file that handles it`);
+ const file = toPosix(e.file.trim()).replace(/^\.\//, '');
+ if (!byPath.has(file)) return err(`${where}.file "${file}" is not one of the planned files${near(file)}`);
+ const key = routeKey(method, e.path);
+ if (seen.has(key)) return err(`${where} duplicates an earlier endpoint`);
+ seen.add(key);
+ if (e.access !== undefined && !ACCESS.includes(e.access)) err(`${where}.access "${e.access}" must be one of ${ACCESS.join(', ')}`);
+ if (ACCESS.includes(e.access)) access[key] = e.access;
+ routes.push({ file, method, path: e.path, line: 0, ...(ACCESS.includes(e.access) ? { access: e.access } : {}), ...(isStr(e.name) ? { name: e.name.trim() } : {}), ...(isStr(e.description) ? { desc: e.description.trim() } : {}) });
+ });
+ const routeKeys = new Set(routes.map((r) => routeKey(r.method, r.path)));
+
+ // imports, calls, and links to outside services and data stores
+ const edges = [], nodeLinks = [], callFiles = [];
+ for (const [p, f] of byPath) {
+ for (const u of strArr(f.uses)) {
+ const to = toPosix(u.trim()).replace(/^\.\//, '');
+ if (!byPath.has(to)) { err(`files "${p}".uses "${u}" is not one of the planned files${near(to)}`); continue; }
+ if (to !== p) edges.push({ from: p, to });
+ }
+ const calls = [];
+ for (const c of strArr(f.calls)) {
+ const pc = parseCall(c);
+ if (!pc) { err(`files "${p}".calls "${c}" must look like "POST /api/orders"`); continue; }
+ if (!routeKeys.has(routeKey(pc.method, pc.path))) warn(`files "${p}".calls "${c}" matches no planned endpoint`);
+ calls.push({ path: pc.path, method: pc.method, line: 0 });
+ }
+ if (calls.length) callFiles.push({ path: p, calls });
+ for (const s of strArr(f.services)) nodeLinks.push({ from: p, to: s.trim(), kind: 'http' });
+ for (const d of strArr(f.data)) nodeLinks.push({ from: p, to: d.trim(), kind: 'data' });
+ }
+ // calls only reach the exact planned endpoint (method and path), never a near miss
+ const http = matchCalls(callFiles, routes).filter((h) => routeKeys.has(routeKey(h.method, h.path)) && h.call === h.path);
+
+ const questions = [];
+ (Array.isArray(plan.questions) ? plan.questions : []).forEach((q, i) => {
+ const text = isStr(q) ? q : q?.question;
+ if (!isStr(text)) return err(`questions[${i}] needs a question`);
+ questions.push({ question: text.trim(), about: strArr(q?.about) });
+ });
+
+ const scan = {
+ version: 1,
+ blueprint: {
+ source: isStr(plan.source) ? plan.source.trim() : '',
+ stack: strArr(plan.stack),
+ assumptions: strArr(plan.assumptions),
+ questions,
+ access,
+ },
+ generatedAt: new Date().toISOString(),
+ root: toPosix(root),
+ rootName: path.basename(root),
+ repos: [],
+ files: [...byPath].map(([p, f]) => {
+ const c = classify(p, 0);
+ return {
+ path: p, repo: null, category: 'code', lang: c.lang || path.posix.extname(p).slice(1) || null, loc: 0, bytes: 0,
+ ...(isStr(f.name) ? { name: f.name.trim() } : {}),
+ ...(isStr(f.description) ? { desc: f.description.trim() } : {}),
+ ...(isStr(f.screen) && f.screen.startsWith('/') ? { screens: [{ fw: 'plan', url: f.screen.trim() }] } : {}),
+ };
+ }),
+ edges,
+ externals: [],
+ extEdges: [],
+ routes,
+ http,
+ hosts: [],
+ nodeLinks,
+ };
+ return { scan, errors, warnings };
+}
+
+/** The design review shown in the Health panel for a blueprint. */
+export function buildPlanHealth({ graph, scan }) {
+ const bp = scan.blueprint || {};
+ const issues = [];
+ const routes = graph.routes || [];
+ const ridOf = new Map(routes.map((r, i) => [routeKey(r.m, r.p), 'r:' + i]));
+ const fileIds = new Set(graph.files.map((f) => 'f:' + f.p));
+ const nodeIds = new Set(graph.nodes.map((n) => 'n:' + n.id));
+ const refOf = (s) => {
+ if (!isStr(s)) return null;
+ const t = s.trim();
+ if (nodeIds.has('n:' + t)) return 'n:' + t;
+ if (fileIds.has('f:' + t)) return 'f:' + t;
+ const pc = parseCall(t);
+ return pc ? ridOf.get(routeKey(pc.method, pc.path)) || null : null;
+ };
+ const line = (r) => `- ${r.m} ${r.p} (${r.f})${r.name ? ` — ${r.name}` : ''}`;
+ const rebuild = 'Then rebuild the blueprint: run plan.mjs and build.mjs from the Floorplan skill, as its instructions say.';
+
+ // ---------- who may call each endpoint ----------
+ const accessOf = (r) => bp.access?.[routeKey(r.m, r.p)];
+ const openWrites = routes.map((r, i) => ({ r, i })).filter(({ r }) => accessOf(r) === 'public' && WRITE.has(r.m));
+ if (openWrites.length) issues.push({
+ id: 'plan-open-writes', kind: 'unprotected-endpoint', severity: 'medium',
+ title: openWrites.length === 1 ? 'Anyone could change data through one planned endpoint' : `Anyone could change data through ${openWrites.length} planned endpoints`,
+ detail: `The plan lets ${openWrites.length === 1 ? 'this endpoint' : 'these endpoints'} create, change or delete data with no sign-in. That's right for things like signing up or a guest checkout, but worth a second look before building: ${openWrites.length === 1 ? 'it is' : 'they are'} the easiest thing for a stranger to misuse.`,
+ items: openWrites.slice(0, 24).map(({ i }) => 'r:' + i),
+ notes: Object.fromEntries(openWrites.slice(0, 24).map(({ i }) => ['r:' + i, 'Planned as open to anyone, and changes data'])),
+ locations: [],
+ fix: [`Design review of floorplan/plan.json: these planned endpoints change data and are marked "access": "public":`, ...openWrites.map(({ r }) => line(r)), ``, `For each one, tell me in plain words whether a stranger should really be able to use it. Where they shouldn't, change its access to "signed-in" or "staff" in plan.json. Where it must stay public (sign-up, guest checkout), add a note on what limits abuse (rate limits, a CAPTCHA, email confirmation) to the endpoint's description. Ask me if you're unsure.`, rebuild].join('\n'),
+ });
+ const unknown = routes.map((r, i) => ({ r, i })).filter(({ r }) => !accessOf(r));
+ if (unknown.length) issues.push({
+ id: 'plan-no-access', kind: 'unprotected-endpoint', severity: 'medium',
+ title: unknown.length === 1 ? 'The plan doesn’t say who may use one endpoint' : `The plan doesn’t say who may use ${unknown.length} endpoints`,
+ detail: `Deciding who can use each part of the system now (anyone, signed-in customers, staff, another service) is much easier than adding sign-in checks after it's built.`,
+ items: unknown.slice(0, 24).map(({ i }) => 'r:' + i),
+ notes: Object.fromEntries(unknown.slice(0, 24).map(({ i }) => ['r:' + i, 'Who may use this isn’t decided'])),
+ locations: [],
+ fix: [`Design review of floorplan/plan.json: these planned endpoints have no "access" set:`, ...unknown.map(({ r }) => line(r)), ``, `For each, choose who may use it: "public" (anyone), "signed-in", "staff", "webhook" (another company's service, which must prove it's them) or "internal" (only our own services). Base it on the PRD; ask me where the PRD doesn't say.`, rebuild].join('\n'),
+ });
+
+ // ---------- open questions from the PRD ----------
+ bp.questions?.forEach((q, k) => {
+ const items = [...new Set(q.about.map(refOf).filter(Boolean))];
+ issues.push({
+ id: 'plan-question:' + k, kind: 'question', severity: 'medium',
+ title: q.question,
+ detail: 'The PRD doesn’t answer this, and the answer changes what gets built. Decide it before building the parts it touches.',
+ items, notes: Object.fromEntries(items.map((id) => [id, 'Depends on an open question'])),
+ locations: [],
+ fix: [`Open question in the blueprint (floorplan/plan.json): ${q.question}`, ``, `Explain the options to me in plain words, with what each would mean for the parts it touches${q.about.length ? ` (${q.about.join(', ')})` : ''}, and recommend one. After I decide, update plan.json and architecture.json to match and remove the question from plan.json's questions.`, rebuild].join('\n'),
+ });
+ });
+
+ // ---------- loose ends ----------
+ const called = new Set(graph.links.filter((l) => l.k === 'http' && l.calls).flatMap((l) => l.calls.map(([ri]) => ri)));
+ const unusedRoutes = routes.map((r, i) => ({ r, i })).filter(({ r, i }) => !called.has(i) && !['webhook', 'internal', 'public'].includes(accessOf(r)));
+ if (unusedRoutes.length) issues.push({
+ id: 'plan-unused-endpoints', kind: 'unused-file', severity: 'low',
+ title: unusedRoutes.length === 1 ? 'Nothing in the plan uses one endpoint' : `Nothing in the plan uses ${unusedRoutes.length} endpoints`,
+ detail: `No planned page or service calls ${unusedRoutes.length === 1 ? 'it' : 'them'}. Either a screen that needs ${unusedRoutes.length === 1 ? 'it is' : 'them is'} missing from the plan, or ${unusedRoutes.length === 1 ? 'it isn’t' : 'they aren’t'} needed.`,
+ items: unusedRoutes.slice(0, 24).map(({ i }) => 'r:' + i),
+ notes: Object.fromEntries(unusedRoutes.slice(0, 24).map(({ i }) => ['r:' + i, 'No planned caller'])),
+ locations: [],
+ fix: [`Design review of floorplan/plan.json: nothing in the plan calls these endpoints:`, ...unusedRoutes.map(({ r }) => line(r)), ``, `For each, find which planned screen or service should call it and add it to that file's "calls", or tell me it isn't needed and remove it.`, rebuild].join('\n'),
+ });
+ const linked = new Set();
+ for (const l of graph.links) { linked.add(l.a); linked.add(l.b); }
+ const screenFiles = new Set((graph.screens || []).map((s) => s.file));
+ const routeFiles = new Set(routes.map((r) => r.f));
+ const loose = graph.files.filter((f) => !linked.has('f:' + f.p) && !screenFiles.has(f.p) && !routeFiles.has(f.p));
+ if (loose.length) issues.push({
+ id: 'plan-loose-files', kind: 'unused-file', severity: 'low',
+ title: loose.length === 1 ? 'One planned file isn’t connected to anything' : `${loose.length} planned files aren’t connected to anything`,
+ detail: `Nothing in the plan uses ${loose.length === 1 ? 'it' : 'them'}, and ${loose.length === 1 ? 'it doesn’t' : 'they don’t'} use anything. That usually means a connection is missing from the plan.`,
+ items: loose.slice(0, 24).map((f) => 'f:' + f.p),
+ notes: Object.fromEntries(loose.slice(0, 24).map((f) => ['f:' + f.p, 'Not connected to anything in the plan'])),
+ locations: [],
+ fix: [`Design review of floorplan/plan.json: these planned files aren't connected to anything:`, ...loose.map((f) => `- ${f.p}`), ``, `Add the missing "uses", "calls", "services" or "data" entries, or remove files that aren't needed.`, rebuild].join('\n'),
+ });
+
+ const ORDER = { high: 0, medium: 1, low: 2 };
+ issues.sort((a, b) => ORDER[a.severity] - ORDER[b.severity]);
+ const summary = { high: 0, medium: 0, low: 0 };
+ for (const i of issues) summary[i.severity]++;
+ return { summary, issues: issues.slice(0, 40), review: true };
+}
diff --git a/skills/floorplan/scripts/plan.mjs b/skills/floorplan/scripts/plan.mjs
new file mode 100644
index 0000000..2b0c87b
--- /dev/null
+++ b/skills/floorplan/scripts/plan.mjs
@@ -0,0 +1,45 @@
+#!/usr/bin/env node
+// floorplan blueprint: turn floorplan/plan.json (the files, endpoints and connections a system would
+// have, planned from a PRD or a description) into floorplan/.cache/scan.json, the same shape scan.mjs
+// writes for real code. build.mjs then draws it as a blueprint: the same map, marked as planned.
+//
+// usage: node plan.mjs [root] [--plan <file>]
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { parseArgs, toPosix, mapDir, keepOutOfGit } from './lib/common.mjs';
+import { planToScan } from './lib/blueprint.mjs';
+
+const args = parseArgs(process.argv.slice(2));
+const root = path.resolve(args._[0] || '.');
+const outDir = mapDir(root);
+const planFile = path.resolve(args.plan || path.join(outDir, 'plan.json'));
+const outFile = path.join(outDir, '.cache', 'scan.json');
+
+const fail = (msg) => { console.error(`✗ ${msg}`); process.exit(1); };
+if (!fs.existsSync(planFile)) fail(`No plan at ${planFile}. Write it first (see references/blueprint.md).`);
+let plan;
+try { plan = JSON.parse(fs.readFileSync(planFile, 'utf8')); } catch (e) { fail(`plan.json is not valid JSON: ${e.message}`); }
+
+const { scan, errors, warnings } = planToScan(plan, root);
+const out = [];
+if (errors.length) { out.push(`✗ ${errors.length} error(s) in ${toPosix(path.relative(root, planFile))}:`); for (const e of errors) out.push(` - ${e}`); }
+if (warnings.length) { out.push(`! ${warnings.length} warning(s):`); for (const w of warnings.slice(0, 40)) out.push(` - ${w}`); }
+if (errors.length) { console.log(out.join('\n')); console.log('\nFix the errors above and run plan.mjs again.'); process.exit(1); }
+
+fs.mkdirSync(path.dirname(outFile), { recursive: true });
+fs.writeFileSync(outFile, JSON.stringify(scan));
+keepOutOfGit(outDir);
+
+const bp = scan.blueprint;
+const byDir = new Map();
+for (const f of scan.files) { const d = f.path.split('/').slice(0, -1).slice(0, 2).join('/') || '.'; byDir.set(d, (byDir.get(d) || 0) + 1); }
+if (out.length) out.push('');
+out.push(`BLUEPRINT ${scan.files.length} planned files · ${scan.routes.length} endpoints · ${scan.http.length} calls matched · ${scan.nodeLinks.length} links to services and data`);
+for (const [d, n] of [...byDir].sort((a, b) => b[1] - a[1]).slice(0, 15)) out.push(` ${String(n).padStart(4)} ${d}/`);
+const screens = scan.files.filter((f) => f.screens).length;
+if (screens) out.push(`SCREENS ${screens} planned`);
+if (bp.questions.length) out.push(`OPEN QUESTIONS ${bp.questions.length} (shown in Health until answered)`);
+out.push('');
+out.push(`✓ wrote ${toPosix(path.relative(root, outFile))}. Next: write or update floorplan/architecture.json, then run build.mjs.`);
+console.log(out.join('\n'));
diff --git a/skills/floorplan/scripts/refresh.mjs b/skills/floorplan/scripts/refresh.mjs
index 1a5b031..cee07a4 100644
--- a/skills/floorplan/scripts/refresh.mjs
+++ b/skills/floorplan/scripts/refresh.mjs
@@ -25,6 +25,17 @@ if (!fs.existsSync(graphFile) || !fs.existsSync(archFile)) {
const old = JSON.parse(fs.readFileSync(graphFile, 'utf8'));
const arch = JSON.parse(fs.readFileSync(archFile, 'utf8'));
+// A blueprint is redrawn from plan.json, not from code. --from-code maps the real code instead
+// (plan.json is kept, so the blueprint can be drawn again with plan.mjs + build.mjs).
+if (old.meta?.blueprint && !args['from-code']) {
+ const run = (script, ...rest) => execFileSync(process.execPath, [path.join(HERE, script), root, ...rest], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] });
+ try {
+ process.stdout.write(run('plan.mjs') + '\n' + run('build.mjs', ...process.argv.slice(2).filter((a) => a.startsWith('--'))));
+ } catch (e) { process.stdout.write(String(e.stdout || '')); process.exit(1); }
+ console.log('\nNEXT This map is a blueprint, redrawn from floorplan/plan.json. Edit plan.json and architecture.json to change the plan. Once the code exists, run refresh.mjs --from-code for a map of the real code; plan.json stays.');
+ process.exit(0);
+}
+
// ---------- 1. re-scan (no tokens) ----------
const node = process.execPath;
execFileSync(node, [path.join(HERE, 'scan.mjs'), root], { stdio: ['ignore', 'ignore', 'inherit'] });
diff --git a/skills/floorplan/scripts/status.mjs b/skills/floorplan/scripts/status.mjs
index e04550c..dc76ac5 100644
--- a/skills/floorplan/scripts/status.mjs
+++ b/skills/floorplan/scripts/status.mjs
@@ -17,6 +17,10 @@ try {
process.exit(0);
}
const g = JSON.parse(fs.readFileSync(graphFile, 'utf8'));
+ if (g.meta.blueprint) {
+ console.log(`a blueprint (planned, not built${g.meta.blueprint.source ? `, from ${g.meta.blueprint.source}` : ''}) built ${g.meta.generatedAt}: ${g.meta.counts.files} planned files, ${g.nodes.length} nodes.\nTo change the plan, edit floorplan/plan.json and architecture.json, then run refresh.mjs (it redraws from plan.json). If the code now exists and the user wants a map of it, run refresh.mjs --from-code.`);
+ process.exit(0);
+ }
const lines = [`map built ${g.meta.generatedAt} covering ${g.meta.counts.files} files, ${g.nodes.length} nodes.`];
for (const r of g.meta.repos || []) {
const abs = path.join(root, r.path);
diff --git a/tests/blueprint.test.mjs b/tests/blueprint.test.mjs
new file mode 100644
index 0000000..b8bda2d
--- /dev/null
+++ b/tests/blueprint.test.mjs
@@ -0,0 +1,143 @@
+// Blueprints: a map planned from a PRD before any code exists. plan.mjs turns floorplan/plan.json
+// into a scan, and build.mjs draws it like a code map, with a design review instead of the code checks.
+import { test, before, after } from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import path from 'node:path';
+import { REPO, makeProject, run, readGraph, readJson, writeJson, routeKeys, cleanup } from './helpers.mjs';
+
+const FIXTURE = path.join(REPO, 'tests', 'fixtures', 'blueprint');
+let root, graph, planOut, buildOut;
+before(() => {
+ root = makeProject({});
+ fs.cpSync(FIXTURE, root, { recursive: true });
+ planOut = run('plan.mjs', root);
+ buildOut = run('build.mjs', root, '--no-claude-md');
+ graph = readGraph(root);
+});
+after(() => cleanup(root));
+
+/** A copy of the sample with plan.json changed, for the error cases. */
+function withPlan(change) {
+ const r = makeProject({});
+ fs.cpSync(FIXTURE, r, { recursive: true });
+ const file = path.join(r, 'floorplan', 'plan.json');
+ const plan = readJson(file);
+ change(plan);
+ writeJson(file, plan);
+ return r;
+}
+const fails = (fn) => { try { fn(); } catch (e) { return String(e.stdout || '') + String(e.stderr || ''); } assert.fail('expected the script to fail'); };
+
+test('the planned files and endpoints are on the map, named as the plan names them', () => {
+ assert.match(planOut, /BLUEPRINT {2}21 planned files · 11 endpoints · 9 calls matched · 5 links to services and data/);
+ assert.equal(graph.files.length, 21);
+ assert.equal(graph.files.filter((f) => f.auto).length, 0, 'every file is described');
+ assert.equal(graph.routes.length, 11);
+ assert.equal(graph.files.find((f) => f.p === 'web/app/page.tsx').name, 'Home page');
+ const book = graph.routes.find((r) => r.m === 'POST' && r.p === '/api/bookings');
+ assert.equal(book.name, 'Book a walk');
+ assert.equal(book.access, 'signed-in');
+ assert.deepEqual(graph.meta.blueprint.stack.slice(0, 2), ['Next.js websites for owners and walkers', 'Node.js + Express server']);
+ assert.equal(graph.meta.blueprint.source, 'docs/prd.md');
+ assert.match(buildOut, /DESCRIPTIONS {2}files 21\/21 · routes 11\/11/);
+ assert.match(buildOut, /BLUEPRINT {2}planned, not built yet/);
+});
+
+test('screens call endpoints, and files reach outside services and the database', () => {
+ const http = graph.links.filter((l) => l.k === 'http' && l.labels?.length && l.a.startsWith('f:web/app/bookings')).map((l) => `${l.b.slice(2)} ${l.labels.join(', ')}`);
+ assert.deepEqual(http, ['api/src/routes/bookings.ts GET /api/bookings, POST /api/bookings/:id/cancel']);
+ const toNodes = graph.links.filter((l) => l.b.startsWith('n:')).map((l) => `${l.a.slice(2)} ${l.k} ${l.b.slice(2)}`).sort();
+ assert.deepEqual(toNodes, [
+ 'api/src/db/bookings.ts data db', 'api/src/db/users.ts data db', 'api/src/db/walkers.ts data db',
+ 'api/src/services/email.ts http postmark', 'api/src/services/payments.ts http stripe',
+ ]);
+});
+
+test('Screens show what each planned page relies on, down to Stripe', () => {
+ assert.deepEqual(graph.screens.map((s) => s.url).sort(), ['/', '/book/:walkerId', '/bookings', '/login', '/schedule']);
+ const book = graph.screens.find((s) => s.url === '/book/:walkerId');
+ const behind = book.behind.map((b) => `${b.kind} ${b.id}`);
+ assert.ok(behind.includes('server f:api/src/routes/bookings.ts'));
+ assert.ok(behind.includes('outside n:stripe'));
+});
+
+test('Health is a design review of the plan', () => {
+ const issues = graph.health.issues;
+ const titles = issues.map((i) => `${i.severity} ${i.title}`);
+ assert.deepEqual(titles, [
+ 'medium Anyone could change data through 2 planned endpoints',
+ 'medium The plan doesn’t say who may use one endpoint',
+ 'medium Can owners cancel a walk for free, and up to when?',
+ 'low Nothing in the plan uses one endpoint',
+ 'low One planned file isn’t connected to anything',
+ ]);
+ const routesOf = (i) => i.items.filter((id) => id.startsWith('r:')).map((id) => `${graph.routes[+id.slice(2)].m} ${graph.routes[+id.slice(2)].p}`).sort();
+ assert.deepEqual(routesOf(issues[0]), ['POST /api/auth/login', 'POST /api/auth/signup']);
+ assert.deepEqual(routesOf(issues[1]), ['DELETE /api/walkers/:id']);
+ assert.deepEqual(issues[2].items.sort(), ['f:web/app/bookings/page.tsx', `r:${graph.routes.findIndex((r) => r.p === '/api/bookings/:id/cancel')}`].sort());
+ assert.deepEqual(routesOf(issues[3]), ['DELETE /api/walkers/:id']);
+ assert.deepEqual(issues[4].items, ['f:api/src/lib/geo.ts']);
+ assert.match(issues[0].fix, /floorplan\/plan\.json/);
+ assert.match(buildOut, /DESIGN REVIEW {2}0 important · 3 worth fixing · 2 minor/);
+});
+
+test('the map page marks it as a blueprint, and Ask knows there is no code to read', () => {
+ const html = fs.readFileSync(path.join(root, 'floorplan', 'index.html'), 'utf8');
+ assert.ok(html.includes('/* ui/06-blueprint.js */'));
+ assert.ok(html.includes('"blueprint":{"source":"docs/prd.md"'));
+ const query = fs.readFileSync(path.join(root, 'floorplan', 'query.mjs'), 'utf8');
+ assert.ok(query.includes('This map is a blueprint'));
+ assert.ok(!fs.existsSync(path.join(root, 'CLAUDE.local.md')));
+});
+
+test('plan.mjs names what is wrong with a plan', () => {
+ const r = withPlan((p) => {
+ p.files[0].uses.push('web/components/WalkerCrad.tsx');
+ p.endpoints[0].access = 'everyone';
+ p.endpoints[1].file = 'api/src/routes/walker.ts';
+ p.files[1].calls.push('POST /api/payments');
+ p.files[2].calls.push('cancel it');
+ });
+ try {
+ const out = fails(() => run('plan.mjs', r));
+ assert.match(out, /files "web\/app\/page\.tsx"\.uses "web\/components\/WalkerCrad\.tsx" is not one of the planned files/);
+ assert.match(out, /access "everyone" must be one of public, signed-in, staff, webhook, internal/);
+ assert.match(out, /\.file "api\/src\/routes\/walker\.ts" is not one of the planned files/);
+ assert.match(out, /calls "cancel it" must look like "POST \/api\/orders"/);
+ assert.match(out, /calls "POST \/api\/payments" matches no planned endpoint/);
+ } finally { cleanup(r); }
+});
+
+test('build.mjs catches a service that is not a node', () => {
+ const r = withPlan((p) => { p.files.find((f) => f.services).services = ['strpe']; });
+ try {
+ run('plan.mjs', r);
+ const out = fails(() => run('build.mjs', r, '--no-claude-md'));
+ assert.match(out, /names "strpe" in its services, which is not a node id in architecture\.json — did you mean "stripe"\?/);
+ } finally { cleanup(r); }
+});
+
+test('refresh redraws a blueprint from plan.json, and --from-code maps the real code instead', () => {
+ const r = withPlan(() => {});
+ try {
+ run('plan.mjs', r);
+ run('build.mjs', r, '--no-claude-md');
+ assert.match(run('status.mjs', r), /a blueprint \(planned, not built, from docs\/prd\.md\)/);
+ const plan = readJson(path.join(r, 'floorplan', 'plan.json'));
+ plan.endpoints.push({ method: 'GET', path: '/api/health', file: 'api/src/server.ts', name: 'Health check', access: 'public' });
+ writeJson(path.join(r, 'floorplan', 'plan.json'), plan);
+ assert.match(run('refresh.mjs', r, '--no-claude-md'), /redrawn from floorplan\/plan\.json/);
+ assert.ok(routeKeys(readGraph(r)).includes('GET /api/health'));
+
+ fs.mkdirSync(path.join(r, 'api', 'src'), { recursive: true });
+ fs.writeFileSync(path.join(r, 'api', 'src', 'server.ts'), `import express from 'express';\nconst app = express();\napp.get('/api/health', (req, res) => res.send('ok'));\napp.listen(3000);\n`);
+ // the blueprint's flows point at files that aren't written yet, so the map of the code gets its own
+ writeJson(path.join(r, 'floorplan', 'architecture.json'), { project: { name: 'Pawprint', summary: 'Being built.' }, nodes: [{ id: 'api', label: 'Main server', kind: 'service', summary: 'The server.', paths: ['api/**'] }] });
+ run('refresh.mjs', r, '--from-code', '--no-claude-md');
+ const g = readGraph(r);
+ assert.equal(g.meta.blueprint, undefined);
+ assert.deepEqual(routeKeys(g), ['GET /api/health']);
+ assert.ok(fs.existsSync(path.join(r, 'floorplan', 'plan.json')), 'the plan is kept');
+ } finally { cleanup(r); }
+});
diff --git a/tests/fixtures/blueprint/docs/prd.md b/tests/fixtures/blueprint/docs/prd.md
new file mode 100644
index 0000000..0fdf846
--- /dev/null
+++ b/tests/fixtures/blueprint/docs/prd.md
@@ -0,0 +1,17 @@
+# Pawprint: book a dog walker
+
+## Problem
+Dog owners in the city find walkers through word of mouth and pay them by bank transfer. Walkers juggle bookings in their phone's notes app.
+
+## What we're building
+- **Customer website.** Owners browse walkers, see each walker's free slots and book a walk. They pay by card when they book, see their upcoming walks and can cancel one.
+- **Walker app.** Walkers sign in, see today's schedule and mark each walk as done.
+- **Reminders.** Owners get an email the evening before a walk.
+- **Payments.** Cards are charged through Stripe. A booking is only confirmed once Stripe says the payment went through.
+- **Staff.** We can remove a walker who leaves.
+
+## Out of scope for v1
+Reviews, tips, a native mobile app.
+
+## Open
+We haven't decided the cancellation policy.
diff --git a/tests/fixtures/blueprint/floorplan/architecture.json b/tests/fixtures/blueprint/floorplan/architecture.json
new file mode 100644
index 0000000..bb27310
--- /dev/null
+++ b/tests/fixtures/blueprint/floorplan/architecture.json
@@ -0,0 +1,33 @@
+{
+ "$schema": "floorplan/architecture@1",
+ "project": { "name": "Pawprint", "summary": "Dog owners book and pay for walks with local walkers, and walkers keep track of their day. Planned from the PRD; nothing is built yet." },
+ "nodes": [
+ { "id": "web", "label": "Customer website", "kind": "ui", "summary": "Where owners find a walker, book and pay, and manage their walks.", "paths": ["web/**"] },
+ { "id": "walker", "label": "Walker app", "kind": "ui", "summary": "Where walkers see today's walks and mark them done.", "paths": ["walker/**"] },
+ { "id": "api", "label": "Main server", "kind": "service", "summary": "Answers both apps, takes payments and keeps the data.", "paths": ["api/**"] },
+ { "id": "api.routes", "parent": "api", "label": "Endpoints", "kind": "feature", "summary": "Everything the apps and Stripe can ask the server to do.", "paths": ["api/src/routes/**", "api/src/server.ts"] },
+ { "id": "api.services", "parent": "api", "label": "Payments and email", "kind": "library", "summary": "Talks to Stripe and Postmark.", "paths": ["api/src/services/**"] },
+ { "id": "api.data", "parent": "api", "label": "Saved data", "kind": "data", "summary": "Reads and saves accounts, walkers and bookings.", "paths": ["api/src/db/**"] },
+ { "id": "jobs", "label": "Reminders", "kind": "worker", "summary": "Emails owners the evening before a walk.", "paths": ["jobs/**"] },
+ { "id": "db", "label": "Database", "kind": "external", "summary": "Postgres, where accounts, walkers and bookings are kept." },
+ { "id": "stripe", "label": "Stripe", "kind": "external", "summary": "Charges and refunds cards." },
+ { "id": "postmark", "label": "Postmark", "kind": "external", "summary": "Sends emails." }
+ ],
+ "edges": [
+ { "from": "stripe", "to": "api/src/routes/webhooks.ts", "kind": "http", "label": "payment succeeded" }
+ ],
+ "flows": [
+ { "id": "book", "title": "Booking a walk", "steps": [
+ { "node": "web/app/book/[walkerId]/page.tsx", "note": "The owner picks a slot and pays" },
+ { "node": "api/src/routes/bookings.ts", "note": "The server holds the slot" },
+ { "node": "api/src/services/payments.ts", "note": "and asks Stripe to charge the card" },
+ { "node": "stripe", "note": "Stripe charges it" },
+ { "node": "api/src/routes/webhooks.ts", "note": "Stripe says it went through, so the booking is confirmed" }
+ ] }
+ ],
+ "tour": [
+ { "node": "web", "title": "Where owners book", "note": "Owners find a walker, pick a time and pay here." },
+ { "node": "api", "title": "The main server", "note": "Both apps talk to it, and it handles payments." },
+ { "node": "walker", "title": "Where walkers work", "note": "Walkers see their day and mark walks done." }
+ ]
+}
diff --git a/tests/fixtures/blueprint/floorplan/plan.json b/tests/fixtures/blueprint/floorplan/plan.json
new file mode 100644
index 0000000..96acd27
--- /dev/null
+++ b/tests/fixtures/blueprint/floorplan/plan.json
@@ -0,0 +1,48 @@
+{
+ "$schema": "floorplan/plan@1",
+ "source": "docs/prd.md",
+ "stack": ["Next.js websites for owners and walkers", "Node.js + Express server", "Postgres database", "Stripe for card payments", "Postmark for email"],
+ "assumptions": [
+ "Owners and walkers use the same sign-in, with walkers marked as staff.",
+ "The walker app is a website that works on phones, not a native app (native is out of scope for v1)."
+ ],
+ "questions": [
+ { "question": "Can owners cancel a walk for free, and up to when?", "about": ["POST /api/bookings/:id/cancel", "web/app/bookings/page.tsx"] }
+ ],
+ "files": [
+ { "path": "web/app/page.tsx", "name": "Home page", "description": "Lists the walkers near you, with their photo and price.", "screen": "/", "uses": ["web/components/WalkerCard.tsx", "web/lib/api.ts"], "calls": ["GET /api/walkers"] },
+ { "path": "web/app/book/[walkerId]/page.tsx", "name": "Booking page", "description": "Shows a walker's free slots and lets the owner pick one and pay.", "screen": "/book/:walkerId", "uses": ["web/lib/api.ts"], "calls": ["GET /api/walkers/:id/slots", "POST /api/bookings"] },
+ { "path": "web/app/bookings/page.tsx", "name": "My walks page", "description": "The owner's upcoming and past walks, with a cancel button.", "screen": "/bookings", "uses": ["web/lib/api.ts"], "calls": ["GET /api/bookings", "POST /api/bookings/:id/cancel"] },
+ { "path": "web/app/login/page.tsx", "name": "Sign-in page", "description": "Sign in or create an account.", "screen": "/login", "uses": ["web/lib/api.ts"], "calls": ["POST /api/auth/login", "POST /api/auth/signup"] },
+ { "path": "web/components/WalkerCard.tsx", "name": "Walker card", "description": "One walker's photo, name and price, used in lists." },
+ { "path": "web/lib/api.ts", "name": "Server connection", "description": "How the website talks to the server, keeping the owner signed in." },
+ { "path": "walker/app/schedule/page.tsx", "name": "Today's schedule", "description": "The walker's walks for today, with a button to mark each one done.", "screen": "/schedule", "calls": ["GET /api/walker/schedule", "POST /api/walks/:id/complete"] },
+ { "path": "api/src/server.ts", "name": "Server start", "description": "Starts the server and plugs in every group of endpoints.", "uses": ["api/src/routes/walkers.ts", "api/src/routes/bookings.ts", "api/src/routes/auth.ts", "api/src/routes/walks.ts", "api/src/routes/webhooks.ts", "api/src/routes/admin.ts"] },
+ { "path": "api/src/routes/walkers.ts", "name": "Walker endpoints", "description": "Lists walkers and their free slots.", "uses": ["api/src/db/walkers.ts"] },
+ { "path": "api/src/routes/bookings.ts", "name": "Booking endpoints", "description": "Books, lists and cancels walks.", "uses": ["api/src/services/payments.ts", "api/src/db/bookings.ts"] },
+ { "path": "api/src/routes/auth.ts", "name": "Sign-in endpoints", "description": "Signs people in and creates accounts.", "uses": ["api/src/db/users.ts"] },
+ { "path": "api/src/routes/walks.ts", "name": "Walker schedule endpoints", "description": "Today's walks for a walker, and marking a walk done.", "uses": ["api/src/db/bookings.ts"] },
+ { "path": "api/src/routes/webhooks.ts", "name": "Stripe messages", "description": "Confirms a booking when Stripe says the payment went through.", "uses": ["api/src/db/bookings.ts", "api/src/services/email.ts"] },
+ { "path": "api/src/routes/admin.ts", "name": "Staff endpoints", "description": "Removes a walker who has left." , "uses": ["api/src/db/walkers.ts"] },
+ { "path": "api/src/services/payments.ts", "name": "Card payments", "description": "Charges and refunds cards through Stripe.", "services": ["stripe"] },
+ { "path": "api/src/services/email.ts", "name": "Emails", "description": "Sends booking confirmations and reminders.", "services": ["postmark"] },
+ { "path": "api/src/db/bookings.ts", "name": "Saved bookings", "description": "Reads and saves walks.", "data": ["db"] },
+ { "path": "api/src/db/users.ts", "name": "Saved accounts", "description": "Reads and saves owners and walkers.", "data": ["db"] },
+ { "path": "api/src/db/walkers.ts", "name": "Saved walkers", "description": "Reads and saves walker profiles and their free slots.", "data": ["db"] },
+ { "path": "api/src/lib/geo.ts", "name": "Distance helper", "description": "Works out how far a walker is from an owner." },
+ { "path": "jobs/reminders.ts", "name": "Evening reminders", "description": "Every evening, emails owners about tomorrow's walks.", "uses": ["api/src/db/bookings.ts", "api/src/services/email.ts"] }
+ ],
+ "endpoints": [
+ { "method": "GET", "path": "/api/walkers", "file": "api/src/routes/walkers.ts", "name": "List walkers", "description": "Walkers near the owner.", "access": "public" },
+ { "method": "GET", "path": "/api/walkers/:id/slots", "file": "api/src/routes/walkers.ts", "name": "A walker's free slots", "description": "When a walker is free this week.", "access": "public" },
+ { "method": "POST", "path": "/api/bookings", "file": "api/src/routes/bookings.ts", "name": "Book a walk", "description": "Holds the slot and starts the card payment.", "access": "signed-in" },
+ { "method": "GET", "path": "/api/bookings", "file": "api/src/routes/bookings.ts", "name": "My walks", "description": "The signed-in owner's walks.", "access": "signed-in" },
+ { "method": "POST", "path": "/api/bookings/:id/cancel", "file": "api/src/routes/bookings.ts", "name": "Cancel a walk", "description": "Cancels a walk and refunds it if allowed.", "access": "signed-in" },
+ { "method": "POST", "path": "/api/auth/login", "file": "api/src/routes/auth.ts", "name": "Sign in", "description": "Checks the email and password.", "access": "public" },
+ { "method": "POST", "path": "/api/auth/signup", "file": "api/src/routes/auth.ts", "name": "Create an account", "description": "Creates an owner account.", "access": "public" },
+ { "method": "GET", "path": "/api/walker/schedule", "file": "api/src/routes/walks.ts", "name": "Today's walks", "description": "The signed-in walker's walks for today.", "access": "staff" },
+ { "method": "POST", "path": "/api/walks/:id/complete", "file": "api/src/routes/walks.ts", "name": "Mark a walk done", "description": "Records that a walk happened.", "access": "staff" },
+ { "method": "POST", "path": "/api/webhooks/stripe", "file": "api/src/routes/webhooks.ts", "name": "Payment went through", "description": "Stripe's message that a card payment succeeded.", "access": "webhook" },
+ { "method": "DELETE", "path": "/api/walkers/:id", "file": "api/src/routes/admin.ts", "name": "Remove a walker", "description": "Removes a walker who has left." }
+ ]
+}