Files
snapcad-studio/docs/scene-bridge/NOTES.md
T

141 lines
7.9 KiB
Markdown
Raw Normal View History

# Scene Bridge — Phase 0 Orientation Notes
Verified against source on 2026-06-26. No code written. Line references are to the
files as read this session.
## Data flow (from CLAUDE.md, restated)
```
MCP (Node) ──POST──▶ local Next route (/api/scene) ──writes──▶ .codex/pending-scenes/<projectId>.json
│
editor page (browser) ──GET /api/scene poll──▶ hydrate into IndexedDB via the app's
existing save path ──▶ editor opens/refreshes the project
```
Node never touches IndexedDB/localStorage — that storage is origin-sandboxed to the page.
The route only stages a file on disk; the browser-side poller is the only thing that writes
the scene store. (Confirmed: the existing `/api/local-download` route is the template — it is
a pure disk-writer behind a same-origin guard.)
## IndexedDB record shape — CONFIRMED
Source: `apps/web/src/app/page.tsx`.
- DB name: `sketchForge.projectShapes` (`PROJECT_SHAPES_DB_NAME`, page.tsx:44), version `1`.
- Object store: `projectShapes` (`PROJECT_SHAPES_STORE_NAME`, page.tsx:45), `keyPath: "id"`
(page.tsx:70).
- Record (`ProjectShapeRecord`, page.tsx:33–41):
```ts
{ id: string; revision: number; shapes: WorkplaneShape[]; updatedAt: number }
```
`id` is the projectId. Matches CLAUDE.md exactly.
## localStorage key — CONFIRMED
- Key: **`sketchForge.projects`** (`PROJECTS_STORAGE_KEY`, page.tsx:43). Note the plural.
- Value: JSON array of project metadata (`StoredDashboardProject[]`), written via
`projectForStorage` (page.tsx:200) at page.tsx:293.
- A project is only listed/openable if it has an entry here. **Confirms CLAUDE.md's rule:**
a project needs BOTH a localStorage metadata entry AND an IndexedDB shapes record.
Other localStorage keys (not the project store, noted to avoid confusion):
`sketchForge.downloadMode`, `sketchForge.downloadFolder` (page.tsx:46–47).
## Read/write helpers to reuse — names confirmed, BUT see "Contradictions" below
IndexedDB (page.tsx):
- `openProjectShapesDb()` — 59
- `loadProjectShapes(projectId)` — 78
- `saveProjectShapes(projectId, shapes, revision)` — 93 (has a revision guard: skips the put
when an existing record's `revision > revision`, page.tsx:104)
- `deleteProjectShapes(projectId)` — 124
localStorage (page.tsx):
- `readStoredProjects()` — 140 (returns `{ projects, legacyShapes }`)
- `readProjects()` — 175
- `mergeProjectForStorage` / `projectForStorage` / `mergeProjectsForStorage` — 179 / 200 / 216
- `newProject(name, index, shapeCount?)` — 222
React-level save path the editor already uses (page.tsx):
- `updateProjectShapes({ projectId, shapes })` — 443. This is the callback passed to the editor
as `onProjectShapesChange` (page.tsx:653). It bumps a monotonic revision
(`Math.max(Date.now(), nextProjectRevisionRef + 1)`, page.tsx:444), updates in-memory state,
AND queues `saveProjectShapes`. **This is the real "existing save path"** the Phase 2 hydrator
should drive, because it keeps localStorage `shapes` count + `revision` consistent with
IndexedDB. Writing IndexedDB directly would desync the dashboard metadata.
Reuse for staging (workplaneShapes.ts):
- `serializeShapesForSync(shapes)` — 117: `canonicalizeShape`s then `JSON.stringify`s. Good
candidate for what the route/hydrator serialize.
- `canonicalizeShape` — 61.
## Editor open-URL — CONFIRMED
- Canonical: `/?editor=1&project=<projectId>` (built at page.tsx:398, `encodeURIComponent`'d).
- Bare `/?editor=1` (no project) also valid.
- Mount-time parse (page.tsx:274–282): editor opens when `editor=1` **or** the test param
`codexBooleanCase` is present. The `project` query param only becomes the active project if
it already exists in stored projects (page.tsx:277) — i.e. **the localStorage entry must
exist first**, otherwise the editor opens with no active project.
## Same-origin guard (Phase 1 template) — CONFIRMED
Source: `apps/web/src/app/api/local-download/route.ts`.
- `isLocalSameOriginRequest(request)` (line 15): hostname must be in
`{localhost, 127.0.0.1, ::1}`; if an `Origin` header is present it must be local same-origin;
`sec-fetch-site` must be absent, `same-origin`, or `none`.
- Implication for the MCP (Node `fetch` to `http://127.0.0.1:3000`): no `Origin` and no
`sec-fetch-site` header are sent by default → **passes**. So the MCP needs no special header.
(To be re-verified empirically in Phase 1, per the plan's acceptance note.)
- Also reusable from this file: `safeFileName` (line 10) regex-strips
`[<>:"/\\|?*-]` after `path.basename` — the pattern for Phase 1's `safeProjectId`.
Size cap pattern: `MAX_LOCAL_DOWNLOAD_BYTES` + `Buffer.byteLength` 413 (lines 8, 48).
## Data contract — CONFIRMED
Source: `apps/web/src/types/sketchforge.ts`.
- `WorkplaneShape` (line 59) is the contract. Cutter = `hole: true` (line 64). Boolean result
carries parts in `groupedShapes: WorkplaneShape[]` (line 102) plus `groupedBase{Width,Depth,Height}`.
- `ShapeKind` union (line 1) has **18** kinds: box, cylinder, sphere, sketch, scribble, cone,
pyramid, roof, text, roundRoof, halfSphere, torus, tube, ring, wedge, polygon, icosahedron, mesh.
## Contradictions / alpha drift to flag
1. **Helpers in `page.tsx` are module-private, not exported.** CLAUDE.md says "reuse the existing
IndexedDB read/write helpers and the localStorage project helpers in page.tsx," but none of
`saveProjectShapes`, `loadProjectShapes`, `readStoredProjects`, etc. are exported — a new
module under `components/` cannot import them. Phase 2 options: (a) drive the existing
`onProjectShapesChange`/`updateProjectShapes` callback that the editor mount already wires
(preferred — keeps localStorage + IndexedDB consistent), or (b) lift the helpers into a shared
module. Pure direct-IndexedDB writes from the hydrator would desync dashboard metadata. Needs a
decision before Phase 2.
2. **"Sane parameter ranges" do not live in `shapeCatalog.ts` / `workplaneShapes.ts`.** CLAUDE.md
says valid kinds + sane ranges live there. Reality: `shapeCatalog.ts` provides per-kind
**defaults** (`makeShapeFromAsset` line 61, `sceneShape` line 21 with width/depth/height
fallbacks of 20), and `workplaneShapes.ts` provides canonicalization/equality/serialization —
**no numeric min/max ranges anywhere.** The Phase 3 zod schema will have to derive ranges from
these defaults / the editor UI, not lift them from a table.
3. **`shapeCatalog` toolbar list is a subset of `ShapeKind`.** `toolbarShapeAssets` (line 7) lists
only 11 user-creatable shapes; the type union has 18. The MCP schema's source of truth for
valid kinds is the `ShapeKind` union in `types/sketchforge.ts`, not the toolbar catalog.
4. **Upstream fork commit still a placeholder.** CLAUDE.md "Forked from upstream commit:
`<FILL IN>`" is unfilled. Pin it before relying on internal-shape stability.
5. **Revision is a large monotonic number (~ms epoch), not a small counter.** `updateProjectShapes`
uses `Math.max(Date.now(), prev+1)` (page.tsx:444) and `saveProjectShapes` refuses older
revisions (page.tsx:104). So a bridge-supplied scene must use a revision that exceeds the
current one (e.g. `Date.now()`-based) or it will be silently dropped. Phase 1's optional
`revision?` field and Phase 2's "bump revision to avoid re-applying" must respect this.
## Open questions for review
- Phase 2 reuse strategy: drive the existing `onProjectShapesChange` callback (preferred) vs.
extracting the private helpers into a shared module — which do you want?
- For a brand-new projectId pushed by the MCP that has no localStorage entry yet: should the
bridge create the metadata entry (via `newProject`-style helper) as part of hydration, or only
push into already-existing projects? (The editor won't activate an unknown `project` param.)
- Confirm the `revision` source of truth for bridge pushes: server-assigned `Date.now()` vs.
MCP-supplied monotonic value.