@lssm/example.learning-patterns 0.0.0-canary-20251213172311

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/.turbo/turbo-build.log +39 -0
  2. package/CHANGELOG.md +7 -0
  3. package/README.md +4 -0
  4. package/dist/docs/index.js +1 -0
  5. package/dist/docs/learning-patterns.docblock.js +12 -0
  6. package/dist/events.js +1 -0
  7. package/dist/example.js +1 -0
  8. package/dist/index.js +1 -0
  9. package/dist/libs/contracts/src/docs/PUBLISHING.docblock.js +76 -0
  10. package/dist/libs/contracts/src/docs/accessibility_wcag_compliance_specs.docblock.js +350 -0
  11. package/dist/libs/contracts/src/docs/index.js +1 -0
  12. package/dist/libs/contracts/src/docs/presentations.js +1 -0
  13. package/dist/libs/contracts/src/docs/registry.js +1 -0
  14. package/dist/libs/contracts/src/docs/tech/PHASE_1_QUICKSTART.docblock.js +383 -0
  15. package/dist/libs/contracts/src/docs/tech/PHASE_2_AI_NATIVE_OPERATIONS.docblock.js +68 -0
  16. package/dist/libs/contracts/src/docs/tech/PHASE_3_AUTO_EVOLUTION.docblock.js +140 -0
  17. package/dist/libs/contracts/src/docs/tech/PHASE_4_PERSONALIZATION_ENGINE.docblock.js +86 -0
  18. package/dist/libs/contracts/src/docs/tech/PHASE_5_ZERO_TOUCH_OPERATIONS.docblock.js +1 -0
  19. package/dist/libs/contracts/src/docs/tech/contracts/openapi-export.docblock.js +38 -0
  20. package/dist/libs/contracts/src/docs/tech/lifecycle-stage-system.docblock.js +213 -0
  21. package/dist/libs/contracts/src/docs/tech/mcp-endpoints.docblock.js +1 -0
  22. package/dist/libs/contracts/src/docs/tech/presentation-runtime.docblock.js +1 -0
  23. package/dist/libs/contracts/src/docs/tech/schema/README.docblock.js +262 -0
  24. package/dist/libs/contracts/src/docs/tech/telemetry-ingest.docblock.js +122 -0
  25. package/dist/libs/contracts/src/docs/tech/templates/runtime.docblock.js +1 -0
  26. package/dist/libs/contracts/src/docs/tech/vscode-extension.docblock.js +68 -0
  27. package/dist/libs/contracts/src/docs/tech/workflows/overview.docblock.js +1 -0
  28. package/dist/tracks/ambient-coach.js +1 -0
  29. package/dist/tracks/drills.js +1 -0
  30. package/dist/tracks/index.js +1 -0
  31. package/dist/tracks/quests.js +1 -0
  32. package/example.ts +1 -0
  33. package/package.json +56 -0
  34. package/src/docs/index.ts +3 -0
  35. package/src/docs/learning-patterns.docblock.ts +30 -0
  36. package/src/events.ts +17 -0
  37. package/src/example.ts +25 -0
  38. package/src/index.ts +12 -0
  39. package/src/learning-patterns.test.ts +221 -0
  40. package/src/tracks/ambient-coach.ts +44 -0
  41. package/src/tracks/drills.ts +50 -0
  42. package/src/tracks/index.ts +5 -0
  43. package/src/tracks/quests.ts +40 -0
  44. package/tsconfig.json +11 -0
  45. package/tsconfig.tsbuildinfo +1 -0
  46. package/tsdown.config.js +9 -0
