@lssm/example.learning-journey-ui-onboarding 0.0.0-canary-20251217062139 → 0.0.0-canary-20251217072406

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