@lssm/example.learning-journey-ui-shared 0.0.0-canary-20251217060834 → 0.0.0-canary-20251217073102

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.
package/dist/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { t as useLearningProgress } from "./hooks-B-tDvppY.mjs";
2
2
  import { i as XpBar, n as BadgeDisplay, r as StreakCounter, t as ViewTabs } from "./components-tyJAN4Ru.mjs";
3
+ import { registerDocBlocks } from "@lssm/lib.contracts/docs";
3
4
 
4
5
  //#region src/example.ts
5
6
  const example = {
@@ -33,3079 +34,9 @@ const example = {
33
34
  };
34
35
  var example_default = example;
35
36
 
36
- //#endregion
37
- //#region ../../libs/contracts/dist/docs/presentations.js
38
- const e = [
39
- `markdown`,
40
- `application/json`,
41
- `application/xml`,
42
- `react`
43
- ];
44
- function t$27(e$1) {
45
- if (!e$1.length) return `/`;
46
- let t$28 = e$1.startsWith(`/`) ? e$1 : `/${e$1}`;
47
- return t$28 === `/` ? `/` : t$28.replace(/\/+$/, ``);
48
- }
49
- function n$1(e$1, n$2) {
50
- if (e$1.route) return t$27(e$1.route);
51
- let r$2 = n$2 ?? `/docs`, i$2 = e$1.id.replace(/^docs\.?/, ``).replace(/\./g, `/`).replace(/\/+/g, `/`);
52
- return t$27(i$2.startsWith(`/`) ? i$2 : `${r$2}/${i$2}`);
53
- }
54
- function r$1(e$1, t$28) {
55
- return t$28 ? `${t$28}.${e$1.id}` : e$1.id;
56
- }
57
- function i$1(t$28, n$2) {
58
- let i$2 = n$2?.defaultTargets ?? e, a$2 = t$28.version ?? n$2?.defaultVersion ?? 1, o$2 = t$28.stability ?? n$2?.defaultStability ?? `stable`;
59
- return {
60
- meta: {
61
- name: r$1(t$28, n$2?.namespace),
62
- version: a$2,
63
- description: t$28.summary ?? t$28.title,
64
- tags: t$28.tags,
65
- owners: t$28.owners,
66
- domain: t$28.domain,
67
- stability: o$2
68
- },
69
- policy: t$28.visibility && t$28.visibility !== `public` ? { flags: [t$28.visibility] } : void 0,
70
- source: {
71
- type: `blocknotejs`,
72
- docJson: t$28.body
73
- },
74
- targets: i$2
75
- };
76
- }
77
- function a$1(e$1, t$28) {
78
- let n$2 = e$1.version ?? t$28?.defaultVersion ?? 1, i$2 = e$1.stability ?? t$28?.defaultStability ?? `stable`;
79
- return {
80
- meta: {
81
- name: r$1(e$1, t$28?.namespace),
82
- version: n$2,
83
- stability: i$2,
84
- tags: e$1.tags,
85
- owners: e$1.owners,
86
- description: e$1.summary ?? e$1.title
87
- },
88
- content: {
89
- kind: `markdown`,
90
- content: e$1.body
91
- }
92
- };
93
- }
94
- function o$1(e$1, t$28) {
95
- return e$1.map((e$2) => ({
96
- block: e$2,
97
- route: n$1(e$2, t$28?.routePrefix),
98
- descriptor: i$1(e$2, t$28)
99
- }));
100
- }
101
-
102
- //#endregion
103
- //#region ../../libs/contracts/dist/docs/registry.js
104
- var n = class {
105
- routes = /* @__PURE__ */ new Map();
106
- constructor(e$1 = [], t$28) {
107
- e$1.forEach((e$2) => this.register(e$2, t$28));
108
- }
109
- register(e$1, n$2) {
110
- let [r$2] = o$1([e$1], n$2);
111
- return r$2 && this.routes.set(e$1.id, r$2), this;
112
- }
113
- list() {
114
- return [...this.routes.values()];
115
- }
116
- get(e$1) {
117
- return this.routes.get(e$1);
118
- }
119
- toRouteTuples() {
120
- return this.list().map(({ route: e$1, descriptor: t$28 }) => [e$1, t$28]);
121
- }
122
- toPresentationSpecs(t$28) {
123
- return this.list().map(({ block: n$2 }) => a$1(n$2, t$28));
124
- }
125
- };
126
- const r = [
127
- `id`,
128
- `title`,
129
- `body`,
130
- `kind`,
131
- `visibility`,
132
- `route`
133
- ], i = new n();
134
- function a(e$1) {
135
- for (let t$28 of e$1) {
136
- for (let e$2 of r) if (!t$28[e$2]) throw Error(`DocBlock ${t$28.id ?? `<missing id>`} missing field ${String(e$2)}`);
137
- i.register(t$28);
138
- }
139
- }
140
-
141
- //#endregion
142
- //#region ../../libs/contracts/dist/docs/PUBLISHING.docblock.js
143
- const t$26 = [{
144
- id: `docs.PUBLISHING`,
145
- title: `Publishing ContractSpec Libraries`,
146
- summary: `This guide describes how we release the ContractSpec libraries to npm. We use a dual-track release system: **Stable** (manual) and **Canary** (automatic).`,
147
- kind: `reference`,
148
- visibility: `public`,
149
- route: `/docs/PUBLISHING`,
150
- tags: [`PUBLISHING`],
151
- body: `# Publishing ContractSpec Libraries
152
-
153
- This guide describes how we release the ContractSpec libraries to npm. We use a dual-track release system: **Stable** (manual) and **Canary** (automatic).
154
-
155
- ## Release Tracks
156
-
157
- | Track | Branch | npm Tag | Frequency | Versioning | Use Case |
158
- |-------|--------|---------|-----------|------------|----------|
159
- | **Stable** | \`release\` | \`latest\` | Manual | SemVer (e.g., \`1.7.4\`) | Production, external users |
160
- | **Canary** | \`main\` | \`canary\` | Every Push | Snapshot (e.g., \`1.7.4-canary...\`) | Dev, internal testing |
161
-
162
- ## Prerequisites
163
-
164
- - ✅ \`NPM_TOKEN\` secret is configured in GitHub (owner or automation token with _publish_ scope).
165
- - ✅ \`GITHUB_TOKEN\` (built-in) has permissions to create PRs (enabled by default in new repos).
166
- - ✅ For stable releases: \`release\` branch exists and is protected.
167
-
168
- ## Canary Workflow (Automatic)
169
-
170
- Every commit pushed to \`main\` triggers the \`.github/workflows/publish-canary.yml\` workflow.
171
-
172
- 1. **Trigger**: Push to \`main\`.
173
- 2. **Versioning**: Runs \`changeset version --snapshot canary\` to generate a temporary snapshot version.
174
- 3. **Publish**: Packages are published to npm with the \`canary\` tag using \`changeset publish --tag canary\`.
175
-
176
- ### Consuming Canary Builds
177
-
178
- To install the latest bleeding-edge version:
179
-
180
- \`\`\`bash
181
- npm install @lssm/lib.contracts@canary
182
- # or
183
- bun add @lssm/lib.contracts@canary
184
- \`\`\`
185
-
186
- ## Stable Release Workflow (Manual)
187
-
188
- Stable releases are managed via the \`release\` branch using the standard [Changesets Action](https://github.com/changesets/action).
189
-
190
- 1. **Develop on \`main\`**: Create features and fixes.
191
- 2. **Add Changesets**: Run \`bun changeset\` to document changes and impact (major/minor/patch).
192
- 3. **Merge to \`release\`**: When ready to ship, open a PR from \`main\` to \`release\` or merge manually.
193
- 4. **"Version Packages" PR**:
194
- - The GitHub Action detects new changesets and automatically creates a Pull Request titled **"Version Packages"**.
195
- - This PR contains the version bumps and updated \`CHANGELOG.md\` files.
196
- 5. **Merge & Publish**:
197
- - Review and merge the "Version Packages" PR.
198
- - The Action runs again, detects the versions have been bumped, builds the libraries, and publishes them to npm with the \`latest\` tag.
199
-
200
- ### Publishing Steps
201
-
202
- 1. Ensure all changesets are present on \`main\`.
203
- 2. Merge \`main\` into \`release\`:
204
- \`\`\`bash
205
- git checkout release
206
- git pull origin release
207
- git merge main
208
- git push origin release
209
- \`\`\`
210
- 3. Go to GitHub Pull Requests. You will see a **"Version Packages"** PR created by the bot.
211
- 4. Merge that PR.
212
- 5. The release is now live on npm!
213
-
214
- ## Manual Verification (Optional)
215
-
216
- Before publishing a new version you can run:
217
-
218
- \`\`\`bash
219
- bun run build:not-apps
220
- npx npm-packlist --json packages/libs/contracts
221
- \`\`\`
222
-
223
- ## Rollback
224
-
225
- If a publish fails mid-way, re-run the workflow once the issue is fixed. Already published packages are skipped automatically. Use \`npm deprecate <package>@<version>\` if we need to warn consumers about a broken release.
226
- `
227
- }];
228
- a(t$26);
229
-
230
- //#endregion
231
- //#region ../../libs/contracts/dist/docs/accessibility_wcag_compliance_specs.docblock.js
232
- const t$25 = [{
233
- id: `docs.accessibility_wcag_compliance_specs`,
234
- title: `Accessibility & WCAG Compliance — **specs.md**`,
235
- summary: `> **Goal:** Ship interfaces that are usable by everyone, by default. This spec sets non‑negotiable rules, checklists, and CI gates to meet **WCAG\xA02.2 AA** (aim for AAA where low‑cost), align with **EN\xA0301\xA0549** (EU), and keep parity on **web (Next.js)** and **mobile (Expo/React\xA0Native)**.`,
236
- kind: `reference`,
237
- visibility: `public`,
238
- route: `/docs/accessibility_wcag_compliance_specs`,
239
- tags: [`accessibility_wcag_compliance_specs`],
240
- body: `# Accessibility & WCAG Compliance — **specs.md**
241
-
242
- > **Goal:** Ship interfaces that are usable by everyone, by default. This spec sets non‑negotiable rules, checklists, and CI gates to meet **WCAG\xA02.2 AA** (aim for AAA where low‑cost), align with **EN\xA0301\xA0549** (EU), and keep parity on **web (Next.js)** and **mobile (Expo/React\xA0Native)**.
243
-
244
- ---
245
-
246
- ## 0) Scope & Principles
247
-
248
- - **Standards:** WCAG\xA02.2\xA0AA (incl. new 2.2 SCs: Focus Not Obscured, Focus Appearance, Target Size, Dragging Movements, Accessible Authentication, Redundant Entry). EN\xA0301\xA0549 compliance by conformance to WCAG.
249
- - **Principles:** Perceivable, Operable, Understandable, Robust (POUR).
250
- - **Rule of ARIA:** “No ARIA is better than bad ARIA.” Prefer native elements.
251
- - **Definition of Done (DoD):** No Critical/Major a11y issues in CI; keyboard complete; SR (screen reader) smoke test passed; contrasts pass; acceptance criteria below satisfied.
252
- - **Repo Alignment:** Web apps use **Radix Primitives + shadcn** wrappers centralized in \`packages/lssm/libs/ui-kit-web\`. Prefer those components over per‑app duplicates (\`packages/*/apps/*/src/components/ui\`). When missing, add to \`ui-kit-web\` first, then adopt app‑side.
253
-
254
- ---
255
-
256
- ## 1) Design Requirements (Design System & Tokens)
257
-
258
- **1.1 Color & Contrast**
259
-
260
- - Body text, icons essential to meaning: **≥\xA04.5:1**; large text (≥\xA018.66px regular / 14px bold): **≥\xA03:1**.
261
- - Interactive states (default/hover/active/disabled/focus) must maintain contrast **≥\xA03:1** against adjacent colors; text within components follows text ratios.
262
- - Provide light & dark themes with tokens that guarantee minimums. **Never rely solely on color** to convey meaning; pair with text, shape, or icon.
263
-
264
- **1.2 Focus Indicators (WCAG\xA02.4.11/12)**
265
-
266
- - Every interactive element has a **visible focus** with clear offset; indicator contrast **≥\xA03:1** vs adjacent colors and indicator **area ≥\xA02\xA0CSS\xA0px** thick.
267
- - Focus **must not be obscured** by sticky headers/footers or scroll containers.
268
-
269
- **1.3 Motion & Preferences**
270
-
271
- - Respect \`prefers-reduced-motion\`: suppress large parallax, auto‑animations; provide instant alternatives.
272
- - Avoid motion that could trigger vestibular issues; under PRM, use fade/scale under **150ms**.
273
-
274
- **1.4 Target Size (2.5.8)**
275
-
276
- - Hit areas **≥\xA024×24\xA0CSS\xA0px** (web) and **≥\xA044×44\xA0dp** (mobile) unless exempt.
277
-
278
- **1.5 Typography & Layout**
279
-
280
- - Support zoom to **400%** without loss of content/functionality; responsive reflow at **320\xA0CSS\xA0px** width.
281
- - Maintain clear heading hierarchy (h1…h6), one **h1** per view.
282
-
283
- - Repository baseline (Web): default body text uses Tailwind \`text-lg\` (≈18px). As of 2025‑09‑20, the repository bumped all Tailwind typography scale usages by +1 step (e.g., \`text-sm\`→\`text-base\`, \`text-base\`→\`text-lg\`, …, \`text-8xl\`→\`text-9xl\`). For long‑form content, default to \`prose-lg\`.
284
- - Do not use \`text-xs\` for body copy. Reserve \`text-sm\` only for non‑essential meta (timestamps, fine print) while ensuring contrast and touch targets remain compliant.
285
- - When increasing font size, ensure line height supports readability. Prefer Tailwind defaults or \`leading-relaxed\`/\`leading-7\` for body text where dense blocks appear.
286
-
287
- **1.6 Iconography & Imagery**
288
-
289
- - Decorative images: \`alt=""\` or \`aria-hidden="true"\`.
290
- - Informative images: concise, specific **alt**; complex charts require a **data table or long description**.
291
-
292
- ---
293
-
294
- ## 2) Content Requirements (UX Writing)
295
-
296
- - Links say **what happens** (avoid “click here”).
297
- - Buttons start with verbs; avoid ambiguous labels.
298
- - Form labels are **visible**; placeholders are **not labels**.
299
- - Error messages: human + programmatic association; avoid color‑only.
300
- - Authentication: allow **copy/paste**, password managers, and avoid cognitive tests alone (**3.3.7/3.3.8/3.3.9**).
301
- - Avoid CAPTCHAs that block users; if unavoidable, provide **multiple alternatives** (logic-free).
302
-
303
- ---
304
-
305
- ## 3) Engineering Requirements (Web — Next.js/React)
306
-
307
- > Use and extend \`packages/lssm/libs/ui-kit-web\` as the default UI surface. It wraps **Radix** primitives with sensible a11y defaults (focus rings, roles, keyboard, ARIA binding). When a gap exists, add it to \`ui-kit-web\` first.
308
-
309
- **3.1 Semantics & Landmarks**
310
-
311
- - Use native elements: \`<button>\`, \`<a href>\`, \`<label for>\`, \`<fieldset>\`, \`<legend>\`, \`<table>\`, etc.
312
- - Landmarks per page: \`header\`, \`nav\`, \`main\`, \`aside\`, \`footer\`. Provide a **Skip to main content** link.
313
- - Provide a **Route Announcer** (\`aria-live="polite"\`) and move focus to page **h1** after navigation.
314
-
315
- **3.2 Keyboard**
316
-
317
- - All functionality available with keyboard alone. Tab order follows DOM/visual order; **no keyboard traps**.
318
- - Common bindings:
319
- - Space/Enter → activate button; Enter on link;
320
- - Esc closes dialogs/menus;
321
- - Arrow keys for lists/menus/tablists with **roving tabindex**.
322
-
323
- **3.3 Focus Management**
324
-
325
- - On route change (Next.js), move focus to the page \`<h1>\` or container and announce via a live region.
326
- - Dialogs/menus: **trap focus** inside; return focus to invoking control on close.
327
- - Don’t steal focus except after explicit user action.
328
-
329
- **3.4 Forms**
330
-
331
- - Each input has a \`<label>\` or \`aria-label\`. Group related inputs with \`<fieldset><legend>\`.
332
- - Associate errors via \`aria-describedby\` or inline IDs; announce with \`role="alert"\` (assertive only for critical).
333
- - Provide **autocomplete** tokens for known fields; show **inline validation** and do not block on **onBlur** alone.
334
-
335
- **3.5 ARIA Usage**
336
-
337
- - Only when needed; match patterns (dialog, menu, combobox, tablist, listbox) per ARIA Authoring Practices.
338
- - Ensure **name/role/value** are programmatically determinable.
339
-
340
- **3.6 Media**
341
-
342
- - Videos: **captions**; provide **transcripts** for audio; audio descriptions for essential visual info.
343
- - No auto‑playing audio. Auto‑playing video must be muted and pausable; provide controls.
344
-
345
- **3.7 Tables & Data**
346
-
347
- - Use \`<th scope>\` for headers; captions via \`<caption>\`; announce sorting via \`aria-sort\`.
348
- - Provide CSV/JSON export where charts are primary.
349
-
350
- **3.8 Performance & Robustness**
351
-
352
- - Avoid content shifts that move focus; reserve space or use skeletons.
353
- - Maintain accessible names through hydration/SSR; avoid \`dangerouslySetInnerHTML\` where possible.
354
-
355
- **3.9 Next.js specifics**
356
-
357
- - Use \`next/link\` for navigation; ensure links are **links**, not buttons.
358
- - \`next/image\` must include **alt** (empty if decorative).
359
- - Announce route changes with a **global live region** and shift focus to the new view.
360
-
361
- **3.10 Accessibility library integration**
362
-
363
- - Import \`@lssm/lib.accessibility\` at app root. It auto-imports its \`styles.css\` via the package entry; ensure bundlers keep CSS side effects. If your app tree-shakes CSS, explicitly import the stylesheet once in your root layout:
364
-
365
- \`\`\`tsx
366
- // app/layout.tsx
367
- import '@lssm/lib.accessibility'; // includes tokens and provider exports
368
- // or if needed: import '@lssm/lib.accessibility/src/styles.css';
369
- \`\`\`
370
-
371
- - Wrap the app with \`AccessibilityProvider\` and include an element with \`id="main"\` for the skip link target.
372
-
373
- ---
374
-
375
- ## 3b) lssm/ui-kit-web — Component Patterns & Defaults
376
-
377
- > Source: \`packages/lssm/libs/ui-kit-web/ui/*\`
378
-
379
- - **Button/Input/Textarea**: Built‑in \`focus-visible\` rings; ensure visible labels via \`FormLabel\` or \`aria-label\`.
380
- - **Form** (\`form.tsx\`): \`FormControl\` wires \`aria-invalid\` and \`aria-describedby\` to \`FormMessage\` and \`FormDescription\`. Prefer \`FormMessage\` for inline errors. Add \`role="alert"\` only for critical.
381
- - **Dialog/Sheet/Dropdown**: Use Radix wrappers for focus‑trap and return‑focus. Provide \`DialogTitle\` + \`DialogDescription\` for name/description.
382
- - **Select/Combobox**: Prefer \`SelectTrigger\` with visible label; for icon‑only triggers, supply \`aria-label\`. Document examples in each app.
383
- - **Tabs**: Use \`TabsList\`, \`TabsTrigger\`, \`TabsContent\`; names are programmatically determinable.
384
- - **Toast/Toaster**: Prefer non‑blocking announcements; map critical to assertive region; include action buttons with clear labels.
385
- - **Table**: Use \`TableCaption\`; ensure \`TableHead\` cells use proper \`scope\`. Provide \`aria-sort\` on sortable headers.
386
- - **Utilities to add (repo action)**:
387
- - \`SkipLink\` component and pattern in layouts.
388
- - \`RouteAnnouncer\` (\`aria-live="polite"\`) and **FocusOnRouteChange** helper.
389
- - \`VisuallyHidden\` wrapper (Radix visually-hidden or minimal utility).
390
- - \`useReducedMotion\` helper; honor in animated components.
391
- - Touch‑size variants (≥44×44) for interactive atoms.
392
-
393
- ---
394
-
395
- ## 4) Engineering Requirements (Mobile — Expo/React\xA0Native)
396
-
397
- - Set \`accessibilityLabel\`, \`accessibilityHint\`, and \`accessibilityRole\` on touchables.
398
- - Ensure **hit slop** / min size **≥\xA044×44\xA0dp**.
399
- - Support Dynamic Type / font scaling; no clipped text at **200%**.
400
- - Respect **Invert Colors** and **Reduce Motion**; avoid flashing.
401
- - Group related items with \`accessibilityElements\` ordering; hide decoration with \`accessible={false}\` or \`importantForAccessibility="no-hide-descendants"\` when appropriate.
402
- - Test with **VoiceOver (iOS)** and **TalkBack (Android)**.
403
-
404
- ---
405
-
406
- ## 5) Component Patterns (Acceptance Rules)
407
-
408
- **Buttons & Links**
409
-
410
- - Use \`<button>\` for actions, \`<a href>\` for navigation. Provide disabled states that are perceivable beyond color.
411
-
412
- **Navigation**
413
-
414
- - Provide **Skip link**. One primary nav landmark. Indicate current page (\`aria-current="page"\`).
415
-
416
- **Menus/Combobox/Autocomplete**
417
-
418
- - Follow ARIA patterns: focus moves into list; \`aria-expanded\`, \`aria-controls\`, \`aria-activedescendant\` when applicable; Esc closes; typing filters.
419
-
420
- **Modals/Dialogs**
421
-
422
- - \`role="dialog"\` or \`alertdialog\` with **label**; focus trapped; background inert; Esc closes; return focus to trigger.
423
-
424
- **Tabs**
425
-
426
- - \`role="tablist"\`; tabs are in the tab order; arrow keys switch focus; content is \`role="tabpanel"\` with \`aria-labelledby\`.
427
-
428
- **Toasts/Notifications**
429
-
430
- - Non-critical: \`aria-live="polite"\`; critical: \`role="alert"\` sparingly.
431
-
432
- **Infinite Scroll / “Load More”**
433
-
434
- - Provide **Load more** control; announce new content to SR; preserve keyboard position.
435
-
436
- **Drag & Drop (2.5.7)**
437
-
438
- - Provide **non‑drag** alternative (e.g., move up/down buttons).
439
-
440
- **Charts & Maps**
441
-
442
- - Provide **table alternative** or textual summary; keyboard access to datapoints where interactive.
443
-
444
- ---
445
-
446
- ## 6) Testing & CI (Blocking Gates)
447
-
448
- **Static & Unit**
449
-
450
- - \`eslint-plugin-jsx-a11y\` — error on violations.
451
- - \`jest-axe\` — unit tests for components.
452
-
453
- **Automated Integration**
454
-
455
- - \`axe-core\` via Playwright or Cypress on critical flows.
456
- - \`pa11y-ci\` on key routes; threshold: **0 Critical / 0 Serious** to merge.
457
- - Lighthouse CI a11y score **≥\xA095** on target pages.
458
-
459
- **Manual QA (per release)**
460
-
461
- - **Keyboard patrol:** navigate primary flows without mouse.
462
- - **Screen reader smoke:** NVDA (Windows) or VoiceOver (macOS/iOS) across login, navigation, forms, dialogs.
463
- - **Zoom & Reflow:** 200–400% & 320\xA0px width.
464
- - **Color/Contrast check:** tokens in both themes.
465
-
466
- **Reporting**
467
-
468
- - A11y issues labeled: \`a11y-blocker\`, \`a11y-bug\`, \`a11y-enhancement\` with WCAG ref.
469
-
470
- ---
471
-
472
- ## 7) Repository‑Specific Adoption Plan
473
-
474
- - Centralize UI usage on \`packages/lssm/libs/ui-kit-web\` and de‑duplicate per‑app \`components/ui\` where feasible.
475
- - Introduce \`SkipLink\`, \`RouteAnnouncer\`, \`FocusOnRouteChange\`, and \`VisuallyHidden\` in \`ui-kit-web\`. Adopt in app layouts (\`app/layout.tsx\`) first.
476
- - Add \`useReducedMotion\` and wire into animated components (e.g., \`drawer\`, \`tooltip\`, \`carousel\`).
477
- - Add touch‑size variants to \`Button\`, \`IconButton\`, \`TabsTrigger\`, toggles.
478
- - Document Select label patterns and error association in Forms.
479
-
480
- ---
481
-
482
- ## 8) Code Snippets
483
-
484
- **Skip Link**
485
-
486
- \`\`\`html
487
- <a
488
- class="sr-only focus:not-sr-only focus-visible:outline focus-visible:ring-4 focus-visible:ring-offset-2"
489
- href="#main"
490
- >Skip to main content</a
491
- >
492
- <main id="main">…</main>
493
- \`\`\`
494
-
495
- **Dialog (Radix + shadcn/ui) — essentials**
496
-
497
- \`\`\`tsx
498
- // Ensure label, description, focus trap, and return focus on close remain intact
499
- <Dialog>
500
- <DialogTrigger asChild>
501
- <button aria-haspopup="dialog">Open settings</button>
502
- </DialogTrigger>
503
- <DialogContent aria-describedby="settings-desc">
504
- <DialogTitle>Settings</DialogTitle>
505
- <p id="settings-desc">Update your preferences.</p>
506
- <DialogClose asChild>
507
- <button>Close</button>
508
- </DialogClose>
509
- </DialogContent>
510
- </Dialog>
511
- \`\`\`
512
-
513
- **Form error association**
514
-
515
- \`\`\`tsx
516
- <label htmlFor="email">Email</label>
517
- <input id="email" name="email" type="email" aria-describedby="email-err" />
518
- <p id="email-err" role="alert">Enter a valid email.</p>
519
- \`\`\`
520
-
521
- **Route change announcement (Next.js)**
522
-
523
- \`\`\`tsx
524
- // Add once at app root
525
- <div
526
- aria-live="polite"
527
- aria-atomic="true"
528
- id="route-announcer"
529
- className="sr-only"
530
- />
531
- \`\`\`
532
-
533
- ---
534
-
535
- ## 9) Exceptions & Waivers
536
-
537
- - If a criterion cannot be met, file an issue with: context, attempted alternatives, WCAG reference, impact assessment, and a remediation date. **Temporary waivers only.**
538
-
539
- ---
540
-
541
- ## 10) Ownership
542
-
543
- - **Design:** maintains token contrast, component specs.
544
- - **Engineering:** enforces CI gates, implements patterns.
545
- - **QA:** runs manual checks per release.
546
- - **PM:** blocks release if AA not met on user‑visible flows.
547
-
548
- ---
549
-
550
- ## 11) References (internalize; no external dependency at runtime)
551
-
552
- - WCAG\xA02.2 (AA), EN\xA0301\xA0549. ARIA Authoring Practices. Platform HIG (Apple, Material).
553
- - \`packages/lssm/libs/ui-kit-web\` as the canonical UI source for web.
554
-
555
- > **Bottom line:** Shipping means **accessible by default**. We don’t trade a11y for speed; we bake it into speed.
556
-
557
- ---
558
-
559
- ## 12) Adoption Status (2025-09-23)
560
-
561
- - web-artisan: AccessibilityProvider integrated; sr-only/forced-colors applied; 44x44 targets; forms announce errors; jest-axe and cypress-axe in place.
562
- - web-strit: AccessibilityProvider integrated; forced-colors, sr-only; forms announce errors; 44x44 targets; contrast tokens and text-scale wired; jest-axe and cypress-axe in place.
563
- - web-coliving: AccessibilityProvider integrated; forced-colors and focus visibility added; text-scale wired; landing pages converted to \`Section\`/stacks with text-lg defaults; CTA capture standardized; ESLint guard for text-xs in main content; jest-axe and cypress-axe in place. Next: audit icon-only controls and ensure 44x44 targets; add role="alert" where critical.
564
-
565
- > CI gates: run eslint a11y, jest-axe on components, and cypress-axe on critical flows per app.
566
-
567
- ---
568
-
569
- ## 13) CI Hardening & Visual QA
570
-
571
- - Linting: Run eslint with jsx-a11y rules across all web apps; block on violations.
572
- - Unit: Run jest-axe for ui-kit-web and app-level components.
573
- - Integration: cypress-axe on key flows (auth, forms, dialogs, tables).
574
- - Synthetic scans: pa11y-ci on critical pages (0 Critical/Serious policy).
575
- - Performance/A11y audit: Lighthouse CI with a11y score >= 95 on target routes.
576
- - Artifacts: Upload pa11y and Lighthouse reports per PR; annotate failures.
577
-
578
- ### Recent additions (2025-09-26)
579
-
580
- - AutocompleteInput (groceries): Upgraded to ARIA combobox pattern with \`aria-controls\`, \`aria-activedescendant\`, \`Escape\`/\`Tab\` handling, and labelled listbox.
581
- - Cypress a11y tests added for furniture and incidents modules on \`/modules\` and operators flows; checks run axe with critical/serious impacts.
582
-
583
- ## 14) Accessibility Telemetry (PostHog)
584
-
585
- - Events (anonymized): a11y_pref_changed (text_scale, contrast_mode, reduce_motion), a11y_panel_opened.
586
- - Properties: app, route, previous_value, new_value, timestamp.
587
- - Dashboards: Adoption over time, per app/route; correlation with reduced bounce on forms.
588
- - Privacy: No PII; aggregate only.
589
- `
590
- }];
591
- a(t$25);
592
-
593
- //#endregion
594
- //#region ../../libs/contracts/dist/docs/tech/PHASE_1_QUICKSTART.docblock.js
595
- const t$24 = [{
596
- id: `docs.tech.PHASE_1_QUICKSTART`,
597
- title: `Phase 1: API Reference Index`,
598
- summary: `Quick reference for all new Phase 1 APIs.`,
599
- kind: `reference`,
600
- visibility: `public`,
601
- route: `/docs/tech/PHASE_1_QUICKSTART`,
602
- tags: [`tech`, `PHASE_1_QUICKSTART`],
603
- body: `# Phase 1: API Reference Index
604
-
605
- Quick reference for all new Phase 1 APIs.
606
-
607
- ---
608
-
609
- ## @lssm/lib.multi-tenancy
610
-
611
- ### RLS
612
- \`\`\`typescript
613
- import { createRlsMiddleware, type TenantIdProvider } from '@lssm/lib.multi-tenancy/rls';
614
- \`\`\`
615
-
616
- ### Provisioning
617
- \`\`\`typescript
618
- import {
619
- TenantProvisioningService,
620
- type CreateTenantInput,
621
- type TenantProvisioningConfig
622
- } from '@lssm/lib.multi-tenancy/provisioning';
623
- \`\`\`
624
-
625
- ### Isolation
626
- \`\`\`typescript
627
- import { IsolationValidator } from '@lssm/lib.multi-tenancy/isolation';
628
- \`\`\`
629
-
630
- ---
631
-
632
- ## @lssm/lib.observability
633
-
634
- ### Tracing
635
- \`\`\`typescript
636
- import {
637
- getTracer,
638
- traceAsync,
639
- traceSync,
640
- createTracingMiddleware
641
- } from '@lssm/lib.observability/tracing';
642
- \`\`\`
643
-
644
- ### Metrics
645
- \`\`\`typescript
646
- import {
647
- getMeter,
648
- createCounter,
649
- createUpDownCounter,
650
- createHistogram,
651
- standardMetrics
652
- } from '@lssm/lib.observability/metrics';
653
- \`\`\`
654
-
655
- ### Logging
656
- \`\`\`typescript
657
- import {
658
- Logger,
659
- logger,
660
- type LogLevel,
661
- type LogEntry
662
- } from '@lssm/lib.observability/logging';
663
- \`\`\`
664
-
665
- ---
666
-
667
- ## @lssm/lib.resilience
668
-
669
- ### Circuit Breaker
670
- \`\`\`typescript
671
- import {
672
- CircuitBreaker,
673
- type CircuitState,
674
- type CircuitBreakerConfig
675
- } from '@lssm/lib.resilience/circuit-breaker';
676
- \`\`\`
677
-
678
- ### Retry
679
- \`\`\`typescript
680
- import { retry } from '@lssm/lib.resilience/retry';
681
- \`\`\`
682
-
683
- ### Timeout
684
- \`\`\`typescript
685
- import { timeout } from '@lssm/lib.resilience/timeout';
686
- \`\`\`
687
-
688
- ### Fallback
689
- \`\`\`typescript
690
- import { fallback } from '@lssm/lib.resilience/fallback';
691
- \`\`\`
692
-
693
- ---
694
-
695
- ## Enhanced: @lssm/lib.contracts
696
-
697
- ### DataViews
698
- \`\`\`typescript
699
- import { DataViewQueryGenerator } from '@lssm/lib.contracts/data-views/query-generator';
700
- import { DataViewRuntime } from '@lssm/lib.contracts/data-views/runtime';
701
- \`\`\`
702
-
703
- ### Workflows
704
- \`\`\`typescript
705
- import { SLAMonitor, type SLABreachEvent } from '@lssm/lib.contracts/workflow/sla-monitor';
706
- import { PrismaStateStore } from '@lssm/lib.contracts/workflow/adapters/db-adapter';
707
- \`\`\`
708
-
709
- ---
710
-
711
- ## Enhanced: @lssm/lib.design-system
712
-
713
- ### DataView Components
714
- \`\`\`typescript
715
- import { DataViewRenderer } from '@lssm/lib.design-system/components/data-view/DataViewRenderer';
716
- // Also available: DataViewList, DataViewTable, DataViewDetail
717
- \`\`\`
718
-
719
- ---
720
-
721
- ## Usage Examples
722
-
723
- ### Complete Workflow with All Features
724
-
725
- \`\`\`typescript
726
- import { WorkflowRunner } from '@lssm/lib.contracts/workflow/runner';
727
- import { PrismaStateStore } from '@lssm/lib.contracts/workflow/adapters/db-adapter';
728
- import { SLAMonitor } from '@lssm/lib.contracts/workflow/sla-monitor';
729
- import { CircuitBreaker } from '@lssm/lib.resilience/circuit-breaker';
730
- import { traceAsync } from '@lssm/lib.observability/tracing';
731
-
732
- const runner = new WorkflowRunner({
733
- registry,
734
- stateStore: new PrismaStateStore(db),
735
- opExecutor: async (op, input, ctx) => {
736
- return traceAsync(\`op.\${op.name}\`, async (span) => {
737
- span.setAttribute('operation', op.name);
738
- const breaker = getCircuitBreaker(op.name);
739
- return breaker.execute(() => executeOperation(op, input, ctx));
740
- });
741
- },
742
- eventEmitter: (event, payload) => {
743
- if (event.startsWith('workflow.')) {
744
- logger.info(event, payload);
745
- }
746
- },
747
- });
748
-
749
- const monitor = new SLAMonitor((event, payload) => {
750
- logger.warn('SLA_BREACH', payload);
751
- alertOps(payload);
752
- });
753
-
754
- // Start workflow
755
- const workflowId = await runner.start('payment.flow', 1);
756
-
757
- // Monitor SLA
758
- const state = await runner.getState(workflowId);
759
- const spec = registry.get('payment.flow', 1);
760
- monitor.check(state, spec!);
761
- \`\`\`
762
-
763
- ### Complete DataView with Observability
764
-
765
- \`\`\`typescript
766
- import { DataViewRenderer } from '@lssm/lib.design-system';
767
- import { DataViewQueryGenerator } from '@lssm/lib.contracts/data-views/query-generator';
768
- import { traceAsync } from '@lssm/lib.observability/tracing';
769
- import { MyDataView } from './specs/users.data-view';
770
-
771
- export function UserListPage() {
772
- const [page, setPage] = useState(1);
773
- const [users, setUsers] = useState([]);
774
-
775
- const loadUsers = async () => {
776
- return traceAsync('load_users', async (span) => {
777
- const generator = new DataViewQueryGenerator(MyDataView);
778
- const query = generator.generate({ pagination: { page, pageSize: 20 } });
779
-
780
- span.setAttribute('page', page);
781
- const result = await api.execute(query);
782
- setUsers(result.data);
783
- });
784
- };
785
-
786
- return (
787
- <DataViewRenderer
788
- spec={MyDataView}
789
- items={users}
790
- pagination={{ page, pageSize: 20, total: users.length }}
791
- onPageChange={setPage}
792
- />
793
- );
794
- }
795
- \`\`\`
796
-
797
- ### Complete Multi-Tenant Setup
798
-
799
- \`\`\`typescript
800
- // 1. RLS Middleware
801
- import { createRlsMiddleware } from '@lssm/lib.multi-tenancy/rls';
802
- db.$use(createRlsMiddleware(() => req.tenantId));
803
-
804
- // 2. Tenant Provisioning
805
- import { TenantProvisioningService } from '@lssm/lib.multi-tenancy/provisioning';
806
- const service = new TenantProvisioningService({ db });
807
-
808
- // 3. Create new tenant
809
- await service.provision({
810
- id: 'acme',
811
- name: 'Acme Corp',
812
- slug: 'acme',
813
- ownerEmail: 'admin@acme.com',
814
- });
815
-
816
- // 4. Validate isolation in tests
817
- import { IsolationValidator } from '@lssm/lib.multi-tenancy/isolation';
818
-
819
- test('queries are isolated', () => {
820
- const isValid = IsolationValidator.validateQuery(
821
- 'User',
822
- 'findMany',
823
- { where: { tenantId: 'acme' } },
824
- 'acme'
825
- );
826
- expect(isValid).toBe(true);
827
- });
828
- \`\`\`
829
-
830
- ---
831
-
832
- ## Testing
833
-
834
- ### Test Circuit Breakers
835
-
836
- \`\`\`typescript
837
- import { CircuitBreaker } from '@lssm/lib.resilience/circuit-breaker';
838
-
839
- test('circuit opens after threshold', async () => {
840
- const breaker = new CircuitBreaker({
841
- failureThreshold: 3,
842
- resetTimeoutMs: 5000,
843
- });
844
-
845
- // Trigger failures
846
- for (let i = 0; i < 3; i++) {
847
- await expect(
848
- breaker.execute(() => Promise.reject('error'))
849
- ).rejects.toThrow();
850
- }
851
-
852
- // Circuit should be open
853
- await expect(
854
- breaker.execute(() => Promise.resolve('ok'))
855
- ).rejects.toThrow('CircuitBreaker is OPEN');
856
- });
857
- \`\`\`
858
-
859
- ### Test Workflow Retry
860
-
861
- \`\`\`typescript
862
- test('workflow retries on failure', async () => {
863
- let attempts = 0;
864
- const opExecutor = async () => {
865
- attempts++;
866
- if (attempts < 3) throw new Error('fail');
867
- return 'success';
868
- };
869
-
870
- const runner = new WorkflowRunner({ /* ... */ opExecutor });
871
- await runner.executeStep(workflowId);
872
-
873
- expect(attempts).toBe(3);
874
- });
875
- \`\`\`
876
-
877
- ---
878
-
879
- ## Common Patterns
880
-
881
- ### Pattern: Resilient External Call
882
-
883
- \`\`\`typescript
884
- import { CircuitBreaker } from '@lssm/lib.resilience/circuit-breaker';
885
- import { retry } from '@lssm/lib.resilience/retry';
886
- import { timeout } from '@lssm/lib.resilience/timeout';
887
- import { traceAsync } from '@lssm/lib.observability/tracing';
888
-
889
- const breaker = new CircuitBreaker({ failureThreshold: 5, resetTimeoutMs: 30000 });
890
-
891
- export async function callExternalAPI(input: any) {
892
- return traceAsync('external_api_call', async (span) => {
893
- span.setAttribute('service', 'stripe');
894
-
895
- return breaker.execute(() =>
896
- retry(
897
- () => timeout(() => stripe.api.call(input), 5000),
898
- 3,
899
- 1000,
900
- true
901
- )
902
- );
903
- });
904
- }
905
- \`\`\`
906
-
907
- **Benefits**: Circuit breaker + retry + timeout + tracing in one place.
908
-
909
- ---
910
-
911
- ### Pattern: Tenant-Aware Operation
912
-
913
- \`\`\`typescript
914
- import { traceAsync } from '@lssm/lib.observability/tracing';
915
-
916
- export async function listUsers(tenantId: string) {
917
- return traceAsync('list_users', async (span) => {
918
- span.setAttribute('tenant_id', tenantId);
919
-
920
- // RLS middleware will inject WHERE tenantId = ?
921
- return db.user.findMany();
922
- });
923
- }
924
- \`\`\`
925
-
926
- ---
927
-
928
- ### Pattern: Monitored Workflow
929
-
930
- \`\`\`typescript
931
- import { WorkflowRunner } from '@lssm/lib.contracts/workflow/runner';
932
- import { SLAMonitor } from '@lssm/lib.contracts/workflow/sla-monitor';
933
- import { logger } from '@lssm/lib.observability/logging';
934
-
935
- const monitor = new SLAMonitor((event, payload) => {
936
- logger.warn('workflow.sla_breach', payload);
937
- });
938
-
939
- // In workflow poller
940
- const state = await runner.getState(workflowId);
941
- const spec = registry.get(state.workflowName, state.workflowVersion);
942
- if (spec) {
943
- monitor.check(state, spec);
944
- }
945
- \`\`\`
946
-
947
- ---
948
-
949
- ## Next Steps
950
-
951
- 1. **Implement one quick win** (30 minutes)
952
- 2. **Add tests for new functionality** (1 hour)
953
- 3. **Deploy to staging and verify observability** (1 hour)
954
- 4. **Roll out to production** (monitor closely)
955
- 5. **Read full documentation** at https://contractspec.lssm.tech/docs
956
-
957
- ---
958
-
959
- **Questions?** See \`/docs/guides/phase-1-migration\` or reach out via https://contractspec.lssm.tech/contact
960
-
961
-
962
-
963
-
964
-
965
-
966
-
967
-
968
-
969
-
970
-
971
-
972
-
973
-
974
-
975
-
976
-
977
-
978
-
979
-
980
-
981
-
982
-
983
-
984
-
985
- `
986
- }];
987
- a(t$24);
988
-
989
- //#endregion
990
- //#region ../../libs/contracts/dist/docs/tech/PHASE_2_AI_NATIVE_OPERATIONS.docblock.js
991
- const t$23 = [{
992
- id: `docs.tech.PHASE_2_AI_NATIVE_OPERATIONS`,
993
- title: `Phase 2: AI-Native Operations`,
994
- summary: `_Last updated: 2025-11-20_`,
995
- kind: `reference`,
996
- visibility: `public`,
997
- route: `/docs/tech/PHASE_2_AI_NATIVE_OPERATIONS`,
998
- tags: [`tech`, `PHASE_2_AI_NATIVE_OPERATIONS`],
999
- body: `# Phase 2: AI-Native Operations
1000
-
1001
- _Last updated: 2025-11-20_
1002
-
1003
- Phase 2 turns ContractSpec into an AI-first operations stack. The new libraries below are the building blocks used by support bots, growth agents, and human-in-the-loop flows.
1004
-
1005
- ## Libraries
1006
-
1007
- ### @lssm/lib.ai-agent
1008
-
1009
- - **Spec + Registry**: \`defineAgent\`, \`AgentRegistry\` keep agent definitions type-safe.
1010
- - **Runner**: \`AgentRunner\` drives LLM conversations, tool calls, retries, escalation, and telemetry hooks.
1011
- - **Tools**: \`ToolExecutor\` standardizes schema validation + timeouts.
1012
- - **Memory**: \`InMemoryAgentMemory\` + interfaces for plugging persistent stores.
1013
- - **Approvals**: new \`ApprovalWorkflow\` + \`InMemoryApprovalStore\` capture low-confidence decisions and surface them to reviewers.
1014
-
1015
- ### @lssm/lib.support-bot
1016
-
1017
- Composable support automation primitives:
1018
-
1019
- - \`TicketClassifier\` → heuristics + optional LLM validation for category, priority, sentiment.
1020
- - \`TicketResolver\` → RAG pipeline backed by knowledge spaces.
1021
- - \`AutoResponder\` → tone-aware drafts with citations.
1022
- - \`SupportFeedbackLoop\` → tracks resolution rates.
1023
- - \`createSupportTools\` → ready-made tool definitions for AgentRunner.
1024
-
1025
- ### @lssm/lib.content-gen
1026
-
1027
- Content generators that consume a \`ContentBrief\` and output production-ready assets:
1028
-
1029
- - \`BlogGenerator\`, \`LandingPageGenerator\`, \`EmailCampaignGenerator\`, \`SocialPostGenerator\`.
1030
- - \`SeoOptimizer\` builds metadata + schema markup.
1031
-
1032
- ### @lssm/lib.analytics
1033
-
1034
- Queryless analytics helpers:
1035
-
1036
- - \`FunnelAnalyzer\` – conversion/drop-off per step.
1037
- - \`CohortTracker\` – retention + LTV per cohort.
1038
- - \`ChurnPredictor\` – recency/frequency/error scoring.
1039
- - \`GrowthHypothesisGenerator\` – surfaces experiment ideas from metric trends.
1040
-
1041
- ### @lssm/lib.growth
1042
-
1043
- A/B testing toolkit:
1044
-
1045
- - \`ExperimentRegistry\` + \`ExperimentRunner\` – deterministic bucketing.
1046
- - \`ExperimentTracker\` – persist exposures + metrics.
1047
- - \`StatsEngine\` – Welch’s t-test + improvement calculations.
1048
-
1049
- ### Human-in-the-loop UI
1050
-
1051
- \`@lssm/lib.design-system\` now exposes:
1052
-
1053
- - \`ApprovalQueue\` – list + act on pending approvals.
1054
- - \`AgentMonitor\` – live view of agent sessions with confidence + status.
1055
-
1056
- ## Examples
1057
-
1058
- - \`examples/ai-support-bot/setup.ts\` shows ticket classification → resolution → response draft.
1059
- - \`examples/content-generation/generate.ts\` produces blog, landing, email, social, SEO output from one brief.
1060
-
1061
- ## Next Steps
1062
-
1063
- 1. Wire these libraries into vertical apps (H-Circle, ArtisanOS, etc.).
1064
- 2. Add background workers that consume the new analytics/growth trackers.
1065
- 3. Expand web-landing to highlight these Phase 2 capabilities (see separate TODO).
1066
- `
1067
- }];
1068
- a(t$23);
1069
-
1070
- //#endregion
1071
- //#region ../../libs/contracts/dist/docs/tech/PHASE_3_AUTO_EVOLUTION.docblock.js
1072
- const t$22 = [{
1073
- id: `docs.tech.PHASE_3_AUTO_EVOLUTION`,
1074
- title: `Phase 3: Auto-Evolution Technical Notes`,
1075
- summary: `**Status**: In progress`,
1076
- kind: `reference`,
1077
- visibility: `public`,
1078
- route: `/docs/tech/PHASE_3_AUTO_EVOLUTION`,
1079
- tags: [`tech`, `PHASE_3_AUTO_EVOLUTION`],
1080
- body: `# Phase 3: Auto-Evolution Technical Notes
1081
-
1082
- **Status**: In progress
1083
- **Last updated**: 2025-11-21
1084
-
1085
- Phase 3 introduces self-learning capabilities that analyze production telemetry, suggest new specs, safely roll out variants, and generate golden tests from real traffic. This document captures the main building blocks delivered in this iteration.
1086
-
1087
- ---
1088
-
1089
- ## 1. Libraries
1090
-
1091
- ### @lssm/lib.evolution
1092
-
1093
- - \`SpecAnalyzer\` converts raw telemetry samples into usage stats + anomalies.
1094
- - \`SpecGenerator\` produces \`SpecSuggestion\` objects and validates confidence thresholds.
1095
- - \`SpecSuggestionOrchestrator\` routes proposals through the AI approval workflow and writes approved specs to \`packages/libs/contracts/src/generated\`.
1096
- - Storage adapters:
1097
- - \`InMemorySpecSuggestionRepository\` for tests.
1098
- - \`PrismaSpecSuggestionRepository\` persists to the new Prisma model (see §4).
1099
- - \`FileSystemSuggestionWriter\` emits JSON envelopes for git review.
1100
-
1101
- ### @lssm/lib.observability
1102
-
1103
- - Added intent detection modules:
1104
- - \`IntentAggregator\` batches telemetry into rolling windows.
1105
- - \`IntentDetector\` surfaces latency/error/throughput regressions and sequential intents.
1106
- - \`EvolutionPipeline\` orchestrates aggregation → detection → intent events and exposes hooks for downstream orchestrators.
1107
- - \`createTracingMiddleware\` now accepts \`resolveOperation\`/\`onSample\` hooks to feed telemetry samples into the pipeline.
1108
-
1109
- ### @lssm/lib.growth
1110
-
1111
- - New \`spec-experiments\` module:
1112
- - \`SpecExperimentRegistry\`, \`SpecExperimentRunner\`, \`SpecExperimentAdapter\`.
1113
- - \`SpecExperimentAnalyzer\` + \`SpecExperimentController\` handle guardrails and staged rollouts.
1114
- - Helper \`createSpecVariantResolver\` plugs directly into \`HandlerCtx.specVariantResolver\`.
1115
- - \`SpecVariantResolver\` is now a first-class concept in \`@lssm/lib.contracts\`. The runtime will attempt to execute variant specs before falling back to the registered handler.
1116
-
1117
- ### @lssm/lib.testing
1118
-
1119
- - \`TrafficRecorder\` + \`TrafficStore\` capture production requests with sampling and sanitization hooks.
1120
- - \`GoldenTestGenerator\` converts \`TrafficSnapshot\`s into Vitest/Jest suites.
1121
- - \`generateVitestSuite\` / \`generateJestSuite\` output self-contained test files, and \`runGoldenTests\` offers a programmatic harness for CI pipelines.
1122
-
1123
- ---
1124
-
1125
- ## 2. Telemetry → Intent → Spec Pipeline
1126
-
1127
- 1. \`createTracingMiddleware({ onSample })\` emits \`TelemetrySample\`s for every HTTP request.
1128
- 2. \`IntentAggregator\` groups samples into statistical windows (default 15 minutes).
1129
- 3. \`IntentDetector\` raises signals for:
1130
- - Error spikes
1131
- - Latency regressions
1132
- - Throughput drops
1133
- - Sequential workflows that hint at missing specs
1134
- 4. \`EvolutionPipeline\` emits \`intent.detected\` events and hands them to \`SpecGenerator\`.
1135
- 5. \`SpecSuggestionOrchestrator\` persists suggestions, triggers approval workflows, and—upon approval—writes JSON envelopes to \`packages/.../contracts/src/generated\`.
1136
-
1137
- ---
1138
-
1139
- ## 3. Spec Experiments & Rollouts
1140
-
1141
- 1. Register spec experiments in \`SpecExperimentRegistry\` with control + variant bindings.
1142
- 2. Expose bucketed specs by attaching \`createSpecVariantResolver\` to \`HandlerCtx.specVariantResolver\` inside adapters.
1143
- 3. Record outcomes via \`SpecExperimentAdapter.trackOutcome()\` (latency + error metrics).
1144
- 4. \`SpecExperimentController\` uses guardrails from config and \`SpecExperimentAnalyzer\` to:
1145
- - Auto-rollback on error/latency breaches.
1146
- - Advance rollout stages (1% → 10% → 50% → 100%) when metrics stay green.
1147
-
1148
- ---
1149
-
1150
- ## 4. Data Models (Prisma)
1151
-
1152
- File: \`packages/libs/database/prisma/schema.prisma\`
1153
-
1154
- - \`SpecSuggestion\` – stores serialized suggestion payloads + statuses.
1155
- - \`IntentSnapshot\` – captured detector output for auditing/training.
1156
- - \`TrafficSnapshot\` – persisted production traffic (input/output/error blobs).
1157
- - \`SpecExperiment\` / \`SpecExperimentMetric\` – rollout state + metrics for each variant.
1158
-
1159
- > Run \`bun database generate\` after pulling to refresh the Prisma client.
1160
-
1161
- ---
1162
-
1163
- ## 5. Golden Test Workflow
1164
-
1165
- 1. Capture traffic via middleware or direct \`TrafficRecorder.record\`.
1166
- 2. Use the new CLI command to materialize suites:
1167
-
1168
- \`\`\`bash
1169
- contractspec test generate \\
1170
- --operation billing.createInvoice \\
1171
- --output tests/billing.createInvoice.golden.test.ts \\
1172
- --runner-import ./tests/run-operation \\
1173
- --runner-fn runBillingCommand \\
1174
- --from-production \\
1175
- --days 7 \\
1176
- --sample-rate 0.05
1177
- \`\`\`
1178
-
1179
- 3. Generated files import your runner and assert against recorded outputs (or expected errors for negative paths).
1180
-
1181
- ---
1182
-
1183
- ## 6. Operational Notes
1184
-
1185
- - **Approvals**: By default, every suggestion still requires human approval. \`EvolutionConfig.autoApproveThreshold\` can be tuned per environment but should remain conservative (<0.3) until OverlaySpec tooling lands.
1186
- - **Sampling**: Keep \`TrafficRecorder.sampleRate\` ≤ 0.05 in production to avoid sensitive payload storage; scrub PII through the \`sanitize\` callback before persistence.
1187
- - **Rollouts**: Guardrails default to 5% error-rate and 750ms P99 latency. Override per experiment to match SLOs.
1188
-
1189
- ---
1190
-
1191
- ## 7. Next Steps
1192
-
1193
- 1. Wire \`SpecExperimentAdapter.trackOutcome\` into adapters (REST, GraphQL, Workers) so every execution logs metrics automatically.
1194
- 2. Add a UI for reviewing \`SpecSuggestion\` objects alongside approval status.
1195
- 3. Expand \`TrafficRecorder\` to ship directly to the Prisma-backed store (currently in-memory by default).
1196
- 4. Integrate \`EvolutionPipeline\` events with the Regenerator to close the loop (auto-open proposals + attach evidence).
1197
-
1198
-
1199
-
1200
-
1201
-
1202
-
1203
-
1204
-
1205
-
1206
-
1207
-
1208
-
1209
-
1210
-
1211
-
1212
-
1213
-
1214
-
1215
-
1216
-
1217
-
1218
-
1219
- `
1220
- }];
1221
- a(t$22);
1222
-
1223
- //#endregion
1224
- //#region ../../libs/contracts/dist/docs/tech/PHASE_4_PERSONALIZATION_ENGINE.docblock.js
1225
- const t$21 = [{
1226
- id: `docs.tech.PHASE_4_PERSONALIZATION_ENGINE`,
1227
- title: `Phase 4: Personalization Engine`,
1228
- summary: `**Status**: Complete`,
1229
- kind: `reference`,
1230
- visibility: `public`,
1231
- route: `/docs/tech/PHASE_4_PERSONALIZATION_ENGINE`,
1232
- tags: [`tech`, `PHASE_4_PERSONALIZATION_ENGINE`],
1233
- body: `# Phase 4: Personalization Engine
1234
-
1235
- **Status**: Complete
1236
- **Last updated**: 2025-11-21
1237
-
1238
- Phase 4 unlocks tenant-scoped personalization with zero bespoke code. We shipped three new libraries, a signing-aware Overlay editor, and the persistence layer required to observe usage and apply overlays safely.
1239
-
1240
- ---
1241
-
1242
- ## 1. Libraries
1243
-
1244
- ### @lssm/lib.overlay-engine
1245
-
1246
- - OverlaySpec types + validator mirror the public spec.
1247
- - Cryptographic signer (\`ed25519\`, \`rsa-pss-sha256\`) with canonical JSON serialization.
1248
- - Registry that merges tenant/role/user/device overlays with predictable specificity.
1249
- - React hooks (\`useOverlay\`, \`useOverlayFields\`) for client-side rendering.
1250
- - Runtime engine audits every applied overlay for traceability.
1251
-
1252
- ### @lssm/lib.personalization
1253
-
1254
- - Behavior tracker buffers field/feature/workflow events and exports OTel metrics.
1255
- - Analyzer summarizes field usage and workflow drop-offs into actionable insights.
1256
- - Adapter translates insights into overlay suggestions or workflow tweaks.
1257
- - In-memory store implementation + interface for plugging Prisma/ClickHouse later.
1258
-
1259
- ### @lssm/lib.workflow-composer
1260
-
1261
- - \`WorkflowComposer\` merges base workflows with tenant/role/device extensions.
1262
- - Step injection utilities keep transitions intact and validate anchor steps.
1263
- - Template helpers for common tenant review/approval, plus merge helpers for multi-scope extensions.
1264
-
1265
- ---
1266
-
1267
- ## 2. Overlay Editor App
1268
-
1269
- Path: \`packages/apps/overlay-editor\`
1270
-
1271
- - Next.js App Router UI for toggling field visibility, renaming labels, and reordering lists.
1272
- - Live JSON preview powered by \`defineOverlay\`.
1273
- - Server action that signs overlays via PEM private keys (Ed25519 by default) using the overlay engine signer.
1274
-
1275
- ---
1276
-
1277
- ## 3. Persistence
1278
-
1279
- Added Prisma models (see \`packages/libs/database/prisma/schema.prisma\`):
1280
-
1281
- - \`UserBehaviorEvent\` – field/feature/workflow telemetry.
1282
- - \`OverlaySigningKey\` – tenant managed signing keys with revocation timestamps.
1283
- - \`Overlay\` – stored overlays (tenant/user/role/device scope) plus signature metadata.
1284
-
1285
- ---
1286
-
1287
- ## 4. Integration Steps
1288
-
1289
- 1. Track usage inside apps via \`createBehaviorTracker\`.
1290
- 2. Periodically run \`BehaviorAnalyzer.analyze\` to generate insights.
1291
- 3. Convert insights into OverlaySpecs or Workflow extensions.
1292
- 4. Register tenant overlays in \`OverlayRegistry\` and serve via presentation runtimes.
1293
- 5. Compose workflows per tenant using \`WorkflowComposer\`.
1294
-
1295
- See the \`docs/tech/personalization/*\` guides for concrete examples.
1296
-
1297
-
1298
-
1299
-
1300
-
1301
-
1302
-
1303
-
1304
-
1305
-
1306
-
1307
-
1308
-
1309
-
1310
-
1311
-
1312
-
1313
-
1314
-
1315
-
1316
-
1317
-
1318
- `
1319
- }];
1320
- a(t$21);
1321
-
1322
- //#endregion
1323
- //#region ../../libs/contracts/dist/docs/tech/PHASE_5_ZERO_TOUCH_OPERATIONS.docblock.js
1324
- const t$20 = [{
1325
- id: `docs.tech.PHASE_5_ZERO_TOUCH_OPERATIONS`,
1326
- title: `Phase 5: Zero-Touch Operations`,
1327
- summary: `**Status**: In progress`,
1328
- kind: `reference`,
1329
- visibility: `public`,
1330
- route: `/docs/tech/PHASE_5_ZERO_TOUCH_OPERATIONS`,
1331
- tags: [`tech`, `PHASE_5_ZERO_TOUCH_OPERATIONS`],
1332
- body: "# Phase 5: Zero-Touch Operations\n\n**Status**: In progress \n**Last updated**: 2025-11-21\n\nPhase 5 delivers progressive delivery, SLO intelligence, cost attribution, and anomaly-driven remediation so the platform can deploy continuously without pager rotations.\n\n---\n\n## 1. New Libraries\n\n### @lssm/lib.progressive-delivery\n- `DeploymentStrategy` types capture canary vs blue-green rollouts.\n- `CanaryController` + `CanaryAnalyzer` orchestrate stage evaluation against telemetry thresholds.\n- `TrafficShifter` keeps stable/candidate splits in sync with feature-flag or router state.\n- `DeploymentCoordinator` drives stage progression, emits events, and triggers rollbacks.\n- `RollbackManager` encapsulates safe revert hooks (spec version revert, traffic shift, etc.).\n\n### @lssm/lib.slo\n- Declarative `SLODefinition` with latency + availability targets per capability/spec.\n- `SLOTracker` stores rolling snapshots + error budget positions.\n- `BurnRateCalculator` implements multi-window burn computations (fast vs slow burn).\n- `SLOMonitor` pushes incidents to Ops tooling automatically when burn exceeds thresholds.\n\n### @lssm/lib.cost-tracking\n- `CostTracker` normalizes DB/API/compute metrics into per-operation cost totals.\n- `BudgetAlertManager` raises tenant budget warnings (80% default) with contextual payloads.\n- `OptimizationRecommender` suggests batching, caching, or contract tweaks to cut spend.\n\n### Observability Anomaly Toolkit\n- `BaselineCalculator` establishes rolling intent metrics (latency, error rate, throughput).\n- `AnomalyDetector` flags spikes/drops via relative deltas after 10+ samples.\n- `RootCauseAnalyzer` correlates anomalies with recent deployments.\n- `AlertManager` deduplicates notifications and feeds MCP/SRE transports.\n\n---\n\n## 2. Data Model Additions\n\nFile: `packages/libs/database/prisma/schema.prisma`\n\n| Model | Purpose |\n| --- | --- |\n| `SLODefinition`, `SLOSnapshot`, `ErrorBudget`, `SLOIncident` | Persist definitions, rolling windows, and incidents. |\n| `OperationCost`, `TenantBudget`, `CostAlert`, `OptimizationSuggestion` | Track per-operation costs, budgets, and generated recommendations. |\n| `Deployment`, `DeploymentStage`, `RollbackEvent` | Audit progressive delivery runs and automated rollbacks. |\n| `MetricBaseline`, `AnomalyEvent` | Store computed baselines and anomaly evidence for training/analytics. |\n\nRun `bun database generate` after pulling to refresh the Prisma client.\n\n---\n\n## 3. Operational Flow\n\n1. **Deploy**: Define a `DeploymentStrategy` and feed telemetry via `@lssm/lib.observability`. Canary stages run automatically.\n2. **Protect**: `CanaryAnalyzer` evaluates error rate + latency thresholds. Failures trigger `RollbackManager`.\n3. **Observe**: `SLOMonitor` consumes snapshots and opens incidents when burn rate exceeds thresholds.\n4. **Optimize**: `CostTracker` aggregates spend per tenant + capability, while `OptimizationRecommender` surfaces fixes.\n5. **Detect**: Anomaly signals route to `RootCauseAnalyzer`, which links them to specific deployments for auto-rollback.\n\n---\n\n## 4. Integration Checklist\n\n1. Instrument adapters with `createTracingMiddleware({ onSample })` to feed metric points into `AnomalyDetector`.\n2. Register SLOs per critical operation (`billing.charge`, `knowledge.search`) and wire monitors to Ops notifications.\n3. Attach `CostTracker.recordSample` to workflow runners (DB instrumentation + external call wrappers).\n4. Store deployment metadata using the new Prisma models for auditing + UI surfacing.\n5. Update `@lssm/app.ops-console` (next iteration) to list deployments, SLO status, costs, and anomalies in one timeline.\n\n---\n\n## 5. Next Steps\n\n- Wire `DeploymentCoordinator` into the Contracts CLI so `contractspec deploy` can run staged rollouts.\n- Add UI for SLO dashboards (burn rate sparkline + incident feed).\n- Ship budget suggestions into Growth Agent for automated cost optimizations.\n- Connect `AnomalyEvent` stream to MCP agents for root-cause playbooks.\n"
1333
- }];
1334
- a(t$20);
1335
-
1336
- //#endregion
1337
- //#region ../../libs/contracts/dist/docs/tech/lifecycle-stage-system.docblock.js
1338
- const t$19 = [{
1339
- id: `docs.tech.lifecycle-stage-system`,
1340
- title: `ContractSpec Lifecycle Stage System – Technical Design`,
1341
- summary: `This document describes how ContractSpec implements lifecycle detection and guidance. It covers architecture, module boundaries, scoring heuristics, and integration points so libraries, modules, bundles, and Studio surfaces stay synchronized.`,
1342
- kind: `reference`,
1343
- visibility: `public`,
1344
- route: `/docs/tech/lifecycle-stage-system`,
1345
- tags: [`tech`, `lifecycle-stage-system`],
1346
- body: `## ContractSpec Lifecycle Stage System – Technical Design
1347
-
1348
- This document describes how ContractSpec implements lifecycle detection and guidance. It covers architecture, module boundaries, scoring heuristics, and integration points so libraries, modules, bundles, and Studio surfaces stay synchronized.
1349
-
1350
- ---
1351
-
1352
- ### 1. Architecture Overview
1353
-
1354
- \`\`\`
1355
- ┌──────────────────────┐
1356
- │ @lssm/lib.lifecycle │ Types, enums, helpers (pure data)
1357
- └───────────┬──────────┘
1358
-
1359
- ┌───────────▼──────────┐ ┌───────────────────────────┐
1360
- │ modules/lifecycle- │ │ modules/lifecycle-advisor │
1361
- │ core (detection) │ │ (guidance & ceremonies) │
1362
- └───────────┬──────────┘ └───────────┬───────────────┘
1363
- │ │
1364
- ├────────────┬──────────────┤
1365
- ▼ ▼ ▼
1366
- Adapters: analytics, intent, questionnaires
1367
-
1368
- ┌───────────▼──────────┐
1369
- │ bundles/lifecycle- │ Managed service for Studio
1370
- │ managed │ (REST handlers, AI agent) │
1371
- └───────────┬──────────┘
1372
-
1373
- ContractSpec Studio surfaces
1374
- (web/mobile APIs, CLI, docs)
1375
- \`\`\`
1376
-
1377
- - **Libraries** provide shared vocabulary.
1378
- - **Modules** encapsulate logic, accepting adapters to avoid environment-specific code.
1379
- - **Bundles** compose modules, register agents/events, and expose APIs for Studio.
1380
- - **Apps** (web-landing, future Studio views) consume bundle APIs; they do not reimplement logic. For web-landing we now resolve \`@lssm/bundle.contractspec-studio\` and \`@lssm/lib.database-contractspec-studio\` directly from their \`packages/.../src\` folders via \`tsconfig\` path aliases so Prisma stays on the server build and Turbopack no longer pulls the prebundled \`dist\` artifacts into client chunks.
1381
-
1382
- ---
1383
-
1384
- ### 2. Core Library (\`@lssm/lib.lifecycle\`)
1385
-
1386
- - Stage enum (0–6) with metadata (\`question\`, \`signals\`, \`traps\`).
1387
- - Axes types (\`ProductPhase\`, \`CompanyPhase\`, \`CapitalPhase\`).
1388
- - \`LifecycleSignal\` (source, metric, value, timestamp).
1389
- - \`LifecycleMetricSnapshot\` (aggregated numbers).
1390
- - \`LifecycleMilestone\`, \`LifecycleAction\`, \`LifecycleAssessment\` interfaces.
1391
- - Utility helpers:
1392
- - \`formatStageSummary(stage, assessment)\`
1393
- - \`rankStageCandidates(scores)\`
1394
-
1395
- The library exports **no runtime dependencies** so it can be imported from apps, modules, and bundles alike.
1396
-
1397
- ---
1398
-
1399
- ### 3. Lifecycle Core Module
1400
-
1401
- **Location:** \`packages/modules/lifecycle-core/\`
1402
-
1403
- #### Components
1404
- 1. **StageSignalCollector**
1405
- - Accepts adapter interfaces:
1406
- - \`AnalyticsAdapter\` (pulls metrics from \`@lssm/lib.analytics\` or fixture streams).
1407
- - \`IntentAdapter\` (hooks into \`@lssm/lib.observability\` intent detectors or logs).
1408
- - \`QuestionnaireAdapter\` (loads JSON questionnaires and responses).
1409
- - Produces normalized \`LifecycleSignal[]\`.
1410
-
1411
- 2. **StageScorer**
1412
- - Weighted scoring model:
1413
- - Base weight per stage (reflecting expected maturity).
1414
- - Feature weights (retention, revenue, team size, qualitative feedback).
1415
- - Confidence computed via variance of contributing signals.
1416
- - Supports pluggable scoring matrices via JSON config.
1417
- - Accepts sparse metric snapshots; the orchestrator sanitizes metrics to numeric-only records before persisting assessments so downstream analytics stay consistent.
1418
-
1419
- 3. **LifecycleOrchestrator**
1420
- - Coordinates collectors + scorer.
1421
- - Returns \`LifecycleAssessment\` with:
1422
- - \`stage\`, \`confidence\`, \`axisSnapshot\`, \`signalsUsed\`.
1423
- - Recommended focus areas (high-level categories only).
1424
- - Emits events (internally) when stage confidence crosses thresholds (consumed later by bundle).
1425
-
1426
- 4. **LifecycleMilestonePlanner**
1427
- - Loads \`milestones-catalog.json\` (no DB).
1428
- - Filters upcoming milestones per stage + axis.
1429
- - Tracks completion using provided IDs (caller persists).
1430
-
1431
- #### Data Files
1432
- - \`configs/stage-weights.json\`
1433
- - \`configs/milestones-catalog.json\`
1434
- - \`questionnaires/stage-readiness.json\`
1435
-
1436
- #### Extension Hooks
1437
- - All adapters exported as TypeScript interfaces.
1438
- - Implementations for analytics/intent can live in bundles or apps without modifying module code.
1439
-
1440
- ---
1441
-
1442
- ### 4. Lifecycle Advisor Module
1443
-
1444
- **Location:** \`packages/modules/lifecycle-advisor/\`
1445
-
1446
- #### Components
1447
- 1. **LifecycleRecommendationEngine**
1448
- - Consumes \`LifecycleAssessment\`.
1449
- - Maps gaps to \`LifecycleAction[]\` using rule tables (\`stage-playbooks.ts\`).
1450
- - Supports override hooks for customer-specific rules.
1451
-
1452
- 2. **ContractSpecLibraryRecommender**
1453
- - Maintains mapping from stage → recommended libraries/modules/bundles.
1454
- - Returns prioritized list with rationale and adoption prerequisites.
1455
-
1456
- 3. **LifecycleCeremonyDesigner**
1457
- - Provides textual/structural data for ceremonies (title, copy, animation cues, soundtrack references).
1458
- - Ensures low-tech friendly instructions (clear copy, undo guidance).
1459
-
1460
- 4. **AI Hooks**
1461
- - Defines prompt templates and tool manifests for lifecycle advisor agents (consumed by bundles).
1462
- - Keeps actual LLM integration outside module.
1463
-
1464
- ---
1465
-
1466
- ### 5. Managed Bundle (\`lifecycle-managed\`)
1467
-
1468
- **Responsibilities**
1469
- - Wire modules together.
1470
- - Provide HTTP/GraphQL handlers (exact transport optional).
1471
- - Register LifecycleAdvisorAgent via \`@lssm/lib.ai-agent\`.
1472
- - LifecycleAdvisorAgent meta: domain \`operations\`, owners \`team-lifecycle\`, stability \`experimental\`, tags \`guide/lifecycle/ops\` so ops tooling can route incidents quickly.
1473
- - Emit lifecycle events through \`@lssm/lib.bus\` + \`@lssm/lib.analytics\`.
1474
- - Integrate with \`contractspec-studio\` packages:
1475
- - Use Studio contracts for authentication/tenant context (without accessing tenant DBs).
1476
- - Store assessments in Studio-managed storage abstractions (in-memory or file-based for now).
1477
-
1478
- **APIs**
1479
- - \`POST /lifecycle/assessments\`: Accepts metrics + optional questionnaire answers. Returns \`LifecycleAssessment\`.
1480
- - \`GET /lifecycle/playbooks/:stage\`: Returns stage playbook + ceremonies.
1481
- - \`POST /lifecycle/advise\`: Invokes LifecycleAdvisorAgent with context.
1482
-
1483
- **Events**
1484
- - \`LifecycleAssessmentCreated\`
1485
- - \`LifecycleStageChanged\`
1486
- - \`LifecycleGuidanceConsumed\`
1487
-
1488
- ---
1489
-
1490
- ### 6. Library Enhancements
1491
-
1492
- | Library | Enhancement |
1493
- | --- | --- |
1494
- | \`@lssm/lib.analytics\` | Lifecycle metric collectors, helper to emit stage events, adapter implementation used by \`StageSignalCollector\`. |
1495
- | \`@lssm/lib.evolution\` | Accepts \`LifecycleContext\` when ranking spec anomalies/suggestions. |
1496
- | \`@lssm/lib.growth\` | Stage-specific experiment templates + guardrails referencing lifecycle enums. |
1497
- | \`@lssm/lib.observability\` | Lifecycle KPI pipeline definitions (drift detection, regression alerts). |
1498
-
1499
- Each enhancement must import stage types from \`@lssm/lib.lifecycle\`.
1500
-
1501
- ---
1502
-
1503
- ### 7. Feature Flags & Progressive Delivery
1504
-
1505
- - Add new flags in progressive-delivery library:
1506
- - \`LIFECYCLE_DETECTION_ALPHA\`
1507
- - \`LIFECYCLE_ADVISOR_ALPHA\`
1508
- - \`LIFECYCLE_MANAGED_SERVICE\`
1509
- - Bundles/modules should check flags before enabling workflows.
1510
- - Flags referenced in docs + Studio UI to avoid accidental exposure.
1511
-
1512
- ---
1513
-
1514
- ### 8. Analytics & Telemetry
1515
-
1516
- - Events defined in analytics library; consumed by bundle/app:
1517
- - \`lifecycle_assessment_run\`
1518
- - \`lifecycle_stage_changed\`
1519
- - \`lifecycle_guidance_consumed\`
1520
- - Observability pipeline includes:
1521
- - Composite lifecycle health metric (weighted sum of KPIs).
1522
- - Drift detection comparing stage predictions over time.
1523
- - Alert manager recipes for regression (e.g., PMF drop).
1524
-
1525
- ---
1526
-
1527
- ### 9. Testing Strategy
1528
-
1529
- 1. **Unit**
1530
- - StageScorer weight matrix.
1531
- - RecommendationEngine mapping.
1532
- - Library recommender stage coverage.
1533
-
1534
- 2. **Contract**
1535
- - Adapters: ensure mock adapters satisfy interfaces.
1536
- - Bundles: ensure HTTP handlers respect request/response contracts even without persistence.
1537
-
1538
- 3. **Integration**
1539
- - CLI example runs detection + guidance end-to-end on fixture data.
1540
- - Dashboard example renders assessments, verifying JSON structures remain stable.
1541
-
1542
- ---
1543
-
1544
- ### 10. Implementation Checklist
1545
-
1546
- - [ ] Documentation (product, tech, ops, user).
1547
- - [ ] Library creation (\`@lssm/lib.lifecycle\`).
1548
- - [ ] Modules (\`lifecycle-core\`, \`lifecycle-advisor\`).
1549
- - [ ] Bundle (\`lifecycle-managed\`) + Studio wiring.
1550
- - [ ] Library enhancements (analytics/evolution/growth/observability).
1551
- - [ ] Examples (CLI + dashboard).
1552
- - [ ] Feature flags + telemetry.
1553
- - [ ] Automated tests + fixtures.
1554
-
1555
- Keep this document in sync as modules evolve. When adding new stages or axes, update \`@lssm/lib.lifecycle\` first, then cascade to adapters, then refresh docs + Studio copy.*** End Patch*** End Patch
1556
-
1557
-
1558
- `
1559
- }];
1560
- a(t$19);
1561
-
1562
- //#endregion
1563
- //#region ../../libs/contracts/dist/docs/tech/presentation-runtime.docblock.js
1564
- const t$18 = [{
1565
- id: `docs.tech.presentation-runtime`,
1566
- title: `Presentation Runtime`,
1567
- summary: `Cross-platform runtime for list pages and presentation flows.`,
1568
- kind: `reference`,
1569
- visibility: `public`,
1570
- route: `/docs/tech/presentation-runtime`,
1571
- tags: [`tech`, `presentation-runtime`],
1572
- body: "## Presentation Runtime\n\nCross-platform runtime for list pages and presentation flows.\n\n### Packages\n\n- `@lssm/lib.presentation-runtime-core`: shared types and config helpers\n- `@lssm/lib.presentation-runtime-react`: React hooks (web/native-compatible API)\n- `@lssm/lib.presentation-runtime-react-native`: Native entrypoint (re-exports React API for now)\n\n### Next.js config helper\n\n```ts\n// next.config.mjs\nimport { withPresentationNextAliases } from '@lssm/lib.presentation-runtime-core/next';\n\nconst nextConfig = {\n webpack: (config) => withPresentationNextAliases(config),\n};\n\nexport default nextConfig;\n```\n\n### Metro config helper\n\n```js\n// metro.config.js (CJS)\nconst { getDefaultConfig } = require('expo/metro-config');\nconst {\n withPresentationMetroAliases,\n} = require('@lssm/lib.presentation-runtime-core/src/metro.cjs');\n\nconst projectRoot = __dirname;\nconst config = getDefaultConfig(projectRoot);\n\nmodule.exports = withPresentationMetroAliases(config);\n```\n\n### React hooks\n\n- `useListCoordinator`: URL + RHF + derived variables (no fetching)\n- `usePresentationController`: Same plus `fetcher` integration\n- `DataViewRenderer` (design-system): render `DataViewSpec` projections (`list`, `table`, `detail`, `grid`) using shared UI atoms\n\nBoth accept a `useUrlState` adapter. On web, use `useListUrlState` (design-system) or a Next adapter.\n\n### KYC molecules (bundle)\n\n- `ComplianceBadge` in `@lssm/bundle.strit/presentation/components/kyc` renders a status badge for KYC/compliance snapshots. It accepts a `state` (missing_core | incomplete | complete | expiring | unknown) and optional localized `labels`. Prefer consuming apps to pass translated labels (e.g., via `useT('appPlatformAdmin')`).\n\n### Markdown routes and llms.txt\n\n- Each web app exposes `/llms` (and `/llms.txt`, `/llms.md`) via rewrites. See [llmstxt.org](https://llmstxt.org/).\n- Catch‑all markdown handler lives at `app/[...slug].md/route.ts`. It resolves a page descriptor from `app/.presentations.manifest.json` and renders via the `presentations.v2` engine (target: `markdown`).\n- Per‑page companion convention: add `app/<route>/ai.ts` exporting a `PresentationDescriptorV2`.\n- Build‑time tool: `tools/generate-presentations-manifest.mjs <app-root>` populates the manifest.\n- CI check: `pnpm llms:check` verifies coverage (% of pages with descriptors) and fails if below threshold.\n"
1573
- }];
1574
- a(t$18);
1575
-
1576
- //#endregion
1577
- //#region ../../libs/contracts/dist/docs/tech/auth/better-auth-nextjs.docblock.js
1578
- const t$17 = [{
1579
- id: `docs.tech.auth.better-auth-nextjs`,
1580
- title: `Better Auth + Next.js integration (ContractSpec)`,
1581
- summary: `How ContractSpec wires Better Auth into Next.js (server config, client singleton, and proxy cookie-only redirects).`,
1582
- kind: `reference`,
1583
- visibility: `public`,
1584
- route: `/docs/tech/auth/better-auth-nextjs`,
1585
- tags: [
1586
- `auth`,
1587
- `better-auth`,
1588
- `nextjs`,
1589
- `cookies`,
1590
- `proxy`,
1591
- `hmr`
1592
- ],
1593
- body: `# Better Auth + Next.js integration (ContractSpec)
1594
-
1595
- This repo uses Better Auth as the primary auth layer (sessions, organizations, teams, API keys, and OAuth).
1596
-
1597
- ## Server config (Better Auth)
1598
-
1599
- - Source: \`packages/bundles/contractspec-studio/src/application/services/auth.ts\`
1600
- - Important: \`nextCookies()\` must be the **last** plugin in the Better Auth plugin list so \`Set-Cookie\` is applied correctly in Next.js environments.
1601
-
1602
- ## Better Auth Admin plugin
1603
-
1604
- ContractSpec Studio enables the Better Auth **Admin plugin** to support platform-admin user operations (list users, impersonation, etc.).
1605
-
1606
- - Server: \`admin()\` plugin in \`packages/bundles/contractspec-studio/src/application/services/auth.ts\`
1607
- - Client: \`adminClient()\` in \`packages/bundles/contractspec-studio/src/presentation/providers/auth/client.ts\`
1608
-
1609
- ### PLATFORM_ADMIN ⇒ Better Auth admin role
1610
-
1611
- Better Auth Admin endpoints authorize via \`user.role\`. ContractSpec enforces an org-driven rule:
1612
-
1613
- - If the **active organization** has \`type = PLATFORM_ADMIN\`, the signed-in user is ensured to have \`User.role\` containing \`admin\`.
1614
- - This is applied in the session creation hook and re-checked in \`assertsPlatformAdmin()\`.
1615
-
1616
- This keeps admin enablement deterministic and avoids manual role backfills.
1617
-
1618
- ## Client config (React web + Expo)
1619
-
1620
- To avoid duplicate background refresh/polling loops in dev (Fast Refresh/HMR), the Better Auth client is implemented as a singleton cached on \`globalThis\`.
1621
-
1622
- - Web client: \`packages/bundles/contractspec-studio/src/presentation/providers/auth/client.ts\`
1623
- - Native client: \`packages/bundles/contractspec-studio/src/presentation/providers/auth/client.native.ts\`
1624
-
1625
- Import guidance:
1626
-
1627
- - If you only need the context/hook, prefer importing from \`@lssm/bundle.contractspec-studio/presentation/providers/auth\`.
1628
- - If you explicitly need the Better Auth client instance (e.g. admin impersonation, direct API calls), import from \`@lssm/bundle.contractspec-studio/presentation/providers/auth/client\`.
1629
-
1630
- ## Public routes (login / signup)
1631
-
1632
- Public auth pages should avoid eager \`authClient\` initialization.
1633
-
1634
- Pattern used:
1635
-
1636
- - In the submit handler, dynamically import \`@lssm/bundle.contractspec-studio/presentation/providers/auth/index.web\` and call \`authClient.signIn.*\` / \`authClient.signUp.*\`.
1637
-
1638
- This prevents session refresh behavior from starting just because a public page rendered.
1639
-
1640
- ## Next.js proxy auth (web-landing)
1641
-
1642
- The Next.js proxy/middleware is used for **redirect decisions only**. It must not perform DB-backed session reads on every request.
1643
-
1644
- - Source: \`packages/apps/web-landing/src/proxy.ts\`
1645
- - Approach: cookie-only checks via Better Auth cookies helpers:
1646
- - \`getSessionCookie(request)\`
1647
- - \`getCookieCache(request)\`
1648
-
1649
- These checks are intentionally optimistic and should only gate routing. Full authorization must still be enforced on server-side actions/routes and GraphQL resolvers.
1650
- `
1651
- }];
1652
- a(t$17);
1653
-
1654
- //#endregion
1655
- //#region ../../libs/contracts/dist/docs/tech/schema/README.docblock.js
1656
- const t$16 = [{
1657
- id: `docs.tech.schema.README`,
1658
- title: `Multi‑File Prisma Schema Conventions (per database)`,
1659
- summary: `We adopt Prisma multi‑file schema (GA ≥ v6.7) to organize each database’s models by domain and to import core LSSM module schemas locally.`,
1660
- kind: `reference`,
1661
- visibility: `public`,
1662
- route: `/docs/tech/schema/README`,
1663
- tags: [
1664
- `tech`,
1665
- `schema`,
1666
- `README`
1667
- ],
1668
- body: `# Multi‑File Prisma Schema Conventions (per database)
1669
-
1670
- We adopt Prisma multi‑file schema (GA ≥ v6.7) to organize each database’s models by domain and to import core LSSM module schemas locally.
1671
-
1672
- Canonical layout per DB:
1673
-
1674
- \`\`\`
1675
- prisma/
1676
- schema/
1677
- main.prisma # datasource + generators only
1678
- imported/
1679
- lssm_sigil/*.prisma # imported models/enums only (no datasource/generator)
1680
- lssm_content/*.prisma # idem
1681
- <domain>/*.prisma # vertical‑specific models split by bounded context
1682
- \`\`\`
1683
-
1684
- Notes:
1685
-
1686
- - Imported files contain only \`model\` and \`enum\` blocks (strip \`datasource\`/\`generator\`).
1687
- - Preserve \`@@schema("…")\` annotations to keep tables in their Postgres schemas; we now explicitly list schemas in \`main.prisma\` to avoid P1012: \`schemas = ["public","lssm_sigil","lssm_content","lssm_featureflags","lssm_ops","lssm_planning","lssm_quill","lssm_geoterro"]\`.
1688
- - Use \`@lssm/app.cli-database\` CLI: \`database import|check|generate|migrate:*|seed\` to manage a single DB; \`@lssm/app.cli-databases\` orchestrates multiple DBs.
1689
-
1690
- ## Typed merger config
1691
-
1692
- - Define imported module list once per DB with a typed config:
1693
-
1694
- \`\`\`ts
1695
- // prisma-merger.config.ts
1696
- import { defineMergedPrismaConfig } from '@lssm/app.cli-database';
1697
-
1698
- export default defineMergedPrismaConfig({
1699
- modules: [
1700
- '@lssm/app.cli-database-sigil',
1701
- '@lssm/app.cli-database-content',
1702
- // ...
1703
- ],
1704
- });
1705
- \`\`\`
1706
-
1707
- - Then run \`database import --target .\` (no need to pass \`--modules\`).
1708
-
1709
- ## Prisma Config (prisma.config.ts)
1710
-
1711
- We use Prisma Config per official docs to point Prisma to the multi-file schema folder and migrations:
1712
-
1713
- \`\`\`ts
1714
- // prisma.config.ts
1715
- import path from 'node:path';
1716
- import { defineConfig } from 'prisma/config';
1717
-
1718
- export default defineConfig({
1719
- schema: path.join('prisma', 'schema'),
1720
- migrations: { path: path.join('prisma', 'migrations') },
1721
- });
1722
- \`\`\`
1723
-
1724
- Reference: Prisma blog – Organize Your Prisma Schema into Multiple Files: https://www.prisma.io/blog/organize-your-prisma-schema-with-multi-file-support
1725
-
1726
- ---
1727
-
1728
- # LSSM Auth (Sigil) – Models & Integration
1729
-
1730
- This document tracks the identity models and integration points used by the LSSM Sigil module.
1731
-
1732
- ## Models (Prisma \`lssm_sigil\`)
1733
-
1734
- - \`User\` – core identity with email, optional phone, role, passkeys, apiKeys
1735
- - \`Session\` – session tokens and metadata; includes \`activeOrganizationId\`
1736
- - \`Account\` – external providers (password, OAuth)
1737
- - \`Organization\` – tenant boundary; includes \`type\` additional field
1738
- - \`Member\`, \`Invitation\`, \`Team\`, \`TeamMember\` – org/teams
1739
- - \`Role\`, \`Permission\`, \`PolicyBinding\` – RBAC
1740
- - \`ApiKey\`, \`Passkey\` – programmable access and WebAuthn
1741
- - \`SsoProvider\` – OIDC/SAML provider configuration (org- or user-scoped)
1742
- - \`OAuthApplication\`, \`OAuthAccessToken\`, \`OAuthConsent\` – first/third-party OAuth
1743
-
1744
- These mirror STRIT additions so Better Auth advanced plugins (admin, organization, apiKey, passkey, genericOAuth) work uniformly across apps.
1745
-
1746
- ## Better Auth (server)
1747
-
1748
- Enabled methods:
1749
-
1750
- - Email & password
1751
- - Phone OTP (Telnyx)
1752
- - Passkey (WebAuthn)
1753
- - API keys
1754
- - Organizations & Teams
1755
- - Generic OAuth (FranceConnect+ via OIDC with JWE/JWS using JOSE)
1756
-
1757
- Server config lives at \`packages/lssm/modules/sigil/src/application/services/auth.ts\`.
1758
-
1759
- ## Clients (Expo / React)
1760
-
1761
- Client config lives at \`packages/lssm/modules/sigil/src/presentation/providers/auth/expo.ts\` with plugins for admin, passkey, apiKey, organization, phone, genericOAuth.
1762
-
1763
- ## Environment Variables
1764
-
1765
- Telnyx (phone OTP):
1766
-
1767
- - \`TELNYX_API_KEY\`
1768
- - \`TELNYX_MESSAGING_PROFILE_ID\`
1769
- - \`TELNYX_FROM_NUMBER\`
1770
-
1771
- FranceConnect+ (prefer LSSM*… but STRIT*… fallbacks are supported):
1772
-
1773
- - \`LSSM_FRANCECONNECTPLUS_DISCOVERY_URL\`
1774
- - \`LSSM_FRANCECONNECTPLUS_CLIENT_ID\`
1775
- - \`LSSM_FRANCECONNECTPLUS_CLIENT_SECRET\`
1776
- - \`LSSM_FRANCECONNECTPLUS_ENC_PRIVATE_KEY_PEM\` (PKCS8; RSA-OAEP-256)
1777
-
1778
- Generic:
1779
-
1780
- - \`API_URL_IDENTITIES\` – base URL for Better Auth server
1781
- - \`BETTER_AUTH_SECRET\` – server secret
1782
-
1783
- Keep this in sync with code changes to avoid drift.
1784
-
1785
- ## HCircle domain splits and auth removal
1786
-
1787
- - Auth/identity models are not defined locally anymore. They come from \`@lssm/app.cli-database-sigil\` under the \`lssm_sigil\` schema.
1788
- - \`packages/hcircle/libs/database-coliving/prisma/schema/domain/\` is split by domain; newsletter/waiting list lives in \`newsletter.prisma\` and uses \`@@map("waiting_list")\`.
1789
- - To avoid collisions with module names, the local event models were renamed to \`SocialEvent\`, \`SocialEventAttendee\`, and \`SocialEventRecurrence\` with \`@@map\` pointing to existing table names.
1790
-
1791
- ---
1792
-
1793
- ## Vertical profiles (current)
1794
-
1795
- ### STRIT
1796
-
1797
- - prisma-merger modules:
1798
- - \`@lssm/app.cli-database-sigil\`, \`@lssm/app.cli-database-content\`, \`@lssm/app.cli-database-ops\`, \`@lssm/app.cli-database-planning\`, \`@lssm/app.cli-database-quill\`, \`@lssm/app.cli-database-geoterro\`
1799
- - main.prisma schemas:
1800
- - \`schemas = ["public","lssm_sigil","lssm_content","lssm_ops","lssm_planning","lssm_quill","lssm_geoterro"]\`
1801
- - domain splits (\`packages/strit/libs/database/prisma/schema/domain/\`):
1802
- - \`bookings.prisma\` (Booking, StritDocument + links to Content \`File\` and Sigil \`Organization\`)
1803
- - \`commerce.prisma\` (Wholesale models; \`sellerId\` linked to Sigil \`Organization\`)
1804
- - \`files.prisma\` (PublicFile, PublicFileAccessLog; \`ownerId\`→Organization, \`uploadedBy\`→User)
1805
- - \`geo.prisma\` (PublicCountry, PublicAddress, City; links to Spots/Series)
1806
- - \`spots.prisma\`, \`urbanism.prisma\`, \`analytics.prisma\`, \`onboarding.prisma\`, \`referrals.prisma\`, \`subscriptions.prisma\`, \`content.prisma\`
1807
- - auth models are imported from Sigil (no local auth tables).
1808
- - Back-relations for \`Organization\` (e.g., \`files\`, seller relations) are declared in the Sigil module to avoid scattering.
1809
-
1810
- ### ARTISANOS
1811
-
1812
- - prisma-merger modules:
1813
- - \`@lssm/app.cli-database-sigil\`, \`@lssm/app.cli-database-content\`, \`@lssm/app.cli-database-featureflags\`, \`@lssm/app.cli-database-ops\`, \`@lssm/app.cli-database-planning\`, \`@lssm/app.cli-database-quill\`, \`@lssm/app.cli-database-geoterro\`
1814
- - main.prisma schemas:
1815
- - \`schemas = ["public","lssm_sigil","lssm_content","lssm_featureflags","lssm_ops","lssm_planning","lssm_quill","lssm_geoterro"]\`
1816
- - domain splits (\`packages/artisanos/libs/database-artisan/prisma/schema/domain/\`):
1817
- - \`sales.prisma\` (Client, Quote, QuoteTemplate, Invoice, FollowUps)
1818
- - \`subsidies.prisma\` (SubsidyProgram, AidApplication, SupportingDocument)
1819
- - \`projects.prisma\` (Project, ProjectPlanningSettings)
1820
- - \`crm.prisma\` (OrganizationProfessionalProfile, OrganizationCertification)
1821
- - \`professions.prisma\`, \`products.prisma\`, \`templates.prisma\`, \`analytics.prisma\`, \`onboarding.prisma\`, \`referrals.prisma\`, \`subscriptions.prisma\`, \`files.prisma\`
1822
- - auth/organization/team models are provided by Sigil; local legacy copies were removed.
1823
- - Where names collide with Content, local models are prefixed (e.g., \`PublicFile\`) and use \`@@map\` to keep existing table names where applicable.
1824
-
1825
- ## Schema Dictionary: \`@lssm/lib.schema\`
1826
-
1827
- ### Purpose
1828
-
1829
- Describe operation I/O once and generate:
1830
-
1831
- - zod (runtime validation)
1832
- - GraphQL (Pothos types/refs)
1833
- - JSON Schema (via \`zod-to-json-schema\` or native descriptors)
1834
-
1835
- ### Primitives
1836
-
1837
- - **FieldType<T>**: describes a scalar or composite field and carries:
1838
- - \`zod\` schema for validation
1839
- - optional JSON Schema descriptor
1840
- - optional GraphQL scalar reference/name
1841
- - **SchemaModel**: named object model composed of fields. Exposes helpers:
1842
- - \`getZod(): z.ZodObject<ZodShapeFromFields<Fields>> | z.ZodArray<z.ZodObject<...>>\`
1843
- - Preserves each field's schema, optionality, and array-ness
1844
- - Top-level lists are supported via \`config.isArray: true\`
1845
- - \`getJsonSchema(): JSONSchema7\` (export for docs, MCP, forms)
1846
- - \`getPothosInput()\` (GraphQL input object name)
1847
-
1848
- ### Conventions
1849
-
1850
- - Name models with PascalCase; suffix with \`Input\`/\`Result\` when ambiguous.
1851
- - Use explicit enums for multi-value constants; reuse the same enum across input/output.
1852
- - Define domain enums via \`defineEnum('Name', [...])\` in the relevant domain package (e.g., \`packages/strit/libs/contracts-strit/src/enums/\`), not in \`ScalarTypeEnum\`.
1853
- - Reference those enums in \`SchemaModel\` fields directly (they expose \`getZod\`, \`getPothos\`, \`getJsonSchema\`).
1854
-
1855
- #### Example (STRIT)
1856
-
1857
- \`\`\`ts
1858
- // packages/strit/libs/contracts-strit/src/enums/recurrence.ts
1859
- import { defineEnum } from '@lssm/lib.schema';
1860
- export const SpotEnum = {
1861
- Weekday: () =>
1862
- defineEnum('Weekday', ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'] as const),
1863
- RecurrenceFrequency: () =>
1864
- defineEnum('RecurrenceFrequency', [
1865
- 'DAILY',
1866
- 'WEEKLY',
1867
- 'MONTHLY',
1868
- 'YEARLY',
1869
- ] as const),
1870
- } as const;
1871
- \`\`\`
1872
-
1873
- \`\`\`ts
1874
- // usage in contracts
1875
- frequency: { type: SpotEnum.RecurrenceFrequency(), isOptional: false },
1876
- byWeekday: { type: SpotEnum.Weekday(), isOptional: true, isArray: true },
1877
- \`\`\`
1878
-
1879
- - Use \`Date\` type for temporal values and ensure ISO strings in JSON transports where needed.
1880
-
1881
- ### Mapping rules (summary)
1882
-
1883
- - Strings → GraphQL \`String\`
1884
- - Numbers → \`Int\` if safe 32-bit integer else \`Float\`
1885
- - Booleans → \`Boolean\`
1886
- - Dates → custom \`Date\` scalar
1887
- - Arrays<T> → list of mapped T (set \`isArray: true\` on the field)
1888
- - Top-level arrays → set \`isArray: true\` on the model config
1889
- - Objects → input/output object types with stable field order
1890
- - Unions → supported for output; input unions map to JSON (structural input is not supported by GraphQL)
1891
-
1892
- ### JSON Schema export
1893
-
1894
- Prefer \`getZod()\` + \`zod-to-json-schema\` for consistency. For advanced cases, provide a custom \`getJsonSchema()\` on the model.
1895
-
1896
- ### Example
1897
-
1898
- \`\`\`ts
1899
- import { ScalarTypeEnum, SchemaModel } from '@lssm/lib.schema';
1900
-
1901
- // Nested model
1902
- const Weekday = new SchemaModel({
1903
- name: 'Weekday',
1904
- fields: {
1905
- value: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
1906
- },
1907
- });
1908
-
1909
- // Parent model with array field and nested object
1910
- const Rule = new SchemaModel({
1911
- name: 'Rule',
1912
- fields: {
1913
- timezone: { type: ScalarTypeEnum.TimeZone(), isOptional: false },
1914
- byWeekday: { type: Weekday, isOptional: true, isArray: true },
1915
- },
1916
- });
1917
-
1918
- const CreateThingInput = new SchemaModel({
1919
- name: 'CreateThingInput',
1920
- fields: {
1921
- name: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
1922
- rule: { type: Rule, isOptional: false },
1923
- },
1924
- });
1925
-
1926
- // zod
1927
- const z = CreateThingInput.getZod();
1928
- \`\`\`
1929
- `
1930
- }];
1931
- a(t$16);
1932
-
1933
- //#endregion
1934
- //#region ../../libs/contracts/dist/docs/tech/templates/runtime.docblock.js
1935
- const t$15 = [{
1936
- id: `docs.tech.templates.runtime`,
1937
- title: `ContractSpec Template Runtime (Phase 9)`,
1938
- summary: `Phase 9 introduces a full local-first runtime for templates so anyone can preview apps directly in the browser without provisioning any infrastructure.`,
1939
- kind: `reference`,
1940
- visibility: `public`,
1941
- route: `/docs/tech/templates/runtime`,
1942
- tags: [
1943
- `tech`,
1944
- `templates`,
1945
- `runtime`
1946
- ],
1947
- body: "## ContractSpec Template Runtime (Phase 9)\n\nPhase 9 introduces a full local-first runtime for templates so anyone can preview apps directly in the browser without provisioning any infrastructure.\n\n### Building Blocks\n\n- **Local database** – `@lssm/lib.runtime-local` wraps `sql.js` (SQLite WASM) and `IndexedDB` so we can seed demo data, run migrations, and persist state between sessions. Tests point the runtime to `node_modules/sql.js/dist` so CI doesn’t need a browser.\n- **Local GraphQL** – `LocalGraphQLClient` wires Apollo Client + SchemaLink to resolvers for tasks, messaging, and i18n recipes. All `/templates`, `/studio`, and `/sandbox` previews use those resolvers so we never call remote APIs during demos.\n- **Template registry + installer** – `.../templates/registry.ts` stores the catalog (todos, messaging, recipes). `TemplateInstaller` can seed the runtime (`install`) or export a base64 snapshot via the new `saveTemplateToStudio` mutation.\n- **TemplateShell** – Shared UI wrapper that creates a `TemplateRuntimeProvider`, shows `LocalDataIndicator`, and (optionally) surfaces the new `SaveToStudioButton`.\n\n### Runtime Flows\n\n1. `/templates` now opens a modal that renders `TemplateShell` for each template. Users can explore without leaving the marketing site.\n2. `/studio` switches to a tabbed mini-app (Projects, Canvas, Specs, Deploy) to showcase Studio surfaces with mock data. Visitors see a **preview** shell, while authenticated users (Better Auth via Sigil) unlock full persistence, versioning, and deployment controls.\n3. `/sandbox` lets visitors pick a template and mode (Playground, Spec Editor, Visual Builder). The console at the bottom streams runtime events for transparency.\n\n### GraphQL Mutations\n\n- `saveTemplateToStudio(input: SaveTemplateInput!): SaveTemplateResult!` writes a placeholder project + spec so that templates installed from the sandbox appear in Studio. The mutation is intentionally simple right now: it records which template was imported, stores metadata, and returns `{ projectId, status: 'QUEUED' }` for the UI.\n- `saveCanvasDraft(input: SaveCanvasDraftInput!): CanvasVersion!` snapshots the current Visual Builder nodes to a draft version tied to a canvas overlay. Inputs include `canvasId`, arbitrary `nodes` JSON, and an optional `label`. The resolver enforces org/org access before calling `CanvasVersionManager`.\n- `deployCanvasVersion(input: DeployCanvasVersionInput!): CanvasVersion!` promotes a previously saved draft (`versionId`) to the deployed state. The returned object includes `status`, `nodes`, `createdAt`, and `createdBy` for UI timelines.\n- `undoCanvasVersion(input: UndoCanvasInput!): CanvasVersion` rewinds the visual builder to the prior snapshot (returns `null` when history is empty) so Studio’s toolbar can surface “Undo” without shelling out to local storage.\n\n### Studio GraphQL endpoint\n\n- The landing app exposes the Studio schema at `/api/studio/graphql` via Yoga so React Query hooks (`useStudioProjects`, `useCreateStudioProject`, `useDeployStudioProject`, etc.) can talk to the bundle without spinning up a separate server.\n\n### Spec Editor typing\n\n- Studio’s spec editor now preloads Monaco with ambient declarations for `@lssm/lib.contracts` and `zod`, so snippets receive autocomplete and inline errors even before the spec ships to the backend. The helper lives in `presentation/components/studio/organisms/monaco-spec-types.ts` and registers the extra libs once per browser session via `monaco.languages.typescript.typescriptDefaults.addExtraLib`.\n- Compiler options are aligned with our frontend toolchain (ES2020 + React JSX) which means drafts written in the editor behave like the compiled artifacts that flow through Studio pipelines.\n\n### Spec templates\n\n- Selecting a spec type now injects a ready-to-edit scaffold (capability, workflow, policy, dataview, component) so authors start from a canonical layout instead of a blank file. Templates live alongside `SpecEditor.tsx`, and we only overwrite the content when the previous value is empty or when the author explicitly switches types via the dropdown.\n\n### Spec preview\n\n- The validation side panel now embeds a `SpecPreview` widget that shows validation errors alongside transport artifacts (GraphQL schema, REST endpoints, component summaries) once a preview run completes. Tabs let authors toggle between “Validation” and “Artifacts,” mirroring the UX described in the Studio plan.\n\n### Testing\n\n- `src/templates/__tests__/runtime.test.ts` covers todos CRUD, messaging delivery, and recipe locale switching through the local GraphQL API.\n- Studio infrastructure tests live in `src/__tests__/e2e/project-lifecycle.test.ts` and continue to exercise project creation + deploy flows.\n\n### Next Steps\n\nFuture templates can register their React components via `registerTemplateComponents(templateId, components)` so TemplateShell can render them automatically. When new templates are added, remember to:\n\n1. Update the registry entry (schema + tags).\n2. Register components inside `presentation/components/templates`.\n3. Document the template under `docs/templates/`.\n\n\n\n\n\n"
1948
- }];
1949
- a(t$15);
1950
-
1951
- //#endregion
1952
- //#region ../../libs/contracts/dist/docs/tech/workflows/overview.docblock.js
1953
- const t$14 = [{
1954
- id: `docs.tech.workflows.overview`,
1955
- title: `WorkflowSpec Overview`,
1956
- summary: "WorkflowSpec provides a declarative, versioned format for long-running flows that mix automation and human review. Specs stay inside `@lssm/lib.contracts` (`src/workflow/spec.ts`) so the same definition powers runtime execution, documentation, and future generation.",
1957
- kind: `reference`,
1958
- visibility: `public`,
1959
- route: `/docs/tech/workflows/overview`,
1960
- tags: [
1961
- `tech`,
1962
- `workflows`,
1963
- `overview`
1964
- ],
1965
- body: "# WorkflowSpec Overview\n\n## Purpose\n\nWorkflowSpec provides a declarative, versioned format for long-running flows that mix automation and human review. Specs stay inside `@lssm/lib.contracts` (`src/workflow/spec.ts`) so the same definition powers runtime execution, documentation, and future generation.\n\n## Core Types\n\n- `WorkflowMeta`: ownership metadata (`title`, `domain`, `owners`, `tags`, `stability`) plus `name` and `version`.\n- `WorkflowDefinition`:\n - `entryStepId?`: optional explicit entry point (defaults to first step).\n - `steps[]`: ordered list of `Step` descriptors.\n - `transitions[]`: directed edges between steps with optional expressions.\n - `sla?`: aggregated timing hints for the overall flow or per-step budgets.\n - `compensation?`: fallback operations executed when a workflow is rolled back or fails.\n- `Step`:\n - `type`: `human`, `automation`, or `decision`.\n - `action`: references either a `ContractSpec` (`operation`) or `FormSpec` (`form`).\n - Optional `guard`, `timeoutMs`, and retry policy (`maxAttempts`, `backoff`, `delayMs`, `maxDelayMs?`).\n - `requiredIntegrations?`: integration slot ids that must be bound before the step may execute.\n - `requiredCapabilities?`: `CapabilityRef[]` that must be enabled in the resolved app config.\n- `Transition`: `from` → `to` with optional `condition` string (simple data expressions).\n\n## Registry & Validation\n\n- `WorkflowRegistry` (`src/workflow/spec.ts`) stores specs by key `<name>.v<version>` and exposes `register`, `list`, and `get`.\n- `validateWorkflowSpec()` (`src/workflow/validation.ts`) checks:\n - Duplicate step IDs.\n - Unknown `from`/`to` transitions.\n - Empty guards/conditions.\n - Reachability from the entry step.\n - Cycles in the graph.\n - Operation/Form references against provided registries.\n- `assertWorkflowSpecValid()` wraps validation and throws `WorkflowValidationError` when errors remain.\n\n## Runtime\n\n- `WorkflowRunner` (`src/workflow/runner.ts`) executes workflows and coordinates steps.\n - `start(name, version?, initialData?)` returns a `workflowId`.\n - `executeStep(workflowId, input?)` runs the current step (automation or human).\n - `getState(workflowId)` retrieves the latest state snapshot.\n - `cancel(workflowId)` marks the workflow as cancelled.\n - `preFlightCheck(name, version?, resolvedConfig?)` evaluates integration/capability requirements before the workflow starts.\n - Throws `WorkflowPreFlightError` if required integration slots are unbound or required capabilities are disabled.\n- `StateStore` (`src/workflow/state.ts`) abstracts persistence. V1 ships with:\n - `InMemoryStateStore` (`src/workflow/adapters/memory-store.ts`) for tests/dev.\n - Placeholder factories for file/database adapters (`adapters/file-adapter.ts`, `adapters/db-adapter.ts`).\n- Guard evaluation: expression guards run through `evaluateExpression()` (`src/workflow/expression.ts`); custom policy guards can be provided via `guardEvaluator`.\n- Events: the runner emits `workflow.started`, `workflow.step_completed`, `workflow.step_failed`, and `workflow.cancelled` through the optional `eventEmitter`.\n- React bindings (`@lssm/lib.presentation-runtime-react`):\n - `useWorkflow` hook (polls state, exposes `executeStep`, `cancel`, `refresh`).\n - `WorkflowStepper` progress indicator using design-system Stepper.\n - `WorkflowStepRenderer` helper to render human/automation/decision steps with sensible fallbacks.\n\n## Authoring Checklist\n\n1. Reuse existing operations/forms; create new specs when missing.\n2. Prefer explicit `entryStepId` for clarity (especially with decision branches).\n3. Give automation steps an `operation` and human steps a `form` (warnings surface otherwise).\n4. Use short, meaningful step IDs (`submit`, `review`, `finalize`) to simplify analytics.\n5. Keep guard expressions deterministic; complex policy logic should move to PolicySpec (Phase 2).\n\n## Testing\n\n- Add unit tests for new workflows via `assertWorkflowSpecValid`.\n- Use the new Vitest suites (`validation.test.ts`, `expression.test.ts`, `runner.test.ts`) as examples.\n- CLI support will arrive in Phase 1 PR 3 (`contractspec create --type workflow`).\n\n## Tooling\n\n- `contractspec create --type workflow` scaffolds a WorkflowSpec with interactive prompts.\n- `contractspec build <spec.workflow.ts>` generates a runner scaffold (`.runner.ts`) wired to `WorkflowRunner` and the in-memory store.\n- `contractspec validate` understands `.workflow.ts` files and checks core structure (meta, steps, transitions).\n\n## Next Steps (Non-MVP)\n\n- Persistence adapters (database/file) for workflow state (Phase 2).\n- React bindings (`useWorkflow`, `WorkflowStepper`) and presentation-runtime integration (PR 3).\n- Policy engine integration (`guard.type === 'policy'` validated against PolicySpec).\n- Telemetry hooks for step execution metrics.\n\n"
1966
- }];
1967
- a(t$14);
1968
-
1969
- //#endregion
1970
- //#region ../../libs/contracts/dist/docs/tech/mcp-endpoints.docblock.js
1971
- const t$13 = [{
1972
- id: `docs.tech.mcp.endpoints`,
1973
- title: `ContractSpec MCP endpoints`,
1974
- summary: `Dedicated MCP servers for docs, CLI usage, and internal development.`,
1975
- kind: `reference`,
1976
- visibility: `mixed`,
1977
- route: `/docs/tech/mcp/endpoints`,
1978
- tags: [
1979
- `mcp`,
1980
- `docs`,
1981
- `cli`,
1982
- `internal`
1983
- ],
1984
- body: "# ContractSpec MCP endpoints\n\nThree dedicated MCP servers keep AI agents efficient and scoped:\n\n- **Docs MCP**: `/api/mcp/docs` — exposes DocBlocks as resources + presentations. Tool: `docs.search`.\n- **CLI MCP**: `/api/mcp/cli` — surfaces CLI quickstart/reference/README and suggests commands. Tool: `cli.suggestCommand`.\n- **Internal MCP**: `/api/mcp/internal` — internal routing hints, playbook, and example registry access. Tool: `internal.describe`.\n\n### Usage notes\n- Transports are HTTP POST (streamable HTTP); SSE is disabled.\n- Resources are namespaced (`docs://*`, `cli://*`, `internal://*`) and are read-only.\n- Internal MCP also exposes the examples registry via `examples://*` resources:\n - `examples://list?q=<query>`\n - `examples://example/<id>`\n- Prompts mirror each surface (navigator, usage, bootstrap) for quick agent onboarding.\n- GraphQL remains at `/graphql`; health at `/health`.\n"
1985
- }];
1986
- a(t$13);
1987
-
1988
- //#endregion
1989
- //#region ../../libs/contracts/dist/docs/tech/vscode-extension.docblock.js
1990
- const t$12 = [{
1991
- id: `docs.tech.vscode.extension`,
1992
- title: `ContractSpec VS Code Extension`,
1993
- summary: `VS Code extension for spec-first development with validation, scaffolding, and MCP integration.`,
1994
- kind: `reference`,
1995
- visibility: `public`,
1996
- route: `/docs/tech/vscode/extension`,
1997
- tags: [
1998
- `vscode`,
1999
- `extension`,
2000
- `tooling`,
2001
- `dx`
2002
- ],
2003
- body: `# ContractSpec VS Code Extension
2004
-
2005
- The ContractSpec VS Code extension provides spec-first development tooling directly in your editor.
2006
-
2007
- ## Features
2008
-
2009
- - **Real-time Validation**: Get instant feedback on spec errors and warnings as you save files
2010
- - **Build/Scaffold**: Generate handler and component skeletons from specs (no AI required)
2011
- - **Spec Explorer**: List and navigate all specs in your workspace
2012
- - **Dependency Analysis**: Visualize spec dependencies and detect cycles
2013
- - **MCP Integration**: Search ContractSpec documentation via Model Context Protocol
2014
- - **Snippets**: Code snippets for common ContractSpec patterns
2015
-
2016
- ## Commands
2017
-
2018
- | Command | Description |
2019
- |---------|-------------|
2020
- | \`ContractSpec: Validate Current Spec\` | Validate the currently open spec file |
2021
- | \`ContractSpec: Validate All Specs\` | Validate all spec files in the workspace |
2022
- | \`ContractSpec: Build/Scaffold\` | Generate handler/component from the current spec |
2023
- | \`ContractSpec: List All Specs\` | Show all specs in the workspace |
2024
- | \`ContractSpec: Analyze Dependencies\` | Analyze and visualize spec dependencies |
2025
- | \`ContractSpec: Search Docs (MCP)\` | Search documentation via MCP |
2026
-
2027
- ## Configuration
2028
-
2029
- | Setting | Description | Default |
2030
- |---------|-------------|---------|
2031
- | \`contractspec.api.baseUrl\` | Base URL for ContractSpec API (enables MCP + remote telemetry) | \`""\` |
2032
- | \`contractspec.telemetry.posthogHost\` | PostHog host URL for direct telemetry | \`"https://eu.posthog.com"\` |
2033
- | \`contractspec.telemetry.posthogProjectKey\` | PostHog project key for direct telemetry | \`""\` |
2034
- | \`contractspec.validation.onSave\` | Run validation on save | \`true\` |
2035
- | \`contractspec.validation.onOpen\` | Run validation on open | \`true\` |
2036
-
2037
- ## Architecture
2038
-
2039
- The extension uses:
2040
- - \`@lssm/module.contractspec-workspace\` for pure analysis + templates
2041
- - \`@lssm/bundle.contractspec-workspace\` for workspace services + adapters
2042
-
2043
- This allows the extension to work without requiring the CLI to be installed.
2044
-
2045
- ## Telemetry
2046
-
2047
- The extension uses a hybrid telemetry approach:
2048
- 1. If \`contractspec.api.baseUrl\` is configured → send to API \`/api/telemetry/ingest\`
2049
- 2. Otherwise → send directly to PostHog (if project key configured)
2050
-
2051
- Telemetry respects VS Code's telemetry settings. No file paths, source code, or PII is collected.
2052
- `
2053
- }, {
2054
- id: `docs.tech.vscode.snippets`,
2055
- title: `ContractSpec Snippets`,
2056
- summary: `Code snippets for common ContractSpec patterns in VS Code.`,
2057
- kind: `reference`,
2058
- visibility: `public`,
2059
- route: `/docs/tech/vscode/snippets`,
2060
- tags: [
2061
- `vscode`,
2062
- `snippets`,
2063
- `dx`
2064
- ],
2065
- body: `# ContractSpec Snippets
2066
-
2067
- The VS Code extension includes snippets for common ContractSpec patterns.
2068
-
2069
- ## Available Snippets
2070
-
2071
- | Prefix | Description |
2072
- |--------|-------------|
2073
- | \`contractspec-command\` | Create a new command (write operation) |
2074
- | \`contractspec-query\` | Create a new query (read-only operation) |
2075
- | \`contractspec-event\` | Create a new event |
2076
- | \`contractspec-docblock\` | Create a new DocBlock |
2077
- | \`contractspec-telemetry\` | Create a new TelemetrySpec |
2078
- | \`contractspec-presentation\` | Create a new Presentation |
2079
-
2080
- ## Usage
2081
-
2082
- Type the prefix in a TypeScript file and press Tab to expand the snippet. Tab through the placeholders to fill in your values.
2083
- `
2084
- }];
2085
- a(t$12);
2086
-
2087
- //#endregion
2088
- //#region ../../libs/contracts/dist/docs/tech/telemetry-ingest.docblock.js
2089
- const t$11 = [{
2090
- id: `docs.tech.telemetry.ingest`,
2091
- title: `Telemetry Ingest Endpoint`,
2092
- summary: `Server-side telemetry ingestion for ContractSpec clients (VS Code extension, CLI, etc.).`,
2093
- kind: `reference`,
2094
- visibility: `internal`,
2095
- route: `/docs/tech/telemetry/ingest`,
2096
- tags: [
2097
- `telemetry`,
2098
- `api`,
2099
- `posthog`,
2100
- `analytics`
2101
- ],
2102
- body: `# Telemetry Ingest Endpoint
2103
-
2104
- The ContractSpec API provides a telemetry ingest endpoint for clients to send product analytics events.
2105
-
2106
- ## Endpoint
2107
-
2108
- \`\`\`
2109
- POST /api/telemetry/ingest
2110
- \`\`\`
2111
-
2112
- ## Request
2113
-
2114
- \`\`\`json
2115
- {
2116
- "event": "contractspec.vscode.command_run",
2117
- "distinct_id": "client-uuid",
2118
- "properties": {
2119
- "command": "validate"
2120
- },
2121
- "timestamp": "2024-01-15T10:30:00.000Z"
2122
- }
2123
- \`\`\`
2124
-
2125
- ### Headers
2126
-
2127
- | Header | Description |
2128
- |--------|-------------|
2129
- | \`x-contractspec-client-id\` | Optional client identifier (used as fallback for distinct_id) |
2130
- | \`Content-Type\` | Must be \`application/json\` |
2131
-
2132
- ### Body
2133
-
2134
- | Field | Type | Required | Description |
2135
- |-------|------|----------|-------------|
2136
- | \`event\` | string | Yes | Event name (e.g., \`contractspec.vscode.activated\`) |
2137
- | \`distinct_id\` | string | Yes | Anonymous client identifier |
2138
- | \`properties\` | object | No | Event properties |
2139
- | \`timestamp\` | string | No | ISO 8601 timestamp |
2140
-
2141
- ## Response
2142
-
2143
- \`\`\`json
2144
- {
2145
- "success": true
2146
- }
2147
- \`\`\`
2148
-
2149
- ## Configuration
2150
-
2151
- The endpoint requires \`POSTHOG_PROJECT_KEY\` environment variable to be set. If not configured, events are accepted but not forwarded.
2152
-
2153
- | Environment Variable | Description | Default |
2154
- |---------------------|-------------|---------|
2155
- | \`POSTHOG_HOST\` | PostHog host URL | \`https://eu.posthog.com\` |
2156
- | \`POSTHOG_PROJECT_KEY\` | PostHog project API key | (required) |
2157
-
2158
- ## Privacy
2159
-
2160
- - No PII is collected or stored
2161
- - \`distinct_id\` is an anonymous client-generated UUID
2162
- - File paths and source code are never included in events
2163
- - Respects VS Code telemetry settings on the client side
2164
-
2165
- ## Events
2166
-
2167
- ### Extension Events
2168
-
2169
- | Event | Description | Properties |
2170
- |-------|-------------|------------|
2171
- | \`contractspec.vscode.activated\` | Extension activated | \`version\` |
2172
- | \`contractspec.vscode.command_run\` | Command executed | \`command\` |
2173
- | \`contractspec.vscode.mcp_call\` | MCP call made | \`endpoint\`, \`tool\` |
2174
-
2175
- ### API Events
2176
-
2177
- | Event | Description | Properties |
2178
- |-------|-------------|------------|
2179
- | \`contractspec.api.mcp_request\` | MCP request processed | \`endpoint\`, \`method\`, \`success\`, \`duration_ms\` |
2180
- `
2181
- }, {
2182
- id: `docs.tech.telemetry.hybrid`,
2183
- title: `Hybrid Telemetry Model`,
2184
- summary: `How ContractSpec clients choose between direct PostHog and API-routed telemetry.`,
2185
- kind: `usage`,
2186
- visibility: `internal`,
2187
- route: `/docs/tech/telemetry/hybrid`,
2188
- tags: [
2189
- `telemetry`,
2190
- `architecture`,
2191
- `posthog`
2192
- ],
2193
- body: `# Hybrid Telemetry Model
2194
-
2195
- ContractSpec uses a hybrid telemetry model where clients can send events either directly to PostHog or via the API server.
2196
-
2197
- ## Decision Flow
2198
-
2199
- \`\`\`
2200
- Is contractspec.api.baseUrl configured?
2201
- ├── Yes → Send via /api/telemetry/ingest
2202
- └── No → Is posthogProjectKey configured?
2203
- ├── Yes → Send directly to PostHog
2204
- └── No → Telemetry disabled
2205
- \`\`\`
2206
-
2207
- ## Benefits
2208
-
2209
- ### Direct PostHog
2210
- - No server dependency
2211
- - Works offline (with batching)
2212
- - Lower latency
2213
-
2214
- ### Via API
2215
- - Centralized key management (no client-side keys)
2216
- - Server-side enrichment and validation
2217
- - Rate limiting and abuse prevention
2218
- - Easier migration to other providers
2219
-
2220
- ## Recommendation
2221
-
2222
- - **Development**: Use direct PostHog with a dev project key
2223
- - **Production**: Route via API for better governance
2224
-
2225
- ## Future: OpenTelemetry
2226
-
2227
- The current PostHog implementation is behind a simple interface that can be swapped for OpenTelemetry:
2228
-
2229
- \`\`\`typescript
2230
- interface TelemetryClient {
2231
- send(event: TelemetryEvent): Promise<void>;
2232
- }
2233
- \`\`\`
2234
-
2235
- This allows future migration without changing client code.
2236
- `
2237
- }];
2238
- a(t$11);
2239
-
2240
- //#endregion
2241
- //#region ../../libs/contracts/dist/docs/tech/contracts/openapi-export.docblock.js
2242
- const t$10 = [{
2243
- id: `docs.tech.contracts.openapi-export`,
2244
- title: `OpenAPI export (OpenAPI 3.1) from SpecRegistry`,
2245
- summary: `Generate a deterministic OpenAPI document from a SpecRegistry using jsonSchemaForSpec + REST transport metadata.`,
2246
- kind: `reference`,
2247
- visibility: `public`,
2248
- route: `/docs/tech/contracts/openapi-export`,
2249
- tags: [
2250
- `contracts`,
2251
- `openapi`,
2252
- `rest`
2253
- ],
2254
- body: `## OpenAPI export (OpenAPI 3.1) from SpecRegistry
2255
-
2256
- ### Purpose
2257
-
2258
- ContractSpec specs can be exported into an **OpenAPI 3.1** document for tooling (SDK generation, docs, gateways).
2259
-
2260
- The export is **spec-first**:
2261
-
2262
- - Uses \`jsonSchemaForSpec(spec)\` for input/output JSON Schema (from SchemaModel → zod → JSON Schema)
2263
- - Uses \`spec.transport.rest.method/path\` when present
2264
- - Falls back to deterministic defaults:
2265
- - Method: \`POST\` for commands, \`GET\` for queries
2266
- - Path: \`defaultRestPath(name, version)\` → \`/<dot/name>/v<version>\`
2267
-
2268
- ### Library API
2269
-
2270
- - Function: \`openApiForRegistry(registry, options?)\`
2271
- - Location: \`@lssm/lib.contracts/openapi\`
2272
-
2273
- ### CLI
2274
-
2275
- Export OpenAPI from a registry module:
2276
-
2277
- \`\`\`bash
2278
- contractspec openapi --registry ./src/registry.ts --out ./openapi.json
2279
- \`\`\`
2280
-
2281
- The registry module must export one of:
2282
-
2283
- - \`registry: SpecRegistry\`
2284
- - \`default(): SpecRegistry | Promise<SpecRegistry>\`
2285
- - \`createRegistry(): SpecRegistry | Promise<SpecRegistry>\`
2286
-
2287
- ### Notes / limitations (current)
2288
-
2289
- - Responses are generated as a basic \`200\` response (plus schemas when available).
2290
- - Query (GET) inputs are currently represented as a JSON request body when an input schema exists.
2291
- - Errors are not yet expanded into OpenAPI responses; that will be added when we standardize error envelopes.`
2292
- }];
2293
- a(t$10);
2294
-
2295
- //#endregion
2296
- //#region ../../libs/contracts/dist/docs/tech/studio/workspaces.docblock.js
2297
- const t$9 = [{
2298
- id: `docs.tech.studio.workspaces`,
2299
- title: `Studio projects, teams, environments`,
2300
- summary: `Organization-first Studio: projects live under an organization; teams refine access; projects deploy to multiple environments.`,
2301
- kind: `reference`,
2302
- visibility: `mixed`,
2303
- route: `/docs/tech/studio/workspaces`,
2304
- tags: [
2305
- `studio`,
2306
- `projects`,
2307
- `teams`,
2308
- `rbac`,
2309
- `environments`
2310
- ],
2311
- body: `## Concepts
2312
-
2313
- - **Organization**: the primary grouping boundary for Studio projects.
2314
- - **Project**: one application (specs, overlays, deployments, integrations, evolution, learning).
2315
- - **Team**: refines who can see/edit a project within an organization.
2316
- - **Environment**: deployment target (Development / Staging / Production).
2317
-
2318
- ## Project access (teams + admin override)
2319
-
2320
- Studio uses multi-team sharing to refine access:
2321
-
2322
- - **Admins/owners** can access all projects.
2323
- - If a project is shared with **no teams**, it is **org-wide** (all org members).
2324
- - If a project is shared with **one or more teams**, it is visible to:
2325
- - admins/owners, and
2326
- - members of any linked team.
2327
-
2328
- ## Current persistence (DB + GraphQL)
2329
-
2330
- - DB (Prisma): \`StudioProject\`, \`Team\`, \`TeamMember\`, \`StudioProjectTeam\`
2331
- - GraphQL:
2332
- - \`myStudioProjects\`
2333
- - \`createStudioProject(input.teamIds?)\`
2334
- - \`myTeams\`
2335
- - \`projectTeams(projectId)\`
2336
- - \`setProjectTeams(projectId, teamIds)\`
2337
-
2338
- ## UI shell behavior
2339
-
2340
- Studio and Sandbox both use a shared shell:
2341
-
2342
- - Project selector → Module navigation → Environment selector
2343
- - Always-on Assistant button (floating)
2344
- - Learning journey progress (Studio persists learning events; Sandbox stays local-only)
2345
-
2346
- ## Routing
2347
-
2348
- - \`/studio/projects\`: create/select/delete projects (organization-first).
2349
- - \`/studio/{projectSlug}/*\`: project modules (canvas/specs/deploy/integrations/evolution/learning).
2350
- - \`/studio/learning\`: learning hub without selecting a project.
2351
- `
2352
- }];
2353
- a(t$9);
2354
-
2355
- //#endregion
2356
- //#region ../../libs/contracts/dist/docs/tech/studio/sandbox-unlogged.docblock.js
2357
- const t$8 = [{
2358
- id: `docs.tech.studio.sandbox.unlogged`,
2359
- title: `Sandbox (unlogged) vs Studio (authenticated)`,
2360
- summary: `The sandbox is a lightweight, unlogged surface that mirrors Studio navigation without auth or analytics.`,
2361
- kind: `reference`,
2362
- visibility: `public`,
2363
- route: `/docs/tech/studio/sandbox-unlogged`,
2364
- tags: [
2365
- `studio`,
2366
- `sandbox`,
2367
- `privacy`,
2368
- `analytics`
2369
- ],
2370
- body: `## Sandbox guarantees
2371
-
2372
- - Route: \`/sandbox\`
2373
- - **No auth requirement**
2374
- - **No PostHog init**
2375
- - **No Vercel Analytics**
2376
- - Local-only state (in-browser runtime + localStorage where needed)
2377
-
2378
- ## What Sandbox is for
2379
-
2380
- - Try templates and feature modules safely
2381
- - Preview specs/builder/evolution/learning
2382
- - Produce copyable CLI commands (no side effects)
2383
-
2384
- ## What Sandbox is *not* for
2385
-
2386
- - Persisted projects/workspaces
2387
- - Real deployments
2388
- - Organization-scoped integrations (unless explicitly enabled later)
2389
- `
2390
- }];
2391
- a(t$8);
2392
-
2393
- //#endregion
2394
- //#region ../../libs/contracts/dist/docs/tech/studio/workspace-ops.docblock.js
2395
- const t$7 = [{
2396
- id: `docs.tech.studio.workspace_ops`,
2397
- title: `Workspace ops (repo-linked): list / validate / deps / diff`,
2398
- summary: `Read-only repo operations used by Studio to inspect and validate a linked ContractSpec workspace.`,
2399
- kind: `reference`,
2400
- visibility: `mixed`,
2401
- route: `/docs/tech/studio/workspace-ops`,
2402
- tags: [
2403
- `studio`,
2404
- `repo`,
2405
- `workspace`,
2406
- `validate`,
2407
- `diff`
2408
- ],
2409
- body: "## API surface (api-contractspec)\n\nBase: `/api/workspace-ops`\n\nThese endpoints are **read-only** in v1 and never push to git:\n\n- `GET /api/workspace-ops/:integrationId/config?organizationId=`\n- `GET /api/workspace-ops/:integrationId/specs?organizationId=`\n- `POST /api/workspace-ops/:integrationId/validate` (body: organizationId, files?, pattern?)\n- `POST /api/workspace-ops/:integrationId/deps` (body: organizationId, pattern?)\n- `POST /api/workspace-ops/:integrationId/diff` (body: organizationId, specPath, baseline?, breakingOnly?)\n\n## Repo resolution\n\n- The repo root is resolved from the Studio Integration (`IntegrationProvider.GITHUB`) config:\n - `config.repoCachePath` (preferred) or `config.localPath`\n- Resolution is constrained to `CONTRACTSPEC_REPO_CACHE_DIR` (default: `/tmp/contractspec-repos`)\n\n## Intended UX\n\n- Studio Assistant can run these checks and present results as suggestions.\n- Users can copy equivalent CLI commands for local runs:\n - `contractspec validate`\n - `contractspec deps`\n - `contractspec diff --baseline <ref>`\n"
2410
- }];
2411
- a(t$7);
2412
-
2413
- //#endregion
2414
- //#region ../../libs/contracts/dist/docs/tech/studio/project-routing.docblock.js
2415
- const t$6 = [{
2416
- id: `docs.tech.studio.project-routing`,
2417
- title: `Studio Project Routing`,
2418
- summary: `Studio uses slugged, project-first routes: /studio/{projectSlug}/* with canonical slug redirects and soft-deleted projects hidden.`,
2419
- kind: `reference`,
2420
- visibility: `public`,
2421
- route: `/docs/tech/studio/project-routing`,
2422
- tags: [
2423
- `studio`,
2424
- `routing`,
2425
- `projects`,
2426
- `slug`,
2427
- `redirects`
2428
- ],
2429
- body: "# Studio Project Routing\n\nContractSpec Studio uses a **project-first URL scheme**:\n\n- `/studio/projects` — create, select, and delete projects.\n- `/studio/{projectSlug}/*` — project modules (canvas/specs/deploy/integrations/evolution/learning).\n- `/studio/learning` — learning hub that does not require selecting a project.\n\n## Studio layout shell\n\nStudio routes are wrapped in a dedicated **Studio app shell** (header + footer) that provides in-app navigation (Projects/Learning/Teams), organization switching, and account actions.\n\nProject module routes (`/studio/{projectSlug}/*`) render their own module shell (`WorkspaceProjectShellLayout`). When combined with the global Studio header, the project shell uses a **sticky header offset** to avoid overlapping sticky headers.\n\n## Slug behavior (rename-safe)\n\n- Each project has a `slug` stored in the database (`StudioProject.slug`).\n- When a project name changes, Studio **updates the slug** and stores the previous slug as an alias (`StudioProjectSlugAlias`).\n- Requests to an alias slug are **redirected to the canonical slug**.\n\nGraphQL entrypoint:\n\n- `studioProjectBySlug(slug: String!)` returns:\n - `project`\n - `canonicalSlug`\n - `wasRedirect`\n\n## Deletion behavior (soft delete)\n\nProjects are **soft-deleted**:\n\n- `deleteStudioProject(id: String!)` sets `StudioProject.deletedAt`.\n- All listings and access checks filter `deletedAt = null`.\n- Soft-deleted projects are treated as “not found” in Studio routes and GraphQL access checks.\n\n## Available modules for a selected project\n\nThe following project modules are expected under `/studio/{projectSlug}`:\n\n- `/canvas` — Visual builder canvas (stored via overlays and canvas versions).\n- `/specs` — Spec editor (stored as `StudioSpec`).\n- `/deploy` — Deployments history + triggers (stored as `StudioDeployment`).\n- `/integrations` — Integrations scoped to project (stored as `StudioIntegration`).\n- `/evolution` — Evolution sessions (stored as `EvolutionSession`).\n- `/learning` — Project learning activity.\n"
2430
- }];
2431
- a(t$6);
2432
-
2433
- //#endregion
2434
- //#region ../../libs/contracts/dist/docs/tech/studio/platform-admin-panel.docblock.js
2435
- const t$5 = [{
2436
- id: `docs.tech.studio.platform-admin-panel`,
2437
- title: `Studio Platform Admin Panel`,
2438
- summary: `How PLATFORM_ADMIN organizations manage tenant orgs and integration connections without session switching.`,
2439
- kind: `reference`,
2440
- visibility: `public`,
2441
- route: `/docs/tech/studio/platform-admin-panel`,
2442
- tags: [
2443
- `studio`,
2444
- `admin`,
2445
- `multi-tenancy`,
2446
- `integrations`,
2447
- `better-auth`
2448
- ],
2449
- body: `# Studio Platform Admin Panel
2450
-
2451
- ContractSpec Studio exposes a dedicated **Platform Admin Panel** for users whose **active organization** has:
2452
-
2453
- - \`Organization.type = PLATFORM_ADMIN\`
2454
-
2455
- The UI route is:
2456
-
2457
- - \`/studio/admin\`
2458
-
2459
- ## Authorization model (no org switching)
2460
-
2461
- Platform admins **remain in their own organization**. Cross-tenant actions are always explicit and scoped:
2462
-
2463
- - Admin operations require an explicit \`targetOrganizationId\`.
2464
- - No session / activeOrganizationId switching is performed as part of admin operations.
2465
-
2466
- ## Integrations management
2467
-
2468
- The admin panel manages the full ContractSpec Integrations system:
2469
-
2470
- - Lists all shipped \`IntegrationSpec\` entries (registry built via \`createDefaultIntegrationSpecRegistry()\`).
2471
- - CRUD \`IntegrationConnection\` records for a selected tenant org.
2472
-
2473
- ### Secrets (reference-only + write-only)
2474
-
2475
- The admin UI supports two modes:
2476
-
2477
- - **Reference-only (BYOK)**: store only \`secretProvider\` + \`secretRef\`.
2478
- - **Write-only provisioning/rotation**: paste a raw secret payload; server writes to the selected backend and stores the resulting reference. The secret value is **never returned or displayed**.
2479
-
2480
- Supported backends:
2481
-
2482
- - Env overrides (\`env://...\`)
2483
- - Google Cloud Secret Manager (\`gcp://...\`)
2484
- - AWS Secrets Manager (\`aws://secretsmanager/...\`)
2485
- - Scaleway Secret Manager (\`scw://secret-manager/...\`)
2486
-
2487
- ## Better Auth Admin plugin
2488
-
2489
- The panel uses the Better Auth **Admin plugin** for user operations (list users, impersonation):
2490
-
2491
- - Client calls use \`authClient.admin.*\`.
2492
- - Server-side, ContractSpec enforces that users in a PLATFORM_ADMIN active org have \`User.role\` containing \`admin\` so Better Auth Admin endpoints authorize.
2493
-
2494
- ## GraphQL surface
2495
-
2496
- The platform-admin GraphQL operations are guarded by the active org type and include:
2497
-
2498
- - \`platformAdminOrganizations(search, limit, offset)\`
2499
- - \`platformAdminIntegrationSpecs\`
2500
- - \`platformAdminIntegrationConnections(input: { targetOrganizationId, category?, status? })\`
2501
- - \`platformAdminIntegrationConnectionCreate(input)\`
2502
- - \`platformAdminIntegrationConnectionUpdate(input)\`
2503
- - \`platformAdminIntegrationConnectionDelete(targetOrganizationId, connectionId)\`
2504
-
2505
- ## Key implementation files
2506
-
2507
- - Auth + role enforcement: \`packages/bundles/contractspec-studio/src/application/services/auth.ts\`
2508
- - Admin GraphQL module: \`packages/bundles/contractspec-studio/src/infrastructure/graphql/modules/platform-admin.ts\`
2509
- - Integrations admin service: \`packages/bundles/contractspec-studio/src/modules/platform-integrations/index.ts\`
2510
- - Web route: \`packages/apps/web-landing/src/app/(app-customer)/studio/admin/*\`
2511
- `
2512
- }];
2513
- a(t$5);
2514
-
2515
- //#endregion
2516
- //#region ../../libs/contracts/dist/docs/tech/studio/learning-events.docblock.js
2517
- const t$4 = [{
2518
- id: `docs.tech.studio.learning-events`,
2519
- title: `Studio Learning Events`,
2520
- summary: `Studio persists learning/activity events to the database; Sandbox keeps learning local-first and unlogged.`,
2521
- kind: `reference`,
2522
- visibility: `public`,
2523
- route: `/docs/tech/studio/learning-events`,
2524
- tags: [
2525
- `studio`,
2526
- `learning`,
2527
- `events`,
2528
- `analytics`,
2529
- `sandbox`
2530
- ],
2531
- body: "# Studio Learning Events\n\nStudio emits lightweight **learning/activity events** to support onboarding, ambient coaching, and learning journeys.\n\n## Persistence model\n\n- **Studio**: events are persisted to the database in `StudioLearningEvent` and are organization-scoped (optionally project-scoped).\n- **Sandbox**: events remain **local-only** (unlogged); they must never be sent to backend services.\n\n## GraphQL API\n\n- `recordLearningEvent(input: { name, projectId?, payload? })`\n- `myLearningEvents(projectId?, limit?)`\n- `myOnboardingTracks(productId?, includeProgress?)`\n- `myOnboardingProgress(trackKey)`\n- `dismissOnboardingTrack(trackKey)`\n\n## Common event names (convention)\n\n- `module.navigated` — user navigated to a Studio module (payload at minimum: `{ moduleId }`).\n- `studio.template.instantiated` — created a new Studio project (starter template). Payload commonly includes `{ templateId, projectSlug }`.\n- `spec.changed` — created or updated a Studio spec. Payload may include `{ action: 'create' | 'update', specId?, specType? }`.\n- `regeneration.completed` — finished a “regen/deploy” action (currently emitted on successful Studio deploy actions).\n- `studio.evolution.applied` — completed an Evolution session (payload commonly includes `{ evolutionSessionId }`).\n\nThese events are intentionally minimal and must avoid PII/secrets in payloads.\n"
2532
- }];
2533
- a(t$4);
2534
-
2535
- //#endregion
2536
- //#region ../../libs/contracts/dist/docs/tech/studio/learning-journeys.docblock.js
2537
- const t$3 = [{
2538
- id: `docs.tech.studio.learning-journeys`,
2539
- title: `Studio learning journeys (onboarding + coach)`,
2540
- summary: `DB-backed learning journeys tracked per organization: seeded tracks/steps, event-driven progress, XP/streaks, and a Studio coach surface.`,
2541
- kind: `reference`,
2542
- visibility: `public`,
2543
- route: `/docs/tech/studio/learning-journeys`,
2544
- tags: [
2545
- `studio`,
2546
- `learning`,
2547
- `onboarding`,
2548
- `journey`,
2549
- `graphql`,
2550
- `database`
2551
- ],
2552
- body: `# Studio learning journeys
2553
-
2554
- Studio supports **DB-backed learning journeys** (onboarding tracks + ambient coach tips) that are advanced by **recorded learning events**.
2555
-
2556
- > See also: \`/docs/tech/studio/learning-events\` for event naming + payload guardrails.
2557
-
2558
- ## Scope (multi-tenancy)
2559
-
2560
- - Progress is tracked **per organization** (tenant/workspace), via a \`Learner\` record keyed by \`(userId, organizationId)\`.
2561
- - Learning events are stored as \`StudioLearningEvent\` under the Studio DB schema, scoped to an organization (optionally a project).
2562
-
2563
- ## Persistence model (Prisma)
2564
-
2565
- Learning journey progress lives in the \`lssm_learning\` schema:
2566
-
2567
- - \`Learner\` — one per \`(userId, organizationId)\`
2568
- - \`OnboardingTrack\` — seeded track definitions (trackKey, name, metadata)
2569
- - \`OnboardingStep\` — seeded step definitions (stepKey, completionCondition, xpReward, metadata)
2570
- - \`OnboardingProgress\` — learner × track progress (progress %, xpEarned, completedAt, dismissedAt)
2571
- - \`OnboardingStepCompletion\` — append-only completion records (stepKey, status, xpEarned, completedAt)
2572
-
2573
- ## Track definition source (spec-first)
2574
-
2575
- - Canonical track specs live in \`@lssm/example.learning-journey-registry\`.
2576
- - The Studio API seeds/updates the DB definitions via an idempotent “ensure tracks” routine.
2577
- - The DB is kept aligned with track specs (stale steps are removed) to prevent drift and unblock completion.
2578
-
2579
- ## Progress advancement (event-driven)
2580
-
2581
- 1) UI records an event via GraphQL \`recordLearningEvent\`
2582
- 2) Backend creates \`StudioLearningEvent\`
2583
- 3) Backend advances onboarding by matching the new event against step completion conditions
2584
- 4) Backend persists step completions and recomputes:
2585
- - \`progress\` percentage
2586
- - \`xpEarned\` (including streak/completion bonuses when configured)
2587
- - track completion state (\`completedAt\`)
2588
-
2589
- ## GraphQL API (Studio)
2590
-
2591
- - \`myOnboardingTracks(productId?, includeProgress?)\`
2592
- - returns all tracks + optional progress for the current learner
2593
- - \`myOnboardingProgress(trackKey)\`
2594
- - returns progress + step completion list for a single track
2595
- - \`dismissOnboardingTrack(trackKey)\`
2596
- - marks a track dismissed for the learner (prevents auto-coach)
2597
-
2598
- ## UI routes/surfaces (web)
2599
-
2600
- - \`/studio/learning\` — learning hub (track list + progress widget)
2601
- - \`/studio/learning/{trackKey}\` — track detail (steps + map)
2602
- - Studio shell mounts a **coach sheet** that can auto-open for incomplete, non-dismissed onboarding.
2603
-
2604
- ## Security + data hygiene
2605
-
2606
- - Do not put secrets/PII in \`payload\` fields of learning events.
2607
- - Prefer shallow payload filters (small, stable keys).
2608
- `
2609
- }];
2610
- a(t$3);
2611
-
2612
- //#endregion
2613
- //#region ../../libs/contracts/dist/docs/tech/studio/project-access-teams.docblock.js
2614
- const t$2 = [{
2615
- id: `docs.tech.studio.project-access-teams`,
2616
- title: `Studio Project Access via Teams`,
2617
- summary: `Projects live under organizations; team sharing refines access with an admin/owner override.`,
2618
- kind: `reference`,
2619
- visibility: `public`,
2620
- route: `/docs/tech/studio/project-access-teams`,
2621
- tags: [
2622
- `studio`,
2623
- `projects`,
2624
- `teams`,
2625
- `rbac`,
2626
- `access-control`
2627
- ],
2628
- body: `# Studio Project Access via Teams
2629
-
2630
- Studio access control is **organization-first** with optional **team-based sharing**.
2631
-
2632
- ## Data model
2633
-
2634
- - \`Team\` and \`TeamMember\` define team membership inside an organization.
2635
- - \`StudioProject\` is owned by an organization.
2636
- - \`StudioProjectTeam\` links projects to 0..N teams.
2637
-
2638
- ## Access rules
2639
-
2640
- - **Admins/owners**: always have access to all projects in the organization.
2641
- - **Org-wide projects**: if a project has **no team links**, all organization members can access it.
2642
- - **Team-scoped projects**: if a project has **one or more team links**, a user must be a member of at least one linked team.
2643
-
2644
- ## GraphQL surfaces
2645
-
2646
- - Read:
2647
- - \`myStudioProjects\` (returns only projects you can access)
2648
- - \`studioProjectBySlug(slug)\` (enforces the same access rules)
2649
- - \`myTeams\`
2650
- - \`projectTeams(projectId)\`
2651
-
2652
- - Write:
2653
- - \`createStudioProject(input.teamIds?)\` (teamIds optional)
2654
- - \`setProjectTeams(projectId, teamIds)\` (admin-only)
2655
-
2656
- ## Related
2657
- +
2658
- +- Team administration + invitations: see \`/docs/tech/studio/team-invitations\`.
2659
- +
2660
- ## Notes
2661
-
2662
- Payloads and events must avoid secrets/PII. For Sandbox, the model remains local-first and unlogged.
2663
- `
2664
- }];
2665
- a(t$2);
2666
-
2667
- //#endregion
2668
- //#region ../../libs/contracts/dist/docs/tech/studio/team-invitations.docblock.js
2669
- const t$1 = [{
2670
- id: `docs.tech.studio.team-invitations`,
2671
- title: `Studio Teams & Invitations`,
2672
- summary: `Admin-only team management and email invitation flow to join an organization and optionally a team.`,
2673
- kind: `reference`,
2674
- visibility: `public`,
2675
- route: `/docs/tech/studio/team-invitations`,
2676
- tags: [
2677
- `studio`,
2678
- `teams`,
2679
- `invitations`,
2680
- `access-control`,
2681
- `onboarding`
2682
- ],
2683
- body: `# Studio Teams & Invitations
2684
-
2685
- Studio uses **organization membership** as the base access model. Teams are optional and used to refine access to projects.
2686
-
2687
- ## Who can manage teams?
2688
-
2689
- - **Admins/owners only**: create, rename, delete teams; manage project team access; issue invitations.
2690
-
2691
- ## Invitation data model
2692
-
2693
- - \`Invitation\` rows are stored under an organization and target an **email** address.
2694
-
2695
- - An invitation can optionally target a \`teamId\`, which will grant the user membership in that team upon acceptance.
2696
-
2697
- Key fields:
2698
- - \`email\`: invited address (must match the accepting user's account email)
2699
-
2700
- - \`status\`: \`pending | accepted | declined | expired\`
2701
-
2702
- - \`teamId?\`: optional team to join
2703
-
2704
- - \`inviterId\`: user who issued the invitation
2705
-
2706
- ## GraphQL surfaces
2707
-
2708
- - Team CRUD (admin-only):
2709
-
2710
- - \`createTeam(name)\`
2711
-
2712
- - \`renameTeam(teamId, name)\`
2713
-
2714
- - \`deleteTeam(teamId)\`
2715
-
2716
-
2717
- - Invitations (admin-only):
2718
-
2719
- - \`organizationInvitations\`
2720
-
2721
- - \`inviteToOrganization(email, role?, teamId?)\` → returns \`inviteUrl\` and whether an email was sent
2722
-
2723
- ## Accepting an invitation
2724
-
2725
- The invite link is served as:
2726
-
2727
- - \`/invite/{invitationId}\`
2728
-
2729
- Acceptance rules:
2730
- - The user must be authenticated.
2731
-
2732
- - The authenticated user’s email must match \`Invitation.email\`.
2733
-
2734
- - If not already a member, create \`Member(userId, organizationId, role)\`.
2735
-
2736
- - If \`teamId\` is present, ensure \`TeamMember(teamId, userId)\`.
2737
-
2738
- - Mark invitation \`status='accepted'\` and set \`acceptedAt\`.
2739
-
2740
- - Set \`activeOrganizationId\` for the session so \`/studio/*\` routes work immediately.
2741
-
2742
- ## Email delivery
2743
-
2744
- - If \`RESEND_API_KEY\` is set, the system attempts to send an email.
2745
-
2746
- - Otherwise, the UI uses the returned \`inviteUrl\` for manual copy/share.
2747
- `
2748
- }];
2749
- a(t$1);
2750
-
2751
- //#endregion
2752
- //#region ../../libs/contracts/dist/docs/tech/llm/llm-integration.docblock.js
2753
- const t = [
2754
- {
2755
- id: `docs.tech.llm.overview`,
2756
- title: `LLM Integration Overview`,
2757
- summary: `Export specs to LLM-friendly formats, generate implementation guides, and verify implementations.`,
2758
- kind: `reference`,
2759
- visibility: `public`,
2760
- route: `/docs/tech/llm/overview`,
2761
- tags: [
2762
- `llm`,
2763
- `ai`,
2764
- `export`,
2765
- `guide`,
2766
- `verify`
2767
- ],
2768
- body: `# LLM Integration
2769
-
2770
- ContractSpec provides first-class LLM integration to bridge specifications and AI coding agents.
2771
-
2772
- ## Core Features
2773
-
2774
- ### 1. Multi-Format Export
2775
-
2776
- Export specs to markdown in formats optimized for LLM consumption:
2777
-
2778
- - **Context format**: Summary for understanding (goal, context, acceptance criteria)
2779
- - **Full format**: Complete spec with all details (I/O schemas, policy, events)
2780
- - **Prompt format**: Actionable prompt with implementation instructions
2781
-
2782
- ### 2. Implementation Guidance
2783
-
2784
- Generate agent-specific implementation plans:
2785
-
2786
- - **Claude Code**: Extended thinking mode with structured prompts
2787
- - **Cursor CLI**: Background/composer mode with .mdc rules generation
2788
- - **Generic MCP**: Standard format for any MCP-compatible agent
2789
-
2790
- ### 3. Tiered Verification
2791
-
2792
- Verify implementations against specs:
2793
-
2794
- - **Tier 1 (Structure)**: Types, exports, imports validation
2795
- - **Tier 2 (Behavior)**: Scenario coverage, error handling, events
2796
- - **Tier 3 (AI Review)**: Semantic compliance analysis via LLM
2797
-
2798
- ## Access Points
2799
-
2800
- | Surface | Commands/Tools |
2801
- |---------|---------------|
2802
- | CLI | \`contractspec llm export\`, \`guide\`, \`verify\`, \`copy\` |
2803
- | MCP | \`llm.export\`, \`llm.guide\`, \`llm.verify\` tools |
2804
- | VSCode | Export to LLM, Generate Guide, Verify, Copy commands |
2805
-
2806
- ## Quick Start
2807
-
2808
- ### CLI Usage
2809
-
2810
- \`\`\`bash
2811
- # Export spec as markdown
2812
- contractspec llm export path/to/my.spec.ts --format full
2813
-
2814
- # Generate implementation guide
2815
- contractspec llm guide path/to/my.spec.ts --agent claude-code
2816
-
2817
- # Verify implementation
2818
- contractspec llm verify path/to/my.spec.ts path/to/impl.ts --tier 2
2819
-
2820
- # Copy spec to clipboard
2821
- contractspec llm copy path/to/my.spec.ts --format context
2822
- \`\`\`
2823
-
2824
- ### MCP Usage
2825
-
2826
- \`\`\`
2827
- # Export spec
2828
- llm.export { specPath: "path/to/my.spec.ts", format: "full" }
2829
-
2830
- # Generate guide
2831
- llm.guide { specPath: "path/to/my.spec.ts", agent: "cursor-cli" }
2832
-
2833
- # Verify implementation
2834
- llm.verify { specPath: "path/to/my.spec.ts", implementationPath: "path/to/impl.ts", tier: "2" }
2835
- \`\`\`
2836
-
2837
- ### Programmatic Usage
2838
-
2839
- \`\`\`typescript
2840
- import { specToFullMarkdown, specToAgentPrompt } from '@lssm/lib.contracts/llm';
2841
- import { createAgentGuideService, createVerifyService } from '@lssm/bundle.contractspec-workspace';
2842
-
2843
- // Export
2844
- const markdown = specToFullMarkdown(mySpec);
2845
-
2846
- // Generate guide
2847
- const guideService = createAgentGuideService({ defaultAgent: 'claude-code' });
2848
- const guide = guideService.generateGuide(mySpec);
2849
-
2850
- // Verify
2851
- const verifyService = createVerifyService();
2852
- const result = await verifyService.verify(mySpec, implementationCode, {
2853
- tiers: ['structure', 'behavior']
2854
- });
2855
- \`\`\`
2856
- `
2857
- },
2858
- {
2859
- id: `docs.tech.llm.export-formats`,
2860
- title: `LLM Export Formats`,
2861
- summary: `Detailed explanation of the three export formats for LLM consumption.`,
2862
- kind: `reference`,
2863
- visibility: `public`,
2864
- route: `/docs/tech/llm/export-formats`,
2865
- tags: [
2866
- `llm`,
2867
- `export`,
2868
- `markdown`
2869
- ],
2870
- body: `# LLM Export Formats
2871
-
2872
- ContractSpec provides three export formats optimized for different LLM use cases.
2873
-
2874
- ## Context Format
2875
-
2876
- Best for: Understanding what a spec does, providing background to LLMs.
2877
-
2878
- Includes:
2879
- - Spec name, version, type
2880
- - Goal and context
2881
- - Description
2882
- - Acceptance scenarios
2883
-
2884
- Example:
2885
-
2886
- \`\`\`markdown
2887
- # users.createUser (v1)
2888
-
2889
- > Create a new user account with email verification.
2890
-
2891
- **Type:** command | **Stability:** stable
2892
-
2893
- ## Goal
2894
- Create a new user in the system and trigger email verification.
2895
-
2896
- ## Context
2897
- Part of the user onboarding flow. Called after signup form submission.
2898
-
2899
- ## Acceptance Criteria
2900
- ### Happy path
2901
- **Given:** Valid email and password
2902
- **When:** User submits registration
2903
- **Then:** Account is created, verification email is sent
2904
- \`\`\`
2905
-
2906
- ## Full Format
2907
-
2908
- Best for: Complete documentation, implementation reference.
2909
-
2910
- Includes everything:
2911
- - All metadata
2912
- - JSON schemas for I/O
2913
- - Error definitions
2914
- - Policy (auth, rate limits, PII)
2915
- - Events emitted
2916
- - Examples
2917
- - Transport configuration
2918
-
2919
- ## Prompt Format
2920
-
2921
- Best for: Feeding directly to coding agents.
2922
-
2923
- Includes:
2924
- - Task header with clear instructions
2925
- - Full spec context
2926
- - Implementation requirements
2927
- - Task-specific guidance (implement/test/refactor/review)
2928
- - Expected output format
2929
-
2930
- The prompt format adapts based on task type:
2931
- - **implement**: Full implementation with tests
2932
- - **test**: Test generation for existing code
2933
- - **refactor**: Refactoring while maintaining behavior
2934
- - **review**: Code review against spec
2935
- `
2936
- },
2937
- {
2938
- id: `docs.tech.llm.agent-adapters`,
2939
- title: `Agent Adapters`,
2940
- summary: `Adapters for different AI coding agents (Claude, Cursor, MCP).`,
2941
- kind: `reference`,
2942
- visibility: `public`,
2943
- route: `/docs/tech/llm/agent-adapters`,
2944
- tags: [
2945
- `llm`,
2946
- `agents`,
2947
- `claude`,
2948
- `cursor`,
2949
- `mcp`
2950
- ],
2951
- body: `# Agent Adapters
2952
-
2953
- ContractSpec provides specialized adapters for different AI coding agents.
2954
-
2955
- ## Claude Code Adapter
2956
-
2957
- Optimized for Anthropic Claude's extended thinking and code generation.
2958
-
2959
- Features:
2960
- - Structured markdown with clear sections
2961
- - Checklists for steps and verification
2962
- - Icons for file operations (📝 create, ✏️ modify)
2963
- - System prompt for ContractSpec context
2964
-
2965
- Usage:
2966
- \`\`\`typescript
2967
- const guideService = createAgentGuideService({ defaultAgent: 'claude-code' });
2968
- const result = guideService.generateGuide(spec, { agent: 'claude-code' });
2969
- // result.prompt.systemPrompt - Claude system context
2970
- // result.prompt.taskPrompt - Task-specific instructions
2971
- \`\`\`
2972
-
2973
- ## Cursor CLI Adapter
2974
-
2975
- Optimized for Cursor's background/composer mode.
2976
-
2977
- Features:
2978
- - Compact format for context efficiency
2979
- - .mdc cursor rules generation
2980
- - Integration with Cursor's file system
2981
- - Concise step lists
2982
-
2983
- Generate Cursor Rules:
2984
- \`\`\`typescript
2985
- const cursorRules = guideService.generateAgentConfig(spec, 'cursor-cli');
2986
- // Save to .cursor/rules/my-spec.mdc
2987
- \`\`\`
2988
-
2989
- ## Generic MCP Adapter
2990
-
2991
- Works with any MCP-compatible agent (Cline, Aider, etc.).
2992
-
2993
- Features:
2994
- - Standard markdown format
2995
- - Table-based metadata
2996
- - JSON resource format support
2997
- - Prompt message format
2998
-
2999
- The generic adapter is the default and works across all agents.
3000
-
3001
- ## Choosing an Adapter
3002
-
3003
- | Agent | Best For | Key Features |
3004
- |-------|----------|--------------|
3005
- | Claude Code | Complex implementations | Extended thinking, detailed steps |
3006
- | Cursor CLI | IDE-integrated work | Cursor rules, compact format |
3007
- | Generic MCP | Any MCP agent | Universal compatibility |
3008
- `
3009
- },
3010
- {
3011
- id: `docs.tech.llm.verification`,
3012
- title: `Implementation Verification`,
3013
- summary: `Tiered verification of implementations against specifications.`,
3014
- kind: `reference`,
3015
- visibility: `public`,
3016
- route: `/docs/tech/llm/verification`,
3017
- tags: [
3018
- `llm`,
3019
- `verify`,
3020
- `validation`,
3021
- `testing`
3022
- ],
3023
- body: `# Implementation Verification
3024
-
3025
- ContractSpec provides tiered verification to check if implementations comply with specs.
3026
-
3027
- ## Verification Tiers
3028
-
3029
- ### Tier 1: Structure (Fast)
3030
-
3031
- Checks TypeScript structure against spec requirements:
3032
-
3033
- | Check | What it validates |
3034
- |-------|------------------|
3035
- | Handler export | Function is properly exported |
3036
- | Contracts import | Imports from @lssm/lib.contracts |
3037
- | Schema import | Imports from @lssm/lib.schema |
3038
- | No \`any\` type | TypeScript strict compliance |
3039
- | Error handling | Error codes are referenced |
3040
- | Event emission | Event patterns exist |
3041
- | Input validation | Validation patterns used |
3042
- | Async patterns | Async/await for commands |
3043
-
3044
- ### Tier 2: Behavior (Comprehensive)
3045
-
3046
- Checks implementation coverage of spec behaviors:
3047
-
3048
- | Check | What it validates |
3049
- |-------|------------------|
3050
- | Scenario coverage | Acceptance scenarios implemented |
3051
- | Example coverage | Example I/O values referenced |
3052
- | Error cases | All error conditions handled |
3053
- | Event conditions | Events emitted correctly |
3054
- | Idempotency | Idempotent patterns (if required) |
3055
-
3056
- ### Tier 3: AI Review (Deep)
3057
-
3058
- Uses LLM for semantic analysis:
3059
-
3060
- - Does the implementation fulfill the spec's intent?
3061
- - Are edge cases properly handled?
3062
- - Is the code quality acceptable?
3063
- - Are there any subtle violations?
3064
-
3065
- Requires AI API key configuration.
3066
-
3067
- ## Running Verification
3068
-
3069
- \`\`\`typescript
3070
- const verifyService = createVerifyService({
3071
- aiApiKey: process.env.ANTHROPIC_API_KEY, // Optional, for Tier 3
3072
- aiProvider: 'anthropic',
3073
- });
3074
-
3075
- const result = await verifyService.verify(spec, implementationCode, {
3076
- tiers: ['structure', 'behavior'],
3077
- failFast: false,
3078
- includeSuggestions: true,
3079
- });
3080
-
3081
- console.log(result.passed); // true/false
3082
- console.log(result.score); // 0-100
3083
- console.log(result.summary); // Human-readable summary
3084
- \`\`\`
3085
-
3086
- ## Verification Report
3087
-
3088
- The report includes:
3089
-
3090
- - **passed**: Overall compliance
3091
- - **score**: 0-100 score
3092
- - **issues**: Array of problems found
3093
- - **suggestions**: Recommended fixes
3094
- - **coverage**: Metrics on scenario/error/field coverage
3095
-
3096
- Each issue has:
3097
- - **severity**: error, warning, or info
3098
- - **category**: type, export, import, scenario, error_handling, semantic
3099
- - **message**: Description of the issue
3100
- - **suggestion**: How to fix it
3101
- `
3102
- }
3103
- ];
3104
- a(t);
3105
-
3106
37
  //#endregion
3107
38
  //#region src/docs/learning-journey-ui-shared.docblock.ts
3108
- a([{
39
+ registerDocBlocks([{
3109
40
  id: "docs.examples.learning-journey-ui-shared",
3110
41
  title: "Learning Journey UI — Shared",
3111
42
  summary: "Shared UI components and hooks for learning journey mini-apps.",