quiver-cli 0.8.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/README.md +110 -45
  2. package/bin/quiver-cli.mjs +3 -1
  3. package/dist/cli.js +546 -458
  4. package/package.json +2 -2
  5. package/template/.agents/AGENTS.md +4 -3
  6. package/template/.agents/config.json +7 -0
  7. package/template/.agents/plugins/opencode/rtk.ts +34 -0
  8. package/template/.agents/skills/agent-browser/SKILL.md +1 -0
  9. package/template/.agents/skills/apps/skybridge/SKILL.md +4 -0
  10. package/template/.agents/skills/design/impeccable/SKILL.md +36 -118
  11. package/template/.agents/skills/design/impeccable/reference/adapt.md +1 -0
  12. package/template/.agents/skills/design/impeccable/reference/adapt.native.md +58 -0
  13. package/template/.agents/skills/design/impeccable/reference/android.md +40 -0
  14. package/template/.agents/skills/design/impeccable/reference/animate.md +73 -188
  15. package/template/.agents/skills/design/impeccable/reference/audit.md +12 -9
  16. package/template/.agents/skills/design/impeccable/reference/audit.native.md +139 -0
  17. package/template/.agents/skills/design/impeccable/reference/bolder.md +19 -101
  18. package/template/.agents/skills/design/impeccable/reference/clarify.md +59 -253
  19. package/template/.agents/skills/design/impeccable/reference/colorize.md +51 -222
  20. package/template/.agents/skills/design/impeccable/reference/craft-floor.md +42 -0
  21. package/template/.agents/skills/design/impeccable/reference/craft.md +3 -121
  22. package/template/.agents/skills/design/impeccable/reference/critique.md +44 -23
  23. package/template/.agents/skills/design/impeccable/reference/degraded/asset-producer.md +90 -0
  24. package/template/.agents/skills/design/impeccable/reference/degraded/documenter.md +24 -0
  25. package/template/.agents/skills/design/impeccable/reference/degraded/finish-reviewer.md +37 -0
  26. package/template/.agents/skills/design/impeccable/reference/degraded/manual-edit-applier.md +92 -0
  27. package/template/.agents/skills/design/impeccable/reference/delight.md +47 -279
  28. package/template/.agents/skills/design/impeccable/reference/distill.md +2 -2
  29. package/template/.agents/skills/design/impeccable/reference/doctor.md +53 -0
  30. package/template/.agents/skills/design/impeccable/reference/document.md +60 -73
  31. package/template/.agents/skills/design/impeccable/reference/harden.md +1 -12
  32. package/template/.agents/skills/design/impeccable/reference/hooks.md +20 -5
  33. package/template/.agents/skills/design/impeccable/reference/init.md +72 -119
  34. package/template/.agents/skills/design/impeccable/reference/ios.md +45 -0
  35. package/template/.agents/skills/design/impeccable/reference/layout.md +54 -131
  36. package/template/.agents/skills/design/impeccable/reference/live-setup.md +102 -0
  37. package/template/.agents/skills/design/impeccable/reference/live.md +116 -511
  38. package/template/.agents/skills/design/impeccable/reference/new-work.md +105 -0
  39. package/template/.agents/skills/design/impeccable/reference/{product.md → operate.md} +6 -5
  40. package/template/.agents/skills/design/impeccable/reference/optimize.md +4 -4
  41. package/template/.agents/skills/design/impeccable/reference/overdrive.md +1 -4
  42. package/template/.agents/skills/design/impeccable/reference/polish.md +68 -212
  43. package/template/.agents/skills/design/impeccable/reference/quieter.md +3 -3
  44. package/template/.agents/skills/design/impeccable/reference/routing.md +18 -0
  45. package/template/.agents/skills/design/impeccable/reference/shape.md +38 -144
  46. package/template/.agents/skills/design/impeccable/reference/typeset.md +51 -250
  47. package/template/.agents/skills/design/impeccable/reference/visualize.md +47 -0
  48. package/template/.agents/skills/design/impeccable/scripts/command-metadata.json +1 -1
  49. package/template/.agents/skills/design/impeccable/scripts/concept-seed.mjs +558 -0
  50. package/template/.agents/skills/design/impeccable/scripts/context-signals.mjs +119 -10
  51. package/template/.agents/skills/design/impeccable/scripts/context.mjs +534 -45
  52. package/template/.agents/skills/design/impeccable/scripts/critique-storage.mjs +18 -47
  53. package/template/.agents/skills/design/impeccable/scripts/detector/browser/injected/index.mjs +96 -10
  54. package/template/.agents/skills/design/impeccable/scripts/detector/cli/main.mjs +174 -26
  55. package/template/.agents/skills/design/impeccable/scripts/detector/design-system.mjs +233 -0
  56. package/template/.agents/skills/design/impeccable/scripts/detector/detect-antipatterns-browser.js +3348 -203
  57. package/template/.agents/skills/design/impeccable/scripts/detector/engines/browser/detect-url.mjs +102 -7
  58. package/template/.agents/skills/design/impeccable/scripts/detector/engines/regex/detect-text.mjs +297 -97
  59. package/template/.agents/skills/design/impeccable/scripts/detector/engines/static-html/css-cascade.mjs +187 -16
  60. package/template/.agents/skills/design/impeccable/scripts/detector/engines/static-html/detect-html.mjs +41 -11
  61. package/template/.agents/skills/design/impeccable/scripts/detector/findings.mjs +7 -1
  62. package/template/.agents/skills/design/impeccable/scripts/detector/node/file-system.mjs +16 -2
  63. package/template/.agents/skills/design/impeccable/scripts/detector/registry/antipatterns.mjs +207 -38
  64. package/template/.agents/skills/design/impeccable/scripts/detector/rules/checks.mjs +3082 -173
  65. package/template/.agents/skills/design/impeccable/scripts/detector/shared/constants.mjs +11 -0
  66. package/template/.agents/skills/design/impeccable/scripts/detector/shared/fonts.mjs +30 -0
  67. package/template/.agents/skills/design/impeccable/scripts/doctor.mjs +336 -0
  68. package/template/.agents/skills/design/impeccable/scripts/embed-prompt.mjs +133 -0
  69. package/template/.agents/skills/design/impeccable/scripts/generate-image.mjs +240 -0
  70. package/template/.agents/skills/design/impeccable/scripts/hook-admin.mjs +98 -18
  71. package/template/.agents/skills/design/impeccable/scripts/hook-before-edit.mjs +46 -6
  72. package/template/.agents/skills/design/impeccable/scripts/hook-lib.mjs +518 -50
  73. package/template/.agents/skills/design/impeccable/scripts/hook.mjs +25 -8
  74. package/template/.agents/skills/design/impeccable/scripts/lib/artifact-schema.mjs +93 -0
  75. package/template/.agents/skills/design/impeccable/scripts/lib/composition-catalog.mjs +200 -0
  76. package/template/.agents/skills/design/impeccable/scripts/lib/concept-catalog.mjs +357 -0
  77. package/template/.agents/skills/design/impeccable/scripts/lib/impeccable-config.mjs +27 -7
  78. package/template/.agents/skills/design/impeccable/scripts/lib/impeccable-paths.mjs +17 -8
  79. package/template/.agents/skills/design/impeccable/scripts/lib/provider.mjs +5 -0
  80. package/template/.agents/skills/design/impeccable/scripts/lib/roll-selection.mjs +362 -0
  81. package/template/.agents/skills/design/impeccable/scripts/lib/staleness-deep.mjs +457 -0
  82. package/template/.agents/skills/design/impeccable/scripts/lib/staleness-notice.mjs +169 -0
  83. package/template/.agents/skills/design/impeccable/scripts/lib/staleness.mjs +457 -0
  84. package/template/.agents/skills/design/impeccable/scripts/lib/surface-briefs.mjs +151 -0
  85. package/template/.agents/skills/design/impeccable/scripts/lib/target-slug.mjs +33 -0
  86. package/template/.agents/skills/design/impeccable/scripts/lib/template-extensions.mjs +146 -0
  87. package/template/.agents/skills/design/impeccable/scripts/live/accept-css.mjs +617 -0
  88. package/template/.agents/skills/design/impeccable/scripts/live/accept-verify.mjs +60 -0
  89. package/template/.agents/skills/design/impeccable/scripts/live/browser-script-parts.mjs +7 -1
  90. package/template/.agents/skills/design/impeccable/scripts/live/completion.mjs +10 -1
  91. package/template/.agents/skills/design/impeccable/scripts/live/event-validation.mjs +67 -5
  92. package/template/.agents/skills/design/impeccable/scripts/live/frameworks/astro.mjs +47 -0
  93. package/template/.agents/skills/design/impeccable/scripts/live/frameworks/detect-utils.mjs +73 -0
  94. package/template/.agents/skills/design/impeccable/scripts/live/frameworks/index.mjs +143 -0
  95. package/template/.agents/skills/design/impeccable/scripts/live/frameworks/journal.mjs +197 -0
  96. package/template/.agents/skills/design/impeccable/scripts/live/frameworks/nextjs.mjs +49 -0
  97. package/template/.agents/skills/design/impeccable/scripts/live/frameworks/nuxt.mjs +161 -0
  98. package/template/.agents/skills/design/impeccable/scripts/live/frameworks/script-src.mjs +17 -0
  99. package/template/.agents/skills/design/impeccable/scripts/live/frameworks/static-html.mjs +26 -0
  100. package/template/.agents/skills/design/impeccable/scripts/live/frameworks/sveltekit.mjs +71 -0
  101. package/template/.agents/skills/design/impeccable/scripts/live/frameworks/tag-strategy.mjs +247 -0
  102. package/template/.agents/skills/design/impeccable/scripts/live/frameworks/tanstack-start.mjs +70 -0
  103. package/template/.agents/skills/design/impeccable/scripts/live/frameworks/vite-generic.mjs +42 -0
  104. package/template/.agents/skills/design/impeccable/scripts/live/generation-preflight.mjs +149 -0
  105. package/template/.agents/skills/design/impeccable/scripts/live/instructions.mjs +142 -0
  106. package/template/.agents/skills/design/impeccable/scripts/live/poll-lanes.mjs +14 -0
  107. package/template/.agents/skills/design/impeccable/scripts/live/roots.mjs +508 -0
  108. package/template/.agents/skills/design/impeccable/scripts/live/session-store.mjs +324 -50
  109. package/template/.agents/skills/design/impeccable/scripts/live/source-lock.mjs +105 -0
  110. package/template/.agents/skills/design/impeccable/scripts/live/source-search.mjs +105 -0
  111. package/template/.agents/skills/design/impeccable/scripts/live/svelte-ast.mjs +961 -0
  112. package/template/.agents/skills/design/impeccable/scripts/live/svelte-component.mjs +588 -72
  113. package/template/.agents/skills/design/impeccable/scripts/live/sveltekit-adapter.mjs +59 -17
  114. package/template/.agents/skills/design/impeccable/scripts/live/tanstack-adapter.mjs +280 -0
  115. package/template/.agents/skills/design/impeccable/scripts/live/vocabulary.mjs +135 -0
  116. package/template/.agents/skills/design/impeccable/scripts/live-accept.mjs +210 -68
  117. package/template/.agents/skills/design/impeccable/scripts/live-browser.js +1562 -223
  118. package/template/.agents/skills/design/impeccable/scripts/live-commit-manual-edits.mjs +3 -0
  119. package/template/.agents/skills/design/impeccable/scripts/live-complete.mjs +33 -1
  120. package/template/.agents/skills/design/impeccable/scripts/live-inject.mjs +175 -255
  121. package/template/.agents/skills/design/impeccable/scripts/live-insert.mjs +26 -6
  122. package/template/.agents/skills/design/impeccable/scripts/live-manual-edit-evidence.mjs +6 -1
  123. package/template/.agents/skills/design/impeccable/scripts/live-poll.mjs +61 -16
  124. package/template/.agents/skills/design/impeccable/scripts/live-resume.mjs +39 -10
  125. package/template/.agents/skills/design/impeccable/scripts/live-server.mjs +573 -47
  126. package/template/.agents/skills/design/impeccable/scripts/live-status.mjs +17 -7
  127. package/template/.agents/skills/design/impeccable/scripts/live-wrap.mjs +124 -91
  128. package/template/.agents/skills/design/impeccable/scripts/live.mjs +88 -26
  129. package/template/.agents/skills/design/impeccable/scripts/palette.mjs +76 -81
  130. package/template/.agents/skills/design/impeccable/scripts/pin.mjs +18 -11
  131. package/template/.agents/skills/design/impeccable/scripts/serve-question.mjs +932 -0
  132. package/template/.agents/skills/design/impeccable/scripts/surface-brief.mjs +74 -0
  133. package/template/.agents/skills/design/shadcn/SKILL.md +46 -11
  134. package/template/.agents/skills/design/shadcn/cli.md +49 -16
  135. package/template/.agents/skills/design/shadcn/customization.md +14 -7
  136. package/template/.agents/skills/design/shadcn/evals/evals.json +30 -0
  137. package/template/.agents/skills/design/shadcn/mcp.md +27 -16
  138. package/template/.agents/skills/design/shadcn/registry.md +277 -0
  139. package/template/.agents/skills/design/shadcn/rules/chat.md +224 -0
  140. package/template/.agents/skills/design/shadcn/rules/composition.md +20 -2
  141. package/template/.agents/skills/design/shadcn/rules/styling.md +23 -0
  142. package/template/.agents/skills/find-skills/SKILL.md +2 -3
  143. package/template/.agents/skills/hono/SKILL.md +579 -0
  144. package/template/.agents/skills/integrations/langfuse/SKILL.md +10 -6
  145. package/template/.agents/skills/integrations/langfuse/references/ci-cd.md +41 -0
  146. package/template/.agents/skills/integrations/langfuse/references/cli.md +8 -0
  147. package/template/.agents/skills/integrations/langfuse/references/error-analysis.md +15 -27
  148. package/template/.agents/skills/integrations/langfuse/references/instrumentation.md +39 -52
  149. package/template/.agents/skills/integrations/langfuse/references/judge-calibration.md +5 -2
  150. package/template/.agents/skills/integrations/langfuse/references/prompt-engineering.md +35 -0
  151. package/template/.agents/skills/integrations/langfuse/references/prompt-migration.md +41 -196
  152. package/template/.agents/skills/integrations/langfuse/references/skill-feedback.md +3 -0
  153. package/template/.agents/skills/integrations/langfuse/references/trace-evaluator-upgrade.md +76 -0
  154. package/template/.agents/skills/integrations/langfuse/references/user-feedback.md +4 -0
  155. package/template/.agents/skills/integrations/langfuse/references/v4-project-migration.md +73 -0
  156. package/template/.agents/skills/supabase/CHANGELOG.md +71 -0
  157. package/template/.agents/skills/supabase/SKILL.md +145 -0
  158. package/template/.agents/skills/supabase/assets/feedback-issue-template.md +17 -0
  159. package/template/.agents/skills/supabase/references/skill-feedback.md +17 -0
  160. package/template/.agents/skills/supabase-postgres-best-practices/CHANGELOG.md +73 -0
  161. package/template/.agents/skills/supabase-postgres-best-practices/SKILL.md +64 -0
  162. package/template/.agents/skills/supabase-postgres-best-practices/references/_contributing.md +170 -0
  163. package/template/.agents/skills/supabase-postgres-best-practices/references/_sections.md +39 -0
  164. package/template/.agents/skills/supabase-postgres-best-practices/references/_template.md +34 -0
  165. package/template/.agents/skills/supabase-postgres-best-practices/references/advanced-full-text-search.md +55 -0
  166. package/template/.agents/skills/supabase-postgres-best-practices/references/advanced-jsonb-indexing.md +49 -0
  167. package/template/.agents/skills/supabase-postgres-best-practices/references/conn-idle-timeout.md +46 -0
  168. package/template/.agents/skills/supabase-postgres-best-practices/references/conn-limits.md +44 -0
  169. package/template/.agents/skills/supabase-postgres-best-practices/references/conn-pooling.md +41 -0
  170. package/template/.agents/skills/supabase-postgres-best-practices/references/conn-prepared-statements.md +46 -0
  171. package/template/.agents/skills/supabase-postgres-best-practices/references/data-batch-inserts.md +54 -0
  172. package/template/.agents/skills/supabase-postgres-best-practices/references/data-n-plus-one.md +53 -0
  173. package/template/.agents/skills/supabase-postgres-best-practices/references/data-pagination.md +50 -0
  174. package/template/.agents/skills/supabase-postgres-best-practices/references/data-upsert.md +50 -0
  175. package/template/.agents/skills/supabase-postgres-best-practices/references/lock-advisory.md +56 -0
  176. package/template/.agents/skills/supabase-postgres-best-practices/references/lock-deadlock-prevention.md +68 -0
  177. package/template/.agents/skills/supabase-postgres-best-practices/references/lock-short-transactions.md +50 -0
  178. package/template/.agents/skills/supabase-postgres-best-practices/references/lock-skip-locked.md +54 -0
  179. package/template/.agents/skills/supabase-postgres-best-practices/references/monitor-explain-analyze.md +45 -0
  180. package/template/.agents/skills/supabase-postgres-best-practices/references/monitor-pg-stat-statements.md +55 -0
  181. package/template/.agents/skills/supabase-postgres-best-practices/references/monitor-vacuum-analyze.md +55 -0
  182. package/template/.agents/skills/supabase-postgres-best-practices/references/query-composite-indexes.md +44 -0
  183. package/template/.agents/skills/supabase-postgres-best-practices/references/query-covering-indexes.md +40 -0
  184. package/template/.agents/skills/supabase-postgres-best-practices/references/query-index-types.md +48 -0
  185. package/template/.agents/skills/supabase-postgres-best-practices/references/query-missing-indexes.md +43 -0
  186. package/template/.agents/skills/supabase-postgres-best-practices/references/query-partial-indexes.md +45 -0
  187. package/template/.agents/skills/supabase-postgres-best-practices/references/schema-constraints.md +80 -0
  188. package/template/.agents/skills/supabase-postgres-best-practices/references/schema-data-types.md +46 -0
  189. package/template/.agents/skills/supabase-postgres-best-practices/references/schema-foreign-key-indexes.md +59 -0
  190. package/template/.agents/skills/supabase-postgres-best-practices/references/schema-lowercase-identifiers.md +55 -0
  191. package/template/.agents/skills/supabase-postgres-best-practices/references/schema-partitioning.md +55 -0
  192. package/template/.agents/skills/supabase-postgres-best-practices/references/schema-primary-keys.md +61 -0
  193. package/template/.agents/skills/supabase-postgres-best-practices/references/security-privileges.md +54 -0
  194. package/template/.agents/skills/supabase-postgres-best-practices/references/security-rls-basics.md +50 -0
  195. package/template/.agents/skills/supabase-postgres-best-practices/references/security-rls-performance.md +63 -0
  196. package/template/.agents/upstreams.json +34 -12
  197. package/template/.agents/skills/design/impeccable/reference/brand.md +0 -108
  198. package/template/.agents/skills/design/impeccable/reference/codex.md +0 -105
  199. package/template/.agents/skills/design/impeccable/reference/interaction-design.md +0 -189
  200. package/template/.agents/skills/integrations/langfuse/references/sdk-upgrade.md +0 -175
