# Code Generation Plan - Unit 1: Start migration and script step Feature: prerendering. Unit: 1 "start-migration". This plan is the single source of truth for Code Generation (Part 2). Execute the steps in order, mark each checkbox `[x]` as soon as its "Done when" is met, and do not deviate from the plan. ## 0. Context an executor needs ### 0.1 What is built React 19 + Vite + TanStack Router + Chakra UI v3 SPA in `web/` moves to TanStack Start static prerendering. Every page is written as an HTML file; a post-build step moves Start's inline scripts into files so the strict CSP (`script-src 'self'` + Umami) stays unchanged. Unit 1 covers: FR-PR-01 to 08, 19, 20, 22; the catch-all route part of FR-PR-14 and 15; NFR-PR-P-03, P-04, S-02, SEC-01 to 04, Q-01 to 05. Out of scope (do not build, do not "prepare"): `Reveal` behaviour (the only allowed `Reveal` change is the temporary, never committed one in Step 34), `DeferredImage` no-JavaScript image, `NoScriptNav`, photo preload, nginx/IIS/`serverConfig.ts`/`deploy/`, Lighthouse targets in `lighthouserc*.cjs` (Step 24 may change only `notFoundPath`), upload order in the CI deploy jobs. There are no user stories; the unit is traced to requirements. Dependencies on other units: none. Unit 2 and 3 depend on this unit (what it must leave: business-rules.md § 3). ### 0.2 Files to read (design, all under `aidlc-docs/features/prerendering/`) 1. `construction/start-migration/functional-design/business-rules.md` (rules BR-xxx, § 3 end state, § 4 verification points V1 to V18). Rule ids in this plan refer to it. 2. `construction/start-migration/functional-design/business-logic-model.md` (algorithms, properties P1 to P17). 3. `construction/start-migration/functional-design/domain-entities.md` (entities, hydration inventory). 4. `construction/start-migration/functional-design/frontend-components.md` (per-component contract, test list). 5. `inception/application-design/` (decisions D1 to D13, spike evidence), `inception/requirements/requirements.md`. Read 1 to 4 completely before the first step of your batch. ### 0.3 Locations and commands - Worktree (work only here): `K:\Development\SlpSoftware\Projects\AndreaSlopFotografie-prerendering`. Application code under `web/`, CI under `.gitea/workflows/`, documentation under `aidlc-docs/`. Never put application code in `aidlc-docs/`. - Run commands from `web/`. Package manager: pnpm (version from `packageManager`). Scripts: `pnpm lint`, `pnpm format:check` (fix with `pnpm exec prettier --write `), `pnpm test` (vitest with coverage and thresholds), `pnpm build`, `pnpm audit:deps`. - Targeted tests while working: `pnpm exec vitest run ` (no coverage). Full suite only at checkpoints. - Shell is Git Bash on Windows (also PowerShell). Use forward slashes in bash. Use plain `rm`/`cp`, never `git rm`/`git mv`. - Verification outcomes V1 to V18 are recorded in ONE file: `aidlc-docs/features/prerendering/construction/start-migration/code/verification-log.md` (created in Step 4: a table with columns V#, Point, Step, Outcome, Evidence, Status OK/BLOCKED/DEVIATION). Update the row in the step that settles it. - Reports and summaries are markdown only, in `aidlc-docs/features/prerendering/construction/start-migration/code/`. ### 0.4 Rules for every executor 1. **No git write commands** (`add`, `commit`, `push`, `stash`, `reset`, `checkout --`, `rm`, `mv`, branch operations). `git status`, `git diff`, `git log`, `git rev-parse` are allowed. The main session commits, only when the owner approved. Never edit `aidlc-docs/features/prerendering/audit.md` or `aidlc-state.md`; the main session does. 2. **Do not install anything except in Steps 1 and 4** (`pnpm install`, `pnpm add`). Do not edit `pnpm-lock.yaml` by hand. 3. **STOP rule.** If an unknown (V point) fails, a design rule cannot be implemented as written, a step's "Done when" cannot be reached, or a fix would change a design decision (any BR rule, any decision D1 to D13): stop at once. Write the finding in the verification log (Status BLOCKED or DEVIATION, with the exact error output and what you tried), leave the tree in a state where `pnpm exec tsc --noEmit` still runs (revert only your own unfinished edits of that step), do not continue with later steps, and return a report to the main session naming the step, the V point or rule, the evidence and the options you see. Never improvise around a design decision, never weaken a check, never delete or skip a test to get green. 4. **Match the surrounding code.** Open the neighbouring files first and copy their idiom: 4-space indentation, single quotes, trailing commas (Prettier config in `web/.prettierrc`), `@/` alias in `src/` but relative imports with explicit `.ts` extension in `config/` (config files run under Node type stripping: no path aliases, no enums, no parameter properties, `import type` for types, `erasableSyntaxOnly`). Comments explain why, not what; density like the neighbours. Language of new comments, test titles and messages follows the neighbouring files: `config/*` and `src/lib` tests and the pages' older code are partly Dutch; hooks, `lib` implementations and newer components are English. When a file has Dutch comments, write Dutch; when its neighbours are English, write English. 5. **Existing tests stay valid.** Change an existing test only where BR-TST-02 says behaviour changed, and say so in the step's record. 6. **Automation-friendly code.** Every new interactive element gets a stable `data-testid` named `{component}-{role}` like the existing ones (`footer-email-link`, `contact-gate-mail`). Placeholders are not interactive but get a testid as listed in the steps. 7. **Coverage.** Thresholds are 100% for `src/lib/**`, `src/seo.ts`, `src/sitemap.ts`; every new or changed function and branch in `src/lib` needs tests in the same batch. 8. **Property-based tests** (fast-check, already a dependency): use the global seed from `config/testSeed.ts` (never set a `seed` yourself, never disable shrinking), put domain generators in shared files under `src/test/` (reuse `src/test/arbitraries.ts`: `validEmail`, `anyEmail`, `routePath`, `pathSegment`, `knownRoutePath` and others; new generators go in the new files named in the steps, not in `arbitraries.ts`), label each property test with its category in the title like the existing ones (`(round-trip)`, `(invariant)`, `(idempotent)`, `(oracle)`), and keep an example-based test next to it. 9. **Concurrent batches** (see § 2): while batches run in parallel, run only targeted `vitest run `, never `pnpm build`, `pnpm test`, `pnpm install` or `pnpm add`, and only touch the files your batch owns. 10. Mark the step `[x]` in this file when done and add one line under "Record" if the step asks for it. Keep the tree compiling after each step. ## 1. Checkpoints | CP | After | State required | |---|---|---| | CP0 | Step 3 | `pnpm test` green (the unchanged old tests), `pnpm exec tsc --noEmit` clean | | CP1 | Step 5 | `pnpm build` green with Start (prerender writes all pages and `404.html`), `pnpm test` green | | CP2 | Steps 13, 15 to 23 all done (merge point after the parallel batches) | `pnpm test` green with coverage thresholds, `pnpm lint`, `pnpm exec tsc --noEmit`, `pnpm build` green (without the runner in `build` yet) | | CP3 | Step 24 | `pnpm build` green including the runner; the runner reports no violation on the real output | | CP4 | Step 28 | `pnpm lint`, `pnpm format:check`, `pnpm test`, `pnpm build`, `pnpm e2e`, `pnpm audit:deps` all green | | CP5 | Step 31 | Step 13.5 complete verification green | ## 2. Batches, executors and parallelism One sub-agent takes one batch. Haiku (H) does mechanical work, running checks, measurements and log keeping; Sonnet (S) does code, tests and documents that need judgement. The executor per step is repeated in the step. | Batch | Steps | Executor | Parallel with | Files owned (disjoint from the parallel batches) | |---|---|---|---|---| | B0 Setup and baseline | 1, 2 | H | none (exclusive: port 4173 and CPU) | none in the repo | | B1 Early proof | 3 to 6 | S | none (sequential; risky unknowns first) | `vite.config.ts`, `package.json`, `config/sitemapPlugin.ts`, `src/router.tsx`, `src/client.tsx`, `src/routes/__root.tsx`, `src/routes/$.tsx`, `src/test/renderApp.tsx`, the hooks of Step 3, `UmamiAnalytics`, `NavigationBar` (ssr only), `ContactSection`, `TestimonialCarousel` | | B2 Script step | 7 to 13 | S | B3, B4 | `config/pageFiles*`, `config/inlineScripts*`, `config/externalizeInlineScripts*`, `src/test/htmlArbitraries.ts` | | B3 Hydration safety | 14 to 21 | S | B2, B4 | `src/**` except the B1 files and `src/test/htmlArbitraries.ts` and `src/test/requestArbitraries.ts` | | B4 Preview server | 22, 23 | S | B2, B3 | `config/previewServer*`, `src/test/requestArbitraries.ts` | | B5 Integration | 24 to 28 | H for 24 and 28, S for 25 to 27 | none (after CP2) | `package.json`, `tsconfig.json`, `eslint.config.js`, `.gitignore`, `vitest.e2e.config.ts`, `vite.config.ts` (test exclude only), `e2e/**`, `.gitea/workflows/continuous_integration.yaml` | | B6 Finish | 29 to 34 | H for 30, 31, 34 runs; S for 29, 32, 33, 34 report | none (34 is exclusive: port 4173 and CPU) | `aidlc-docs/**`, comments | B3 starts with Step 14 (needs nothing from B2 or B4) and may run its sub-steps sequentially. B2, B3 and B4 may run at the same time because their files are disjoint. If you run them one after another, the order B2, B4, B3 is fine. Step 24 and all of B5 wait for CP2. ## 3. Traceability ### 3.1 Properties (PBT-01) to steps | Property | Function | Test step | |---|---|---| | P1 to P8 | `externalizeInlineScripts`, `findExecutableInlineScripts` | 9 | | P9 | `externalizeInlineScripts` (split and join) | 9 | | P10 | `pageFile` and `pagePath` | 10 | | P11, P12 | `planExternalization` | 12 | | P13 | address scan helper | 12 | | P14, P15 | `contactChannels`, `isEmailAddressValid` | 15 | | P16, P17 | `resolveRequest` | 23 | PBT-02 (round-trip): P3, P10. PBT-03 (invariant): P1, P2, P5, P6, P8, P14, P16. PBT-04 (idempotence): P4, P11. PBT-05 (oracle): P7, P12, P13, P15, P17. PBT-06 (stateful): N/A, no stateful logic in this unit. PBT-07 (generators): domain generators in `src/test/htmlArbitraries.ts` and `src/test/requestArbitraries.ts`, reuse of `arbitraries.ts`. PBT-08: global seed, shrinking left on. PBT-10: each property has example-based tests next to it. P9 is the split-and-join variant of PBT-03/05. ### 3.2 Verification points to steps | V | Settled in step | Recorded in | |---|---|---| | V1 client entry | 4 | verification log | | V2 `shellComponent` in jsdom | 5 | verification log | | V3 inline scripts per real page | 4 (first look), 13 (final list) | verification log | | V4 minimum moved scripts | 13 | verification log | | V5 `index.html`, crawling | 4 | verification log | | V6 code splitting, unused router plugin | 4, 30 | verification log | | V7 sitemap environment | 4 | verification log | | V8 lazy `ContactForm` in HTML and hydration | 27 | verification log | | V9 testimonials in HTML, hidden slides | 21, 27 | verification log | | V10 placeholder sizes, CLS below 0.01 | 17, 34 | verification log, measurement report | | V11 one title, one noindex meta | 4 (normal pages), 27 (`404.html`) | verification log | | V12 404 hydration with real shell | 27 | verification log | | V13 timestamps and build paths | 4, 13 | verification log | | V14 focus on first load, tidy navigation | 27 | verification log | | V15 Emotion/Chakra flicker | 4 (styles in HTML), 27 (screenshots) | verification log | | V16 `Intl` price text | 27 | verification log | | V17 no `on*=` or `javascript:` | 13, 27 | verification log | | V18 CI artifact layout | 28 | verification log | ### 3.3 Requirements to steps | Requirement | Steps | |---|---| | FR-PR-01 to 04 | 4, 7, 11, 13, 24, 27 | | FR-PR-05 to 07 | 3, 16, 17, 18, 19 to 21, 27 | | FR-PR-08 | 3, 4, 27 | | FR-PR-19, 20 | 8, 9, 11, 12, 13, 24 | | FR-PR-22 | 14, 15, 17, 21, 11, 27 | | FR-PR-14, 15 (route part) | 4, 16, 20, 27 | | NFR-PR-P-03, P-04 | 2, 34 | | NFR-PR-S-02 | 27 | | NFR-PR-SEC-01 to 04 | 4, 11, 22, 27, 30 | | NFR-PR-Q-01 to 05 | 1, 5, 9 to 12, 15, 19 to 21, 23, 25 to 28, 29, 31 to 33 | --- ## Part A: Setup and baseline (batch B0, Haiku, exclusive) ### Step 1: Install and confirm a green baseline [x] - Executor: Haiku. - Implements: NFR-PR-Q-01 (baseline), setup. - Do: 1. In `web/`: `pnpm install --frozen-lockfile` (the worktree has no `node_modules`; `postinstall` runs `chakra typegen`). 2. Run `pnpm lint`, `pnpm format:check`, `pnpm test`, `pnpm build`, in that order. Note the number of test files and tests passed and the fast-check seed line. 3. Run `git rev-parse HEAD` and `git status --short`. - Done when: all four commands succeed on the untouched tree. If any fails, STOP (the baseline must be green before changes) and report the output. - Record: create `aidlc-docs/features/prerendering/construction/start-migration/code/baseline-checks.md` with the commit hash, the date, Node and pnpm versions, test counts, seed, and the `git status` output (the main session needs the pre-change status, including the untracked `web/.tanstack/`). ### Step 2: Baseline measurement (BR-MEA-01) [x] - Record (2026-10-31): `code/measurement-baseline.md`; the summary script is in the scratch folder `summarize-lhr.mjs` (path in the report). Mobile and desktop both ran with no page errors (about 16 min for both). - Executor: Haiku. Exclusive: nothing else may run during this step. - Implements: BR-MEA-01; NFR-PR-P-03. - Preconditions: Step 1 done; `web/dist` is the master build from Step 1. **Port 4173 must be free** (`Get-NetTCPConnection -LocalPort 4173` in PowerShell must return nothing) because Lighthouse CI starts `pnpm preview --port 4173 --strictPort` itself. **No CPU-heavy work may run during the measurement**: no other build, test run, install, editor indexing job or other sub-agent. If the machine is busy, wait. Use the same machine, power plan and Node version for Step 34. - Do (all in `web/`; use a scratch folder outside the repository, for example `$env:TEMP\prerendering-measure`, for raw results and the helper script; neither is committed): 1. Delete `.lighthouseci` and `lighthouse-reports` if present. 2. Mobile: `pnpm exec lhci collect --config=lighthouserc.cjs --numberOfRuns=3`. Move `.lighthouseci` to `/baseline/mobile`. 3. Desktop: `pnpm exec lhci collect --config=lighthouserc.desktop.cjs --numberOfRuns=3`. Move `.lighthouseci` to `/baseline/desktop`. (`collect` does not assert, so existing targets do not matter. The URL list includes `/bestaat-niet`, which master answers with 200 through the SPA fallback; keep it.) 4. Write a small Node script in the scratch folder that reads every `lhr-*.json` of a folder and prints, per URL, the median over the three runs of: `categories.performance.score`, FCP, LCP, TBT (`audits.*.numericValue`), CLS, and the sum of `transferSize` of the `network-requests` items with `resourceType` `Script`. It takes the folder as an argument. 5. Compute gzip sizes with Node `zlib.gzipSync` of: every file referenced by `` (BR-SCR-06). Parse attributes with quote awareness; compare tag and attribute names case-insensitively. A header comment explains why this step exists (NFR-PR-Q-05, BR-BLD-12): the strict `script-src 'self'` blocks Start's inline scripts. - Done when: `pnpm exec tsc --noEmit` clean; a quick manual call on the worked-example table of business-logic-model.md § 3.1 gives the listed outputs (the real tests come in Step 9). ### Step 9: Tests for `inlineScripts` (P1 to P9) [x] - Executor: Sonnet. - Implements: NFR-PR-Q-02; PBT-02 to 05, 07, 08, 10; P1 to P9. - Files: `web/src/test/htmlArbitraries.ts` (create), `web/config/inlineScripts.test.ts` (create). - Do: 1. `htmlArbitraries.ts`: generators for HTML pieces with a model of what each is: executable inline scripts (classic and module, varied attributes, bodies without `` inside a quoted attribute, uppercase tag names, duplicate bodies. Property tests with titles carrying the category: P1 (invariant), P2 (invariant), P3 (round-trip), P4 (idempotent), P5 (invariant), P6 (invariant), P7 (oracle, `findExecutableInlineScripts` against the model), P8 (invariant), P9 (split and join). - Done when: `pnpm exec vitest run config/inlineScripts.test.ts` passes; the shrunk counterexample and seed would be printed on failure (do not catch or disable). ### Step 10: Tests for `pageFiles` (P10) [x] - Executor: Sonnet. - Implements: PBT-02, 10; P10. - Files: `web/config/pageFiles.test.ts` (create). - Do: examples for `/`, `/over-mij`, `/soorten-fotoshoots/newborn`, `404.html`, a non-page file; property (round-trip): `pagePath(pageFile(p)) === p` for every key of `sitePages` and for generated route-like paths (`routePath` from `arbitraries.ts`); invariant: the file never starts with `/` and ends with `.html`. - Done when: `pnpm exec vitest run config/pageFiles.test.ts` passes. ### Step 11: Runner `config/externalizeInlineScripts.ts` [x] - Executor: Sonnet. - Implements: BR-SCR-12 to 21, BR-MAIL-10, BR-SEC-02, 03, BR-BLD-04, 09 (check part); FR-PR-03, 19, 20, 22; NFR-PR-SEC-03, 04. - Do: create the module with - `planExternalization(files, context)` (pure; shapes in domain-entities.md: `files` is a map of relative path to content for all text files under the client directory; `context` has the expected pages, the address or `null`, the sitemap text, the root paths) returning `{ writes, violations }`. It applies `externalizeInlineScripts` to every `.html`, then all checks: NO_HTML, PAGE_MISSING, NOT_FOUND_PAGE_MISSING, UNEXPECTED_HTML, NO_SCRIPTS_MOVED (final HTML references at least one `/assets/inline-<12 hex>.js`, so running twice is not an error), EXECUTABLE_REMAINS, COLLISION (an existing `assets/inline-.js` with other content), UNSUPPORTED_SCRIPT, UNTERMINATED_SCRIPT, EMAIL_IN_OUTPUT (all listed encodings, case-insensitive, in every text file including moved bodies; export the pure scan helper `containsAddress(text, address)` for P13), SITEMAP_MISSING, SITEMAP_DIFFERS, SOURCE_MAP_PRESENT, BUILD_PATH_LEAK (both slash styles of the root path). Messages `: : `; never print script bodies or the address (BR-SCR-21). - `externalizeOutput(clientDir)` that reads the directory (`.html`, `.js`, `.css`, `.xml`, `.txt`, `.json`, `.webmanifest`, and detects `.map`), builds the context (`pageFile` of every `sitePages` key, `emailAddress(siteContent.email)`, `sitemapXml(pageList(sitePages), siteUrl)`, `path.resolve(clientDir, '../..')`), calls the plan, and on violations prints them all, sets exit code 1 and writes nothing; otherwise writes script files first, then the changed HTML, then prints one summary line (pages checked, scripts moved, files written). - A guard so that importing the module for tests does not run it, and the CLI entry runs it for `dist/client` (default) with an optional directory argument. Import `sitePages`, `siteContent`, `emailAddress`, `sitemapXml`, `seo` constants with relative `.ts` paths. A header comment explains why the step exists (BR-BLD-12). - Done when: `pnpm exec tsc --noEmit` clean; running `node config/externalizeInlineScripts.ts` on the Step 4 output prints violations (expected at this point: EMAIL_IN_OUTPUT until Step 17) and writes nothing. ### Step 12: Tests for the runner core (P11 to P13) [x] - Executor: Sonnet. - Implements: NFR-PR-Q-02; PBT-04, 05, 07, 08, 10; P11 to P13. - Files: `web/config/externalizeInlineScripts.test.ts` (create); generators for file maps may extend `src/test/htmlArbitraries.ts` (owned by B2). - Do: example-based test for each violation code and for the success path (including a second run being a no-op and a `404.html` present); use `anySiteContent`/`validEmail` from `arbitraries.ts` for addresses; a temp-directory test for `externalizeOutput` (writes script files first, writes nothing on violation, exit code via a returned or thrown result you can assert). Properties: P11 (idempotent: apply the plan's writes to the file map, plan again: no writes, no violations), P12 (oracle: violations equal a simple model), P13 (oracle for `containsAddress` with all encodings and random insertion; clean text never flagged). - Done when: `pnpm exec vitest run config/externalizeInlineScripts.test.ts` passes. ### Step 13: Run the script step on the real output (V3, V4, V13, V17) [x] - Executor: Sonnet. - Implements: FR-PR-19, 20; BR-SCR-17; V3, V4, V13, V17. - Preconditions: Steps 8 and 11 done. Because B3 and B4 may still be running, do not run `pnpm build` here; use the `dist/client` from Step 4 (or copy it to a scratch folder and run the runner on the copy: `node config/externalizeInlineScripts.ts `). - Do: run the runner on the copy. Expected violations: only EMAIL_IN_OUTPUT. Any other violation (for example UNSUPPORTED_SCRIPT because Start emits `async` or `