@lssm/example.learning-journey-ui-gamified 0.0.0-canary-20251212230121 → 0.0.0-canary-20251215220103
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/.turbo/turbo-build.log +14 -14
- package/CHANGELOG.md +7 -7
- package/README.md +1 -2
- package/dist/components/index.d.mts +1 -1
- package/dist/{index-C7CBKOil.d.mts → index-CcWC6Zo9.d.mts} +4 -4
- package/dist/{index-DiAD2ivN.d.mts → index-X03x0lCK.d.mts} +5 -5
- package/dist/index.d.mts +36 -5
- package/dist/index.mjs +1285 -1
- package/dist/views/index.d.mts +1 -1
- package/example.ts +1 -0
- package/package.json +10 -6
- package/src/GamifiedMiniApp.tsx +0 -1
- package/src/components/DayCalendar.tsx +0 -1
- package/src/components/FlashCard.tsx +0 -1
- package/src/components/MasteryRing.tsx +0 -1
- package/src/components/index.ts +0 -1
- package/src/docs/index.ts +1 -0
- package/src/docs/learning-journey-ui-gamified.docblock.ts +18 -0
- package/src/example.ts +24 -0
- package/src/index.ts +2 -1
- package/src/views/Overview.tsx +0 -1
- package/src/views/Progress.tsx +1 -2
- package/src/views/Steps.tsx +0 -1
- package/src/views/Timeline.tsx +0 -1
- package/src/views/index.ts +0 -1
- package/tsconfig.tsbuildinfo +1 -1
package/dist/index.mjs
CHANGED
|
@@ -56,4 +56,1288 @@ function GamifiedMiniApp({ track, progress: externalProgress, onStepComplete: ex
|
|
|
56
56
|
}
|
|
57
57
|
|
|
58
58
|
//#endregion
|
|
59
|
-
|
|
59
|
+
//#region src/example.ts
|
|
60
|
+
const example = {
|
|
61
|
+
id: "learning-journey-ui-gamified",
|
|
62
|
+
title: "Learning Journey UI — Gamified",
|
|
63
|
+
summary: "UI mini-app for gamified learning: flashcards, mastery ring, calendar.",
|
|
64
|
+
tags: [
|
|
65
|
+
"learning",
|
|
66
|
+
"ui",
|
|
67
|
+
"gamified"
|
|
68
|
+
],
|
|
69
|
+
kind: "ui",
|
|
70
|
+
visibility: "public",
|
|
71
|
+
docs: { rootDocId: "docs.examples.learning-journey-ui-gamified" },
|
|
72
|
+
entrypoints: {
|
|
73
|
+
packageName: "@lssm/example.learning-journey-ui-gamified",
|
|
74
|
+
docs: "./docs"
|
|
75
|
+
},
|
|
76
|
+
surfaces: {
|
|
77
|
+
templates: true,
|
|
78
|
+
sandbox: {
|
|
79
|
+
enabled: true,
|
|
80
|
+
modes: ["playground", "markdown"]
|
|
81
|
+
},
|
|
82
|
+
studio: {
|
|
83
|
+
enabled: true,
|
|
84
|
+
installable: true
|
|
85
|
+
},
|
|
86
|
+
mcp: { enabled: true }
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
var example_default = example;
|
|
90
|
+
|
|
91
|
+
//#endregion
|
|
92
|
+
//#region ../../libs/contracts/src/docs/presentations.ts
|
|
93
|
+
const DEFAULT_TARGETS = [
|
|
94
|
+
"markdown",
|
|
95
|
+
"application/json",
|
|
96
|
+
"application/xml",
|
|
97
|
+
"react"
|
|
98
|
+
];
|
|
99
|
+
function normalizeRoute(route) {
|
|
100
|
+
if (!route.length) return "/";
|
|
101
|
+
const withLeading = route.startsWith("/") ? route : `/${route}`;
|
|
102
|
+
return withLeading === "/" ? "/" : withLeading.replace(/\/+$/, "");
|
|
103
|
+
}
|
|
104
|
+
function deriveRoute(block, routePrefix) {
|
|
105
|
+
if (block.route) return normalizeRoute(block.route);
|
|
106
|
+
const prefix = routePrefix ?? "/docs";
|
|
107
|
+
const slug = block.id.replace(/^docs\.?/, "").replace(/\./g, "/").replace(/\/+/g, "/");
|
|
108
|
+
return normalizeRoute(slug.startsWith("/") ? slug : `${prefix}/${slug}`);
|
|
109
|
+
}
|
|
110
|
+
function buildName(block, namespace) {
|
|
111
|
+
return namespace ? `${namespace}.${block.id}` : block.id;
|
|
112
|
+
}
|
|
113
|
+
function docBlockToPresentationV2(block, options) {
|
|
114
|
+
const targets = options?.defaultTargets ?? DEFAULT_TARGETS;
|
|
115
|
+
const version = block.version ?? options?.defaultVersion ?? 1;
|
|
116
|
+
const stability = block.stability ?? options?.defaultStability ?? "stable";
|
|
117
|
+
return {
|
|
118
|
+
meta: {
|
|
119
|
+
name: buildName(block, options?.namespace),
|
|
120
|
+
version,
|
|
121
|
+
description: block.summary ?? block.title,
|
|
122
|
+
tags: block.tags,
|
|
123
|
+
owners: block.owners,
|
|
124
|
+
domain: block.domain,
|
|
125
|
+
stability
|
|
126
|
+
},
|
|
127
|
+
policy: block.visibility && block.visibility !== "public" ? { flags: [block.visibility] } : void 0,
|
|
128
|
+
source: {
|
|
129
|
+
type: "blocknotejs",
|
|
130
|
+
docJson: block.body
|
|
131
|
+
},
|
|
132
|
+
targets
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
function docBlockToPresentationSpec(block, options) {
|
|
136
|
+
const version = block.version ?? options?.defaultVersion ?? 1;
|
|
137
|
+
const stability = block.stability ?? options?.defaultStability ?? "stable";
|
|
138
|
+
return {
|
|
139
|
+
meta: {
|
|
140
|
+
name: buildName(block, options?.namespace),
|
|
141
|
+
version,
|
|
142
|
+
stability,
|
|
143
|
+
tags: block.tags,
|
|
144
|
+
owners: block.owners,
|
|
145
|
+
description: block.summary ?? block.title
|
|
146
|
+
},
|
|
147
|
+
content: {
|
|
148
|
+
kind: "markdown",
|
|
149
|
+
content: block.body
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
function docBlocksToPresentationRoutes(blocks, options) {
|
|
154
|
+
return blocks.map((block) => ({
|
|
155
|
+
block,
|
|
156
|
+
route: deriveRoute(block, options?.routePrefix),
|
|
157
|
+
descriptor: docBlockToPresentationV2(block, options)
|
|
158
|
+
}));
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
//#endregion
|
|
162
|
+
//#region ../../libs/contracts/src/docs/registry.ts
|
|
163
|
+
var DocRegistry = class {
|
|
164
|
+
routes = /* @__PURE__ */ new Map();
|
|
165
|
+
constructor(blocks = [], options) {
|
|
166
|
+
blocks.forEach((block) => this.register(block, options));
|
|
167
|
+
}
|
|
168
|
+
register(block, options) {
|
|
169
|
+
const [route] = docBlocksToPresentationRoutes([block], options);
|
|
170
|
+
if (route) this.routes.set(block.id, route);
|
|
171
|
+
return this;
|
|
172
|
+
}
|
|
173
|
+
list() {
|
|
174
|
+
return [...this.routes.values()];
|
|
175
|
+
}
|
|
176
|
+
get(id) {
|
|
177
|
+
return this.routes.get(id);
|
|
178
|
+
}
|
|
179
|
+
toRouteTuples() {
|
|
180
|
+
return this.list().map(({ route, descriptor }) => [route, descriptor]);
|
|
181
|
+
}
|
|
182
|
+
toPresentationSpecs(options) {
|
|
183
|
+
return this.list().map(({ block }) => docBlockToPresentationSpec(block, options));
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
const requiredFields = [
|
|
187
|
+
"id",
|
|
188
|
+
"title",
|
|
189
|
+
"body",
|
|
190
|
+
"kind",
|
|
191
|
+
"visibility",
|
|
192
|
+
"route"
|
|
193
|
+
];
|
|
194
|
+
const defaultDocRegistry = new DocRegistry();
|
|
195
|
+
function registerDocBlocks(blocks) {
|
|
196
|
+
for (const block of blocks) {
|
|
197
|
+
for (const field of requiredFields) if (!block[field]) throw new Error(`DocBlock ${block.id ?? "<missing id>"} missing field ${String(field)}`);
|
|
198
|
+
defaultDocRegistry.register(block);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
//#endregion
|
|
203
|
+
//#region ../../libs/contracts/src/docs/PUBLISHING.docblock.ts
|
|
204
|
+
const PUBLISHING_DocBlocks = [{
|
|
205
|
+
id: "docs.PUBLISHING",
|
|
206
|
+
title: "Publishing ContractSpec Libraries",
|
|
207
|
+
summary: "This guide describes how we release the ContractSpec libraries to npm. We use a dual-track release system: **Stable** (manual) and **Canary** (automatic).",
|
|
208
|
+
kind: "reference",
|
|
209
|
+
visibility: "public",
|
|
210
|
+
route: "/docs/PUBLISHING",
|
|
211
|
+
tags: ["PUBLISHING"],
|
|
212
|
+
body: "# Publishing ContractSpec Libraries\n\nThis guide describes how we release the ContractSpec libraries to npm. We use a dual-track release system: **Stable** (manual) and **Canary** (automatic).\n\n## Release Tracks\n\n| Track | Branch | npm Tag | Frequency | Versioning | Use Case |\n|-------|--------|---------|-----------|------------|----------|\n| **Stable** | `release` | `latest` | Manual | SemVer (e.g., `1.7.4`) | Production, external users |\n| **Canary** | `main` | `canary` | Every Push | Snapshot (e.g., `1.7.4-canary...`) | Dev, internal testing |\n\n## Prerequisites\n\n- ✅ `NPM_TOKEN` secret is configured in GitHub (owner or automation token with _publish_ scope).\n- ✅ `GITHUB_TOKEN` (built-in) has permissions to create PRs (enabled by default in new repos).\n- ✅ For stable releases: `release` branch exists and is protected.\n\n## Canary Workflow (Automatic)\n\nEvery commit pushed to `main` triggers the `.github/workflows/publish-canary.yml` workflow.\n\n1. **Trigger**: Push to `main`.\n2. **Versioning**: Runs `changeset version --snapshot canary` to generate a temporary snapshot version.\n3. **Publish**: Packages are published to npm with the `canary` tag using `changeset publish --tag canary`.\n\n### Consuming Canary Builds\n\nTo install the latest bleeding-edge version:\n\n```bash\nnpm install @lssm/lib.contracts@canary\n# or\nbun add @lssm/lib.contracts@canary\n```\n\n## Stable Release Workflow (Manual)\n\nStable releases are managed via the `release` branch using the standard [Changesets Action](https://github.com/changesets/action).\n\n1. **Develop on `main`**: Create features and fixes.\n2. **Add Changesets**: Run `bun changeset` to document changes and impact (major/minor/patch).\n3. **Merge to `release`**: When ready to ship, open a PR from `main` to `release` or merge manually.\n4. **\"Version Packages\" PR**:\n - The GitHub Action detects new changesets and automatically creates a Pull Request titled **\"Version Packages\"**.\n - This PR contains the version bumps and updated `CHANGELOG.md` files.\n5. **Merge & Publish**:\n - Review and merge the \"Version Packages\" PR.\n - The Action runs again, detects the versions have been bumped, builds the libraries, and publishes them to npm with the `latest` tag.\n\n### Publishing Steps\n\n1. Ensure all changesets are present on `main`.\n2. Merge `main` into `release`:\n ```bash\n git checkout release\n git pull origin release\n git merge main\n git push origin release\n ```\n3. Go to GitHub Pull Requests. You will see a **\"Version Packages\"** PR created by the bot.\n4. Merge that PR.\n5. The release is now live on npm!\n\n## Manual Verification (Optional)\n\nBefore publishing a new version you can run:\n\n```bash\nbun run build:not-apps\nnpx npm-packlist --json packages/libs/contracts\n```\n\n## Rollback\n\nIf 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.\n"
|
|
213
|
+
}];
|
|
214
|
+
registerDocBlocks(PUBLISHING_DocBlocks);
|
|
215
|
+
|
|
216
|
+
//#endregion
|
|
217
|
+
//#region ../../libs/contracts/src/docs/accessibility_wcag_compliance_specs.docblock.ts
|
|
218
|
+
const accessibility_wcag_compliance_specs_DocBlocks = [{
|
|
219
|
+
id: "docs.accessibility_wcag_compliance_specs",
|
|
220
|
+
title: "Accessibility & WCAG Compliance — **specs.md**",
|
|
221
|
+
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)**.",
|
|
222
|
+
kind: "reference",
|
|
223
|
+
visibility: "public",
|
|
224
|
+
route: "/docs/accessibility_wcag_compliance_specs",
|
|
225
|
+
tags: ["accessibility_wcag_compliance_specs"],
|
|
226
|
+
body: "# Accessibility & WCAG Compliance — **specs.md**\n\n> **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)**.\n\n---\n\n## 0) Scope & Principles\n\n- **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.\n- **Principles:** Perceivable, Operable, Understandable, Robust (POUR).\n- **Rule of ARIA:** “No ARIA is better than bad ARIA.” Prefer native elements.\n- **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.\n- **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.\n\n---\n\n## 1) Design Requirements (Design System & Tokens)\n\n**1.1 Color & Contrast**\n\n- Body text, icons essential to meaning: **≥\xA04.5:1**; large text (≥\xA018.66px regular / 14px bold): **≥\xA03:1**.\n- Interactive states (default/hover/active/disabled/focus) must maintain contrast **≥\xA03:1** against adjacent colors; text within components follows text ratios.\n- Provide light & dark themes with tokens that guarantee minimums. **Never rely solely on color** to convey meaning; pair with text, shape, or icon.\n\n**1.2 Focus Indicators (WCAG\xA02.4.11/12)**\n\n- Every interactive element has a **visible focus** with clear offset; indicator contrast **≥\xA03:1** vs adjacent colors and indicator **area ≥\xA02\xA0CSS\xA0px** thick.\n- Focus **must not be obscured** by sticky headers/footers or scroll containers.\n\n**1.3 Motion & Preferences**\n\n- Respect `prefers-reduced-motion`: suppress large parallax, auto‑animations; provide instant alternatives.\n- Avoid motion that could trigger vestibular issues; under PRM, use fade/scale under **150ms**.\n\n**1.4 Target Size (2.5.8)**\n\n- Hit areas **≥\xA024×24\xA0CSS\xA0px** (web) and **≥\xA044×44\xA0dp** (mobile) unless exempt.\n\n**1.5 Typography & Layout**\n\n- Support zoom to **400%** without loss of content/functionality; responsive reflow at **320\xA0CSS\xA0px** width.\n- Maintain clear heading hierarchy (h1…h6), one **h1** per view.\n\n- 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`.\n- 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.\n- When increasing font size, ensure line height supports readability. Prefer Tailwind defaults or `leading-relaxed`/`leading-7` for body text where dense blocks appear.\n\n**1.6 Iconography & Imagery**\n\n- Decorative images: `alt=\"\"` or `aria-hidden=\"true\"`.\n- Informative images: concise, specific **alt**; complex charts require a **data table or long description**.\n\n---\n\n## 2) Content Requirements (UX Writing)\n\n- Links say **what happens** (avoid “click here”).\n- Buttons start with verbs; avoid ambiguous labels.\n- Form labels are **visible**; placeholders are **not labels**.\n- Error messages: human + programmatic association; avoid color‑only.\n- Authentication: allow **copy/paste**, password managers, and avoid cognitive tests alone (**3.3.7/3.3.8/3.3.9**).\n- Avoid CAPTCHAs that block users; if unavoidable, provide **multiple alternatives** (logic-free).\n\n---\n\n## 3) Engineering Requirements (Web — Next.js/React)\n\n> 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.\n\n**3.1 Semantics & Landmarks**\n\n- Use native elements: `<button>`, `<a href>`, `<label for>`, `<fieldset>`, `<legend>`, `<table>`, etc.\n- Landmarks per page: `header`, `nav`, `main`, `aside`, `footer`. Provide a **Skip to main content** link.\n- Provide a **Route Announcer** (`aria-live=\"polite\"`) and move focus to page **h1** after navigation.\n\n**3.2 Keyboard**\n\n- All functionality available with keyboard alone. Tab order follows DOM/visual order; **no keyboard traps**.\n- Common bindings:\n - Space/Enter → activate button; Enter on link;\n - Esc closes dialogs/menus;\n - Arrow keys for lists/menus/tablists with **roving tabindex**.\n\n**3.3 Focus Management**\n\n- On route change (Next.js), move focus to the page `<h1>` or container and announce via a live region.\n- Dialogs/menus: **trap focus** inside; return focus to invoking control on close.\n- Don’t steal focus except after explicit user action.\n\n**3.4 Forms**\n\n- Each input has a `<label>` or `aria-label`. Group related inputs with `<fieldset><legend>`.\n- Associate errors via `aria-describedby` or inline IDs; announce with `role=\"alert\"` (assertive only for critical).\n- Provide **autocomplete** tokens for known fields; show **inline validation** and do not block on **onBlur** alone.\n\n**3.5 ARIA Usage**\n\n- Only when needed; match patterns (dialog, menu, combobox, tablist, listbox) per ARIA Authoring Practices.\n- Ensure **name/role/value** are programmatically determinable.\n\n**3.6 Media**\n\n- Videos: **captions**; provide **transcripts** for audio; audio descriptions for essential visual info.\n- No auto‑playing audio. Auto‑playing video must be muted and pausable; provide controls.\n\n**3.7 Tables & Data**\n\n- Use `<th scope>` for headers; captions via `<caption>`; announce sorting via `aria-sort`.\n- Provide CSV/JSON export where charts are primary.\n\n**3.8 Performance & Robustness**\n\n- Avoid content shifts that move focus; reserve space or use skeletons.\n- Maintain accessible names through hydration/SSR; avoid `dangerouslySetInnerHTML` where possible.\n\n**3.9 Next.js specifics**\n\n- Use `next/link` for navigation; ensure links are **links**, not buttons.\n- `next/image` must include **alt** (empty if decorative).\n- Announce route changes with a **global live region** and shift focus to the new view.\n\n**3.10 Accessibility library integration**\n\n- 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:\n\n```tsx\n// app/layout.tsx\nimport '@lssm/lib.accessibility'; // includes tokens and provider exports\n// or if needed: import '@lssm/lib.accessibility/src/styles.css';\n```\n\n- Wrap the app with `AccessibilityProvider` and include an element with `id=\"main\"` for the skip link target.\n\n---\n\n## 3b) lssm/ui-kit-web — Component Patterns & Defaults\n\n> Source: `packages/lssm/libs/ui-kit-web/ui/*`\n\n- **Button/Input/Textarea**: Built‑in `focus-visible` rings; ensure visible labels via `FormLabel` or `aria-label`.\n- **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.\n- **Dialog/Sheet/Dropdown**: Use Radix wrappers for focus‑trap and return‑focus. Provide `DialogTitle` + `DialogDescription` for name/description.\n- **Select/Combobox**: Prefer `SelectTrigger` with visible label; for icon‑only triggers, supply `aria-label`. Document examples in each app.\n- **Tabs**: Use `TabsList`, `TabsTrigger`, `TabsContent`; names are programmatically determinable.\n- **Toast/Toaster**: Prefer non‑blocking announcements; map critical to assertive region; include action buttons with clear labels.\n- **Table**: Use `TableCaption`; ensure `TableHead` cells use proper `scope`. Provide `aria-sort` on sortable headers.\n- **Utilities to add (repo action)**:\n - `SkipLink` component and pattern in layouts.\n - `RouteAnnouncer` (`aria-live=\"polite\"`) and **FocusOnRouteChange** helper.\n - `VisuallyHidden` wrapper (Radix visually-hidden or minimal utility).\n - `useReducedMotion` helper; honor in animated components.\n - Touch‑size variants (≥44×44) for interactive atoms.\n\n---\n\n## 4) Engineering Requirements (Mobile — Expo/React\xA0Native)\n\n- Set `accessibilityLabel`, `accessibilityHint`, and `accessibilityRole` on touchables.\n- Ensure **hit slop** / min size **≥\xA044×44\xA0dp**.\n- Support Dynamic Type / font scaling; no clipped text at **200%**.\n- Respect **Invert Colors** and **Reduce Motion**; avoid flashing.\n- Group related items with `accessibilityElements` ordering; hide decoration with `accessible={false}` or `importantForAccessibility=\"no-hide-descendants\"` when appropriate.\n- Test with **VoiceOver (iOS)** and **TalkBack (Android)**.\n\n---\n\n## 5) Component Patterns (Acceptance Rules)\n\n**Buttons & Links**\n\n- Use `<button>` for actions, `<a href>` for navigation. Provide disabled states that are perceivable beyond color.\n\n**Navigation**\n\n- Provide **Skip link**. One primary nav landmark. Indicate current page (`aria-current=\"page\"`).\n\n**Menus/Combobox/Autocomplete**\n\n- Follow ARIA patterns: focus moves into list; `aria-expanded`, `aria-controls`, `aria-activedescendant` when applicable; Esc closes; typing filters.\n\n**Modals/Dialogs**\n\n- `role=\"dialog\"` or `alertdialog` with **label**; focus trapped; background inert; Esc closes; return focus to trigger.\n\n**Tabs**\n\n- `role=\"tablist\"`; tabs are in the tab order; arrow keys switch focus; content is `role=\"tabpanel\"` with `aria-labelledby`.\n\n**Toasts/Notifications**\n\n- Non-critical: `aria-live=\"polite\"`; critical: `role=\"alert\"` sparingly.\n\n**Infinite Scroll / “Load More”**\n\n- Provide **Load more** control; announce new content to SR; preserve keyboard position.\n\n**Drag & Drop (2.5.7)**\n\n- Provide **non‑drag** alternative (e.g., move up/down buttons).\n\n**Charts & Maps**\n\n- Provide **table alternative** or textual summary; keyboard access to datapoints where interactive.\n\n---\n\n## 6) Testing & CI (Blocking Gates)\n\n**Static & Unit**\n\n- `eslint-plugin-jsx-a11y` — error on violations.\n- `jest-axe` — unit tests for components.\n\n**Automated Integration**\n\n- `axe-core` via Playwright or Cypress on critical flows.\n- `pa11y-ci` on key routes; threshold: **0 Critical / 0 Serious** to merge.\n- Lighthouse CI a11y score **≥\xA095** on target pages.\n\n**Manual QA (per release)**\n\n- **Keyboard patrol:** navigate primary flows without mouse.\n- **Screen reader smoke:** NVDA (Windows) or VoiceOver (macOS/iOS) across login, navigation, forms, dialogs.\n- **Zoom & Reflow:** 200–400% & 320\xA0px width.\n- **Color/Contrast check:** tokens in both themes.\n\n**Reporting**\n\n- A11y issues labeled: `a11y-blocker`, `a11y-bug`, `a11y-enhancement` with WCAG ref.\n\n---\n\n## 7) Repository‑Specific Adoption Plan\n\n- Centralize UI usage on `packages/lssm/libs/ui-kit-web` and de‑duplicate per‑app `components/ui` where feasible.\n- Introduce `SkipLink`, `RouteAnnouncer`, `FocusOnRouteChange`, and `VisuallyHidden` in `ui-kit-web`. Adopt in app layouts (`app/layout.tsx`) first.\n- Add `useReducedMotion` and wire into animated components (e.g., `drawer`, `tooltip`, `carousel`).\n- Add touch‑size variants to `Button`, `IconButton`, `TabsTrigger`, toggles.\n- Document Select label patterns and error association in Forms.\n\n---\n\n## 8) Code Snippets\n\n**Skip Link**\n\n```html\n<a\n class=\"sr-only focus:not-sr-only focus-visible:outline focus-visible:ring-4 focus-visible:ring-offset-2\"\n href=\"#main\"\n >Skip to main content</a\n>\n<main id=\"main\">…</main>\n```\n\n**Dialog (Radix + shadcn/ui) — essentials**\n\n```tsx\n// Ensure label, description, focus trap, and return focus on close remain intact\n<Dialog>\n <DialogTrigger asChild>\n <button aria-haspopup=\"dialog\">Open settings</button>\n </DialogTrigger>\n <DialogContent aria-describedby=\"settings-desc\">\n <DialogTitle>Settings</DialogTitle>\n <p id=\"settings-desc\">Update your preferences.</p>\n <DialogClose asChild>\n <button>Close</button>\n </DialogClose>\n </DialogContent>\n</Dialog>\n```\n\n**Form error association**\n\n```tsx\n<label htmlFor=\"email\">Email</label>\n<input id=\"email\" name=\"email\" type=\"email\" aria-describedby=\"email-err\" />\n<p id=\"email-err\" role=\"alert\">Enter a valid email.</p>\n```\n\n**Route change announcement (Next.js)**\n\n```tsx\n// Add once at app root\n<div\n aria-live=\"polite\"\n aria-atomic=\"true\"\n id=\"route-announcer\"\n className=\"sr-only\"\n/>\n```\n\n---\n\n## 9) Exceptions & Waivers\n\n- If a criterion cannot be met, file an issue with: context, attempted alternatives, WCAG reference, impact assessment, and a remediation date. **Temporary waivers only.**\n\n---\n\n## 10) Ownership\n\n- **Design:** maintains token contrast, component specs.\n- **Engineering:** enforces CI gates, implements patterns.\n- **QA:** runs manual checks per release.\n- **PM:** blocks release if AA not met on user‑visible flows.\n\n---\n\n## 11) References (internalize; no external dependency at runtime)\n\n- WCAG\xA02.2 (AA), EN\xA0301\xA0549. ARIA Authoring Practices. Platform HIG (Apple, Material).\n- `packages/lssm/libs/ui-kit-web` as the canonical UI source for web.\n\n> **Bottom line:** Shipping means **accessible by default**. We don’t trade a11y for speed; we bake it into speed.\n\n---\n\n## 12) Adoption Status (2025-09-23)\n\n- web-artisan: AccessibilityProvider integrated; sr-only/forced-colors applied; 44x44 targets; forms announce errors; jest-axe and cypress-axe in place.\n- 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.\n- 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.\n\n> CI gates: run eslint a11y, jest-axe on components, and cypress-axe on critical flows per app.\n\n---\n\n## 13) CI Hardening & Visual QA\n\n- Linting: Run eslint with jsx-a11y rules across all web apps; block on violations.\n- Unit: Run jest-axe for ui-kit-web and app-level components.\n- Integration: cypress-axe on key flows (auth, forms, dialogs, tables).\n- Synthetic scans: pa11y-ci on critical pages (0 Critical/Serious policy).\n- Performance/A11y audit: Lighthouse CI with a11y score >= 95 on target routes.\n- Artifacts: Upload pa11y and Lighthouse reports per PR; annotate failures.\n\n### Recent additions (2025-09-26)\n\n- AutocompleteInput (groceries): Upgraded to ARIA combobox pattern with `aria-controls`, `aria-activedescendant`, `Escape`/`Tab` handling, and labelled listbox.\n- Cypress a11y tests added for furniture and incidents modules on `/modules` and operators flows; checks run axe with critical/serious impacts.\n\n## 14) Accessibility Telemetry (PostHog)\n\n- Events (anonymized): a11y_pref_changed (text_scale, contrast_mode, reduce_motion), a11y_panel_opened.\n- Properties: app, route, previous_value, new_value, timestamp.\n- Dashboards: Adoption over time, per app/route; correlation with reduced bounce on forms.\n- Privacy: No PII; aggregate only.\n"
|
|
227
|
+
}];
|
|
228
|
+
registerDocBlocks(accessibility_wcag_compliance_specs_DocBlocks);
|
|
229
|
+
|
|
230
|
+
//#endregion
|
|
231
|
+
//#region ../../libs/contracts/src/docs/tech/PHASE_1_QUICKSTART.docblock.ts
|
|
232
|
+
const tech_PHASE_1_QUICKSTART_DocBlocks = [{
|
|
233
|
+
id: "docs.tech.PHASE_1_QUICKSTART",
|
|
234
|
+
title: "Phase 1: API Reference Index",
|
|
235
|
+
summary: "Quick reference for all new Phase 1 APIs.",
|
|
236
|
+
kind: "reference",
|
|
237
|
+
visibility: "public",
|
|
238
|
+
route: "/docs/tech/PHASE_1_QUICKSTART",
|
|
239
|
+
tags: ["tech", "PHASE_1_QUICKSTART"],
|
|
240
|
+
body: "# Phase 1: API Reference Index\n\nQuick reference for all new Phase 1 APIs.\n\n---\n\n## @lssm/lib.multi-tenancy\n\n### RLS\n```typescript\nimport { createRlsMiddleware, type TenantIdProvider } from '@lssm/lib.multi-tenancy/rls';\n```\n\n### Provisioning\n```typescript\nimport { \n TenantProvisioningService,\n type CreateTenantInput,\n type TenantProvisioningConfig \n} from '@lssm/lib.multi-tenancy/provisioning';\n```\n\n### Isolation\n```typescript\nimport { IsolationValidator } from '@lssm/lib.multi-tenancy/isolation';\n```\n\n---\n\n## @lssm/lib.observability\n\n### Tracing\n```typescript\nimport { \n getTracer,\n traceAsync,\n traceSync,\n createTracingMiddleware \n} from '@lssm/lib.observability/tracing';\n```\n\n### Metrics\n```typescript\nimport {\n getMeter,\n createCounter,\n createUpDownCounter,\n createHistogram,\n standardMetrics\n} from '@lssm/lib.observability/metrics';\n```\n\n### Logging\n```typescript\nimport {\n Logger,\n logger,\n type LogLevel,\n type LogEntry\n} from '@lssm/lib.observability/logging';\n```\n\n---\n\n## @lssm/lib.resilience\n\n### Circuit Breaker\n```typescript\nimport {\n CircuitBreaker,\n type CircuitState,\n type CircuitBreakerConfig\n} from '@lssm/lib.resilience/circuit-breaker';\n```\n\n### Retry\n```typescript\nimport { retry } from '@lssm/lib.resilience/retry';\n```\n\n### Timeout\n```typescript\nimport { timeout } from '@lssm/lib.resilience/timeout';\n```\n\n### Fallback\n```typescript\nimport { fallback } from '@lssm/lib.resilience/fallback';\n```\n\n---\n\n## Enhanced: @lssm/lib.contracts\n\n### DataViews\n```typescript\nimport { DataViewQueryGenerator } from '@lssm/lib.contracts/data-views/query-generator';\nimport { DataViewRuntime } from '@lssm/lib.contracts/data-views/runtime';\n```\n\n### Workflows\n```typescript\nimport { SLAMonitor, type SLABreachEvent } from '@lssm/lib.contracts/workflow/sla-monitor';\nimport { PrismaStateStore } from '@lssm/lib.contracts/workflow/adapters/db-adapter';\n```\n\n---\n\n## Enhanced: @lssm/lib.design-system\n\n### DataView Components\n```typescript\nimport { DataViewRenderer } from '@lssm/lib.design-system/components/data-view/DataViewRenderer';\n// Also available: DataViewList, DataViewTable, DataViewDetail\n```\n\n---\n\n## Usage Examples\n\n### Complete Workflow with All Features\n\n```typescript\nimport { WorkflowRunner } from '@lssm/lib.contracts/workflow/runner';\nimport { PrismaStateStore } from '@lssm/lib.contracts/workflow/adapters/db-adapter';\nimport { SLAMonitor } from '@lssm/lib.contracts/workflow/sla-monitor';\nimport { CircuitBreaker } from '@lssm/lib.resilience/circuit-breaker';\nimport { traceAsync } from '@lssm/lib.observability/tracing';\n\nconst runner = new WorkflowRunner({\n registry,\n stateStore: new PrismaStateStore(db),\n opExecutor: async (op, input, ctx) => {\n return traceAsync(`op.${op.name}`, async (span) => {\n span.setAttribute('operation', op.name);\n const breaker = getCircuitBreaker(op.name);\n return breaker.execute(() => executeOperation(op, input, ctx));\n });\n },\n eventEmitter: (event, payload) => {\n if (event.startsWith('workflow.')) {\n logger.info(event, payload);\n }\n },\n});\n\nconst monitor = new SLAMonitor((event, payload) => {\n logger.warn('SLA_BREACH', payload);\n alertOps(payload);\n});\n\n// Start workflow\nconst workflowId = await runner.start('payment.flow', 1);\n\n// Monitor SLA\nconst state = await runner.getState(workflowId);\nconst spec = registry.get('payment.flow', 1);\nmonitor.check(state, spec!);\n```\n\n### Complete DataView with Observability\n\n```typescript\nimport { DataViewRenderer } from '@lssm/lib.design-system';\nimport { DataViewQueryGenerator } from '@lssm/lib.contracts/data-views/query-generator';\nimport { traceAsync } from '@lssm/lib.observability/tracing';\nimport { MyDataView } from './specs/users.data-view';\n\nexport function UserListPage() {\n const [page, setPage] = useState(1);\n const [users, setUsers] = useState([]);\n\n const loadUsers = async () => {\n return traceAsync('load_users', async (span) => {\n const generator = new DataViewQueryGenerator(MyDataView);\n const query = generator.generate({ pagination: { page, pageSize: 20 } });\n \n span.setAttribute('page', page);\n const result = await api.execute(query);\n setUsers(result.data);\n });\n };\n\n return (\n <DataViewRenderer\n spec={MyDataView}\n items={users}\n pagination={{ page, pageSize: 20, total: users.length }}\n onPageChange={setPage}\n />\n );\n}\n```\n\n### Complete Multi-Tenant Setup\n\n```typescript\n// 1. RLS Middleware\nimport { createRlsMiddleware } from '@lssm/lib.multi-tenancy/rls';\ndb.$use(createRlsMiddleware(() => req.tenantId));\n\n// 2. Tenant Provisioning\nimport { TenantProvisioningService } from '@lssm/lib.multi-tenancy/provisioning';\nconst service = new TenantProvisioningService({ db });\n\n// 3. Create new tenant\nawait service.provision({\n id: 'acme',\n name: 'Acme Corp',\n slug: 'acme',\n ownerEmail: 'admin@acme.com',\n});\n\n// 4. Validate isolation in tests\nimport { IsolationValidator } from '@lssm/lib.multi-tenancy/isolation';\n\ntest('queries are isolated', () => {\n const isValid = IsolationValidator.validateQuery(\n 'User',\n 'findMany',\n { where: { tenantId: 'acme' } },\n 'acme'\n );\n expect(isValid).toBe(true);\n});\n```\n\n---\n\n## Testing\n\n### Test Circuit Breakers\n\n```typescript\nimport { CircuitBreaker } from '@lssm/lib.resilience/circuit-breaker';\n\ntest('circuit opens after threshold', async () => {\n const breaker = new CircuitBreaker({\n failureThreshold: 3,\n resetTimeoutMs: 5000,\n });\n\n // Trigger failures\n for (let i = 0; i < 3; i++) {\n await expect(\n breaker.execute(() => Promise.reject('error'))\n ).rejects.toThrow();\n }\n\n // Circuit should be open\n await expect(\n breaker.execute(() => Promise.resolve('ok'))\n ).rejects.toThrow('CircuitBreaker is OPEN');\n});\n```\n\n### Test Workflow Retry\n\n```typescript\ntest('workflow retries on failure', async () => {\n let attempts = 0;\n const opExecutor = async () => {\n attempts++;\n if (attempts < 3) throw new Error('fail');\n return 'success';\n };\n\n const runner = new WorkflowRunner({ /* ... */ opExecutor });\n await runner.executeStep(workflowId);\n \n expect(attempts).toBe(3);\n});\n```\n\n---\n\n## Common Patterns\n\n### Pattern: Resilient External Call\n\n```typescript\nimport { CircuitBreaker } from '@lssm/lib.resilience/circuit-breaker';\nimport { retry } from '@lssm/lib.resilience/retry';\nimport { timeout } from '@lssm/lib.resilience/timeout';\nimport { traceAsync } from '@lssm/lib.observability/tracing';\n\nconst breaker = new CircuitBreaker({ failureThreshold: 5, resetTimeoutMs: 30000 });\n\nexport async function callExternalAPI(input: any) {\n return traceAsync('external_api_call', async (span) => {\n span.setAttribute('service', 'stripe');\n \n return breaker.execute(() =>\n retry(\n () => timeout(() => stripe.api.call(input), 5000),\n 3,\n 1000,\n true\n )\n );\n });\n}\n```\n\n**Benefits**: Circuit breaker + retry + timeout + tracing in one place.\n\n---\n\n### Pattern: Tenant-Aware Operation\n\n```typescript\nimport { traceAsync } from '@lssm/lib.observability/tracing';\n\nexport async function listUsers(tenantId: string) {\n return traceAsync('list_users', async (span) => {\n span.setAttribute('tenant_id', tenantId);\n \n // RLS middleware will inject WHERE tenantId = ?\n return db.user.findMany();\n });\n}\n```\n\n---\n\n### Pattern: Monitored Workflow\n\n```typescript\nimport { WorkflowRunner } from '@lssm/lib.contracts/workflow/runner';\nimport { SLAMonitor } from '@lssm/lib.contracts/workflow/sla-monitor';\nimport { logger } from '@lssm/lib.observability/logging';\n\nconst monitor = new SLAMonitor((event, payload) => {\n logger.warn('workflow.sla_breach', payload);\n});\n\n// In workflow poller\nconst state = await runner.getState(workflowId);\nconst spec = registry.get(state.workflowName, state.workflowVersion);\nif (spec) {\n monitor.check(state, spec);\n}\n```\n\n---\n\n## Next Steps\n\n1. **Implement one quick win** (30 minutes)\n2. **Add tests for new functionality** (1 hour)\n3. **Deploy to staging and verify observability** (1 hour)\n4. **Roll out to production** (monitor closely)\n5. **Read full documentation** at https://contractspec.lssm.tech/docs\n\n---\n\n**Questions?** See `/docs/guides/phase-1-migration` or reach out via https://contractspec.lssm.tech/contact\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
|
|
241
|
+
}];
|
|
242
|
+
registerDocBlocks(tech_PHASE_1_QUICKSTART_DocBlocks);
|
|
243
|
+
|
|
244
|
+
//#endregion
|
|
245
|
+
//#region ../../libs/contracts/src/docs/tech/PHASE_2_AI_NATIVE_OPERATIONS.docblock.ts
|
|
246
|
+
const tech_PHASE_2_AI_NATIVE_OPERATIONS_DocBlocks = [{
|
|
247
|
+
id: "docs.tech.PHASE_2_AI_NATIVE_OPERATIONS",
|
|
248
|
+
title: "Phase 2: AI-Native Operations",
|
|
249
|
+
summary: "_Last updated: 2025-11-20_",
|
|
250
|
+
kind: "reference",
|
|
251
|
+
visibility: "public",
|
|
252
|
+
route: "/docs/tech/PHASE_2_AI_NATIVE_OPERATIONS",
|
|
253
|
+
tags: ["tech", "PHASE_2_AI_NATIVE_OPERATIONS"],
|
|
254
|
+
body: "# Phase 2: AI-Native Operations\n\n_Last updated: 2025-11-20_\n\nPhase 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.\n\n## Libraries\n\n### @lssm/lib.ai-agent\n\n- **Spec + Registry**: `defineAgent`, `AgentRegistry` keep agent definitions type-safe.\n- **Runner**: `AgentRunner` drives LLM conversations, tool calls, retries, escalation, and telemetry hooks.\n- **Tools**: `ToolExecutor` standardizes schema validation + timeouts.\n- **Memory**: `InMemoryAgentMemory` + interfaces for plugging persistent stores.\n- **Approvals**: new `ApprovalWorkflow` + `InMemoryApprovalStore` capture low-confidence decisions and surface them to reviewers.\n\n### @lssm/lib.support-bot\n\nComposable support automation primitives:\n\n- `TicketClassifier` → heuristics + optional LLM validation for category, priority, sentiment.\n- `TicketResolver` → RAG pipeline backed by knowledge spaces.\n- `AutoResponder` → tone-aware drafts with citations.\n- `SupportFeedbackLoop` → tracks resolution rates.\n- `createSupportTools` → ready-made tool definitions for AgentRunner.\n\n### @lssm/lib.content-gen\n\nContent generators that consume a `ContentBrief` and output production-ready assets:\n\n- `BlogGenerator`, `LandingPageGenerator`, `EmailCampaignGenerator`, `SocialPostGenerator`.\n- `SeoOptimizer` builds metadata + schema markup.\n\n### @lssm/lib.analytics\n\nQueryless analytics helpers:\n\n- `FunnelAnalyzer` – conversion/drop-off per step.\n- `CohortTracker` – retention + LTV per cohort.\n- `ChurnPredictor` – recency/frequency/error scoring.\n- `GrowthHypothesisGenerator` – surfaces experiment ideas from metric trends.\n\n### @lssm/lib.growth\n\nA/B testing toolkit:\n\n- `ExperimentRegistry` + `ExperimentRunner` – deterministic bucketing.\n- `ExperimentTracker` – persist exposures + metrics.\n- `StatsEngine` – Welch’s t-test + improvement calculations.\n\n### Human-in-the-loop UI\n\n`@lssm/lib.design-system` now exposes:\n\n- `ApprovalQueue` – list + act on pending approvals.\n- `AgentMonitor` – live view of agent sessions with confidence + status.\n\n## Examples\n\n- `examples/ai-support-bot/setup.ts` shows ticket classification → resolution → response draft.\n- `examples/content-generation/generate.ts` produces blog, landing, email, social, SEO output from one brief.\n\n## Next Steps\n\n1. Wire these libraries into vertical apps (H-Circle, ArtisanOS, etc.).\n2. Add background workers that consume the new analytics/growth trackers.\n3. Expand web-landing to highlight these Phase 2 capabilities (see separate TODO).\n"
|
|
255
|
+
}];
|
|
256
|
+
registerDocBlocks(tech_PHASE_2_AI_NATIVE_OPERATIONS_DocBlocks);
|
|
257
|
+
|
|
258
|
+
//#endregion
|
|
259
|
+
//#region ../../libs/contracts/src/docs/tech/PHASE_3_AUTO_EVOLUTION.docblock.ts
|
|
260
|
+
const tech_PHASE_3_AUTO_EVOLUTION_DocBlocks = [{
|
|
261
|
+
id: "docs.tech.PHASE_3_AUTO_EVOLUTION",
|
|
262
|
+
title: "Phase 3: Auto-Evolution Technical Notes",
|
|
263
|
+
summary: "**Status**: In progress",
|
|
264
|
+
kind: "reference",
|
|
265
|
+
visibility: "public",
|
|
266
|
+
route: "/docs/tech/PHASE_3_AUTO_EVOLUTION",
|
|
267
|
+
tags: ["tech", "PHASE_3_AUTO_EVOLUTION"],
|
|
268
|
+
body: "# Phase 3: Auto-Evolution Technical Notes\n\n**Status**: In progress \n**Last updated**: 2025-11-21 \n\nPhase 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.\n\n---\n\n## 1. Libraries\n\n### @lssm/lib.evolution\n\n- `SpecAnalyzer` converts raw telemetry samples into usage stats + anomalies.\n- `SpecGenerator` produces `SpecSuggestion` objects and validates confidence thresholds.\n- `SpecSuggestionOrchestrator` routes proposals through the AI approval workflow and writes approved specs to `packages/libs/contracts/src/generated`.\n- Storage adapters:\n - `InMemorySpecSuggestionRepository` for tests.\n - `PrismaSpecSuggestionRepository` persists to the new Prisma model (see §4).\n - `FileSystemSuggestionWriter` emits JSON envelopes for git review.\n\n### @lssm/lib.observability\n\n- Added intent detection modules:\n - `IntentAggregator` batches telemetry into rolling windows.\n - `IntentDetector` surfaces latency/error/throughput regressions and sequential intents.\n- `EvolutionPipeline` orchestrates aggregation → detection → intent events and exposes hooks for downstream orchestrators.\n- `createTracingMiddleware` now accepts `resolveOperation`/`onSample` hooks to feed telemetry samples into the pipeline.\n\n### @lssm/lib.growth\n\n- New `spec-experiments` module:\n - `SpecExperimentRegistry`, `SpecExperimentRunner`, `SpecExperimentAdapter`.\n - `SpecExperimentAnalyzer` + `SpecExperimentController` handle guardrails and staged rollouts.\n - Helper `createSpecVariantResolver` plugs directly into `HandlerCtx.specVariantResolver`.\n- `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.\n\n### @lssm/lib.testing\n\n- `TrafficRecorder` + `TrafficStore` capture production requests with sampling and sanitization hooks.\n- `GoldenTestGenerator` converts `TrafficSnapshot`s into Vitest/Jest suites.\n- `generateVitestSuite` / `generateJestSuite` output self-contained test files, and `runGoldenTests` offers a programmatic harness for CI pipelines.\n\n---\n\n## 2. Telemetry → Intent → Spec Pipeline\n\n1. `createTracingMiddleware({ onSample })` emits `TelemetrySample`s for every HTTP request.\n2. `IntentAggregator` groups samples into statistical windows (default 15 minutes).\n3. `IntentDetector` raises signals for:\n - Error spikes\n - Latency regressions\n - Throughput drops\n - Sequential workflows that hint at missing specs\n4. `EvolutionPipeline` emits `intent.detected` events and hands them to `SpecGenerator`.\n5. `SpecSuggestionOrchestrator` persists suggestions, triggers approval workflows, and—upon approval—writes JSON envelopes to `packages/.../contracts/src/generated`.\n\n---\n\n## 3. Spec Experiments & Rollouts\n\n1. Register spec experiments in `SpecExperimentRegistry` with control + variant bindings.\n2. Expose bucketed specs by attaching `createSpecVariantResolver` to `HandlerCtx.specVariantResolver` inside adapters.\n3. Record outcomes via `SpecExperimentAdapter.trackOutcome()` (latency + error metrics).\n4. `SpecExperimentController` uses guardrails from config and `SpecExperimentAnalyzer` to:\n - Auto-rollback on error/latency breaches.\n - Advance rollout stages (1% → 10% → 50% → 100%) when metrics stay green.\n\n---\n\n## 4. Data Models (Prisma)\n\nFile: `packages/libs/database/prisma/schema.prisma`\n\n- `SpecSuggestion` – stores serialized suggestion payloads + statuses.\n- `IntentSnapshot` – captured detector output for auditing/training.\n- `TrafficSnapshot` – persisted production traffic (input/output/error blobs).\n- `SpecExperiment` / `SpecExperimentMetric` – rollout state + metrics for each variant.\n\n> Run `bun database generate` after pulling to refresh the Prisma client.\n\n---\n\n## 5. Golden Test Workflow\n\n1. Capture traffic via middleware or direct `TrafficRecorder.record`.\n2. Use the new CLI command to materialize suites:\n\n```bash\ncontractspec test generate \\\n --operation billing.createInvoice \\\n --output tests/billing.createInvoice.golden.test.ts \\\n --runner-import ./tests/run-operation \\\n --runner-fn runBillingCommand \\\n --from-production \\\n --days 7 \\\n --sample-rate 0.05\n```\n\n3. Generated files import your runner and assert against recorded outputs (or expected errors for negative paths).\n\n---\n\n## 6. Operational Notes\n\n- **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.\n- **Sampling**: Keep `TrafficRecorder.sampleRate` ≤ 0.05 in production to avoid sensitive payload storage; scrub PII through the `sanitize` callback before persistence.\n- **Rollouts**: Guardrails default to 5% error-rate and 750ms P99 latency. Override per experiment to match SLOs.\n\n---\n\n## 7. Next Steps\n\n1. Wire `SpecExperimentAdapter.trackOutcome` into adapters (REST, GraphQL, Workers) so every execution logs metrics automatically.\n2. Add a UI for reviewing `SpecSuggestion` objects alongside approval status.\n3. Expand `TrafficRecorder` to ship directly to the Prisma-backed store (currently in-memory by default).\n4. Integrate `EvolutionPipeline` events with the Regenerator to close the loop (auto-open proposals + attach evidence).\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
|
|
269
|
+
}];
|
|
270
|
+
registerDocBlocks(tech_PHASE_3_AUTO_EVOLUTION_DocBlocks);
|
|
271
|
+
|
|
272
|
+
//#endregion
|
|
273
|
+
//#region ../../libs/contracts/src/docs/tech/PHASE_4_PERSONALIZATION_ENGINE.docblock.ts
|
|
274
|
+
const tech_PHASE_4_PERSONALIZATION_ENGINE_DocBlocks = [{
|
|
275
|
+
id: "docs.tech.PHASE_4_PERSONALIZATION_ENGINE",
|
|
276
|
+
title: "Phase 4: Personalization Engine",
|
|
277
|
+
summary: "**Status**: Complete",
|
|
278
|
+
kind: "reference",
|
|
279
|
+
visibility: "public",
|
|
280
|
+
route: "/docs/tech/PHASE_4_PERSONALIZATION_ENGINE",
|
|
281
|
+
tags: ["tech", "PHASE_4_PERSONALIZATION_ENGINE"],
|
|
282
|
+
body: "# Phase 4: Personalization Engine\n\n**Status**: Complete \n**Last updated**: 2025-11-21\n\nPhase 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.\n\n---\n\n## 1. Libraries\n\n### @lssm/lib.overlay-engine\n\n- OverlaySpec types + validator mirror the public spec.\n- Cryptographic signer (`ed25519`, `rsa-pss-sha256`) with canonical JSON serialization.\n- Registry that merges tenant/role/user/device overlays with predictable specificity.\n- React hooks (`useOverlay`, `useOverlayFields`) for client-side rendering.\n- Runtime engine audits every applied overlay for traceability.\n\n### @lssm/lib.personalization\n\n- Behavior tracker buffers field/feature/workflow events and exports OTel metrics.\n- Analyzer summarizes field usage and workflow drop-offs into actionable insights.\n- Adapter translates insights into overlay suggestions or workflow tweaks.\n- In-memory store implementation + interface for plugging Prisma/ClickHouse later.\n\n### @lssm/lib.workflow-composer\n\n- `WorkflowComposer` merges base workflows with tenant/role/device extensions.\n- Step injection utilities keep transitions intact and validate anchor steps.\n- Template helpers for common tenant review/approval, plus merge helpers for multi-scope extensions.\n\n---\n\n## 2. Overlay Editor App\n\nPath: `packages/apps/overlay-editor`\n\n- Next.js App Router UI for toggling field visibility, renaming labels, and reordering lists.\n- Live JSON preview powered by `defineOverlay`.\n- Server action that signs overlays via PEM private keys (Ed25519 by default) using the overlay engine signer.\n\n---\n\n## 3. Persistence\n\nAdded Prisma models (see `packages/libs/database/prisma/schema.prisma`):\n\n- `UserBehaviorEvent` – field/feature/workflow telemetry.\n- `OverlaySigningKey` – tenant managed signing keys with revocation timestamps.\n- `Overlay` – stored overlays (tenant/user/role/device scope) plus signature metadata.\n\n---\n\n## 4. Integration Steps\n\n1. Track usage inside apps via `createBehaviorTracker`.\n2. Periodically run `BehaviorAnalyzer.analyze` to generate insights.\n3. Convert insights into OverlaySpecs or Workflow extensions.\n4. Register tenant overlays in `OverlayRegistry` and serve via presentation runtimes.\n5. Compose workflows per tenant using `WorkflowComposer`.\n\nSee the `docs/tech/personalization/*` guides for concrete examples.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
|
|
283
|
+
}];
|
|
284
|
+
registerDocBlocks(tech_PHASE_4_PERSONALIZATION_ENGINE_DocBlocks);
|
|
285
|
+
|
|
286
|
+
//#endregion
|
|
287
|
+
//#region ../../libs/contracts/src/docs/tech/PHASE_5_ZERO_TOUCH_OPERATIONS.docblock.ts
|
|
288
|
+
const tech_PHASE_5_ZERO_TOUCH_OPERATIONS_DocBlocks = [{
|
|
289
|
+
id: "docs.tech.PHASE_5_ZERO_TOUCH_OPERATIONS",
|
|
290
|
+
title: "Phase 5: Zero-Touch Operations",
|
|
291
|
+
summary: "**Status**: In progress",
|
|
292
|
+
kind: "reference",
|
|
293
|
+
visibility: "public",
|
|
294
|
+
route: "/docs/tech/PHASE_5_ZERO_TOUCH_OPERATIONS",
|
|
295
|
+
tags: ["tech", "PHASE_5_ZERO_TOUCH_OPERATIONS"],
|
|
296
|
+
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"
|
|
297
|
+
}];
|
|
298
|
+
registerDocBlocks(tech_PHASE_5_ZERO_TOUCH_OPERATIONS_DocBlocks);
|
|
299
|
+
|
|
300
|
+
//#endregion
|
|
301
|
+
//#region ../../libs/contracts/src/docs/tech/lifecycle-stage-system.docblock.ts
|
|
302
|
+
const tech_lifecycle_stage_system_DocBlocks = [{
|
|
303
|
+
id: "docs.tech.lifecycle-stage-system",
|
|
304
|
+
title: "ContractSpec Lifecycle Stage System – Technical Design",
|
|
305
|
+
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.",
|
|
306
|
+
kind: "reference",
|
|
307
|
+
visibility: "public",
|
|
308
|
+
route: "/docs/tech/lifecycle-stage-system",
|
|
309
|
+
tags: ["tech", "lifecycle-stage-system"],
|
|
310
|
+
body: "## ContractSpec Lifecycle Stage System – Technical Design\n\nThis 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.\n\n---\n\n### 1. Architecture Overview\n\n```\n┌──────────────────────┐\n│ @lssm/lib.lifecycle │ Types, enums, helpers (pure data)\n└───────────┬──────────┘\n │\n┌───────────▼──────────┐ ┌───────────────────────────┐\n│ modules/lifecycle- │ │ modules/lifecycle-advisor │\n│ core (detection) │ │ (guidance & ceremonies) │\n└───────────┬──────────┘ └───────────┬───────────────┘\n │ │\n ├────────────┬──────────────┤\n ▼ ▼ ▼\n Adapters: analytics, intent, questionnaires\n │\n┌───────────▼──────────┐\n│ bundles/lifecycle- │ Managed service for Studio\n│ managed │ (REST handlers, AI agent) │\n└───────────┬──────────┘\n │\n ContractSpec Studio surfaces\n (web/mobile APIs, CLI, docs)\n```\n\n- **Libraries** provide shared vocabulary.\n- **Modules** encapsulate logic, accepting adapters to avoid environment-specific code.\n- **Bundles** compose modules, register agents/events, and expose APIs for Studio.\n- **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.\n\n---\n\n### 2. Core Library (`@lssm/lib.lifecycle`)\n\n- Stage enum (0–6) with metadata (`question`, `signals`, `traps`).\n- Axes types (`ProductPhase`, `CompanyPhase`, `CapitalPhase`).\n- `LifecycleSignal` (source, metric, value, timestamp).\n- `LifecycleMetricSnapshot` (aggregated numbers).\n- `LifecycleMilestone`, `LifecycleAction`, `LifecycleAssessment` interfaces.\n- Utility helpers:\n - `formatStageSummary(stage, assessment)`\n - `rankStageCandidates(scores)`\n\nThe library exports **no runtime dependencies** so it can be imported from apps, modules, and bundles alike.\n\n---\n\n### 3. Lifecycle Core Module\n\n**Location:** `packages/modules/lifecycle-core/`\n\n#### Components\n1. **StageSignalCollector**\n - Accepts adapter interfaces:\n - `AnalyticsAdapter` (pulls metrics from `@lssm/lib.analytics` or fixture streams).\n - `IntentAdapter` (hooks into `@lssm/lib.observability` intent detectors or logs).\n - `QuestionnaireAdapter` (loads JSON questionnaires and responses).\n - Produces normalized `LifecycleSignal[]`.\n\n2. **StageScorer**\n - Weighted scoring model:\n - Base weight per stage (reflecting expected maturity).\n - Feature weights (retention, revenue, team size, qualitative feedback).\n - Confidence computed via variance of contributing signals.\n - Supports pluggable scoring matrices via JSON config.\n - Accepts sparse metric snapshots; the orchestrator sanitizes metrics to numeric-only records before persisting assessments so downstream analytics stay consistent.\n\n3. **LifecycleOrchestrator**\n - Coordinates collectors + scorer.\n - Returns `LifecycleAssessment` with:\n - `stage`, `confidence`, `axisSnapshot`, `signalsUsed`.\n - Recommended focus areas (high-level categories only).\n - Emits events (internally) when stage confidence crosses thresholds (consumed later by bundle).\n\n4. **LifecycleMilestonePlanner**\n - Loads `milestones-catalog.json` (no DB).\n - Filters upcoming milestones per stage + axis.\n - Tracks completion using provided IDs (caller persists).\n\n#### Data Files\n- `configs/stage-weights.json`\n- `configs/milestones-catalog.json`\n- `questionnaires/stage-readiness.json`\n\n#### Extension Hooks\n- All adapters exported as TypeScript interfaces.\n- Implementations for analytics/intent can live in bundles or apps without modifying module code.\n\n---\n\n### 4. Lifecycle Advisor Module\n\n**Location:** `packages/modules/lifecycle-advisor/`\n\n#### Components\n1. **LifecycleRecommendationEngine**\n - Consumes `LifecycleAssessment`.\n - Maps gaps to `LifecycleAction[]` using rule tables (`stage-playbooks.ts`).\n - Supports override hooks for customer-specific rules.\n\n2. **ContractSpecLibraryRecommender**\n - Maintains mapping from stage → recommended libraries/modules/bundles.\n - Returns prioritized list with rationale and adoption prerequisites.\n\n3. **LifecycleCeremonyDesigner**\n - Provides textual/structural data for ceremonies (title, copy, animation cues, soundtrack references).\n - Ensures low-tech friendly instructions (clear copy, undo guidance).\n\n4. **AI Hooks**\n - Defines prompt templates and tool manifests for lifecycle advisor agents (consumed by bundles).\n - Keeps actual LLM integration outside module.\n\n---\n\n### 5. Managed Bundle (`lifecycle-managed`)\n\n**Responsibilities**\n- Wire modules together.\n- Provide HTTP/GraphQL handlers (exact transport optional).\n- Register LifecycleAdvisorAgent via `@lssm/lib.ai-agent`.\n- LifecycleAdvisorAgent meta: domain `operations`, owners `team-lifecycle`, stability `experimental`, tags `guide/lifecycle/ops` so ops tooling can route incidents quickly.\n- Emit lifecycle events through `@lssm/lib.bus` + `@lssm/lib.analytics`.\n- Integrate with `contractspec-studio` packages:\n - Use Studio contracts for authentication/tenant context (without accessing tenant DBs).\n - Store assessments in Studio-managed storage abstractions (in-memory or file-based for now).\n\n**APIs**\n- `POST /lifecycle/assessments`: Accepts metrics + optional questionnaire answers. Returns `LifecycleAssessment`.\n- `GET /lifecycle/playbooks/:stage`: Returns stage playbook + ceremonies.\n- `POST /lifecycle/advise`: Invokes LifecycleAdvisorAgent with context.\n\n**Events**\n- `LifecycleAssessmentCreated`\n- `LifecycleStageChanged`\n- `LifecycleGuidanceConsumed`\n\n---\n\n### 6. Library Enhancements\n\n| Library | Enhancement |\n| --- | --- |\n| `@lssm/lib.analytics` | Lifecycle metric collectors, helper to emit stage events, adapter implementation used by `StageSignalCollector`. |\n| `@lssm/lib.evolution` | Accepts `LifecycleContext` when ranking spec anomalies/suggestions. |\n| `@lssm/lib.growth` | Stage-specific experiment templates + guardrails referencing lifecycle enums. |\n| `@lssm/lib.observability` | Lifecycle KPI pipeline definitions (drift detection, regression alerts). |\n\nEach enhancement must import stage types from `@lssm/lib.lifecycle`.\n\n---\n\n### 7. Feature Flags & Progressive Delivery\n\n- Add new flags in progressive-delivery library:\n - `LIFECYCLE_DETECTION_ALPHA`\n - `LIFECYCLE_ADVISOR_ALPHA`\n - `LIFECYCLE_MANAGED_SERVICE`\n- Bundles/modules should check flags before enabling workflows.\n- Flags referenced in docs + Studio UI to avoid accidental exposure.\n\n---\n\n### 8. Analytics & Telemetry\n\n- Events defined in analytics library; consumed by bundle/app:\n - `lifecycle_assessment_run`\n - `lifecycle_stage_changed`\n - `lifecycle_guidance_consumed`\n- Observability pipeline includes:\n - Composite lifecycle health metric (weighted sum of KPIs).\n - Drift detection comparing stage predictions over time.\n - Alert manager recipes for regression (e.g., PMF drop).\n\n---\n\n### 9. Testing Strategy\n\n1. **Unit**\n - StageScorer weight matrix.\n - RecommendationEngine mapping.\n - Library recommender stage coverage.\n\n2. **Contract**\n - Adapters: ensure mock adapters satisfy interfaces.\n - Bundles: ensure HTTP handlers respect request/response contracts even without persistence.\n\n3. **Integration**\n - CLI example runs detection + guidance end-to-end on fixture data.\n - Dashboard example renders assessments, verifying JSON structures remain stable.\n\n---\n\n### 10. Implementation Checklist\n\n- [ ] Documentation (product, tech, ops, user).\n- [ ] Library creation (`@lssm/lib.lifecycle`).\n- [ ] Modules (`lifecycle-core`, `lifecycle-advisor`).\n- [ ] Bundle (`lifecycle-managed`) + Studio wiring.\n- [ ] Library enhancements (analytics/evolution/growth/observability).\n- [ ] Examples (CLI + dashboard).\n- [ ] Feature flags + telemetry.\n- [ ] Automated tests + fixtures.\n\nKeep 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\n\n\n"
|
|
311
|
+
}];
|
|
312
|
+
registerDocBlocks(tech_lifecycle_stage_system_DocBlocks);
|
|
313
|
+
|
|
314
|
+
//#endregion
|
|
315
|
+
//#region ../../libs/contracts/src/docs/tech/presentation-runtime.docblock.ts
|
|
316
|
+
const tech_presentation_runtime_DocBlocks = [{
|
|
317
|
+
id: "docs.tech.presentation-runtime",
|
|
318
|
+
title: "Presentation Runtime",
|
|
319
|
+
summary: "Cross-platform runtime for list pages and presentation flows.",
|
|
320
|
+
kind: "reference",
|
|
321
|
+
visibility: "public",
|
|
322
|
+
route: "/docs/tech/presentation-runtime",
|
|
323
|
+
tags: ["tech", "presentation-runtime"],
|
|
324
|
+
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"
|
|
325
|
+
}];
|
|
326
|
+
registerDocBlocks(tech_presentation_runtime_DocBlocks);
|
|
327
|
+
|
|
328
|
+
//#endregion
|
|
329
|
+
//#region ../../libs/contracts/src/docs/tech/auth/better-auth-nextjs.docblock.ts
|
|
330
|
+
const tech_auth_better_auth_nextjs_DocBlocks = [{
|
|
331
|
+
id: "docs.tech.auth.better-auth-nextjs",
|
|
332
|
+
title: "Better Auth + Next.js integration (ContractSpec)",
|
|
333
|
+
summary: "How ContractSpec wires Better Auth into Next.js (server config, client singleton, and proxy cookie-only redirects).",
|
|
334
|
+
kind: "reference",
|
|
335
|
+
visibility: "public",
|
|
336
|
+
route: "/docs/tech/auth/better-auth-nextjs",
|
|
337
|
+
tags: [
|
|
338
|
+
"auth",
|
|
339
|
+
"better-auth",
|
|
340
|
+
"nextjs",
|
|
341
|
+
"cookies",
|
|
342
|
+
"proxy",
|
|
343
|
+
"hmr"
|
|
344
|
+
],
|
|
345
|
+
body: `# Better Auth + Next.js integration (ContractSpec)
|
|
346
|
+
|
|
347
|
+
This repo uses Better Auth as the primary auth layer (sessions, organizations, teams, API keys, and OAuth).
|
|
348
|
+
|
|
349
|
+
## Server config (Better Auth)
|
|
350
|
+
|
|
351
|
+
- Source: \`packages/bundles/contractspec-studio/src/application/services/auth.ts\`
|
|
352
|
+
- Important: \`nextCookies()\` must be the **last** plugin in the Better Auth plugin list so \`Set-Cookie\` is applied correctly in Next.js environments.
|
|
353
|
+
|
|
354
|
+
## Better Auth Admin plugin
|
|
355
|
+
|
|
356
|
+
ContractSpec Studio enables the Better Auth **Admin plugin** to support platform-admin user operations (list users, impersonation, etc.).
|
|
357
|
+
|
|
358
|
+
- Server: \`admin()\` plugin in \`packages/bundles/contractspec-studio/src/application/services/auth.ts\`
|
|
359
|
+
- Client: \`adminClient()\` in \`packages/bundles/contractspec-studio/src/presentation/providers/auth/client.ts\`
|
|
360
|
+
|
|
361
|
+
### PLATFORM_ADMIN ⇒ Better Auth admin role
|
|
362
|
+
|
|
363
|
+
Better Auth Admin endpoints authorize via \`user.role\`. ContractSpec enforces an org-driven rule:
|
|
364
|
+
|
|
365
|
+
- If the **active organization** has \`type = PLATFORM_ADMIN\`, the signed-in user is ensured to have \`User.role\` containing \`admin\`.
|
|
366
|
+
- This is applied in the session creation hook and re-checked in \`assertsPlatformAdmin()\`.
|
|
367
|
+
|
|
368
|
+
This keeps admin enablement deterministic and avoids manual role backfills.
|
|
369
|
+
|
|
370
|
+
## Client config (React web + Expo)
|
|
371
|
+
|
|
372
|
+
To avoid duplicate background refresh/polling loops in dev (Fast Refresh/HMR), the Better Auth client is implemented as a singleton cached on \`globalThis\`.
|
|
373
|
+
|
|
374
|
+
- Web client: \`packages/bundles/contractspec-studio/src/presentation/providers/auth/client.ts\`
|
|
375
|
+
- Native client: \`packages/bundles/contractspec-studio/src/presentation/providers/auth/client.native.ts\`
|
|
376
|
+
|
|
377
|
+
Import guidance:
|
|
378
|
+
|
|
379
|
+
- If you only need the context/hook, prefer importing from \`@lssm/bundle.contractspec-studio/presentation/providers/auth\`.
|
|
380
|
+
- 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\`.
|
|
381
|
+
|
|
382
|
+
## Public routes (login / signup)
|
|
383
|
+
|
|
384
|
+
Public auth pages should avoid eager \`authClient\` initialization.
|
|
385
|
+
|
|
386
|
+
Pattern used:
|
|
387
|
+
|
|
388
|
+
- In the submit handler, dynamically import \`@lssm/bundle.contractspec-studio/presentation/providers/auth/index.web\` and call \`authClient.signIn.*\` / \`authClient.signUp.*\`.
|
|
389
|
+
|
|
390
|
+
This prevents session refresh behavior from starting just because a public page rendered.
|
|
391
|
+
|
|
392
|
+
## Next.js proxy auth (web-landing)
|
|
393
|
+
|
|
394
|
+
The Next.js proxy/middleware is used for **redirect decisions only**. It must not perform DB-backed session reads on every request.
|
|
395
|
+
|
|
396
|
+
- Source: \`packages/apps/web-landing/src/proxy.ts\`
|
|
397
|
+
- Approach: cookie-only checks via Better Auth cookies helpers:
|
|
398
|
+
- \`getSessionCookie(request)\`
|
|
399
|
+
- \`getCookieCache(request)\`
|
|
400
|
+
|
|
401
|
+
These checks are intentionally optimistic and should only gate routing. Full authorization must still be enforced on server-side actions/routes and GraphQL resolvers.
|
|
402
|
+
`
|
|
403
|
+
}];
|
|
404
|
+
registerDocBlocks(tech_auth_better_auth_nextjs_DocBlocks);
|
|
405
|
+
|
|
406
|
+
//#endregion
|
|
407
|
+
//#region ../../libs/contracts/src/docs/tech/schema/README.docblock.ts
|
|
408
|
+
const tech_schema_README_DocBlocks = [{
|
|
409
|
+
id: "docs.tech.schema.README",
|
|
410
|
+
title: "Multi‑File Prisma Schema Conventions (per database)",
|
|
411
|
+
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.",
|
|
412
|
+
kind: "reference",
|
|
413
|
+
visibility: "public",
|
|
414
|
+
route: "/docs/tech/schema/README",
|
|
415
|
+
tags: [
|
|
416
|
+
"tech",
|
|
417
|
+
"schema",
|
|
418
|
+
"README"
|
|
419
|
+
],
|
|
420
|
+
body: "# Multi‑File Prisma Schema Conventions (per database)\n\nWe adopt Prisma multi‑file schema (GA ≥ v6.7) to organize each database’s models by domain and to import core LSSM module schemas locally.\n\nCanonical layout per DB:\n\n```\nprisma/\n schema/\n main.prisma # datasource + generators only\n imported/\n lssm_sigil/*.prisma # imported models/enums only (no datasource/generator)\n lssm_content/*.prisma # idem\n <domain>/*.prisma # vertical‑specific models split by bounded context\n```\n\nNotes:\n\n- Imported files contain only `model` and `enum` blocks (strip `datasource`/`generator`).\n- 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\"]`.\n- Use `@lssm/app.cli-database` CLI: `database import|check|generate|migrate:*|seed` to manage a single DB; `@lssm/app.cli-databases` orchestrates multiple DBs.\n\n## Typed merger config\n\n- Define imported module list once per DB with a typed config:\n\n```ts\n// prisma-merger.config.ts\nimport { defineMergedPrismaConfig } from '@lssm/app.cli-database';\n\nexport default defineMergedPrismaConfig({\n modules: [\n '@lssm/app.cli-database-sigil',\n '@lssm/app.cli-database-content',\n // ...\n ],\n});\n```\n\n- Then run `database import --target .` (no need to pass `--modules`).\n\n## Prisma Config (prisma.config.ts)\n\nWe use Prisma Config per official docs to point Prisma to the multi-file schema folder and migrations:\n\n```ts\n// prisma.config.ts\nimport path from 'node:path';\nimport { defineConfig } from 'prisma/config';\n\nexport default defineConfig({\n schema: path.join('prisma', 'schema'),\n migrations: { path: path.join('prisma', 'migrations') },\n});\n```\n\nReference: Prisma blog – Organize Your Prisma Schema into Multiple Files: https://www.prisma.io/blog/organize-your-prisma-schema-with-multi-file-support\n\n---\n\n# LSSM Auth (Sigil) – Models & Integration\n\nThis document tracks the identity models and integration points used by the LSSM Sigil module.\n\n## Models (Prisma `lssm_sigil`)\n\n- `User` – core identity with email, optional phone, role, passkeys, apiKeys\n- `Session` – session tokens and metadata; includes `activeOrganizationId`\n- `Account` – external providers (password, OAuth)\n- `Organization` – tenant boundary; includes `type` additional field\n- `Member`, `Invitation`, `Team`, `TeamMember` – org/teams\n- `Role`, `Permission`, `PolicyBinding` – RBAC\n- `ApiKey`, `Passkey` – programmable access and WebAuthn\n- `SsoProvider` – OIDC/SAML provider configuration (org- or user-scoped)\n- `OAuthApplication`, `OAuthAccessToken`, `OAuthConsent` – first/third-party OAuth\n\nThese mirror STRIT additions so Better Auth advanced plugins (admin, organization, apiKey, passkey, genericOAuth) work uniformly across apps.\n\n## Better Auth (server)\n\nEnabled methods:\n\n- Email & password\n- Phone OTP (Telnyx)\n- Passkey (WebAuthn)\n- API keys\n- Organizations & Teams\n- Generic OAuth (FranceConnect+ via OIDC with JWE/JWS using JOSE)\n\nServer config lives at `packages/lssm/modules/sigil/src/application/services/auth.ts`.\n\n## Clients (Expo / React)\n\nClient config lives at `packages/lssm/modules/sigil/src/presentation/providers/auth/expo.ts` with plugins for admin, passkey, apiKey, organization, phone, genericOAuth.\n\n## Environment Variables\n\nTelnyx (phone OTP):\n\n- `TELNYX_API_KEY`\n- `TELNYX_MESSAGING_PROFILE_ID`\n- `TELNYX_FROM_NUMBER`\n\nFranceConnect+ (prefer LSSM*… but STRIT*… fallbacks are supported):\n\n- `LSSM_FRANCECONNECTPLUS_DISCOVERY_URL`\n- `LSSM_FRANCECONNECTPLUS_CLIENT_ID`\n- `LSSM_FRANCECONNECTPLUS_CLIENT_SECRET`\n- `LSSM_FRANCECONNECTPLUS_ENC_PRIVATE_KEY_PEM` (PKCS8; RSA-OAEP-256)\n\nGeneric:\n\n- `API_URL_IDENTITIES` – base URL for Better Auth server\n- `BETTER_AUTH_SECRET` – server secret\n\nKeep this in sync with code changes to avoid drift.\n\n## HCircle domain splits and auth removal\n\n- Auth/identity models are not defined locally anymore. They come from `@lssm/app.cli-database-sigil` under the `lssm_sigil` schema.\n- `packages/hcircle/libs/database-coliving/prisma/schema/domain/` is split by domain; newsletter/waiting list lives in `newsletter.prisma` and uses `@@map(\"waiting_list\")`.\n- To avoid collisions with module names, the local event models were renamed to `SocialEvent`, `SocialEventAttendee`, and `SocialEventRecurrence` with `@@map` pointing to existing table names.\n\n---\n\n## Vertical profiles (current)\n\n### STRIT\n\n- prisma-merger modules:\n - `@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`\n- main.prisma schemas:\n - `schemas = [\"public\",\"lssm_sigil\",\"lssm_content\",\"lssm_ops\",\"lssm_planning\",\"lssm_quill\",\"lssm_geoterro\"]`\n- domain splits (`packages/strit/libs/database/prisma/schema/domain/`):\n - `bookings.prisma` (Booking, StritDocument + links to Content `File` and Sigil `Organization`)\n - `commerce.prisma` (Wholesale models; `sellerId` linked to Sigil `Organization`)\n - `files.prisma` (PublicFile, PublicFileAccessLog; `ownerId`→Organization, `uploadedBy`→User)\n - `geo.prisma` (PublicCountry, PublicAddress, City; links to Spots/Series)\n - `spots.prisma`, `urbanism.prisma`, `analytics.prisma`, `onboarding.prisma`, `referrals.prisma`, `subscriptions.prisma`, `content.prisma`\n- auth models are imported from Sigil (no local auth tables).\n- Back-relations for `Organization` (e.g., `files`, seller relations) are declared in the Sigil module to avoid scattering.\n\n### ARTISANOS\n\n- prisma-merger modules:\n - `@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`\n- main.prisma schemas:\n - `schemas = [\"public\",\"lssm_sigil\",\"lssm_content\",\"lssm_featureflags\",\"lssm_ops\",\"lssm_planning\",\"lssm_quill\",\"lssm_geoterro\"]`\n- domain splits (`packages/artisanos/libs/database-artisan/prisma/schema/domain/`):\n - `sales.prisma` (Client, Quote, QuoteTemplate, Invoice, FollowUps)\n - `subsidies.prisma` (SubsidyProgram, AidApplication, SupportingDocument)\n - `projects.prisma` (Project, ProjectPlanningSettings)\n - `crm.prisma` (OrganizationProfessionalProfile, OrganizationCertification)\n - `professions.prisma`, `products.prisma`, `templates.prisma`, `analytics.prisma`, `onboarding.prisma`, `referrals.prisma`, `subscriptions.prisma`, `files.prisma`\n- auth/organization/team models are provided by Sigil; local legacy copies were removed.\n- Where names collide with Content, local models are prefixed (e.g., `PublicFile`) and use `@@map` to keep existing table names where applicable.\n\n## Schema Dictionary: `@lssm/lib.schema`\n\n### Purpose\n\nDescribe operation I/O once and generate:\n\n- zod (runtime validation)\n- GraphQL (Pothos types/refs)\n- JSON Schema (via `zod-to-json-schema` or native descriptors)\n\n### Primitives\n\n- **FieldType<T>**: describes a scalar or composite field and carries:\n - `zod` schema for validation\n - optional JSON Schema descriptor\n - optional GraphQL scalar reference/name\n- **SchemaModel**: named object model composed of fields. Exposes helpers:\n - `getZod(): z.ZodObject<ZodShapeFromFields<Fields>> | z.ZodArray<z.ZodObject<...>>`\n - Preserves each field's schema, optionality, and array-ness\n - Top-level lists are supported via `config.isArray: true`\n - `getJsonSchema(): JSONSchema7` (export for docs, MCP, forms)\n - `getPothosInput()` (GraphQL input object name)\n\n### Conventions\n\n- Name models with PascalCase; suffix with `Input`/`Result` when ambiguous.\n- Use explicit enums for multi-value constants; reuse the same enum across input/output.\n- Define domain enums via `defineEnum('Name', [...])` in the relevant domain package (e.g., `packages/strit/libs/contracts-strit/src/enums/`), not in `ScalarTypeEnum`.\n- Reference those enums in `SchemaModel` fields directly (they expose `getZod`, `getPothos`, `getJsonSchema`).\n\n#### Example (STRIT)\n\n```ts\n// packages/strit/libs/contracts-strit/src/enums/recurrence.ts\nimport { defineEnum } from '@lssm/lib.schema';\nexport const SpotEnum = {\n Weekday: () =>\n defineEnum('Weekday', ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'] as const),\n RecurrenceFrequency: () =>\n defineEnum('RecurrenceFrequency', [\n 'DAILY',\n 'WEEKLY',\n 'MONTHLY',\n 'YEARLY',\n ] as const),\n} as const;\n```\n\n```ts\n// usage in contracts\nfrequency: { type: SpotEnum.RecurrenceFrequency(), isOptional: false },\nbyWeekday: { type: SpotEnum.Weekday(), isOptional: true, isArray: true },\n```\n\n- Use `Date` type for temporal values and ensure ISO strings in JSON transports where needed.\n\n### Mapping rules (summary)\n\n- Strings → GraphQL `String`\n- Numbers → `Int` if safe 32-bit integer else `Float`\n- Booleans → `Boolean`\n- Dates → custom `Date` scalar\n- Arrays<T> → list of mapped T (set `isArray: true` on the field)\n- Top-level arrays → set `isArray: true` on the model config\n- Objects → input/output object types with stable field order\n- Unions → supported for output; input unions map to JSON (structural input is not supported by GraphQL)\n\n### JSON Schema export\n\nPrefer `getZod()` + `zod-to-json-schema` for consistency. For advanced cases, provide a custom `getJsonSchema()` on the model.\n\n### Example\n\n```ts\nimport { ScalarTypeEnum, SchemaModel } from '@lssm/lib.schema';\n\n// Nested model\nconst Weekday = new SchemaModel({\n name: 'Weekday',\n fields: {\n value: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },\n },\n});\n\n// Parent model with array field and nested object\nconst Rule = new SchemaModel({\n name: 'Rule',\n fields: {\n timezone: { type: ScalarTypeEnum.TimeZone(), isOptional: false },\n byWeekday: { type: Weekday, isOptional: true, isArray: true },\n },\n});\n\nconst CreateThingInput = new SchemaModel({\n name: 'CreateThingInput',\n fields: {\n name: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },\n rule: { type: Rule, isOptional: false },\n },\n});\n\n// zod\nconst z = CreateThingInput.getZod();\n```\n"
|
|
421
|
+
}];
|
|
422
|
+
registerDocBlocks(tech_schema_README_DocBlocks);
|
|
423
|
+
|
|
424
|
+
//#endregion
|
|
425
|
+
//#region ../../libs/contracts/src/docs/tech/templates/runtime.docblock.ts
|
|
426
|
+
const tech_templates_runtime_DocBlocks = [{
|
|
427
|
+
id: "docs.tech.templates.runtime",
|
|
428
|
+
title: "ContractSpec Template Runtime (Phase 9)",
|
|
429
|
+
summary: "Phase 9 introduces a full local-first runtime for templates so anyone can preview apps directly in the browser without provisioning any infrastructure.",
|
|
430
|
+
kind: "reference",
|
|
431
|
+
visibility: "public",
|
|
432
|
+
route: "/docs/tech/templates/runtime",
|
|
433
|
+
tags: [
|
|
434
|
+
"tech",
|
|
435
|
+
"templates",
|
|
436
|
+
"runtime"
|
|
437
|
+
],
|
|
438
|
+
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"
|
|
439
|
+
}];
|
|
440
|
+
registerDocBlocks(tech_templates_runtime_DocBlocks);
|
|
441
|
+
|
|
442
|
+
//#endregion
|
|
443
|
+
//#region ../../libs/contracts/src/docs/tech/workflows/overview.docblock.ts
|
|
444
|
+
const tech_workflows_overview_DocBlocks = [{
|
|
445
|
+
id: "docs.tech.workflows.overview",
|
|
446
|
+
title: "WorkflowSpec Overview",
|
|
447
|
+
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.",
|
|
448
|
+
kind: "reference",
|
|
449
|
+
visibility: "public",
|
|
450
|
+
route: "/docs/tech/workflows/overview",
|
|
451
|
+
tags: [
|
|
452
|
+
"tech",
|
|
453
|
+
"workflows",
|
|
454
|
+
"overview"
|
|
455
|
+
],
|
|
456
|
+
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"
|
|
457
|
+
}];
|
|
458
|
+
registerDocBlocks(tech_workflows_overview_DocBlocks);
|
|
459
|
+
|
|
460
|
+
//#endregion
|
|
461
|
+
//#region ../../libs/contracts/src/docs/tech/mcp-endpoints.docblock.ts
|
|
462
|
+
const tech_mcp_endpoints_DocBlocks = [{
|
|
463
|
+
id: "docs.tech.mcp.endpoints",
|
|
464
|
+
title: "ContractSpec MCP endpoints",
|
|
465
|
+
summary: "Dedicated MCP servers for docs, CLI usage, and internal development.",
|
|
466
|
+
kind: "reference",
|
|
467
|
+
visibility: "mixed",
|
|
468
|
+
route: "/docs/tech/mcp/endpoints",
|
|
469
|
+
tags: [
|
|
470
|
+
"mcp",
|
|
471
|
+
"docs",
|
|
472
|
+
"cli",
|
|
473
|
+
"internal"
|
|
474
|
+
],
|
|
475
|
+
body: `# ContractSpec MCP endpoints
|
|
476
|
+
|
|
477
|
+
Three dedicated MCP servers keep AI agents efficient and scoped:
|
|
478
|
+
|
|
479
|
+
- **Docs MCP**: \`/api/mcp/docs\` — exposes DocBlocks as resources + presentations. Tool: \`docs.search\`.
|
|
480
|
+
- **CLI MCP**: \`/api/mcp/cli\` — surfaces CLI quickstart/reference/README and suggests commands. Tool: \`cli.suggestCommand\`.
|
|
481
|
+
- **Internal MCP**: \`/api/mcp/internal\` — internal routing hints, playbook, and example registry access. Tool: \`internal.describe\`.
|
|
482
|
+
|
|
483
|
+
### Usage notes
|
|
484
|
+
- Transports are HTTP POST (streamable HTTP); SSE is disabled.
|
|
485
|
+
- Resources are namespaced (\`docs://*\`, \`cli://*\`, \`internal://*\`) and are read-only.
|
|
486
|
+
- Internal MCP also exposes the examples registry via \`examples://*\` resources:
|
|
487
|
+
- \`examples://list?q=<query>\`
|
|
488
|
+
- \`examples://example/<id>\`
|
|
489
|
+
- Prompts mirror each surface (navigator, usage, bootstrap) for quick agent onboarding.
|
|
490
|
+
- GraphQL remains at \`/graphql\`; health at \`/health\`.
|
|
491
|
+
`
|
|
492
|
+
}];
|
|
493
|
+
registerDocBlocks(tech_mcp_endpoints_DocBlocks);
|
|
494
|
+
|
|
495
|
+
//#endregion
|
|
496
|
+
//#region ../../libs/contracts/src/docs/tech/vscode-extension.docblock.ts
|
|
497
|
+
const tech_vscode_extension_DocBlocks = [{
|
|
498
|
+
id: "docs.tech.vscode.extension",
|
|
499
|
+
title: "ContractSpec VS Code Extension",
|
|
500
|
+
summary: "VS Code extension for spec-first development with validation, scaffolding, and MCP integration.",
|
|
501
|
+
kind: "reference",
|
|
502
|
+
visibility: "public",
|
|
503
|
+
route: "/docs/tech/vscode/extension",
|
|
504
|
+
tags: [
|
|
505
|
+
"vscode",
|
|
506
|
+
"extension",
|
|
507
|
+
"tooling",
|
|
508
|
+
"dx"
|
|
509
|
+
],
|
|
510
|
+
body: `# ContractSpec VS Code Extension
|
|
511
|
+
|
|
512
|
+
The ContractSpec VS Code extension provides spec-first development tooling directly in your editor.
|
|
513
|
+
|
|
514
|
+
## Features
|
|
515
|
+
|
|
516
|
+
- **Real-time Validation**: Get instant feedback on spec errors and warnings as you save files
|
|
517
|
+
- **Build/Scaffold**: Generate handler and component skeletons from specs (no AI required)
|
|
518
|
+
- **Spec Explorer**: List and navigate all specs in your workspace
|
|
519
|
+
- **Dependency Analysis**: Visualize spec dependencies and detect cycles
|
|
520
|
+
- **MCP Integration**: Search ContractSpec documentation via Model Context Protocol
|
|
521
|
+
- **Snippets**: Code snippets for common ContractSpec patterns
|
|
522
|
+
|
|
523
|
+
## Commands
|
|
524
|
+
|
|
525
|
+
| Command | Description |
|
|
526
|
+
|---------|-------------|
|
|
527
|
+
| \`ContractSpec: Validate Current Spec\` | Validate the currently open spec file |
|
|
528
|
+
| \`ContractSpec: Validate All Specs\` | Validate all spec files in the workspace |
|
|
529
|
+
| \`ContractSpec: Build/Scaffold\` | Generate handler/component from the current spec |
|
|
530
|
+
| \`ContractSpec: List All Specs\` | Show all specs in the workspace |
|
|
531
|
+
| \`ContractSpec: Analyze Dependencies\` | Analyze and visualize spec dependencies |
|
|
532
|
+
| \`ContractSpec: Search Docs (MCP)\` | Search documentation via MCP |
|
|
533
|
+
|
|
534
|
+
## Configuration
|
|
535
|
+
|
|
536
|
+
| Setting | Description | Default |
|
|
537
|
+
|---------|-------------|---------|
|
|
538
|
+
| \`contractspec.api.baseUrl\` | Base URL for ContractSpec API (enables MCP + remote telemetry) | \`""\` |
|
|
539
|
+
| \`contractspec.telemetry.posthogHost\` | PostHog host URL for direct telemetry | \`"https://eu.posthog.com"\` |
|
|
540
|
+
| \`contractspec.telemetry.posthogProjectKey\` | PostHog project key for direct telemetry | \`""\` |
|
|
541
|
+
| \`contractspec.validation.onSave\` | Run validation on save | \`true\` |
|
|
542
|
+
| \`contractspec.validation.onOpen\` | Run validation on open | \`true\` |
|
|
543
|
+
|
|
544
|
+
## Architecture
|
|
545
|
+
|
|
546
|
+
The extension uses:
|
|
547
|
+
- \`@lssm/module.contractspec-workspace\` for pure analysis + templates
|
|
548
|
+
- \`@lssm/bundle.contractspec-workspace\` for workspace services + adapters
|
|
549
|
+
|
|
550
|
+
This allows the extension to work without requiring the CLI to be installed.
|
|
551
|
+
|
|
552
|
+
## Telemetry
|
|
553
|
+
|
|
554
|
+
The extension uses a hybrid telemetry approach:
|
|
555
|
+
1. If \`contractspec.api.baseUrl\` is configured → send to API \`/api/telemetry/ingest\`
|
|
556
|
+
2. Otherwise → send directly to PostHog (if project key configured)
|
|
557
|
+
|
|
558
|
+
Telemetry respects VS Code's telemetry settings. No file paths, source code, or PII is collected.
|
|
559
|
+
`
|
|
560
|
+
}, {
|
|
561
|
+
id: "docs.tech.vscode.snippets",
|
|
562
|
+
title: "ContractSpec Snippets",
|
|
563
|
+
summary: "Code snippets for common ContractSpec patterns in VS Code.",
|
|
564
|
+
kind: "reference",
|
|
565
|
+
visibility: "public",
|
|
566
|
+
route: "/docs/tech/vscode/snippets",
|
|
567
|
+
tags: [
|
|
568
|
+
"vscode",
|
|
569
|
+
"snippets",
|
|
570
|
+
"dx"
|
|
571
|
+
],
|
|
572
|
+
body: `# ContractSpec Snippets
|
|
573
|
+
|
|
574
|
+
The VS Code extension includes snippets for common ContractSpec patterns.
|
|
575
|
+
|
|
576
|
+
## Available Snippets
|
|
577
|
+
|
|
578
|
+
| Prefix | Description |
|
|
579
|
+
|--------|-------------|
|
|
580
|
+
| \`contractspec-command\` | Create a new command (write operation) |
|
|
581
|
+
| \`contractspec-query\` | Create a new query (read-only operation) |
|
|
582
|
+
| \`contractspec-event\` | Create a new event |
|
|
583
|
+
| \`contractspec-docblock\` | Create a new DocBlock |
|
|
584
|
+
| \`contractspec-telemetry\` | Create a new TelemetrySpec |
|
|
585
|
+
| \`contractspec-presentation\` | Create a new Presentation |
|
|
586
|
+
|
|
587
|
+
## Usage
|
|
588
|
+
|
|
589
|
+
Type the prefix in a TypeScript file and press Tab to expand the snippet. Tab through the placeholders to fill in your values.
|
|
590
|
+
`
|
|
591
|
+
}];
|
|
592
|
+
registerDocBlocks(tech_vscode_extension_DocBlocks);
|
|
593
|
+
|
|
594
|
+
//#endregion
|
|
595
|
+
//#region ../../libs/contracts/src/docs/tech/telemetry-ingest.docblock.ts
|
|
596
|
+
const tech_telemetry_ingest_DocBlocks = [{
|
|
597
|
+
id: "docs.tech.telemetry.ingest",
|
|
598
|
+
title: "Telemetry Ingest Endpoint",
|
|
599
|
+
summary: "Server-side telemetry ingestion for ContractSpec clients (VS Code extension, CLI, etc.).",
|
|
600
|
+
kind: "reference",
|
|
601
|
+
visibility: "internal",
|
|
602
|
+
route: "/docs/tech/telemetry/ingest",
|
|
603
|
+
tags: [
|
|
604
|
+
"telemetry",
|
|
605
|
+
"api",
|
|
606
|
+
"posthog",
|
|
607
|
+
"analytics"
|
|
608
|
+
],
|
|
609
|
+
body: `# Telemetry Ingest Endpoint
|
|
610
|
+
|
|
611
|
+
The ContractSpec API provides a telemetry ingest endpoint for clients to send product analytics events.
|
|
612
|
+
|
|
613
|
+
## Endpoint
|
|
614
|
+
|
|
615
|
+
\`\`\`
|
|
616
|
+
POST /api/telemetry/ingest
|
|
617
|
+
\`\`\`
|
|
618
|
+
|
|
619
|
+
## Request
|
|
620
|
+
|
|
621
|
+
\`\`\`json
|
|
622
|
+
{
|
|
623
|
+
"event": "contractspec.vscode.command_run",
|
|
624
|
+
"distinct_id": "client-uuid",
|
|
625
|
+
"properties": {
|
|
626
|
+
"command": "validate"
|
|
627
|
+
},
|
|
628
|
+
"timestamp": "2024-01-15T10:30:00.000Z"
|
|
629
|
+
}
|
|
630
|
+
\`\`\`
|
|
631
|
+
|
|
632
|
+
### Headers
|
|
633
|
+
|
|
634
|
+
| Header | Description |
|
|
635
|
+
|--------|-------------|
|
|
636
|
+
| \`x-contractspec-client-id\` | Optional client identifier (used as fallback for distinct_id) |
|
|
637
|
+
| \`Content-Type\` | Must be \`application/json\` |
|
|
638
|
+
|
|
639
|
+
### Body
|
|
640
|
+
|
|
641
|
+
| Field | Type | Required | Description |
|
|
642
|
+
|-------|------|----------|-------------|
|
|
643
|
+
| \`event\` | string | Yes | Event name (e.g., \`contractspec.vscode.activated\`) |
|
|
644
|
+
| \`distinct_id\` | string | Yes | Anonymous client identifier |
|
|
645
|
+
| \`properties\` | object | No | Event properties |
|
|
646
|
+
| \`timestamp\` | string | No | ISO 8601 timestamp |
|
|
647
|
+
|
|
648
|
+
## Response
|
|
649
|
+
|
|
650
|
+
\`\`\`json
|
|
651
|
+
{
|
|
652
|
+
"success": true
|
|
653
|
+
}
|
|
654
|
+
\`\`\`
|
|
655
|
+
|
|
656
|
+
## Configuration
|
|
657
|
+
|
|
658
|
+
The endpoint requires \`POSTHOG_PROJECT_KEY\` environment variable to be set. If not configured, events are accepted but not forwarded.
|
|
659
|
+
|
|
660
|
+
| Environment Variable | Description | Default |
|
|
661
|
+
|---------------------|-------------|---------|
|
|
662
|
+
| \`POSTHOG_HOST\` | PostHog host URL | \`https://eu.posthog.com\` |
|
|
663
|
+
| \`POSTHOG_PROJECT_KEY\` | PostHog project API key | (required) |
|
|
664
|
+
|
|
665
|
+
## Privacy
|
|
666
|
+
|
|
667
|
+
- No PII is collected or stored
|
|
668
|
+
- \`distinct_id\` is an anonymous client-generated UUID
|
|
669
|
+
- File paths and source code are never included in events
|
|
670
|
+
- Respects VS Code telemetry settings on the client side
|
|
671
|
+
|
|
672
|
+
## Events
|
|
673
|
+
|
|
674
|
+
### Extension Events
|
|
675
|
+
|
|
676
|
+
| Event | Description | Properties |
|
|
677
|
+
|-------|-------------|------------|
|
|
678
|
+
| \`contractspec.vscode.activated\` | Extension activated | \`version\` |
|
|
679
|
+
| \`contractspec.vscode.command_run\` | Command executed | \`command\` |
|
|
680
|
+
| \`contractspec.vscode.mcp_call\` | MCP call made | \`endpoint\`, \`tool\` |
|
|
681
|
+
|
|
682
|
+
### API Events
|
|
683
|
+
|
|
684
|
+
| Event | Description | Properties |
|
|
685
|
+
|-------|-------------|------------|
|
|
686
|
+
| \`contractspec.api.mcp_request\` | MCP request processed | \`endpoint\`, \`method\`, \`success\`, \`duration_ms\` |
|
|
687
|
+
`
|
|
688
|
+
}, {
|
|
689
|
+
id: "docs.tech.telemetry.hybrid",
|
|
690
|
+
title: "Hybrid Telemetry Model",
|
|
691
|
+
summary: "How ContractSpec clients choose between direct PostHog and API-routed telemetry.",
|
|
692
|
+
kind: "usage",
|
|
693
|
+
visibility: "internal",
|
|
694
|
+
route: "/docs/tech/telemetry/hybrid",
|
|
695
|
+
tags: [
|
|
696
|
+
"telemetry",
|
|
697
|
+
"architecture",
|
|
698
|
+
"posthog"
|
|
699
|
+
],
|
|
700
|
+
body: `# Hybrid Telemetry Model
|
|
701
|
+
|
|
702
|
+
ContractSpec uses a hybrid telemetry model where clients can send events either directly to PostHog or via the API server.
|
|
703
|
+
|
|
704
|
+
## Decision Flow
|
|
705
|
+
|
|
706
|
+
\`\`\`
|
|
707
|
+
Is contractspec.api.baseUrl configured?
|
|
708
|
+
├── Yes → Send via /api/telemetry/ingest
|
|
709
|
+
└── No → Is posthogProjectKey configured?
|
|
710
|
+
├── Yes → Send directly to PostHog
|
|
711
|
+
└── No → Telemetry disabled
|
|
712
|
+
\`\`\`
|
|
713
|
+
|
|
714
|
+
## Benefits
|
|
715
|
+
|
|
716
|
+
### Direct PostHog
|
|
717
|
+
- No server dependency
|
|
718
|
+
- Works offline (with batching)
|
|
719
|
+
- Lower latency
|
|
720
|
+
|
|
721
|
+
### Via API
|
|
722
|
+
- Centralized key management (no client-side keys)
|
|
723
|
+
- Server-side enrichment and validation
|
|
724
|
+
- Rate limiting and abuse prevention
|
|
725
|
+
- Easier migration to other providers
|
|
726
|
+
|
|
727
|
+
## Recommendation
|
|
728
|
+
|
|
729
|
+
- **Development**: Use direct PostHog with a dev project key
|
|
730
|
+
- **Production**: Route via API for better governance
|
|
731
|
+
|
|
732
|
+
## Future: OpenTelemetry
|
|
733
|
+
|
|
734
|
+
The current PostHog implementation is behind a simple interface that can be swapped for OpenTelemetry:
|
|
735
|
+
|
|
736
|
+
\`\`\`typescript
|
|
737
|
+
interface TelemetryClient {
|
|
738
|
+
send(event: TelemetryEvent): Promise<void>;
|
|
739
|
+
}
|
|
740
|
+
\`\`\`
|
|
741
|
+
|
|
742
|
+
This allows future migration without changing client code.
|
|
743
|
+
`
|
|
744
|
+
}];
|
|
745
|
+
registerDocBlocks(tech_telemetry_ingest_DocBlocks);
|
|
746
|
+
|
|
747
|
+
//#endregion
|
|
748
|
+
//#region ../../libs/contracts/src/docs/tech/contracts/openapi-export.docblock.ts
|
|
749
|
+
const tech_contracts_openapi_export_DocBlocks = [{
|
|
750
|
+
id: "docs.tech.contracts.openapi-export",
|
|
751
|
+
title: "OpenAPI export (OpenAPI 3.1) from SpecRegistry",
|
|
752
|
+
summary: "Generate a deterministic OpenAPI document from a SpecRegistry using jsonSchemaForSpec + REST transport metadata.",
|
|
753
|
+
kind: "reference",
|
|
754
|
+
visibility: "public",
|
|
755
|
+
route: "/docs/tech/contracts/openapi-export",
|
|
756
|
+
tags: [
|
|
757
|
+
"contracts",
|
|
758
|
+
"openapi",
|
|
759
|
+
"rest"
|
|
760
|
+
],
|
|
761
|
+
body: `## OpenAPI export (OpenAPI 3.1) from SpecRegistry
|
|
762
|
+
|
|
763
|
+
### Purpose
|
|
764
|
+
|
|
765
|
+
ContractSpec specs can be exported into an **OpenAPI 3.1** document for tooling (SDK generation, docs, gateways).
|
|
766
|
+
|
|
767
|
+
The export is **spec-first**:
|
|
768
|
+
|
|
769
|
+
- Uses \`jsonSchemaForSpec(spec)\` for input/output JSON Schema (from SchemaModel → zod → JSON Schema)
|
|
770
|
+
- Uses \`spec.transport.rest.method/path\` when present
|
|
771
|
+
- Falls back to deterministic defaults:
|
|
772
|
+
- Method: \`POST\` for commands, \`GET\` for queries
|
|
773
|
+
- Path: \`defaultRestPath(name, version)\` → \`/<dot/name>/v<version>\`
|
|
774
|
+
|
|
775
|
+
### Library API
|
|
776
|
+
|
|
777
|
+
- Function: \`openApiForRegistry(registry, options?)\`
|
|
778
|
+
- Location: \`@lssm/lib.contracts/openapi\`
|
|
779
|
+
|
|
780
|
+
### CLI
|
|
781
|
+
|
|
782
|
+
Export OpenAPI from a registry module:
|
|
783
|
+
|
|
784
|
+
\`\`\`bash
|
|
785
|
+
contractspec openapi --registry ./src/registry.ts --out ./openapi.json
|
|
786
|
+
\`\`\`
|
|
787
|
+
|
|
788
|
+
The registry module must export one of:
|
|
789
|
+
|
|
790
|
+
- \`registry: SpecRegistry\`
|
|
791
|
+
- \`default(): SpecRegistry | Promise<SpecRegistry>\`
|
|
792
|
+
- \`createRegistry(): SpecRegistry | Promise<SpecRegistry>\`
|
|
793
|
+
|
|
794
|
+
### Notes / limitations (current)
|
|
795
|
+
|
|
796
|
+
- Responses are generated as a basic \`200\` response (plus schemas when available).
|
|
797
|
+
- Query (GET) inputs are currently represented as a JSON request body when an input schema exists.
|
|
798
|
+
- Errors are not yet expanded into OpenAPI responses; that will be added when we standardize error envelopes.`
|
|
799
|
+
}];
|
|
800
|
+
registerDocBlocks(tech_contracts_openapi_export_DocBlocks);
|
|
801
|
+
|
|
802
|
+
//#endregion
|
|
803
|
+
//#region ../../libs/contracts/src/docs/tech/studio/workspaces.docblock.ts
|
|
804
|
+
const tech_studio_workspaces_DocBlocks = [{
|
|
805
|
+
id: "docs.tech.studio.workspaces",
|
|
806
|
+
title: "Studio projects, teams, environments",
|
|
807
|
+
summary: "Organization-first Studio: projects live under an organization; teams refine access; projects deploy to multiple environments.",
|
|
808
|
+
kind: "reference",
|
|
809
|
+
visibility: "mixed",
|
|
810
|
+
route: "/docs/tech/studio/workspaces",
|
|
811
|
+
tags: [
|
|
812
|
+
"studio",
|
|
813
|
+
"projects",
|
|
814
|
+
"teams",
|
|
815
|
+
"rbac",
|
|
816
|
+
"environments"
|
|
817
|
+
],
|
|
818
|
+
body: `## Concepts
|
|
819
|
+
|
|
820
|
+
- **Organization**: the primary grouping boundary for Studio projects.
|
|
821
|
+
- **Project**: one application (specs, overlays, deployments, integrations, evolution, learning).
|
|
822
|
+
- **Team**: refines who can see/edit a project within an organization.
|
|
823
|
+
- **Environment**: deployment target (Development / Staging / Production).
|
|
824
|
+
|
|
825
|
+
## Project access (teams + admin override)
|
|
826
|
+
|
|
827
|
+
Studio uses multi-team sharing to refine access:
|
|
828
|
+
|
|
829
|
+
- **Admins/owners** can access all projects.
|
|
830
|
+
- If a project is shared with **no teams**, it is **org-wide** (all org members).
|
|
831
|
+
- If a project is shared with **one or more teams**, it is visible to:
|
|
832
|
+
- admins/owners, and
|
|
833
|
+
- members of any linked team.
|
|
834
|
+
|
|
835
|
+
## Current persistence (DB + GraphQL)
|
|
836
|
+
|
|
837
|
+
- DB (Prisma): \`StudioProject\`, \`Team\`, \`TeamMember\`, \`StudioProjectTeam\`
|
|
838
|
+
- GraphQL:
|
|
839
|
+
- \`myStudioProjects\`
|
|
840
|
+
- \`createStudioProject(input.teamIds?)\`
|
|
841
|
+
- \`myTeams\`
|
|
842
|
+
- \`projectTeams(projectId)\`
|
|
843
|
+
- \`setProjectTeams(projectId, teamIds)\`
|
|
844
|
+
|
|
845
|
+
## UI shell behavior
|
|
846
|
+
|
|
847
|
+
Studio and Sandbox both use a shared shell:
|
|
848
|
+
|
|
849
|
+
- Project selector → Module navigation → Environment selector
|
|
850
|
+
- Always-on Assistant button (floating)
|
|
851
|
+
- Learning journey progress (Studio persists learning events; Sandbox stays local-only)
|
|
852
|
+
|
|
853
|
+
## Routing
|
|
854
|
+
|
|
855
|
+
- \`/studio/projects\`: create/select/delete projects (organization-first).
|
|
856
|
+
- \`/studio/{projectSlug}/*\`: project modules (canvas/specs/deploy/integrations/evolution/learning).
|
|
857
|
+
- \`/studio/learning\`: learning hub without selecting a project.
|
|
858
|
+
`
|
|
859
|
+
}];
|
|
860
|
+
registerDocBlocks(tech_studio_workspaces_DocBlocks);
|
|
861
|
+
|
|
862
|
+
//#endregion
|
|
863
|
+
//#region ../../libs/contracts/src/docs/tech/studio/sandbox-unlogged.docblock.ts
|
|
864
|
+
const tech_studio_sandbox_unlogged_DocBlocks = [{
|
|
865
|
+
id: "docs.tech.studio.sandbox.unlogged",
|
|
866
|
+
title: "Sandbox (unlogged) vs Studio (authenticated)",
|
|
867
|
+
summary: "The sandbox is a lightweight, unlogged surface that mirrors Studio navigation without auth or analytics.",
|
|
868
|
+
kind: "reference",
|
|
869
|
+
visibility: "public",
|
|
870
|
+
route: "/docs/tech/studio/sandbox-unlogged",
|
|
871
|
+
tags: [
|
|
872
|
+
"studio",
|
|
873
|
+
"sandbox",
|
|
874
|
+
"privacy",
|
|
875
|
+
"analytics"
|
|
876
|
+
],
|
|
877
|
+
body: `## Sandbox guarantees
|
|
878
|
+
|
|
879
|
+
- Route: \`/sandbox\`
|
|
880
|
+
- **No auth requirement**
|
|
881
|
+
- **No PostHog init**
|
|
882
|
+
- **No Vercel Analytics**
|
|
883
|
+
- Local-only state (in-browser runtime + localStorage where needed)
|
|
884
|
+
|
|
885
|
+
## What Sandbox is for
|
|
886
|
+
|
|
887
|
+
- Try templates and feature modules safely
|
|
888
|
+
- Preview specs/builder/evolution/learning
|
|
889
|
+
- Produce copyable CLI commands (no side effects)
|
|
890
|
+
|
|
891
|
+
## What Sandbox is *not* for
|
|
892
|
+
|
|
893
|
+
- Persisted projects/workspaces
|
|
894
|
+
- Real deployments
|
|
895
|
+
- Organization-scoped integrations (unless explicitly enabled later)
|
|
896
|
+
`
|
|
897
|
+
}];
|
|
898
|
+
registerDocBlocks(tech_studio_sandbox_unlogged_DocBlocks);
|
|
899
|
+
|
|
900
|
+
//#endregion
|
|
901
|
+
//#region ../../libs/contracts/src/docs/tech/studio/workspace-ops.docblock.ts
|
|
902
|
+
const tech_studio_workspace_ops_DocBlocks = [{
|
|
903
|
+
id: "docs.tech.studio.workspace_ops",
|
|
904
|
+
title: "Workspace ops (repo-linked): list / validate / deps / diff",
|
|
905
|
+
summary: "Read-only repo operations used by Studio to inspect and validate a linked ContractSpec workspace.",
|
|
906
|
+
kind: "reference",
|
|
907
|
+
visibility: "mixed",
|
|
908
|
+
route: "/docs/tech/studio/workspace-ops",
|
|
909
|
+
tags: [
|
|
910
|
+
"studio",
|
|
911
|
+
"repo",
|
|
912
|
+
"workspace",
|
|
913
|
+
"validate",
|
|
914
|
+
"diff"
|
|
915
|
+
],
|
|
916
|
+
body: `## API surface (api-contractspec)
|
|
917
|
+
|
|
918
|
+
Base: \`/api/workspace-ops\`
|
|
919
|
+
|
|
920
|
+
These endpoints are **read-only** in v1 and never push to git:
|
|
921
|
+
|
|
922
|
+
- \`GET /api/workspace-ops/:integrationId/config?organizationId=\`
|
|
923
|
+
- \`GET /api/workspace-ops/:integrationId/specs?organizationId=\`
|
|
924
|
+
- \`POST /api/workspace-ops/:integrationId/validate\` (body: organizationId, files?, pattern?)
|
|
925
|
+
- \`POST /api/workspace-ops/:integrationId/deps\` (body: organizationId, pattern?)
|
|
926
|
+
- \`POST /api/workspace-ops/:integrationId/diff\` (body: organizationId, specPath, baseline?, breakingOnly?)
|
|
927
|
+
|
|
928
|
+
## Repo resolution
|
|
929
|
+
|
|
930
|
+
- The repo root is resolved from the Studio Integration (\`IntegrationProvider.GITHUB\`) config:
|
|
931
|
+
- \`config.repoCachePath\` (preferred) or \`config.localPath\`
|
|
932
|
+
- Resolution is constrained to \`CONTRACTSPEC_REPO_CACHE_DIR\` (default: \`/tmp/contractspec-repos\`)
|
|
933
|
+
|
|
934
|
+
## Intended UX
|
|
935
|
+
|
|
936
|
+
- Studio Assistant can run these checks and present results as suggestions.
|
|
937
|
+
- Users can copy equivalent CLI commands for local runs:
|
|
938
|
+
- \`contractspec validate\`
|
|
939
|
+
- \`contractspec deps\`
|
|
940
|
+
- \`contractspec diff --baseline <ref>\`
|
|
941
|
+
`
|
|
942
|
+
}];
|
|
943
|
+
registerDocBlocks(tech_studio_workspace_ops_DocBlocks);
|
|
944
|
+
|
|
945
|
+
//#endregion
|
|
946
|
+
//#region ../../libs/contracts/src/docs/tech/studio/project-routing.docblock.ts
|
|
947
|
+
const tech_studio_project_routing_DocBlocks = [{
|
|
948
|
+
id: "docs.tech.studio.project-routing",
|
|
949
|
+
title: "Studio Project Routing",
|
|
950
|
+
summary: "Studio uses slugged, project-first routes: /studio/{projectSlug}/* with canonical slug redirects and soft-deleted projects hidden.",
|
|
951
|
+
kind: "reference",
|
|
952
|
+
visibility: "public",
|
|
953
|
+
route: "/docs/tech/studio/project-routing",
|
|
954
|
+
tags: [
|
|
955
|
+
"studio",
|
|
956
|
+
"routing",
|
|
957
|
+
"projects",
|
|
958
|
+
"slug",
|
|
959
|
+
"redirects"
|
|
960
|
+
],
|
|
961
|
+
body: `# Studio Project Routing
|
|
962
|
+
|
|
963
|
+
ContractSpec Studio uses a **project-first URL scheme**:
|
|
964
|
+
|
|
965
|
+
- \`/studio/projects\` — create, select, and delete projects.
|
|
966
|
+
- \`/studio/{projectSlug}/*\` — project modules (canvas/specs/deploy/integrations/evolution/learning).
|
|
967
|
+
- \`/studio/learning\` — learning hub that does not require selecting a project.
|
|
968
|
+
|
|
969
|
+
## Studio layout shell
|
|
970
|
+
|
|
971
|
+
Studio routes are wrapped in a dedicated **Studio app shell** (header + footer) that provides in-app navigation (Projects/Learning/Teams), organization switching, and account actions.
|
|
972
|
+
|
|
973
|
+
Project 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.
|
|
974
|
+
|
|
975
|
+
## Slug behavior (rename-safe)
|
|
976
|
+
|
|
977
|
+
- Each project has a \`slug\` stored in the database (\`StudioProject.slug\`).
|
|
978
|
+
- When a project name changes, Studio **updates the slug** and stores the previous slug as an alias (\`StudioProjectSlugAlias\`).
|
|
979
|
+
- Requests to an alias slug are **redirected to the canonical slug**.
|
|
980
|
+
|
|
981
|
+
GraphQL entrypoint:
|
|
982
|
+
|
|
983
|
+
- \`studioProjectBySlug(slug: String!)\` returns:
|
|
984
|
+
- \`project\`
|
|
985
|
+
- \`canonicalSlug\`
|
|
986
|
+
- \`wasRedirect\`
|
|
987
|
+
|
|
988
|
+
## Deletion behavior (soft delete)
|
|
989
|
+
|
|
990
|
+
Projects are **soft-deleted**:
|
|
991
|
+
|
|
992
|
+
- \`deleteStudioProject(id: String!)\` sets \`StudioProject.deletedAt\`.
|
|
993
|
+
- All listings and access checks filter \`deletedAt = null\`.
|
|
994
|
+
- Soft-deleted projects are treated as “not found” in Studio routes and GraphQL access checks.
|
|
995
|
+
|
|
996
|
+
## Available modules for a selected project
|
|
997
|
+
|
|
998
|
+
The following project modules are expected under \`/studio/{projectSlug}\`:
|
|
999
|
+
|
|
1000
|
+
- \`/canvas\` — Visual builder canvas (stored via overlays and canvas versions).
|
|
1001
|
+
- \`/specs\` — Spec editor (stored as \`StudioSpec\`).
|
|
1002
|
+
- \`/deploy\` — Deployments history + triggers (stored as \`StudioDeployment\`).
|
|
1003
|
+
- \`/integrations\` — Integrations scoped to project (stored as \`StudioIntegration\`).
|
|
1004
|
+
- \`/evolution\` — Evolution sessions (stored as \`EvolutionSession\`).
|
|
1005
|
+
- \`/learning\` — Project learning activity.
|
|
1006
|
+
`
|
|
1007
|
+
}];
|
|
1008
|
+
registerDocBlocks(tech_studio_project_routing_DocBlocks);
|
|
1009
|
+
|
|
1010
|
+
//#endregion
|
|
1011
|
+
//#region ../../libs/contracts/src/docs/tech/studio/platform-admin-panel.docblock.ts
|
|
1012
|
+
const tech_studio_platform_admin_panel_DocBlocks = [{
|
|
1013
|
+
id: "docs.tech.studio.platform-admin-panel",
|
|
1014
|
+
title: "Studio Platform Admin Panel",
|
|
1015
|
+
summary: "How PLATFORM_ADMIN organizations manage tenant orgs and integration connections without session switching.",
|
|
1016
|
+
kind: "reference",
|
|
1017
|
+
visibility: "public",
|
|
1018
|
+
route: "/docs/tech/studio/platform-admin-panel",
|
|
1019
|
+
tags: [
|
|
1020
|
+
"studio",
|
|
1021
|
+
"admin",
|
|
1022
|
+
"multi-tenancy",
|
|
1023
|
+
"integrations",
|
|
1024
|
+
"better-auth"
|
|
1025
|
+
],
|
|
1026
|
+
body: `# Studio Platform Admin Panel
|
|
1027
|
+
|
|
1028
|
+
ContractSpec Studio exposes a dedicated **Platform Admin Panel** for users whose **active organization** has:
|
|
1029
|
+
|
|
1030
|
+
- \`Organization.type = PLATFORM_ADMIN\`
|
|
1031
|
+
|
|
1032
|
+
The UI route is:
|
|
1033
|
+
|
|
1034
|
+
- \`/studio/admin\`
|
|
1035
|
+
|
|
1036
|
+
## Authorization model (no org switching)
|
|
1037
|
+
|
|
1038
|
+
Platform admins **remain in their own organization**. Cross-tenant actions are always explicit and scoped:
|
|
1039
|
+
|
|
1040
|
+
- Admin operations require an explicit \`targetOrganizationId\`.
|
|
1041
|
+
- No session / activeOrganizationId switching is performed as part of admin operations.
|
|
1042
|
+
|
|
1043
|
+
## Integrations management
|
|
1044
|
+
|
|
1045
|
+
The admin panel manages the full ContractSpec Integrations system:
|
|
1046
|
+
|
|
1047
|
+
- Lists all shipped \`IntegrationSpec\` entries (registry built via \`createDefaultIntegrationSpecRegistry()\`).
|
|
1048
|
+
- CRUD \`IntegrationConnection\` records for a selected tenant org.
|
|
1049
|
+
|
|
1050
|
+
### Secrets (reference-only + write-only)
|
|
1051
|
+
|
|
1052
|
+
The admin UI supports two modes:
|
|
1053
|
+
|
|
1054
|
+
- **Reference-only (BYOK)**: store only \`secretProvider\` + \`secretRef\`.
|
|
1055
|
+
- **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**.
|
|
1056
|
+
|
|
1057
|
+
Supported backends:
|
|
1058
|
+
|
|
1059
|
+
- Env overrides (\`env://...\`)
|
|
1060
|
+
- Google Cloud Secret Manager (\`gcp://...\`)
|
|
1061
|
+
- AWS Secrets Manager (\`aws://secretsmanager/...\`)
|
|
1062
|
+
- Scaleway Secret Manager (\`scw://secret-manager/...\`)
|
|
1063
|
+
|
|
1064
|
+
## Better Auth Admin plugin
|
|
1065
|
+
|
|
1066
|
+
The panel uses the Better Auth **Admin plugin** for user operations (list users, impersonation):
|
|
1067
|
+
|
|
1068
|
+
- Client calls use \`authClient.admin.*\`.
|
|
1069
|
+
- Server-side, ContractSpec enforces that users in a PLATFORM_ADMIN active org have \`User.role\` containing \`admin\` so Better Auth Admin endpoints authorize.
|
|
1070
|
+
|
|
1071
|
+
## GraphQL surface
|
|
1072
|
+
|
|
1073
|
+
The platform-admin GraphQL operations are guarded by the active org type and include:
|
|
1074
|
+
|
|
1075
|
+
- \`platformAdminOrganizations(search, limit, offset)\`
|
|
1076
|
+
- \`platformAdminIntegrationSpecs\`
|
|
1077
|
+
- \`platformAdminIntegrationConnections(input: { targetOrganizationId, category?, status? })\`
|
|
1078
|
+
- \`platformAdminIntegrationConnectionCreate(input)\`
|
|
1079
|
+
- \`platformAdminIntegrationConnectionUpdate(input)\`
|
|
1080
|
+
- \`platformAdminIntegrationConnectionDelete(targetOrganizationId, connectionId)\`
|
|
1081
|
+
|
|
1082
|
+
## Key implementation files
|
|
1083
|
+
|
|
1084
|
+
- Auth + role enforcement: \`packages/bundles/contractspec-studio/src/application/services/auth.ts\`
|
|
1085
|
+
- Admin GraphQL module: \`packages/bundles/contractspec-studio/src/infrastructure/graphql/modules/platform-admin.ts\`
|
|
1086
|
+
- Integrations admin service: \`packages/bundles/contractspec-studio/src/modules/platform-integrations/index.ts\`
|
|
1087
|
+
- Web route: \`packages/apps/web-landing/src/app/(app-customer)/studio/admin/*\`
|
|
1088
|
+
`
|
|
1089
|
+
}];
|
|
1090
|
+
registerDocBlocks(tech_studio_platform_admin_panel_DocBlocks);
|
|
1091
|
+
|
|
1092
|
+
//#endregion
|
|
1093
|
+
//#region ../../libs/contracts/src/docs/tech/studio/learning-events.docblock.ts
|
|
1094
|
+
const tech_studio_learning_events_DocBlocks = [{
|
|
1095
|
+
id: "docs.tech.studio.learning-events",
|
|
1096
|
+
title: "Studio Learning Events",
|
|
1097
|
+
summary: "Studio persists learning/activity events to the database; Sandbox keeps learning local-first and unlogged.",
|
|
1098
|
+
kind: "reference",
|
|
1099
|
+
visibility: "public",
|
|
1100
|
+
route: "/docs/tech/studio/learning-events",
|
|
1101
|
+
tags: [
|
|
1102
|
+
"studio",
|
|
1103
|
+
"learning",
|
|
1104
|
+
"events",
|
|
1105
|
+
"analytics",
|
|
1106
|
+
"sandbox"
|
|
1107
|
+
],
|
|
1108
|
+
body: `# Studio Learning Events
|
|
1109
|
+
|
|
1110
|
+
Studio emits lightweight **learning/activity events** to support onboarding, ambient coaching, and learning journeys.
|
|
1111
|
+
|
|
1112
|
+
## Persistence model
|
|
1113
|
+
|
|
1114
|
+
- **Studio**: events are persisted to the database in \`StudioLearningEvent\` and are organization-scoped (optionally project-scoped).
|
|
1115
|
+
- **Sandbox**: events remain **local-only** (unlogged); they must never be sent to backend services.
|
|
1116
|
+
|
|
1117
|
+
## GraphQL API
|
|
1118
|
+
|
|
1119
|
+
- \`recordLearningEvent(input: { name, projectId?, payload? })\`
|
|
1120
|
+
- \`myLearningEvents(projectId?, limit?)\`
|
|
1121
|
+
- \`myOnboardingTracks(productId?, includeProgress?)\`
|
|
1122
|
+
- \`myOnboardingProgress(trackKey)\`
|
|
1123
|
+
- \`dismissOnboardingTrack(trackKey)\`
|
|
1124
|
+
|
|
1125
|
+
## Common event names (convention)
|
|
1126
|
+
|
|
1127
|
+
- \`module.navigated\` — user navigated to a Studio module (payload at minimum: \`{ moduleId }\`).
|
|
1128
|
+
- \`studio.template.instantiated\` — created a new Studio project (starter template). Payload commonly includes \`{ templateId, projectSlug }\`.
|
|
1129
|
+
- \`spec.changed\` — created or updated a Studio spec. Payload may include \`{ action: 'create' | 'update', specId?, specType? }\`.
|
|
1130
|
+
- \`regeneration.completed\` — finished a “regen/deploy” action (currently emitted on successful Studio deploy actions).
|
|
1131
|
+
- \`studio.evolution.applied\` — completed an Evolution session (payload commonly includes \`{ evolutionSessionId }\`).
|
|
1132
|
+
|
|
1133
|
+
These events are intentionally minimal and must avoid PII/secrets in payloads.
|
|
1134
|
+
`
|
|
1135
|
+
}];
|
|
1136
|
+
registerDocBlocks(tech_studio_learning_events_DocBlocks);
|
|
1137
|
+
|
|
1138
|
+
//#endregion
|
|
1139
|
+
//#region ../../libs/contracts/src/docs/tech/studio/learning-journeys.docblock.ts
|
|
1140
|
+
const tech_studio_learning_journeys_DocBlocks = [{
|
|
1141
|
+
id: "docs.tech.studio.learning-journeys",
|
|
1142
|
+
title: "Studio learning journeys (onboarding + coach)",
|
|
1143
|
+
summary: "DB-backed learning journeys tracked per organization: seeded tracks/steps, event-driven progress, XP/streaks, and a Studio coach surface.",
|
|
1144
|
+
kind: "reference",
|
|
1145
|
+
visibility: "public",
|
|
1146
|
+
route: "/docs/tech/studio/learning-journeys",
|
|
1147
|
+
tags: [
|
|
1148
|
+
"studio",
|
|
1149
|
+
"learning",
|
|
1150
|
+
"onboarding",
|
|
1151
|
+
"journey",
|
|
1152
|
+
"graphql",
|
|
1153
|
+
"database"
|
|
1154
|
+
],
|
|
1155
|
+
body: `# Studio learning journeys
|
|
1156
|
+
|
|
1157
|
+
Studio supports **DB-backed learning journeys** (onboarding tracks + ambient coach tips) that are advanced by **recorded learning events**.
|
|
1158
|
+
|
|
1159
|
+
> See also: \`/docs/tech/studio/learning-events\` for event naming + payload guardrails.
|
|
1160
|
+
|
|
1161
|
+
## Scope (multi-tenancy)
|
|
1162
|
+
|
|
1163
|
+
- Progress is tracked **per organization** (tenant/workspace), via a \`Learner\` record keyed by \`(userId, organizationId)\`.
|
|
1164
|
+
- Learning events are stored as \`StudioLearningEvent\` under the Studio DB schema, scoped to an organization (optionally a project).
|
|
1165
|
+
|
|
1166
|
+
## Persistence model (Prisma)
|
|
1167
|
+
|
|
1168
|
+
Learning journey progress lives in the \`lssm_learning\` schema:
|
|
1169
|
+
|
|
1170
|
+
- \`Learner\` — one per \`(userId, organizationId)\`
|
|
1171
|
+
- \`OnboardingTrack\` — seeded track definitions (trackKey, name, metadata)
|
|
1172
|
+
- \`OnboardingStep\` — seeded step definitions (stepKey, completionCondition, xpReward, metadata)
|
|
1173
|
+
- \`OnboardingProgress\` — learner × track progress (progress %, xpEarned, completedAt, dismissedAt)
|
|
1174
|
+
- \`OnboardingStepCompletion\` — append-only completion records (stepKey, status, xpEarned, completedAt)
|
|
1175
|
+
|
|
1176
|
+
## Track definition source (spec-first)
|
|
1177
|
+
|
|
1178
|
+
- Canonical track specs live in \`@lssm/example.learning-journey-registry\`.
|
|
1179
|
+
- The Studio API seeds/updates the DB definitions via an idempotent “ensure tracks” routine.
|
|
1180
|
+
- The DB is kept aligned with track specs (stale steps are removed) to prevent drift and unblock completion.
|
|
1181
|
+
|
|
1182
|
+
## Progress advancement (event-driven)
|
|
1183
|
+
|
|
1184
|
+
1) UI records an event via GraphQL \`recordLearningEvent\`
|
|
1185
|
+
2) Backend creates \`StudioLearningEvent\`
|
|
1186
|
+
3) Backend advances onboarding by matching the new event against step completion conditions
|
|
1187
|
+
4) Backend persists step completions and recomputes:
|
|
1188
|
+
- \`progress\` percentage
|
|
1189
|
+
- \`xpEarned\` (including streak/completion bonuses when configured)
|
|
1190
|
+
- track completion state (\`completedAt\`)
|
|
1191
|
+
|
|
1192
|
+
## GraphQL API (Studio)
|
|
1193
|
+
|
|
1194
|
+
- \`myOnboardingTracks(productId?, includeProgress?)\`
|
|
1195
|
+
- returns all tracks + optional progress for the current learner
|
|
1196
|
+
- \`myOnboardingProgress(trackKey)\`
|
|
1197
|
+
- returns progress + step completion list for a single track
|
|
1198
|
+
- \`dismissOnboardingTrack(trackKey)\`
|
|
1199
|
+
- marks a track dismissed for the learner (prevents auto-coach)
|
|
1200
|
+
|
|
1201
|
+
## UI routes/surfaces (web)
|
|
1202
|
+
|
|
1203
|
+
- \`/studio/learning\` — learning hub (track list + progress widget)
|
|
1204
|
+
- \`/studio/learning/{trackKey}\` — track detail (steps + map)
|
|
1205
|
+
- Studio shell mounts a **coach sheet** that can auto-open for incomplete, non-dismissed onboarding.
|
|
1206
|
+
|
|
1207
|
+
## Security + data hygiene
|
|
1208
|
+
|
|
1209
|
+
- Do not put secrets/PII in \`payload\` fields of learning events.
|
|
1210
|
+
- Prefer shallow payload filters (small, stable keys).
|
|
1211
|
+
`
|
|
1212
|
+
}];
|
|
1213
|
+
registerDocBlocks(tech_studio_learning_journeys_DocBlocks);
|
|
1214
|
+
|
|
1215
|
+
//#endregion
|
|
1216
|
+
//#region ../../libs/contracts/src/docs/tech/studio/project-access-teams.docblock.ts
|
|
1217
|
+
const tech_studio_project_access_teams_DocBlocks = [{
|
|
1218
|
+
id: "docs.tech.studio.project-access-teams",
|
|
1219
|
+
title: "Studio Project Access via Teams",
|
|
1220
|
+
summary: "Projects live under organizations; team sharing refines access with an admin/owner override.",
|
|
1221
|
+
kind: "reference",
|
|
1222
|
+
visibility: "public",
|
|
1223
|
+
route: "/docs/tech/studio/project-access-teams",
|
|
1224
|
+
tags: [
|
|
1225
|
+
"studio",
|
|
1226
|
+
"projects",
|
|
1227
|
+
"teams",
|
|
1228
|
+
"rbac",
|
|
1229
|
+
"access-control"
|
|
1230
|
+
],
|
|
1231
|
+
body: `# Studio Project Access via Teams
|
|
1232
|
+
|
|
1233
|
+
Studio access control is **organization-first** with optional **team-based sharing**.
|
|
1234
|
+
|
|
1235
|
+
## Data model
|
|
1236
|
+
|
|
1237
|
+
- \`Team\` and \`TeamMember\` define team membership inside an organization.
|
|
1238
|
+
- \`StudioProject\` is owned by an organization.
|
|
1239
|
+
- \`StudioProjectTeam\` links projects to 0..N teams.
|
|
1240
|
+
|
|
1241
|
+
## Access rules
|
|
1242
|
+
|
|
1243
|
+
- **Admins/owners**: always have access to all projects in the organization.
|
|
1244
|
+
- **Org-wide projects**: if a project has **no team links**, all organization members can access it.
|
|
1245
|
+
- **Team-scoped projects**: if a project has **one or more team links**, a user must be a member of at least one linked team.
|
|
1246
|
+
|
|
1247
|
+
## GraphQL surfaces
|
|
1248
|
+
|
|
1249
|
+
- Read:\n - \`myStudioProjects\` (returns only projects you can access)\n - \`studioProjectBySlug(slug)\` (enforces the same access rules)\n - \`myTeams\`\n - \`projectTeams(projectId)\`\n\n- Write:\n - \`createStudioProject(input.teamIds?)\` (teamIds optional)\n - \`setProjectTeams(projectId, teamIds)\` (admin-only)\n
|
|
1250
|
+
## Related\n+\n+- Team administration + invitations: see \`/docs/tech/studio/team-invitations\`.\n+
|
|
1251
|
+
## Notes
|
|
1252
|
+
|
|
1253
|
+
Payloads and events must avoid secrets/PII. For Sandbox, the model remains local-first and unlogged.
|
|
1254
|
+
`
|
|
1255
|
+
}];
|
|
1256
|
+
registerDocBlocks(tech_studio_project_access_teams_DocBlocks);
|
|
1257
|
+
|
|
1258
|
+
//#endregion
|
|
1259
|
+
//#region ../../libs/contracts/src/docs/tech/studio/team-invitations.docblock.ts
|
|
1260
|
+
const tech_studio_team_invitations_DocBlocks = [{
|
|
1261
|
+
id: "docs.tech.studio.team-invitations",
|
|
1262
|
+
title: "Studio Teams & Invitations",
|
|
1263
|
+
summary: "Admin-only team management and email invitation flow to join an organization and optionally a team.",
|
|
1264
|
+
kind: "reference",
|
|
1265
|
+
visibility: "public",
|
|
1266
|
+
route: "/docs/tech/studio/team-invitations",
|
|
1267
|
+
tags: [
|
|
1268
|
+
"studio",
|
|
1269
|
+
"teams",
|
|
1270
|
+
"invitations",
|
|
1271
|
+
"access-control",
|
|
1272
|
+
"onboarding"
|
|
1273
|
+
],
|
|
1274
|
+
body: `# Studio Teams & Invitations
|
|
1275
|
+
|
|
1276
|
+
Studio uses **organization membership** as the base access model. Teams are optional and used to refine access to projects.
|
|
1277
|
+
|
|
1278
|
+
## Who can manage teams?
|
|
1279
|
+
|
|
1280
|
+
- **Admins/owners only**: create, rename, delete teams; manage project team access; issue invitations.
|
|
1281
|
+
|
|
1282
|
+
## Invitation data model
|
|
1283
|
+
|
|
1284
|
+
- \`Invitation\` rows are stored under an organization and target an **email** address.\n
|
|
1285
|
+
- An invitation can optionally target a \`teamId\`, which will grant the user membership in that team upon acceptance.
|
|
1286
|
+
|
|
1287
|
+
Key fields:
|
|
1288
|
+
- \`email\`: invited address (must match the accepting user's account email)\n
|
|
1289
|
+
- \`status\`: \`pending | accepted | declined | expired\`\n
|
|
1290
|
+
- \`teamId?\`: optional team to join\n
|
|
1291
|
+
- \`inviterId\`: user who issued the invitation
|
|
1292
|
+
|
|
1293
|
+
## GraphQL surfaces
|
|
1294
|
+
|
|
1295
|
+
- Team CRUD (admin-only):\n
|
|
1296
|
+
- \`createTeam(name)\`\n
|
|
1297
|
+
- \`renameTeam(teamId, name)\`\n
|
|
1298
|
+
- \`deleteTeam(teamId)\`\n
|
|
1299
|
+
|
|
1300
|
+
- Invitations (admin-only):\n
|
|
1301
|
+
- \`organizationInvitations\`\n
|
|
1302
|
+
- \`inviteToOrganization(email, role?, teamId?)\` → returns \`inviteUrl\` and whether an email was sent
|
|
1303
|
+
|
|
1304
|
+
## Accepting an invitation
|
|
1305
|
+
|
|
1306
|
+
The invite link is served as:\n
|
|
1307
|
+
- \`/invite/{invitationId}\`
|
|
1308
|
+
|
|
1309
|
+
Acceptance rules:
|
|
1310
|
+
- The user must be authenticated.\n
|
|
1311
|
+
- The authenticated user’s email must match \`Invitation.email\`.\n
|
|
1312
|
+
- If not already a member, create \`Member(userId, organizationId, role)\`.\n
|
|
1313
|
+
- If \`teamId\` is present, ensure \`TeamMember(teamId, userId)\`.\n
|
|
1314
|
+
- Mark invitation \`status='accepted'\` and set \`acceptedAt\`.\n
|
|
1315
|
+
- Set \`activeOrganizationId\` for the session so \`/studio/*\` routes work immediately.
|
|
1316
|
+
|
|
1317
|
+
## Email delivery
|
|
1318
|
+
|
|
1319
|
+
- If \`RESEND_API_KEY\` is set, the system attempts to send an email.\n
|
|
1320
|
+
- Otherwise, the UI uses the returned \`inviteUrl\` for manual copy/share.
|
|
1321
|
+
`
|
|
1322
|
+
}];
|
|
1323
|
+
registerDocBlocks(tech_studio_team_invitations_DocBlocks);
|
|
1324
|
+
|
|
1325
|
+
//#endregion
|
|
1326
|
+
//#region src/docs/learning-journey-ui-gamified.docblock.ts
|
|
1327
|
+
registerDocBlocks([{
|
|
1328
|
+
id: "docs.examples.learning-journey-ui-gamified",
|
|
1329
|
+
title: "Learning Journey UI — Gamified",
|
|
1330
|
+
summary: "UI mini-app components for gamified learning: flashcards, mastery, streak/calendar.",
|
|
1331
|
+
kind: "reference",
|
|
1332
|
+
visibility: "public",
|
|
1333
|
+
route: "/docs/examples/learning-journey-ui-gamified",
|
|
1334
|
+
tags: [
|
|
1335
|
+
"learning",
|
|
1336
|
+
"ui",
|
|
1337
|
+
"gamified"
|
|
1338
|
+
],
|
|
1339
|
+
body: `## Includes\n- Gamified mini-app shell\n- Views: overview, steps, progress, timeline\n- Components: flash card, mastery ring, day calendar\n\n## Notes\n- Compose with design system components.\n- Respect prefers-reduced-motion; keep tap targets large.`
|
|
1340
|
+
}]);
|
|
1341
|
+
|
|
1342
|
+
//#endregion
|
|
1343
|
+
export { DayCalendar, FlashCard, GamifiedMiniApp, MasteryRing, Overview, Progress, Steps, Timeline, example_default as example };
|