@@ -10,9 +10,38 @@ import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import os from 'node:os';
12
12
  import { createHash } from 'node:crypto';
13
-
13
+ import {
14
+ analyzeSvelteMarkup,
15
+ buildPropsScriptV2,
16
+ loadSvelteCompiler,
17
+ restoreSvelteMarkup,
18
+ } from './svelte-ast.mjs';
19
+ import {
20
+ bakeParamValues,
21
+ collectAllSelectors,
22
+ collectUnusedSelectors,
23
+ normalizeSelector,
24
+ parseStylesheet,
25
+ pruneUnusedSelectors,
26
+ reconcileCss,
27
+ serializeNodes,
28
+ splitSelectorList,
29
+ } from './accept-css.mjs';
30
+ import { verifyAcceptedSource } from './accept-verify.mjs';
31
+
32
+ // Preview modules stay under node_modules on purpose: SvelteKit restricts
33
+ // vite's server.fs.allow to src/lib, src/routes, .svelte-kit, and
34
+ // node_modules, so an .impeccable/ tree under the app root 403s (verified
35
+ // against a real SvelteKit dev server). Staleness from node_modules being
36
+ // unwatched is solved by REVISIONED module paths instead: every publish
37
+ // snapshots the variant files into a fresh r<N>/ directory and the browser
38
+ // imports from there, so a republished fix can never be pinned by a
39
+ // transform cache keyed on the old path.
14
40
  export const SVELTE_COMPONENT_ROOT = 'node_modules/.impeccable-live';