@@ -0,0 +1,38 @@
1
+ import{registerDocBlocks as e}from"../../registry.js";e([{id:`docs.tech.contracts.openapi-export`,title:`OpenAPI export (OpenAPI 3.1) from SpecRegistry`,summary:`Generate a deterministic OpenAPI document from a SpecRegistry using jsonSchemaForSpec + REST transport metadata.`,kind:`reference`,visibility:`public`,route:`/docs/tech/contracts/openapi-export`,tags:[`contracts`,`openapi`,`rest`],body:`## OpenAPI export (OpenAPI 3.1) from SpecRegistry
2
+
3
+ ### Purpose
4
+
5
+ ContractSpec specs can be exported into an **OpenAPI 3.1** document for tooling (SDK generation, docs, gateways).
6
+
7
+ The export is **spec-first**:
8
+
9
+ - Uses \`jsonSchemaForSpec(spec)\` for input/output JSON Schema (from SchemaModel → zod → JSON Schema)
10
+ - Uses \`spec.transport.rest.method/path\` when present
11
+ - Falls back to deterministic defaults:
12
+ - Method: \`POST\` for commands, \`GET\` for queries
13
+ - Path: \`defaultRestPath(name, version)\` → \`/<dot/name>/v<version>\`
14
+
15
+ ### Library API
16
+
17
+ - Function: \`openApiForRegistry(registry, options?)\`
18
+ - Location: \`@lssm/lib.contracts/openapi\`
19
+
20
+ ### CLI
21
+
22
+ Export OpenAPI from a registry module:
23
+
24
+ \`\`\`bash
25
+ contractspec openapi --registry ./src/registry.ts --out ./openapi.json
26
+ \`\`\`
27
+
28
+ The registry module must export one of:
29
+
30
+ - \`registry: SpecRegistry\`
31
+ - \`default(): SpecRegistry | Promise<SpecRegistry>\`
32
+ - \`createRegistry(): SpecRegistry | Promise<SpecRegistry>\`
33
+
34
+ ### Notes / limitations (current)
35
+
36
+ - Responses are generated as a basic \`200\` response (plus schemas when available).
37
+ - Query (GET) inputs are currently represented as a JSON request body when an input schema exists.
38
+ - Errors are not yet expanded into OpenAPI responses; that will be added when we standardize error envelopes.`}]);
@@ -0,0 +1,213 @@
1
+ import{registerDocBlocks as e}from"../registry.js";e([{id:`docs.tech.lifecycle-stage-system`,title:`ContractSpec Lifecycle Stage System – Technical Design`,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.`,kind:`reference`,visibility:`public`,route:`/docs/tech/lifecycle-stage-system`,tags:[`tech`,`lifecycle-stage-system`],body:`## ContractSpec Lifecycle Stage System – Technical Design
2
+
3
+ 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.
4
+
5
+ ---
6
+
7
+ ### 1. Architecture Overview
8
+
9
+ \`\`\`
10
+ ┌──────────────────────┐
11
+ │ @lssm/lib.lifecycle │ Types, enums, helpers (pure data)
12
+ └───────────┬──────────┘
13
+
14
+ ┌───────────▼──────────┐ ┌───────────────────────────┐
15
+ │ modules/lifecycle- │ │ modules/lifecycle-advisor │
16
+ │ core (detection) │ │ (guidance & ceremonies) │
17
+ └───────────┬──────────┘ └───────────┬───────────────┘
18
+ │ │
19
+ ├────────────┬──────────────┤
20
+ ▼ ▼ ▼
21
+ Adapters: analytics, intent, questionnaires
22
+
23
+ ┌───────────▼──────────┐
24
+ │ bundles/lifecycle- │ Managed service for Studio
25
+ │ managed │ (REST handlers, AI agent) │
26
+ └───────────┬──────────┘
27
+
28
+ ContractSpec Studio surfaces
29
+ (web/mobile APIs, CLI, docs)
30
+ \`\`\`
31
+
32
+ - **Libraries** provide shared vocabulary.
33
+ - **Modules** encapsulate logic, accepting adapters to avoid environment-specific code.
34
+ - **Bundles** compose modules, register agents/events, and expose APIs for Studio.
35
+ - **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.
36
+
37
+ ---
38
+
39
+ ### 2. Core Library (\`@lssm/lib.lifecycle\`)
40
+
41
+ - Stage enum (0–6) with metadata (\`question\`, \`signals\`, \`traps\`).
42
+ - Axes types (\`ProductPhase\`, \`CompanyPhase\`, \`CapitalPhase\`).
43
+ - \`LifecycleSignal\` (source, metric, value, timestamp).
44
+ - \`LifecycleMetricSnapshot\` (aggregated numbers).
45
+ - \`LifecycleMilestone\`, \`LifecycleAction\`, \`LifecycleAssessment\` interfaces.
46
+ - Utility helpers:
47
+ - \`formatStageSummary(stage, assessment)\`
48
+ - \`rankStageCandidates(scores)\`
49
+
50
+ The library exports **no runtime dependencies** so it can be imported from apps, modules, and bundles alike.
51
+
52
+ ---
53
+
54
+ ### 3. Lifecycle Core Module
55
+
56
+ **Location:** \`packages/modules/lifecycle-core/\`
57
+
58
+ #### Components
59
+ 1. **StageSignalCollector**
60
+ - Accepts adapter interfaces:
61
+ - \`AnalyticsAdapter\` (pulls metrics from \`@lssm/lib.analytics\` or fixture streams).
62
+ - \`IntentAdapter\` (hooks into \`@lssm/lib.observability\` intent detectors or logs).
63
+ - \`QuestionnaireAdapter\` (loads JSON questionnaires and responses).
64
+ - Produces normalized \`LifecycleSignal[]\`.
65
+
66
+ 2. **StageScorer**
67
+ - Weighted scoring model:
68
+ - Base weight per stage (reflecting expected maturity).
69
+ - Feature weights (retention, revenue, team size, qualitative feedback).
70
+ - Confidence computed via variance of contributing signals.
71
+ - Supports pluggable scoring matrices via JSON config.
72
+ - Accepts sparse metric snapshots; the orchestrator sanitizes metrics to numeric-only records before persisting assessments so downstream analytics stay consistent.
73
+
74
+ 3. **LifecycleOrchestrator**
75
+ - Coordinates collectors + scorer.
76
+ - Returns \`LifecycleAssessment\` with:
77
+ - \`stage\`, \`confidence\`, \`axisSnapshot\`, \`signalsUsed\`.
78
+ - Recommended focus areas (high-level categories only).
79
+ - Emits events (internally) when stage confidence crosses thresholds (consumed later by bundle).
80
+
81
+ 4. **LifecycleMilestonePlanner**
82
+ - Loads \`milestones-catalog.json\` (no DB).
83
+ - Filters upcoming milestones per stage + axis.
84
+ - Tracks completion using provided IDs (caller persists).
85
+
86
+ #### Data Files
87
+ - \`configs/stage-weights.json\`
88
+ - \`configs/milestones-catalog.json\`
89
+ - \`questionnaires/stage-readiness.json\`
90
+
91
+ #### Extension Hooks
92
+ - All adapters exported as TypeScript interfaces.
93
+ - Implementations for analytics/intent can live in bundles or apps without modifying module code.
94
+
95
+ ---
96
+
97
+ ### 4. Lifecycle Advisor Module
98
+
99
+ **Location:** \`packages/modules/lifecycle-advisor/\`
100
+
101
+ #### Components
102
+ 1. **LifecycleRecommendationEngine**
103
+ - Consumes \`LifecycleAssessment\`.
104
+ - Maps gaps to \`LifecycleAction[]\` using rule tables (\`stage-playbooks.ts\`).
105
+ - Supports override hooks for customer-specific rules.
106
+
107
+ 2. **ContractSpecLibraryRecommender**
108
+ - Maintains mapping from stage → recommended libraries/modules/bundles.
109
+ - Returns prioritized list with rationale and adoption prerequisites.
110
+
111
+ 3. **LifecycleCeremonyDesigner**
112
+ - Provides textual/structural data for ceremonies (title, copy, animation cues, soundtrack references).
113
+ - Ensures low-tech friendly instructions (clear copy, undo guidance).
114
+
115
+ 4. **AI Hooks**
116
+ - Defines prompt templates and tool manifests for lifecycle advisor agents (consumed by bundles).
117
+ - Keeps actual LLM integration outside module.
118
+
119
+ ---
120
+
121
+ ### 5. Managed Bundle (\`lifecycle-managed\`)
122
+
123
+ **Responsibilities**
124
+ - Wire modules together.
125
+ - Provide HTTP/GraphQL handlers (exact transport optional).
126
+ - Register LifecycleAdvisorAgent via \`@lssm/lib.ai-agent\`.
127
+ - LifecycleAdvisorAgent meta: domain \`operations\`, owners \`team-lifecycle\`, stability \`experimental\`, tags \`guide/lifecycle/ops\` so ops tooling can route incidents quickly.
128
+ - Emit lifecycle events through \`@lssm/lib.bus\` + \`@lssm/lib.analytics\`.
129
+ - Integrate with \`contractspec-studio\` packages:
130
+ - Use Studio contracts for authentication/tenant context (without accessing tenant DBs).
131
+ - Store assessments in Studio-managed storage abstractions (in-memory or file-based for now).
132
+
133
+ **APIs**
134
+ - \`POST /lifecycle/assessments\`: Accepts metrics + optional questionnaire answers. Returns \`LifecycleAssessment\`.
135
+ - \`GET /lifecycle/playbooks/:stage\`: Returns stage playbook + ceremonies.
136
+ - \`POST /lifecycle/advise\`: Invokes LifecycleAdvisorAgent with context.
137
+
138
+ **Events**
139
+ - \`LifecycleAssessmentCreated\`
140
+ - \`LifecycleStageChanged\`
141
+ - \`LifecycleGuidanceConsumed\`
142
+
143
+ ---
144
+
145
+ ### 6. Library Enhancements
146
+
147
+ | Library | Enhancement |
148
+ | --- | --- |
149
+ | \`@lssm/lib.analytics\` | Lifecycle metric collectors, helper to emit stage events, adapter implementation used by \`StageSignalCollector\`. |
150
+ | \`@lssm/lib.evolution\` | Accepts \`LifecycleContext\` when ranking spec anomalies/suggestions. |
151
+ | \`@lssm/lib.growth\` | Stage-specific experiment templates + guardrails referencing lifecycle enums. |
152
+ | \`@lssm/lib.observability\` | Lifecycle KPI pipeline definitions (drift detection, regression alerts). |
153
+
154
+ Each enhancement must import stage types from \`@lssm/lib.lifecycle\`.
155
+
156
+ ---
157
+
158
+ ### 7. Feature Flags & Progressive Delivery
159
+
160
+ - Add new flags in progressive-delivery library:
161
+ - \`LIFECYCLE_DETECTION_ALPHA\`
162
+ - \`LIFECYCLE_ADVISOR_ALPHA\`
163
+ - \`LIFECYCLE_MANAGED_SERVICE\`
164
+ - Bundles/modules should check flags before enabling workflows.
165
+ - Flags referenced in docs + Studio UI to avoid accidental exposure.
166
+
167
+ ---
168
+
169
+ ### 8. Analytics & Telemetry
170
+
171
+ - Events defined in analytics library; consumed by bundle/app:
172
+ - \`lifecycle_assessment_run\`
173
+ - \`lifecycle_stage_changed\`
174
+ - \`lifecycle_guidance_consumed\`
175
+ - Observability pipeline includes:
176
+ - Composite lifecycle health metric (weighted sum of KPIs).
177
+ - Drift detection comparing stage predictions over time.
178
+ - Alert manager recipes for regression (e.g., PMF drop).
179
+
180
+ ---
181
+
182
+ ### 9. Testing Strategy
183
+
184
+ 1. **Unit**
185
+ - StageScorer weight matrix.
186
+ - RecommendationEngine mapping.
187
+ - Library recommender stage coverage.
188
+
189
+ 2. **Contract**
190
+ - Adapters: ensure mock adapters satisfy interfaces.
191
+ - Bundles: ensure HTTP handlers respect request/response contracts even without persistence.
192
+
193
+ 3. **Integration**
194
+ - CLI example runs detection + guidance end-to-end on fixture data.
195
+ - Dashboard example renders assessments, verifying JSON structures remain stable.
196
+
197
+ ---
198
+
199
+ ### 10. Implementation Checklist
200
+
201
+ - [ ] Documentation (product, tech, ops, user).
202
+ - [ ] Library creation (\`@lssm/lib.lifecycle\`).
203
+ - [ ] Modules (\`lifecycle-core\`, \`lifecycle-advisor\`).
204
+ - [ ] Bundle (\`lifecycle-managed\`) + Studio wiring.
205
+ - [ ] Library enhancements (analytics/evolution/growth/observability).
206
+ - [ ] Examples (CLI + dashboard).
207
+ - [ ] Feature flags + telemetry.
208
+ - [ ] Automated tests + fixtures.
209
+
210
+ Keep this document in sync as modules evolve. When adding new stages or axes, update \`@lssm/lib.lifecycle\` first, then cascade to adapters, then refresh docs + Studio copy.*** End Patch*** End Patch
211
+
212
+
213
+ `}]);
@@ -0,0 +1 @@
1
+ import{registerDocBlocks as e}from"../registry.js";e([{id:`docs.tech.mcp.endpoints`,title:`ContractSpec MCP endpoints`,summary:`Dedicated MCP servers for docs, CLI usage, and internal development.`,kind:`reference`,visibility:`mixed`,route:`/docs/tech/mcp/endpoints`,tags:[`mcp`,`docs`,`cli`,`internal`],body:"# ContractSpec MCP endpoints\n\nThree dedicated MCP servers keep AI agents efficient and scoped:\n\n- **Docs MCP**: `/api/mcp/docs` — exposes DocBlocks as resources + presentations. Tool: `docs.search`.\n- **CLI MCP**: `/api/mcp/cli` — surfaces CLI quickstart/reference/README and suggests commands. Tool: `cli.suggestCommand`.\n- **Internal MCP**: `/api/mcp/internal` — internal routing hints, playbook, and example registry access. Tool: `internal.describe`.\n\n### Usage notes\n- Transports are HTTP POST (streamable HTTP); SSE is disabled.\n- Resources are namespaced (`docs://*`, `cli://*`, `internal://*`) and are read-only.\n- Internal MCP also exposes the examples registry via `examples://*` resources:\n - `examples://list?q=<query>`\n - `examples://example/<id>`\n- Prompts mirror each surface (navigator, usage, bootstrap) for quick agent onboarding.\n- GraphQL remains at `/graphql`; health at `/health`.\n"}]);
@@ -0,0 +1 @@
1
+ import{registerDocBlocks as e}from"../registry.js";e([{id:`docs.tech.presentation-runtime`,title:`Presentation Runtime`,summary:`Cross-platform runtime for list pages and presentation flows.`,kind:`reference`,visibility:`public`,route:`/docs/tech/presentation-runtime`,tags:[`tech`,`presentation-runtime`],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"}]);
@@ -0,0 +1,262 @@
1
+ import{registerDocBlocks as e}from"../../registry.js";e([{id:`docs.tech.schema.README`,title:`Multi‑File Prisma Schema Conventions (per database)`,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.`,kind:`reference`,visibility:`public`,route:`/docs/tech/schema/README`,tags:[`tech`,`schema`,`README`],body:`# Multi‑File Prisma Schema Conventions (per database)
2
+
3
+ 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.
4
+
5
+ Canonical layout per DB:
6
+
7
+ \`\`\`
8
+ prisma/
9
+ schema/
10
+ main.prisma # datasource + generators only
11
+ imported/
12
+ lssm_sigil/*.prisma # imported models/enums only (no datasource/generator)
13
+ lssm_content/*.prisma # idem
14
+ <domain>/*.prisma # vertical‑specific models split by bounded context
15
+ \`\`\`
16
+
17
+ Notes:
18
+
19
+ - Imported files contain only \`model\` and \`enum\` blocks (strip \`datasource\`/\`generator\`).
20
+ - 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"]\`.
21
+ - Use \`@lssm/app.cli-database\` CLI: \`database import|check|generate|migrate:*|seed\` to manage a single DB; \`@lssm/app.cli-databases\` orchestrates multiple DBs.
22
+
23
+ ## Typed merger config
24
+
25
+ - Define imported module list once per DB with a typed config:
26
+
27
+ \`\`\`ts
28
+ // prisma-merger.config.ts
29
+ import { defineMergedPrismaConfig } from '@lssm/app.cli-database';
30
+
31
+ export default defineMergedPrismaConfig({
32
+ modules: [
33
+ '@lssm/app.cli-database-sigil',
34
+ '@lssm/app.cli-database-content',
35
+ // ...
36
+ ],
37
+ });
38
+ \`\`\`
39
+
40
+ - Then run \`database import --target .\` (no need to pass \`--modules\`).
41
+
42
+ ## Prisma Config (prisma.config.ts)
43
+
44
+ We use Prisma Config per official docs to point Prisma to the multi-file schema folder and migrations:
45
+
46
+ \`\`\`ts
47
+ // prisma.config.ts
48
+ import path from 'node:path';
49
+ import { defineConfig } from 'prisma/config';
50
+
51
+ export default defineConfig({
52
+ schema: path.join('prisma', 'schema'),
53
+ migrations: { path: path.join('prisma', 'migrations') },
54
+ });
55
+ \`\`\`
56
+
57
+ Reference: Prisma blog – Organize Your Prisma Schema into Multiple Files: https://www.prisma.io/blog/organize-your-prisma-schema-with-multi-file-support
58
+
59
+ ---
60
+
61
+ # LSSM Auth (Sigil) – Models & Integration
62
+
63
+ This document tracks the identity models and integration points used by the LSSM Sigil module.
64
+
65
+ ## Models (Prisma \`lssm_sigil\`)
66
+
67
+ - \`User\` – core identity with email, optional phone, role, passkeys, apiKeys
68
+ - \`Session\` – session tokens and metadata; includes \`activeOrganizationId\`
69
+ - \`Account\` – external providers (password, OAuth)
70
+ - \`Organization\` – tenant boundary; includes \`type\` additional field
71
+ - \`Member\`, \`Invitation\`, \`Team\`, \`TeamMember\` – org/teams
72
+ - \`Role\`, \`Permission\`, \`PolicyBinding\` – RBAC
73
+ - \`ApiKey\`, \`Passkey\` – programmable access and WebAuthn
74
+ - \`SsoProvider\` – OIDC/SAML provider configuration (org- or user-scoped)
75
+ - \`OAuthApplication\`, \`OAuthAccessToken\`, \`OAuthConsent\` – first/third-party OAuth
76
+
77
+ These mirror STRIT additions so Better Auth advanced plugins (admin, organization, apiKey, passkey, genericOAuth) work uniformly across apps.
78
+
79
+ ## Better Auth (server)
80
+
81
+ Enabled methods:
82
+
83
+ - Email & password
84
+ - Phone OTP (Telnyx)
85
+ - Passkey (WebAuthn)
86
+ - API keys
87
+ - Organizations & Teams
88
+ - Generic OAuth (FranceConnect+ via OIDC with JWE/JWS using JOSE)
89
+
90
+ Server config lives at \`packages/lssm/modules/sigil/src/application/services/auth.ts\`.
91
+
92
+ ## Clients (Expo / React)
93
+
94
+ Client config lives at \`packages/lssm/modules/sigil/src/presentation/providers/auth/expo.ts\` with plugins for admin, passkey, apiKey, organization, phone, genericOAuth.
95
+
96
+ ## Environment Variables
97
+
98
+ Telnyx (phone OTP):
99
+
100
+ - \`TELNYX_API_KEY\`
101
+ - \`TELNYX_MESSAGING_PROFILE_ID\`
102
+ - \`TELNYX_FROM_NUMBER\`
103
+
104
+ FranceConnect+ (prefer LSSM*… but STRIT*… fallbacks are supported):
105
+
106
+ - \`LSSM_FRANCECONNECTPLUS_DISCOVERY_URL\`
107
+ - \`LSSM_FRANCECONNECTPLUS_CLIENT_ID\`
108
+ - \`LSSM_FRANCECONNECTPLUS_CLIENT_SECRET\`
109
+ - \`LSSM_FRANCECONNECTPLUS_ENC_PRIVATE_KEY_PEM\` (PKCS8; RSA-OAEP-256)
110
+
111
+ Generic:
112
+
113
+ - \`API_URL_IDENTITIES\` – base URL for Better Auth server
114
+ - \`BETTER_AUTH_SECRET\` – server secret
115
+
116
+ Keep this in sync with code changes to avoid drift.
117
+
118
+ ## HCircle domain splits and auth removal
119
+
120
+ - Auth/identity models are not defined locally anymore. They come from \`@lssm/app.cli-database-sigil\` under the \`lssm_sigil\` schema.
121
+ - \`packages/hcircle/libs/database-coliving/prisma/schema/domain/\` is split by domain; newsletter/waiting list lives in \`newsletter.prisma\` and uses \`@@map("waiting_list")\`.
122
+ - To avoid collisions with module names, the local event models were renamed to \`SocialEvent\`, \`SocialEventAttendee\`, and \`SocialEventRecurrence\` with \`@@map\` pointing to existing table names.
123
+
124
+ ---
125
+
126
+ ## Vertical profiles (current)
127
+
128
+ ### STRIT
129
+
130
+ - prisma-merger modules:
131
+ - \`@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\`
132
+ - main.prisma schemas:
133
+ - \`schemas = ["public","lssm_sigil","lssm_content","lssm_ops","lssm_planning","lssm_quill","lssm_geoterro"]\`
134
+ - domain splits (\`packages/strit/libs/database/prisma/schema/domain/\`):
135
+ - \`bookings.prisma\` (Booking, StritDocument + links to Content \`File\` and Sigil \`Organization\`)
136
+ - \`commerce.prisma\` (Wholesale models; \`sellerId\` linked to Sigil \`Organization\`)
137
+ - \`files.prisma\` (PublicFile, PublicFileAccessLog; \`ownerId\`→Organization, \`uploadedBy\`→User)
138
+ - \`geo.prisma\` (PublicCountry, PublicAddress, City; links to Spots/Series)
139
+ - \`spots.prisma\`, \`urbanism.prisma\`, \`analytics.prisma\`, \`onboarding.prisma\`, \`referrals.prisma\`, \`subscriptions.prisma\`, \`content.prisma\`
140
+ - auth models are imported from Sigil (no local auth tables).
141
+ - Back-relations for \`Organization\` (e.g., \`files\`, seller relations) are declared in the Sigil module to avoid scattering.
142
+
143
+ ### ARTISANOS
144
+
145
+ - prisma-merger modules:
146
+ - \`@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\`
147
+ - main.prisma schemas:
148
+ - \`schemas = ["public","lssm_sigil","lssm_content","lssm_featureflags","lssm_ops","lssm_planning","lssm_quill","lssm_geoterro"]\`
149
+ - domain splits (\`packages/artisanos/libs/database-artisan/prisma/schema/domain/\`):
150
+ - \`sales.prisma\` (Client, Quote, QuoteTemplate, Invoice, FollowUps)
151
+ - \`subsidies.prisma\` (SubsidyProgram, AidApplication, SupportingDocument)
152
+ - \`projects.prisma\` (Project, ProjectPlanningSettings)
153
+ - \`crm.prisma\` (OrganizationProfessionalProfile, OrganizationCertification)
154
+ - \`professions.prisma\`, \`products.prisma\`, \`templates.prisma\`, \`analytics.prisma\`, \`onboarding.prisma\`, \`referrals.prisma\`, \`subscriptions.prisma\`, \`files.prisma\`
155
+ - auth/organization/team models are provided by Sigil; local legacy copies were removed.
156
+ - Where names collide with Content, local models are prefixed (e.g., \`PublicFile\`) and use \`@@map\` to keep existing table names where applicable.
157
+
158
+ ## Schema Dictionary: \`@lssm/lib.schema\`
159
+
160
+ ### Purpose
161
+
162
+ Describe operation I/O once and generate:
163
+
164
+ - zod (runtime validation)
165
+ - GraphQL (Pothos types/refs)
166
+ - JSON Schema (via \`zod-to-json-schema\` or native descriptors)
167
+
168
+ ### Primitives
169
+
170
+ - **FieldType<T>**: describes a scalar or composite field and carries:
171
+ - \`zod\` schema for validation
172
+ - optional JSON Schema descriptor
173
+ - optional GraphQL scalar reference/name
174
+ - **SchemaModel**: named object model composed of fields. Exposes helpers:
175
+ - \`getZod(): z.ZodObject<ZodShapeFromFields<Fields>> | z.ZodArray<z.ZodObject<...>>\`
176
+ - Preserves each field's schema, optionality, and array-ness
177
+ - Top-level lists are supported via \`config.isArray: true\`
178
+ - \`getJsonSchema(): JSONSchema7\` (export for docs, MCP, forms)
179
+ - \`getPothosInput()\` (GraphQL input object name)
180
+
181
+ ### Conventions
182
+
183
+ - Name models with PascalCase; suffix with \`Input\`/\`Result\` when ambiguous.
184
+ - Use explicit enums for multi-value constants; reuse the same enum across input/output.
185
+ - Define domain enums via \`defineEnum('Name', [...])\` in the relevant domain package (e.g., \`packages/strit/libs/contracts-strit/src/enums/\`), not in \`ScalarTypeEnum\`.
186
+ - Reference those enums in \`SchemaModel\` fields directly (they expose \`getZod\`, \`getPothos\`, \`getJsonSchema\`).
187
+
188
+ #### Example (STRIT)
189
+
190
+ \`\`\`ts
191
+ // packages/strit/libs/contracts-strit/src/enums/recurrence.ts
192
+ import { defineEnum } from '@lssm/lib.schema';
193
+ export const SpotEnum = {
194
+ Weekday: () =>
195
+ defineEnum('Weekday', ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'] as const),
196
+ RecurrenceFrequency: () =>
197
+ defineEnum('RecurrenceFrequency', [
198
+ 'DAILY',
199
+ 'WEEKLY',
200
+ 'MONTHLY',
201
+ 'YEARLY',
202
+ ] as const),
203
+ } as const;
204
+ \`\`\`
205
+
206
+ \`\`\`ts
207
+ // usage in contracts
208
+ frequency: { type: SpotEnum.RecurrenceFrequency(), isOptional: false },
209
+ byWeekday: { type: SpotEnum.Weekday(), isOptional: true, isArray: true },
210
+ \`\`\`
211
+
212
+ - Use \`Date\` type for temporal values and ensure ISO strings in JSON transports where needed.
213
+
214
+ ### Mapping rules (summary)
215
+
216
+ - Strings → GraphQL \`String\`
217
+ - Numbers → \`Int\` if safe 32-bit integer else \`Float\`
218
+ - Booleans → \`Boolean\`
219
+ - Dates → custom \`Date\` scalar
220
+ - Arrays<T> → list of mapped T (set \`isArray: true\` on the field)
221
+ - Top-level arrays → set \`isArray: true\` on the model config
222
+ - Objects → input/output object types with stable field order
223
+ - Unions → supported for output; input unions map to JSON (structural input is not supported by GraphQL)
224
+
225
+ ### JSON Schema export
226
+
227
+ Prefer \`getZod()\` + \`zod-to-json-schema\` for consistency. For advanced cases, provide a custom \`getJsonSchema()\` on the model.
228
+
229
+ ### Example
230
+
231
+ \`\`\`ts
232
+ import { ScalarTypeEnum, SchemaModel } from '@lssm/lib.schema';
233
+
234
+ // Nested model
235
+ const Weekday = new SchemaModel({
236
+ name: 'Weekday',
237
+ fields: {
238
+ value: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
239
+ },
240
+ });
241
+
242
+ // Parent model with array field and nested object
243
+ const Rule = new SchemaModel({
244
+ name: 'Rule',
245
+ fields: {
246
+ timezone: { type: ScalarTypeEnum.TimeZone(), isOptional: false },
247
+ byWeekday: { type: Weekday, isOptional: true, isArray: true },
248
+ },
249
+ });
250
+
251
+ const CreateThingInput = new SchemaModel({
252
+ name: 'CreateThingInput',
253
+ fields: {
254
+ name: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
255
+ rule: { type: Rule, isOptional: false },
256
+ },
257
+ });
258
+
259
+ // zod
260
+ const z = CreateThingInput.getZod();
261
+ \`\`\`
262
+ `}]);
@@ -0,0 +1,122 @@
1
+ import{registerDocBlocks as e}from"../registry.js";e([{id:`docs.tech.telemetry.ingest`,title:`Telemetry Ingest Endpoint`,summary:`Server-side telemetry ingestion for ContractSpec clients (VS Code extension, CLI, etc.).`,kind:`reference`,visibility:`internal`,route:`/docs/tech/telemetry/ingest`,tags:[`telemetry`,`api`,`posthog`,`analytics`],body:`# Telemetry Ingest Endpoint
2
+
3
+ The ContractSpec API provides a telemetry ingest endpoint for clients to send product analytics events.
4
+
5
+ ## Endpoint
6
+
7
+ \`\`\`
8
+ POST /api/telemetry/ingest
9
+ \`\`\`
10
+
11
+ ## Request
12
+
13
+ \`\`\`json
14
+ {
15
+ "event": "contractspec.vscode.command_run",
16
+ "distinct_id": "client-uuid",
17
+ "properties": {
18
+ "command": "validate"
19
+ },
20
+ "timestamp": "2024-01-15T10:30:00.000Z"
21
+ }
22
+ \`\`\`
23
+
24
+ ### Headers
25
+
26
+ | Header | Description |
27
+ |--------|-------------|
28
+ | \`x-contractspec-client-id\` | Optional client identifier (used as fallback for distinct_id) |
29
+ | \`Content-Type\` | Must be \`application/json\` |
30
+
31
+ ### Body
32
+
33
+ | Field | Type | Required | Description |
34
+ |-------|------|----------|-------------|
35
+ | \`event\` | string | Yes | Event name (e.g., \`contractspec.vscode.activated\`) |
36
+ | \`distinct_id\` | string | Yes | Anonymous client identifier |
37
+ | \`properties\` | object | No | Event properties |
38
+ | \`timestamp\` | string | No | ISO 8601 timestamp |
39
+
40
+ ## Response
41
+
42
+ \`\`\`json
43
+ {
44
+ "success": true
45
+ }
46
+ \`\`\`
47
+
48
+ ## Configuration
49
+
50
+ The endpoint requires \`POSTHOG_PROJECT_KEY\` environment variable to be set. If not configured, events are accepted but not forwarded.
51
+
52
+ | Environment Variable | Description | Default |
53
+ |---------------------|-------------|---------|
54
+ | \`POSTHOG_HOST\` | PostHog host URL | \`https://eu.posthog.com\` |
55
+ | \`POSTHOG_PROJECT_KEY\` | PostHog project API key | (required) |
56
+
57
+ ## Privacy
58
+
59
+ - No PII is collected or stored
60
+ - \`distinct_id\` is an anonymous client-generated UUID
61
+ - File paths and source code are never included in events
62
+ - Respects VS Code telemetry settings on the client side
63
+
64
+ ## Events
65
+
66
+ ### Extension Events
67
+
68
+ | Event | Description | Properties |
69
+ |-------|-------------|------------|
70
+ | \`contractspec.vscode.activated\` | Extension activated | \`version\` |
71
+ | \`contractspec.vscode.command_run\` | Command executed | \`command\` |
72
+ | \`contractspec.vscode.mcp_call\` | MCP call made | \`endpoint\`, \`tool\` |
73
+
74
+ ### API Events
75
+
76
+ | Event | Description | Properties |
77
+ |-------|-------------|------------|
78
+ | \`contractspec.api.mcp_request\` | MCP request processed | \`endpoint\`, \`method\`, \`success\`, \`duration_ms\` |
79
+ `},{id:`docs.tech.telemetry.hybrid`,title:`Hybrid Telemetry Model`,summary:`How ContractSpec clients choose between direct PostHog and API-routed telemetry.`,kind:`usage`,visibility:`internal`,route:`/docs/tech/telemetry/hybrid`,tags:[`telemetry`,`architecture`,`posthog`],body:`# Hybrid Telemetry Model
80
+
81
+ ContractSpec uses a hybrid telemetry model where clients can send events either directly to PostHog or via the API server.
82
+
83
+ ## Decision Flow
84
+
85
+ \`\`\`
86
+ Is contractspec.api.baseUrl configured?
87
+ ├── Yes → Send via /api/telemetry/ingest
88
+ └── No → Is posthogProjectKey configured?
89
+ ├── Yes → Send directly to PostHog
90
+ └── No → Telemetry disabled
91
+ \`\`\`
92
+
93
+ ## Benefits
94
+
95
+ ### Direct PostHog
96
+ - No server dependency
97
+ - Works offline (with batching)
98
+ - Lower latency
99
+
100
+ ### Via API
101
+ - Centralized key management (no client-side keys)
102
+ - Server-side enrichment and validation
103
+ - Rate limiting and abuse prevention
104
+ - Easier migration to other providers
105
+
106
+ ## Recommendation
107
+
108
+ - **Development**: Use direct PostHog with a dev project key
109
+ - **Production**: Route via API for better governance
110
+
111
+ ## Future: OpenTelemetry
112
+
113
+ The current PostHog implementation is behind a simple interface that can be swapped for OpenTelemetry:
114
+
115
+ \`\`\`typescript
116
+ interface TelemetryClient {
117
+ send(event: TelemetryEvent): Promise<void>;
118
+ }
119
+ \`\`\`
120
+
121
+ This allows future migration without changing client code.
122
+ `}]);
@@ -0,0 +1 @@
1
+ import{registerDocBlocks as e}from"../../registry.js";e([{id:`docs.tech.templates.runtime`,title:`ContractSpec Template Runtime (Phase 9)`,summary:`Phase 9 introduces a full local-first runtime for templates so anyone can preview apps directly in the browser without provisioning any infrastructure.`,kind:`reference`,visibility:`public`,route:`/docs/tech/templates/runtime`,tags:[`tech`,`templates`,`runtime`],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"}]);