41
+ // A short-lived interim location; swept so no project keeps a stray tree.
42
+ export const LEGACY_SVELTE_COMPONENT_ROOT = '.impeccable/live/previews';
15
43
  export const SVELTE_RUNTIME_FILE = `${SVELTE_COMPONENT_ROOT}/__runtime.js`;
44
+ export const SVELTE_PROBE_FILE = `${SVELTE_COMPONENT_ROOT}/__probe.js`;
16
45
  export const DEFERRED_ACCEPTS_FILE = '.impeccable/live/deferred-svelte-component-accepts.json';
17
46
 
18
47
  const MUSTACHE_RE = /\{([^{}]+)\}/g;
@@ -32,9 +61,18 @@ export function manifestPathForSession(id, cwd = process.cwd()) {
32
61
 
33
62
  export function ensureRuntimeHelper(cwd = process.cwd()) {
34
63
  const file = path.join(cwd, SVELTE_RUNTIME_FILE);
35
- if (fs.existsSync(file)) return file;
36
64
  fs.mkdirSync(path.dirname(file), { recursive: true });
37
- fs.writeFileSync(file, `export { mount, unmount } from 'svelte';\n`, 'utf-8');
65
+ if (!fs.existsSync(file)) {
66
+ fs.writeFileSync(file, `export { mount, unmount } from 'svelte';\n`, 'utf-8');
67
+ }
68
+ // Attach-time probe: the browser imports this through the dev server before
69
+ // the first mount. A 404 here means the resolved app root and the dev
70
+ // server's root disagree, and the session fails with a named error instead
71
+ // of a silent fall-back to the picker at first variant.
72
+ const probe = path.join(cwd, SVELTE_PROBE_FILE);
73
+ if (!fs.existsSync(probe)) {
74
+ fs.writeFileSync(probe, `export const impeccableLivePreviewProbe = true;\n`, 'utf-8');
75
+ }
38
76
  return file;
39
77
  }
40
78
 
@@ -136,6 +174,14 @@ function buildInsertVariantStub(variantNum) {
136
174
  return `${buildPropsScript([])}<div class="impeccable-insert-preview">Insert variant ${variantNum}</div>\n\n<style>\n .impeccable-insert-preview { display: block; }\n</style>\n`;
137
175
  }
138
176
 
177
+ /**
178
+ * Scaffold a component-preview session. The scaffold is AST-based: the app's
179
+ * own svelte compiler parses the selected markup, control-flow blocks are
180
+ * preserved (an each collection crosses the prop contract as ONE structured
181
+ * prop, its loop body verbatim), and constructs a detached preview cannot
182
+ * support return `{ fallback: 'source-preview', reason }` so the caller keeps
183
+ * the markup inside the route file instead of shipping a wrong preview.
184
+ */
139
185
  export function scaffoldSvelteComponentSession({
140
186
  id,
141
187
  count,
@@ -145,25 +191,55 @@ export function scaffoldSvelteComponentSession({
145
191
  originalLines,
146
192
  cwd = process.cwd(),
147
193
  }) {
194
+ const originalMarkup = originalLines.join('\n');
195
+
196
+ const compiler = loadSvelteCompiler(cwd);
197
+ if (!compiler) {
198
+ return { fallback: 'source-preview', reason: 'svelte 5 compiler not resolvable from the app root' };
199
+ }
200
+ const analysis = analyzeSvelteMarkup(originalMarkup, compiler.parse);
201
+ if (!analysis.ok) {
202
+ return { fallback: 'source-preview', reason: analysis.reason };
203
+ }
204
+
148
205
  ensureRuntimeHelper(cwd);
149
206
  const dir = componentSessionDir(id, cwd);
150
207
  fs.mkdirSync(dir, { recursive: true });
151
208
 
152
- const originalMarkup = originalLines.join('\n');
153
- const contract = buildPropContract(extractMustacheExpressions(originalMarkup));
154
- const originalWithProps = substituteExprsWithProps(originalMarkup, contract);
209
+ const contract = analysis.contract;
210
+ const seeded = extractMatchingSourceCss(
211
+ safeReadSource(path.resolve(cwd, sourceFile)),
212
+ originalMarkup,
213
+ );
214
+ const seededCss = seeded.css;
215
+ // The preview compiles in isolation, so NONE of these source rules applied
216
+ // to what the user approved. Accept enforces that preview truth: any of
217
+ // them the variant does not re-declare is superseded and removed, instead
218
+ // of re-attaching to the accepted markup through kept class names (the
219
+ // ".decisions grid grabs the new board" failure). Only the CLASS-matched
220
+ // selectors are candidates; tag rules style shared route elements.
221
+ const seededSelectors = [...seeded.supersedable];
155
222
 
156
223
  const manifest = {
157
224
  id,
158
225
  previewMode: 'svelte-component',
226
+ contractVersion: 2,
159
227
  sourceFile: sourceFile.split(path.sep).join('/'),
160
228
  sourceStartLine,
161
229
  sourceEndLine,
162
230
  count,
163
231
  propContract: contract,
164
232
  originalMarkup,
233
+ seededSelectors,
165
234
  componentDir: path.relative(cwd, dir).split(path.sep).join('/'),
235
+ // Absolute paths let the browser fall back to /@fs/ imports when the dev
236
+ // server's base or root makes root-relative URLs miss, and probe whether
237
+ // the preview tree is reachable at all before blaming a variant.
238
+ componentDirAbs: dir.split(path.sep).join('/'),
166
239
  runtimeModule: `/${SVELTE_RUNTIME_FILE}`,
240
+ runtimeModuleAbs: path.join(cwd, SVELTE_RUNTIME_FILE).split(path.sep).join('/'),
241
+ probeModule: `/${SVELTE_PROBE_FILE}`,
242
+ probeModuleAbs: path.join(cwd, SVELTE_PROBE_FILE).split(path.sep).join('/'),
167
243
  };
168
244
 
169
245
  fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf-8');
@@ -171,7 +247,7 @@ export function scaffoldSvelteComponentSession({
171
247
  for (let n = 1; n <= count; n++) {
172
248
  const variantFile = path.join(dir, `v${n}.svelte`);
173
249
  if (!fs.existsSync(variantFile)) {
174
- fs.writeFileSync(variantFile, buildVariantStub(n, originalWithProps, contract), 'utf-8');
250
+ fs.writeFileSync(variantFile, buildVariantStubV2(n, analysis.markupWithProps, contract, seededCss), 'utf-8');
175
251
  }
176
252
  }
177
253
 
@@ -180,9 +256,100 @@ export function scaffoldSvelteComponentSession({
180
256
  manifestFile: path.relative(cwd, path.join(dir, 'manifest.json')).split(path.sep).join('/'),
181
257
  componentDir: manifest.componentDir,
182
258
  propContract: contract,
259
+ // Inlined so the generate event's scaffold payload carries the stub
260
+ // shape; the agent edits vN.svelte in place instead of spending reads on
261
+ // the manifest and stub files (or deleting and recreating them).
262
+ stubMarkup: analysis.markupWithProps,
263
+ seededCss,
183
264
  };
184
265
  }
185
266
 
267
+ function safeReadSource(filePath) {
268
+ try { return fs.readFileSync(filePath, 'utf-8'); } catch { return ''; }
269
+ }
270
+
271
+ function escapeSelectorToken(token) {
272
+ return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
273
+ }
274
+
275
+ /**
276
+ * Seed variant stubs with the source component's rules that already style the
277
+ * selected markup, so variants start from the real cascade (a detached
278
+ * preview inherits none of the route's compile-scoped CSS) instead of
279
+ * reimplementing it blind.
280
+ *
281
+ * Returns { css, supersedable }. `css` is every matching rule (class OR tag
282
+ * matched). `supersedable` holds only the CLASS-matched selectors: those are
283
+ * the accept-time removal candidates. Tag selectors (h1, a, p) style shared
284
+ * elements across the whole route, so they seed the preview but are never
285
+ * candidates for removal.
286
+ */
287
+ export function extractMatchingSourceCss(routeSource, originalMarkup) {
288
+ const empty = { css: '', supersedable: new Set() };
289
+ const styleMatch = String(routeSource || '').match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/i);
290
+ if (!styleMatch) return empty;
291
+ const classNames = new Set();
292
+ const classRe = /class\s*=\s*(["'])(.*?)\1/g;
293
+ let m;
294
+ while ((m = classRe.exec(originalMarkup))) {
295
+ for (const cls of m[2].split(/\s+/)) if (cls && !cls.includes('{')) classNames.add(cls);
296
+ }
297
+ const tagRe = /<([a-z][a-z0-9-]*)/gi;
298
+ const tags = new Set();
299
+ while ((m = tagRe.exec(originalMarkup))) tags.add(m[1].toLowerCase());
300
+ if (classNames.size === 0 && tags.size === 0) return empty;
301
+
302
+ // Token-boundary matching, never substring: `.btn` must not match
303
+ // `.btn-primary`, and `.stage` must not match `.stages`. A substring hit
304
+ // seeds a rule that never styled the pick, and a falsely seeded selector
305
+ // becomes an accept-time DELETION of a hand-written rule.
306
+ const classRes = [...classNames].map((cls) => new RegExp('\\.' + escapeSelectorToken(cls) + '(?![A-Za-z0-9_-])'));
307
+ const tagRes = [...tags].map((tag) => new RegExp('(^|[\\s>+~,(])' + escapeSelectorToken(tag) + '(?![A-Za-z0-9_-])', 'i'));
308
+ const classMatches = (selector) => classRes.some((re) => re.test(selector));
309
+ const tagMatches = (selector) => tagRes.some((re) => re.test(selector));
310
+
311
+ const supersedable = new Set();
312
+ const ruleMatches = (prelude) => {
313
+ let matched = false;
314
+ for (const selector of splitSelectorList(prelude)) {
315
+ if (classMatches(selector)) {
316
+ matched = true;
317
+ supersedable.add(normalizeSelector(selector));
318
+ } else if (tagMatches(selector)) {
319
+ matched = true;
320
+ }
321
+ }
322
+ return matched;
323
+ };
324
+
325
+ const pick = (nodes) => {
326
+ const kept = [];
327
+ for (const node of nodes) {
328
+ if (node.type === 'rule' && ruleMatches(node.prelude)) kept.push(node);
329
+ else if (node.type === 'at' && node.children) {
330
+ const children = pick(node.children);
331
+ if (children.length) kept.push({ ...node, children });
332
+ }
333
+ }
334
+ return kept;
335
+ };
336
+ return { css: serializeNodes(pick(parseStylesheet(styleMatch[1]))), supersedable };
337
+ }
338
+
339
+ function buildVariantStubV2(variantNum, markupWithProps, contract, seededCss) {
340
+ const propsComment = contract.length > 0
341
+ ? `\n<!-- Props: ${contract.map((c) => `${c.prop} (${c.kind}) <- {${c.expr}}`).join(', ')} -->\n`
342
+ : '';
343
+ // The guard comments must never contain the literal "<style" character
344
+ // sequence: agents (and the fake test agent) locate the style block with
345
+ // string searches, and a mention inside a comment truncates their surgery
346
+ // mid-comment.
347
+ const css = seededCss
348
+ ? `\n<style>\n /* Variant ${variantNum}: seeded from the route's current rules; restyle or delete freely.\n ALL rules go inside THIS block. Svelte allows exactly one top-level style\n element per component; appending a second one is a compile error. */\n${seededCss.split('\n').map((l) => (l.trim() ? ' ' + l : '')).join('\n')}\n</style>\n`
349
+ : `\n<style>\n /* Variant ${variantNum}: add all CSS inside THIS block. Svelte allows exactly\n one top-level style element; a second one is a compile error. */\n</style>\n`;
350
+ return `${buildPropsScriptV2(contract)}${propsComment}${markupWithProps.trim()}\n${css}`;
351
+ }
352
+
186
353
  export function scaffoldSvelteComponentInsertSession({
187
354
  id,
188
355
  count,
@@ -213,7 +380,11 @@ export function scaffoldSvelteComponentInsertSession({
213
380
  count,
214
381
  propContract: [],
215
382
  componentDir: path.relative(cwd, dir).split(path.sep).join('/'),
383
+ componentDirAbs: dir.split(path.sep).join('/'),
216
384
  runtimeModule: `/${SVELTE_RUNTIME_FILE}`,
385
+ runtimeModuleAbs: path.join(cwd, SVELTE_RUNTIME_FILE).split(path.sep).join('/'),
386
+ probeModule: `/${SVELTE_PROBE_FILE}`,
387
+ probeModuleAbs: path.join(cwd, SVELTE_PROBE_FILE).split(path.sep).join('/'),
217
388
  };
218
389
 
219
390
  fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf-8');
@@ -238,16 +409,24 @@ export function findSvelteComponentManifest(id, cwd = process.cwd()) {
238
409
  if (fs.existsSync(direct)) {
239
410
  return readManifest(direct);
240
411
  }
241
- const root = path.join(cwd, SVELTE_COMPONENT_ROOT);
242
- if (!fs.existsSync(root)) return null;
243
- for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
244
- if (!entry.isDirectory()) continue;
245
- const candidate = path.join(root, entry.name, 'manifest.json');
246
- if (!fs.existsSync(candidate)) continue;
247
- try {
248
- const manifest = readManifest(candidate);
249
- if (manifest?.id === id) return { ...manifest, manifestPath: candidate };
250
- } catch { /* skip */ }
412
+ // Legacy location: a session scaffolded by an older version can still be
413
+ // accepted after an upgrade.
414
+ const legacyDirect = path.join(cwd, LEGACY_SVELTE_COMPONENT_ROOT, id, 'manifest.json');
415
+ if (fs.existsSync(legacyDirect)) {
416
+ return readManifest(legacyDirect);
417
+ }
418
+ for (const rootRel of [SVELTE_COMPONENT_ROOT, LEGACY_SVELTE_COMPONENT_ROOT]) {
419
+ const root = path.join(cwd, rootRel);
420
+ if (!fs.existsSync(root)) continue;
421
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
422
+ if (!entry.isDirectory()) continue;
423
+ const candidate = path.join(root, entry.name, 'manifest.json');
424
+ if (!fs.existsSync(candidate)) continue;
425
+ try {
426
+ const manifest = readManifest(candidate);
427
+ if (manifest?.id === id) return { ...manifest, manifestPath: candidate };
428
+ } catch { /* skip */ }
429
+ }
251
430
  }
252
431
  return null;
253
432
  }
@@ -451,35 +630,6 @@ function rewriteParamSelectors(selector, paramValues) {
451
630
  return { keep, selector: next };
452
631
  }
453
632
 
454
- function splitSelectorList(prelude) {
455
- const selectors = [];
456
- let start = 0;
457
- let bracket = 0;
458
- let paren = 0;
459
- let quote = null;
460
- for (let i = 0; i < prelude.length; i++) {
461
- const ch = prelude[i];
462
- if (quote) {
463
- if (ch === '\\') i++;
464
- else if (ch === quote) quote = null;
465
- continue;
466
- }
467
- if (ch === '"' || ch === "'") {
468
- quote = ch;
469
- continue;
470
- }
471
- if (ch === '[') bracket++;
472
- else if (ch === ']') bracket = Math.max(0, bracket - 1);
473
- else if (ch === '(') paren++;
474
- else if (ch === ')') paren = Math.max(0, paren - 1);
475
- else if (ch === ',' && bracket === 0 && paren === 0) {
476
- selectors.push(prelude.slice(start, i));
477
- start = i + 1;
478
- }
479
- }
480
- selectors.push(prelude.slice(start));
481
- return selectors;
482
- }
483
633
 
484
634
  function selectorHasVariant(selector, variantNum) {
485
635
  return variantSelectorRegex(variantNum).test(selector);
@@ -527,10 +677,24 @@ export function inlineSvelteComponentAccept(manifest, variantNum, paramValues =
527
677
 
528
678
  const rootTag = matchOpeningTag(markup)?.tag || 'div';
529
679
  const contract = manifest.propContract || [];
680
+ const compiler = loadSvelteCompiler(cwd);
530
681
  const mergedMarkup = mergeOriginalTopLevelAttrs(markup, manifest.originalMarkup || '');
531
- const restoredMarkup = substitutePropsWithExprs(mergedMarkup, contract)
532
- .split('\n')
533
- .map((line) => line.trimEnd());
682
+
683
+ // Restore props back to route expressions. Contract v2 restores through the
684
+ // AST so a prop used without braces (each headers, attribute positions)
685
+ // still maps back to its original expression; v1 falls back to the textual
686
+ // placeholder swap.
687
+ let restoredText;
688
+ if (Number(manifest.contractVersion) === 2 && compiler) {
689
+ const restored = restoreSvelteMarkup(mergedMarkup, contract, compiler.parse);
690
+ if (!restored.ok) {
691
+ return { handled: false, error: 'Accepted variant does not parse: ' + restored.reason, ...resultBase };
692
+ }
693
+ restoredText = restored.markup;
694
+ } else {
695
+ restoredText = substitutePropsWithExprs(mergedMarkup, contract);
696
+ }
697
+ const restoredMarkup = restoredText.split('\n').map((line) => line.trimEnd());
534
698
 
535
699
  const sourceContent = fs.readFileSync(sourceFile, 'utf-8');
536
700
  const sourceLines = sourceContent.split('\n');
@@ -541,10 +705,7 @@ export function inlineSvelteComponentAccept(manifest, variantNum, paramValues =
541
705
  }
542
706
 
543
707
  const indent = sourceLines[start].match(/^(\s*)/)?.[1] || '';
544
- const indentedMarkup = restoredMarkup.map((line) => {
545
- if (line.trim() === '') return '';
546
- return indent + line.trimStart();
547
- });
708
+ const indentedMarkup = reindentPreservingStructure(restoredMarkup, indent);
548
709
 
549
710
  let newLines = [
550
711
  ...sourceLines.slice(0, start),
@@ -552,25 +713,235 @@ export function inlineSvelteComponentAccept(manifest, variantNum, paramValues =
552
713
  ...sourceLines.slice(end + 1),
553
714
  ];
554
715
 
555
- const sanitizedCss = sanitizeAcceptedSvelteCss(cssLines, variantNum, paramValues, rootTag);
556
- const bakedCss = bakeParamValuesInCss(sanitizedCss, paramValues);
557
- if (bakedCss.length > 0) {
558
- newLines = appendCssToSvelteStyle(newLines, bakedCss);
716
+ // Selectors that were already unused before this accept are the user's
717
+ // pre-existing code; the pruning pass must not touch them.
718
+ const preUnused = compiler ? collectUnusedSelectors(sourceContent, compiler.compile) : new Set();
719
+
720
+ // Bake params (declared kinds from params.json drive branch pruning), then
721
+ // MERGE into the component's existing style block: matching selectors are
722
+ // replaced, new ones appended. Appending alone is how superseded rules used
723
+ // to survive their own replacement.
724
+ const declaredParams = readDeclaredParams(manifest, variantNum, cwd);
725
+ let variantCss = cssLines.join('\n');
726
+ if (/data-impeccable-variant|impeccable-variant-ready/.test(variantCss)) {
727
+ // Defensive: strip preview-wrapper selectors that authoring rules forbid
728
+ // on this path but an off-spec agent may still emit.
729
+ variantCss = sanitizeAcceptedSvelteCss(cssLines, variantNum, paramValues, rootTag).join('\n');
730
+ }
731
+ const bakedCss = bakeParamValues(variantCss, declaredParams, paramValues || {});
732
+ const cssStats = { replaced: 0, appended: 0, pruned: [], superseded: [] };
733
+ if (bakedCss.trim()) {
734
+ const merged = mergeCssIntoSvelteSource(newLines.join('\n'), bakedCss);
735
+ newLines = merged.text.split('\n');
736
+ cssStats.replaced = merged.replaced;
737
+ cssStats.appended = merged.appended;
738
+ }
739
+
740
+ let finalText = newLines.join('\n');
741
+
742
+ // Preview truth: the detached preview never applied the source rules that
743
+ // styled the replaced selection, so the user approved a design without
744
+ // them. Any seeded selector the variant did not re-declare is superseded;
745
+ // left in place it re-attaches through kept class names (the accepted root
746
+ // keeps its original classes) and re-layouts markup it no longer owns.
747
+ //
748
+ // Removal is bounded by ownership: a selector whose classes are still used
749
+ // by route markup OUTSIDE the replaced region does not belong to the pick
750
+ // alone, and removing it would strip styling from markup this accept never
751
+ // touched. Keeping it risks a visible re-attachment quirk on the accepted
752
+ // region; deleting it breaks the rest of the route. Keep it.
753
+ const outsideMarkup = [...sourceLines.slice(0, start), ...sourceLines.slice(end + 1)]
754
+ .join('\n')
755
+ .replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/gi, '');
756
+ const outsideClasses = new Set();
757
+ {
758
+ const attrRe = /class\s*=\s*(["'])(.*?)\1/g;
759
+ let cm;
760
+ while ((cm = attrRe.exec(outsideMarkup))) {
761
+ for (const cls of cm[2].split(/\s+/)) if (cls && !cls.includes('{')) outsideClasses.add(cls);
762
+ }
763
+ const directiveRe = /class:([A-Za-z0-9_-]+)/g;
764
+ while ((cm = directiveRe.exec(outsideMarkup))) outsideClasses.add(cm[1]);
765
+ }
766
+ const usedOutsideReplacedRegion = (selector) => {
767
+ const classTokenRe = /\.([A-Za-z0-9_-]+)/g;
768
+ let tm;
769
+ while ((tm = classTokenRe.exec(selector))) {
770
+ if (outsideClasses.has(tm[1])) return true;
771
+ }
772
+ return false;
773
+ };
774
+ const incomingSelectors = collectAllSelectors(bakedCss);
775
+ const superseded = (manifest.seededSelectors || [])
776
+ .map((selector) => normalizeSelector(selector))
777
+ .filter((selector) => selector && !incomingSelectors.has(selector) && !usedOutsideReplacedRegion(selector));
778
+ if (superseded.length > 0) {
779
+ const scrubbed = removeSelectorsFromSvelteSource(finalText, new Set(superseded));
780
+ finalText = scrubbed.text;
781
+ cssStats.superseded = scrubbed.removed;
782
+ }
783
+
784
+ if (compiler) {
785
+ const pruned = pruneUnusedSelectors(finalText, compiler.compile, { skipSelectors: preUnused });
786
+ finalText = pruned.source;
787
+ cssStats.pruned = pruned.removed;
788
+ }
789
+
790
+ // Postcondition: no selector from the user's pre-accept CSS may vanish
791
+ // unless the compiler-driven prune or the preview-truth supersession
792
+ // deliberately removed it. This turns any parser or reconciler defect into
793
+ // a loud refusal instead of silent damage to a hand-written style block.
794
+ const lostSelectors = findLostSelectors(sourceContent, finalText, [
795
+ ...cssStats.pruned,
796
+ ...cssStats.superseded,
797
+ ]);
798
+ if (lostSelectors.length > 0) {
799
+ return {
800
+ handled: false,
801
+ error: 'CSS reconciliation would lose selectors from the existing style block: '
802
+ + lostSelectors.join(', ')
803
+ + '. Source not modified; accept the variant manually.',
804
+ mode: 'error',
805
+ ...resultBase,
806
+ };
559
807
  }
560
808
 
561
809
  try {
562
- fs.writeFileSync(sourceFile, newLines.join('\n'), 'utf-8');
810
+ fs.writeFileSync(sourceFile, finalText, 'utf-8');
563
811
  } catch (err) {
564
812
  return { handled: false, error: 'Failed to write Svelte source: ' + err.message, ...resultBase };
565
813
  }
566
814
  removeSvelteComponentSession(manifest.id, cwd);
567
815
 
816
+ const verify = verifyAcceptedSource(finalText);
568
817
  return {
569
818
  handled: true,
819
+ css: cssStats,
820
+ verify,
570
821
  ...resultBase,
571
822
  };
572
823
  }
573
824
 
825
+ /** Re-indent a block onto `indent` while preserving its internal structure. */
826
+ export function reindentPreservingStructure(lines, indent) {
827
+ const nonEmpty = lines.filter((line) => line.trim() !== '');
828
+ if (nonEmpty.length === 0) return lines.map(() => '');
829
+ const minIndent = Math.min(...nonEmpty.map((line) => (line.match(/^\s*/) || [''])[0].length));
830
+ return lines.map((line) => {
831
+ if (line.trim() === '') return '';
832
+ const current = (line.match(/^\s*/) || [''])[0].length;
833
+ return indent + line.slice(Math.min(minIndent, current));
834
+ });
835
+ }
836
+
837
+ function styleBlockText(sourceText) {
838
+ const match = String(sourceText || '').match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/i);
839
+ return match ? match[1] : '';
840
+ }
841
+
842
+ /**
843
+ * Remove every rule whose (normalized) selector list is fully contained in
844
+ * `selectors` from the component's style block, at any at-rule nesting depth.
845
+ * Rules that mix doomed and surviving selectors keep the survivors.
846
+ */
847
+ export function removeSelectorsFromSvelteSource(sourceText, selectors) {
848
+ const text = String(sourceText || '');
849
+ const styleRe = /<style\b[^>]*>([\s\S]*?)<\/style\s*>/gi;
850
+ let lastMatch = null;
851
+ let m;
852
+ while ((m = styleRe.exec(text))) lastMatch = m;
853
+ if (!lastMatch) return { text, removed: [] };
854
+
855
+ const removed = [];
856
+ const transform = (nodes) => {
857
+ const kept = [];
858
+ for (const node of nodes) {
859
+ if (node.type === 'rule') {
860
+ const survivors = [];
861
+ for (const selector of splitSelectorList(node.prelude)) {
862
+ if (selectors.has(normalizeSelector(selector))) removed.push(normalizeSelector(selector));
863
+ else survivors.push(selector);
864
+ }
865
+ if (survivors.length > 0) kept.push({ ...node, prelude: survivors.join(', ') });
866
+ } else if (node.type === 'at' && node.children) {
867
+ const children = transform(node.children);
868
+ if (children.length > 0) kept.push({ ...node, children });
869
+ } else {
870
+ kept.push(node);
871
+ }
872
+ }
873
+ return kept;
874
+ };
875
+
876
+ const nodes = transform(parseStylesheet(lastMatch[1]));
877
+ if (removed.length === 0) return { text, removed };
878
+ const openTag = lastMatch[0].slice(0, lastMatch[0].indexOf('>') + 1);
879
+ const rebuilt = `${openTag}\n${serializeNodes(nodes).split('\n').map((l) => (l.trim() ? ' ' + l : '')).join('\n')}\n</style>`;
880
+ return {
881
+ text: text.slice(0, lastMatch.index) + rebuilt + text.slice(lastMatch.index + lastMatch[0].length),
882
+ removed,
883
+ };
884
+ }
885
+
886
+ export function findLostSelectors(beforeSource, afterSource, prunedSelectors = []) {
887
+ const before = collectAllSelectors(styleBlockText(beforeSource));
888
+ const after = collectAllSelectors(styleBlockText(afterSource));
889
+ const pruned = new Set((prunedSelectors || []).map((s) => normalizeSelector(s)));
890
+ const lost = [];
891
+ for (const selector of before) {
892
+ if (!after.has(selector) && !pruned.has(selector)) lost.push(selector);
893
+ }
894
+ return lost;
895
+ }
896
+
897
+ function readDeclaredParams(manifest, variantNum, cwd) {
898
+ try {
899
+ const raw = JSON.parse(fs.readFileSync(path.join(cwd, manifest.componentDir, 'params.json'), 'utf-8'));
900
+ const list = raw?.[String(variantNum)];
901
+ return Array.isArray(list) ? list : [];
902
+ } catch {
903
+ return [];
904
+ }
905
+ }
906
+
907
+ /**
908
+ * Merge CSS into a svelte component's top-level style block (created when
909
+ * absent), replacing rules whose selectors match and appending the rest.
910
+ */
911
+ export function mergeCssIntoSvelteSource(sourceText, incomingCss) {
912
+ const text = String(sourceText || '');
913
+ const styleRe = /<style\b[^>]*>([\s\S]*?)<\/style\s*>/gi;
914
+ let lastMatch = null;
915
+ let m;
916
+ while ((m = styleRe.exec(text))) lastMatch = m;
917
+
918
+ if (!lastMatch) {
919
+ const { css, replaced, appended } = reconcileCss('', incomingCss);
920
+ return {
921
+ text: `${text.replace(/\s*$/, '')}\n\n<style>\n${indentCssBlock(css)}\n</style>\n`,
922
+ replaced,
923
+ appended,
924
+ };
925
+ }
926
+
927
+ const inner = lastMatch[1];
928
+ const { css, replaced, appended } = reconcileCss(inner, incomingCss);
929
+ const openTag = lastMatch[0].slice(0, lastMatch[0].indexOf('>') + 1);
930
+ const replacedBlock = `${openTag}\n${indentCssBlock(css)}\n</style>`;
931
+ return {
932
+ text: text.slice(0, lastMatch.index) + replacedBlock + text.slice(lastMatch.index + lastMatch[0].length),
933
+ replaced,
934
+ appended,
935
+ };
936
+ }
937
+
938
+ function indentCssBlock(css) {
939
+ return String(css || '')
940
+ .split('\n')
941
+ .map((line) => (line.trim() === '' ? '' : ' ' + line))
942
+ .join('\n');
943
+ }
944
+
574
945
  function inlineSvelteComponentInsertAccept({
575
946
  manifest,
576
947
  markup,
@@ -601,10 +972,7 @@ function inlineSvelteComponentInsertAccept({
601
972
 
602
973
  const nearbyLine = sourceLines[insertIndex] ?? sourceLines[insertIndex - 1] ?? '';
603
974
  const indent = nearbyLine.match(/^(\s*)/)?.[1] || '';
604
- const indentedMarkup = restoredMarkup.map((line) => {
605
- if (line.trim() === '') return '';
606
- return indent + line.trimStart();
607
- });
975
+ const indentedMarkup = reindentPreservingStructure(restoredMarkup, indent);
608
976
 
609
977
  let newLines = [
610
978
  ...sourceLines.slice(0, insertIndex),
@@ -612,10 +980,15 @@ function inlineSvelteComponentInsertAccept({
612
980
  ...sourceLines.slice(insertIndex),
613
981
  ];
614
982
 
615
- const sanitizedCss = sanitizeAcceptedSvelteCss(cssLines, variantNum, paramValues, rootTag);
616
- const bakedCss = bakeParamValuesInCss(sanitizedCss, paramValues);
617
- if (bakedCss.length > 0) {
618
- newLines = appendCssToSvelteStyle(newLines, bakedCss);
983
+ let variantCss = cssLines.join('\n');
984
+ if (/data-impeccable-variant|impeccable-variant-ready/.test(variantCss)) {
985
+ variantCss = sanitizeAcceptedSvelteCss(cssLines, variantNum, paramValues, rootTag).join('\n');
986
+ }
987
+ const declaredParams = readDeclaredParams(manifest, variantNum, cwd);
988
+ const bakedCss = bakeParamValues(variantCss, declaredParams, paramValues || {});
989
+ if (bakedCss.trim()) {
990
+ const merged = mergeCssIntoSvelteSource(newLines.join('\n'), bakedCss);
991
+ newLines = merged.text.split('\n');
619
992
  }
620
993
 
621
994
  try {
@@ -625,8 +998,10 @@ function inlineSvelteComponentInsertAccept({
625
998
  }
626
999
  removeSvelteComponentSession(manifest.id, cwd);
627
1000
 
1001
+ const verify = verifyAcceptedSource(newLines.join('\n'));
628
1002
  return {
629
1003
  handled: true,
1004
+ verify,
630
1005
  ...resultBase,
631
1006
  };
632
1007
  }
@@ -729,18 +1104,159 @@ export function removeSvelteComponentSession(id, cwd = process.cwd()) {
729
1104
  } catch { /* non-fatal */ }
730
1105
  }
731
1106
 
1107
+ /**
1108
+ * Compile-check every variant component of a session with the app's own
1109
+ * compiler, BEFORE the browser ever imports them. A variant that does not
1110
+ * compile (the classic: a second top-level <style> appended next to the
1111
+ * seeded one) used to surface as a red Vite overlay in the user's page plus
1112
+ * a mount-failure round trip; bounced at publish time it is a private
1113
+ * agent-side fix with the exact file and line.
1114
+ */
1115
+ export function compileCheckVariants(id, cwd = process.cwd()) {
1116
+ const manifest = findSvelteComponentManifest(id, cwd);
1117
+ if (!manifest || !manifest.manifestPath) return { ok: true, failures: [], checked: 0 };
1118
+ const compiler = loadSvelteCompiler(cwd);
1119
+ if (!compiler || typeof compiler.compile !== 'function') return { ok: true, failures: [], checked: 0 };
1120
+ const sessionDir = path.dirname(manifest.manifestPath);
1121
+ const failures = [];
1122
+ let checked = 0;
1123
+ let entries = [];
1124
+ try { entries = fs.readdirSync(sessionDir); } catch { return { ok: true, failures: [], checked: 0 }; }
1125
+ for (const name of entries) {
1126
+ if (!/^v\d+\.svelte$/.test(name)) continue;
1127
+ checked++;
1128
+ try {
1129
+ compiler.compile(fs.readFileSync(path.join(sessionDir, name), 'utf-8'), { generate: false });
1130
+ } catch (err) {
1131
+ failures.push({
1132
+ file: `${manifest.componentDir}/${name}`,
1133
+ line: err?.start?.line ?? null,
1134
+ column: err?.start?.column ?? null,
1135
+ message: String(err?.message || err).split('\n')[0].slice(0, 300),
1136
+ });
1137
+ }
1138
+ }
1139
+ return { ok: failures.length === 0, failures, checked };
1140
+ }
1141
+
1142
+ /**
1143
+ * Snapshot the agent-authored variant files into a fresh revision directory
1144
+ * and stamp the manifest. Called by the server on every publish (`done`
1145
+ * reply) for a component session; the browser imports from the revision dir,
1146
+ * so the dev server can never serve a stale compile of a republished file.
1147
+ */
1148
+ export function bumpSvelteComponentPreviewRevision(id, cwd = process.cwd()) {
1149
+ const manifest = findSvelteComponentManifest(id, cwd);
1150
+ if (!manifest || !manifest.manifestPath) return null;
1151
+ const sessionDir = path.dirname(manifest.manifestPath);
1152
+ const revision = Number(manifest.revision || 0) + 1;
1153
+ const revDirName = `r${revision}`;
1154
+ const revDir = path.join(sessionDir, revDirName);
1155
+ try {
1156
+ fs.mkdirSync(revDir, { recursive: true });
1157
+ let entries = [];
1158
+ try { entries = fs.readdirSync(sessionDir, { withFileTypes: true }); } catch { /* empty */ }
1159
+ for (const entry of entries) {
1160
+ if (!entry.isFile()) continue;
1161
+ if (entry.name === 'manifest.json') continue;
1162
+ fs.copyFileSync(path.join(sessionDir, entry.name), path.join(revDir, entry.name));
1163
+ }
1164
+ // Previous revision dirs are dead the moment a new one exists.
1165
+ for (const entry of entries) {
1166
+ if (entry.isDirectory() && /^r\d+$/.test(entry.name) && entry.name !== revDirName) {
1167
+ try { fs.rmSync(path.join(sessionDir, entry.name), { recursive: true, force: true }); } catch { /* non-fatal */ }
1168
+ }
1169
+ }
1170
+ const relSessionDir = path.relative(cwd, sessionDir).split(path.sep).join('/');
1171
+ const updated = {
1172
+ ...manifest,
1173
+ revision,
1174
+ revisionDir: `${relSessionDir}/${revDirName}`,
1175
+ revisionDirAbs: revDir.split(path.sep).join('/'),
1176
+ };
1177
+ delete updated.manifestPath;
1178
+ fs.writeFileSync(manifest.manifestPath, JSON.stringify(updated, null, 2) + '\n', 'utf-8');
1179
+ return { revision, revisionDir: updated.revisionDir };
1180
+ } catch {
1181
+ return null;
1182
+ }
1183
+ }
1184
+
1185
+ /**
1186
+ * Stop-path sweep. The whole `node_modules/.impeccable-live` tree is
1187
+ * impeccable-owned and gitignored, so once no session should survive there is
1188
+ * nothing left worth keeping: the per-session dirs, the generated
1189
+ * `__runtime.js`, and the parent directory all go. The old per-entry loop
1190
+ * skipped `__*` entries and the parent, which left the runtime shim and an
1191
+ * empty directory in every project that ever ran live mode once.
1192
+ */
732
1193
  export function removeAllSvelteComponentSessions(cwd = process.cwd()) {
733
- const root = path.join(cwd, SVELTE_COMPONENT_ROOT);
734
- if (!fs.existsSync(root)) return;
735
- for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
736
- if (!entry.isDirectory()) continue;
737
- if (entry.name.startsWith('__')) continue;
1194
+ for (const rootRel of [SVELTE_COMPONENT_ROOT, LEGACY_SVELTE_COMPONENT_ROOT]) {
1195
+ const root = path.join(cwd, rootRel);
1196
+ if (!fs.existsSync(root)) continue;
738
1197
  try {
739
- fs.rmSync(path.join(root, entry.name), { recursive: true, force: true });
1198
+ fs.rmSync(root, { recursive: true, force: true });
740
1199
  } catch { /* non-fatal */ }
741
1200
  }
742
1201
  }
743
1202
 
1203
+ /**
1204
+ * Boot-path sweep. A restart must not delete the tree wholesale: sessions
1205
+ * recorded in the session store may still be mid-generation. Remove only the
1206
+ * session dirs whose id has no active snapshot, then drop `__runtime.js` and
1207
+ * the parent directory when nothing is left to serve.
1208
+ *
1209
+ * @param {Iterable<string>} activeIds session ids that must be preserved
1210
+ * @returns {{ removed: string[], removedRoot: boolean, kept: string[] }}
1211
+ */
1212
+ export function sweepInactiveSvelteComponentSessions(activeIds = [], cwd = process.cwd()) {
1213
+ const result = { removed: [], removedRoot: false, kept: [] };
1214
+ const active = new Set();
1215
+ for (const id of activeIds || []) {
1216
+ if (typeof id === 'string' && id) active.add(id);
1217
+ }
1218
+
1219
+ for (const rootRel of [SVELTE_COMPONENT_ROOT, LEGACY_SVELTE_COMPONENT_ROOT]) {
1220
+ const root = path.join(cwd, rootRel);
1221
+ if (!fs.existsSync(root)) continue;
1222
+
1223
+ let entries;
1224
+ try {
1225
+ entries = fs.readdirSync(root, { withFileTypes: true });
1226
+ } catch {
1227
+ continue;
1228
+ }
1229
+
1230
+ let keptHere = 0;
1231
+ for (const entry of entries) {
1232
+ if (!entry.isDirectory()) continue;
1233
+ if (entry.name.startsWith('__')) continue;
1234
+ if (active.has(entry.name)) {
1235
+ result.kept.push(entry.name);
1236
+ keptHere++;
1237
+ continue;
1238
+ }
1239
+ try {
1240
+ fs.rmSync(path.join(root, entry.name), { recursive: true, force: true });
1241
+ result.removed.push(entry.name);
1242
+ } catch {
1243
+ // Could not remove it, so it still occupies the tree; treat it as kept
1244
+ // so the parent directory is not torn out from under it.
1245
+ result.kept.push(entry.name);
1246
+ keptHere++;
1247
+ }
1248
+ }
1249
+
1250
+ if (keptHere === 0) {
1251
+ try {
1252
+ fs.rmSync(root, { recursive: true, force: true });
1253
+ result.removedRoot = true;
1254
+ } catch { /* non-fatal */ }
1255
+ }
1256
+ }
1257
+ return result;
1258
+ }
1259
+
744
1260
  export function deferredAcceptsPath(cwd = process.cwd()) {
745
1261
  const key = createHash('sha1').update(path.resolve(cwd)).digest('hex').slice(0, 16);
746
1262
  return path.join(os.tmpdir(), 'impeccable-live', key, 'deferred-svelte-component-accepts.json');