@lssm/bundle.contractspec-workspace 0.0.0-canary-20251217060834 → 0.0.0-canary-20251217072406

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/dist/_virtual/rolldown_runtime.js +22 -1
  2. package/dist/adapters/ai.js +82 -1
  3. package/dist/adapters/factory.js +36 -1
  4. package/dist/adapters/fs.js +118 -1
  5. package/dist/adapters/git.js +54 -1
  6. package/dist/adapters/index.js +7 -1
  7. package/dist/adapters/logger.js +80 -1
  8. package/dist/adapters/watcher.js +69 -1
  9. package/dist/adapters/workspace.js +190 -2
  10. package/dist/ai/agents/claude-code-agent.js +146 -9
  11. package/dist/ai/agents/cursor-agent.js +286 -17
  12. package/dist/ai/agents/index.js +5 -1
  13. package/dist/ai/agents/openai-codex-agent.js +140 -8
  14. package/dist/ai/agents/orchestrator.js +142 -1
  15. package/dist/ai/agents/simple-agent.js +80 -4
  16. package/dist/ai/client.js +162 -1
  17. package/dist/ai/index.js +27 -1
  18. package/dist/ai/prompts/code-generation.js +55 -13
  19. package/dist/ai/prompts/index.js +12 -1
  20. package/dist/ai/prompts/spec-creation.js +61 -20
  21. package/dist/ai/providers.js +40 -1
  22. package/dist/formatters/index.js +18 -1
  23. package/dist/formatters/json.js +71 -1
  24. package/dist/formatters/sarif.js +163 -1
  25. package/dist/formatters/text.js +208 -2
  26. package/dist/index.d.ts +0 -3
  27. package/dist/index.js +81 -1
  28. package/dist/libs/ai-providers/dist/factory.js +154 -0
  29. package/dist/libs/ai-providers/dist/index.js +4 -0
  30. package/dist/libs/ai-providers/dist/legacy.js +72 -0
  31. package/dist/libs/ai-providers/dist/models.js +287 -0
  32. package/dist/libs/ai-providers/dist/validation.js +1 -0
  33. package/dist/libs/contracts/dist/capabilities/openbanking.js +88 -0
  34. package/dist/libs/contracts/dist/client/index.js +5 -0
  35. package/dist/libs/contracts/dist/client/react/feature-render.js +2 -0
  36. package/dist/libs/contracts/dist/client/react/form-render.js +4 -0
  37. package/dist/libs/contracts/dist/client/react/index.js +4 -0
  38. package/dist/libs/contracts/dist/contract-registry/index.js +1 -0
  39. package/dist/libs/contracts/dist/contract-registry/schemas.js +60 -0
  40. package/dist/libs/contracts/dist/docs/PUBLISHING.docblock.js +16 -0
  41. package/dist/libs/contracts/dist/docs/accessibility_wcag_compliance_specs.docblock.js +16 -0
  42. package/dist/libs/contracts/dist/docs/index.js +29 -0
  43. package/dist/libs/contracts/dist/docs/presentations.js +71 -0
  44. package/dist/libs/contracts/dist/docs/registry.js +44 -0
  45. package/dist/libs/contracts/dist/docs/tech/PHASE_1_QUICKSTART.docblock.js +16 -0
  46. package/dist/libs/contracts/dist/docs/tech/PHASE_2_AI_NATIVE_OPERATIONS.docblock.js +16 -0
  47. package/dist/libs/contracts/dist/docs/tech/PHASE_3_AUTO_EVOLUTION.docblock.js +16 -0
  48. package/dist/libs/contracts/dist/docs/tech/PHASE_4_PERSONALIZATION_ENGINE.docblock.js +16 -0
  49. package/dist/libs/contracts/dist/docs/tech/PHASE_5_ZERO_TOUCH_OPERATIONS.docblock.js +16 -0
  50. package/dist/libs/contracts/dist/docs/tech/auth/better-auth-nextjs.docblock.js +80 -0
  51. package/dist/libs/contracts/dist/docs/tech/contracts/openapi-export.docblock.js +57 -0
  52. package/dist/libs/contracts/dist/docs/tech/lifecycle-stage-system.docblock.js +16 -0
  53. package/dist/libs/contracts/dist/docs/tech/llm/llm-integration.docblock.js +357 -0
  54. package/dist/libs/contracts/dist/docs/tech/mcp-endpoints.docblock.js +37 -0
  55. package/dist/libs/contracts/dist/docs/tech/presentation-runtime.docblock.js +16 -0
  56. package/dist/libs/contracts/dist/docs/tech/schema/README.docblock.js +20 -0
  57. package/dist/libs/contracts/dist/docs/tech/studio/learning-events.docblock.js +48 -0
  58. package/dist/libs/contracts/dist/docs/tech/studio/learning-journeys.docblock.js +79 -0
  59. package/dist/libs/contracts/dist/docs/tech/studio/platform-admin-panel.docblock.js +84 -0
  60. package/dist/libs/contracts/dist/docs/tech/studio/project-access-teams.docblock.js +45 -0
  61. package/dist/libs/contracts/dist/docs/tech/studio/project-routing.docblock.js +67 -0
  62. package/dist/libs/contracts/dist/docs/tech/studio/sandbox-unlogged.docblock.js +40 -0
  63. package/dist/libs/contracts/dist/docs/tech/studio/team-invitations.docblock.js +69 -0
  64. package/dist/libs/contracts/dist/docs/tech/studio/workspace-ops.docblock.js +47 -0
  65. package/dist/libs/contracts/dist/docs/tech/studio/workspaces.docblock.js +62 -0
  66. package/dist/libs/contracts/dist/docs/tech/telemetry-ingest.docblock.js +155 -0
  67. package/dist/libs/contracts/dist/docs/tech/templates/runtime.docblock.js +20 -0
  68. package/dist/libs/contracts/dist/docs/tech/vscode-extension.docblock.js +101 -0
  69. package/dist/libs/contracts/dist/docs/tech/workflows/overview.docblock.js +20 -0
  70. package/dist/libs/contracts/dist/events.js +8 -0
  71. package/dist/libs/contracts/dist/experiments/evaluator.js +1 -0
  72. package/dist/libs/contracts/dist/index.js +72 -0
  73. package/dist/libs/contracts/dist/install.js +2 -0
  74. package/dist/libs/contracts/dist/integrations/contracts.js +377 -0
  75. package/dist/libs/contracts/dist/integrations/index.js +18 -0
  76. package/dist/libs/contracts/dist/integrations/openbanking/contracts/accounts.js +228 -0
  77. package/dist/libs/contracts/dist/integrations/openbanking/contracts/balances.js +159 -0
  78. package/dist/libs/contracts/dist/integrations/openbanking/contracts/index.js +3 -0
  79. package/dist/libs/contracts/dist/integrations/openbanking/contracts/transactions.js +210 -0
  80. package/dist/libs/contracts/dist/integrations/openbanking/models.js +242 -0
  81. package/dist/libs/contracts/dist/integrations/openbanking/telemetry.js +13 -0
  82. package/dist/libs/contracts/dist/integrations/providers/elevenlabs.js +52 -0
  83. package/dist/libs/contracts/dist/integrations/providers/gcs-storage.js +75 -0
  84. package/dist/libs/contracts/dist/integrations/providers/gmail.js +87 -0
  85. package/dist/libs/contracts/dist/integrations/providers/google-calendar.js +66 -0
  86. package/dist/libs/contracts/dist/integrations/providers/index.js +11 -0
  87. package/dist/libs/contracts/dist/integrations/providers/mistral.js +68 -0
  88. package/dist/libs/contracts/dist/integrations/providers/postmark.js +68 -0
  89. package/dist/libs/contracts/dist/integrations/providers/powens.js +116 -0
  90. package/dist/libs/contracts/dist/integrations/providers/qdrant.js +73 -0
  91. package/dist/libs/contracts/dist/integrations/providers/registry.js +10 -0
  92. package/dist/libs/contracts/dist/integrations/providers/stripe.js +83 -0
  93. package/dist/libs/contracts/dist/integrations/providers/twilio-sms.js +61 -0
  94. package/dist/libs/contracts/dist/jsonschema.js +24 -0
  95. package/dist/libs/contracts/dist/knowledge/contracts.js +306 -0
  96. package/dist/libs/contracts/dist/knowledge/index.js +7 -0
  97. package/dist/libs/contracts/dist/knowledge/spaces/email-threads.js +34 -0
  98. package/dist/libs/contracts/dist/knowledge/spaces/financial-docs.js +34 -0
  99. package/dist/libs/contracts/dist/knowledge/spaces/financial-overview.js +38 -0
  100. package/dist/libs/contracts/dist/knowledge/spaces/index.js +6 -0
  101. package/dist/libs/contracts/dist/knowledge/spaces/product-canon.js +34 -0
  102. package/dist/libs/contracts/dist/knowledge/spaces/support-faq.js +37 -0
  103. package/dist/libs/contracts/dist/knowledge/spaces/uploaded-docs.js +34 -0
  104. package/dist/libs/contracts/dist/llm/exporters.js +352 -0
  105. package/dist/libs/contracts/dist/llm/index.js +2 -0
  106. package/dist/libs/contracts/dist/llm/prompts.js +211 -0
  107. package/dist/libs/contracts/dist/onboarding-base.js +196 -0
  108. package/dist/libs/contracts/dist/openapi.js +75 -0
  109. package/dist/libs/contracts/dist/ownership.js +21 -0
  110. package/dist/libs/contracts/dist/presentations.js +1 -0
  111. package/dist/libs/contracts/dist/presentations.v2.js +11 -0
  112. package/dist/libs/contracts/dist/prompt.js +1 -0
  113. package/dist/libs/contracts/dist/promptRegistry.js +1 -0
  114. package/dist/libs/contracts/dist/regenerator/index.js +2 -0
  115. package/dist/libs/contracts/dist/regenerator/service.js +92 -0
  116. package/dist/libs/contracts/dist/regenerator/utils.js +51 -0
  117. package/dist/libs/contracts/dist/registry.js +208 -0
  118. package/dist/libs/contracts/dist/resources.js +1 -0
  119. package/dist/libs/contracts/dist/schema/dist/EnumType.js +2 -0
  120. package/dist/libs/contracts/dist/schema/dist/FieldType.js +49 -0
  121. package/dist/libs/contracts/dist/schema/dist/ScalarTypeEnum.js +236 -0
  122. package/dist/libs/contracts/dist/schema/dist/SchemaModel.js +34 -0
  123. package/dist/libs/contracts/dist/schema/dist/entity/defineEntity.js +1 -0
  124. package/dist/libs/contracts/dist/schema/dist/entity/index.js +2 -0
  125. package/dist/libs/contracts/dist/schema/dist/entity/types.js +1 -0
  126. package/dist/libs/contracts/dist/schema/dist/index.js +6 -0
  127. package/dist/libs/contracts/dist/server/graphql-pothos.js +6 -0
  128. package/dist/libs/contracts/dist/server/index.js +8 -0
  129. package/dist/libs/contracts/dist/server/mcp/createMcpServer.js +4 -0
  130. package/dist/libs/contracts/dist/server/mcp/registerPresentations.js +2 -0
  131. package/dist/libs/contracts/dist/server/mcp/registerPrompts.js +1 -0
  132. package/dist/libs/contracts/dist/server/mcp/registerResources.js +2 -0
  133. package/dist/libs/contracts/dist/server/mcp/registerTools.js +1 -0
  134. package/dist/libs/contracts/dist/server/provider-mcp.js +1 -0
  135. package/dist/libs/contracts/dist/server/rest-elysia.js +1 -0
  136. package/dist/libs/contracts/dist/server/rest-express.js +1 -0
  137. package/dist/libs/contracts/dist/server/rest-generic.js +1 -0
  138. package/dist/libs/contracts/dist/server/rest-next-app.js +1 -0
  139. package/dist/libs/contracts/dist/server/rest-next-pages.js +1 -0
  140. package/dist/libs/contracts/dist/spec.js +35 -0
  141. package/dist/libs/contracts/dist/telemetry/index.js +1 -0
  142. package/dist/libs/contracts/dist/telemetry/tracker.js +1 -0
  143. package/dist/libs/contracts/dist/tests/index.js +1 -0
  144. package/dist/libs/contracts/dist/tests/runner.js +150 -0
  145. package/dist/libs/contracts/dist/workflow/index.js +1 -0
  146. package/dist/libs/contracts/dist/workflow/runner.js +1 -0
  147. package/dist/libs/contracts-transformers/dist/common/utils.js +47 -0
  148. package/dist/libs/contracts-transformers/dist/openapi/exporter.js +1 -0
  149. package/dist/libs/contracts-transformers/dist/openapi/importer.js +255 -0
  150. package/dist/libs/contracts-transformers/dist/openapi/index.js +4 -0
  151. package/dist/libs/contracts-transformers/dist/openapi/parser.js +231 -0
  152. package/dist/libs/contracts-transformers/dist/openapi/schema-converter.js +201 -0
  153. package/dist/modules/contractspec-workspace/dist/ai/code-generation.js +137 -0
  154. package/dist/modules/contractspec-workspace/dist/ai/spec-creation.js +101 -0
  155. package/dist/modules/contractspec-workspace/dist/analysis/deps/graph.js +84 -0
  156. package/dist/modules/contractspec-workspace/dist/analysis/deps/parse-imports.js +30 -0
  157. package/dist/modules/contractspec-workspace/dist/analysis/diff/semantic.js +96 -0
  158. package/dist/modules/contractspec-workspace/dist/analysis/feature-scan.js +151 -0
  159. package/dist/modules/contractspec-workspace/dist/analysis/spec-scan.js +344 -0
  160. package/dist/modules/contractspec-workspace/dist/analysis/validate/spec-structure.js +122 -0
  161. package/dist/modules/contractspec-workspace/dist/templates/app-config.js +105 -0
  162. package/dist/modules/contractspec-workspace/dist/templates/data-view.js +68 -0
  163. package/dist/modules/contractspec-workspace/dist/templates/event.js +38 -0
  164. package/dist/modules/contractspec-workspace/dist/templates/experiment.js +87 -0
  165. package/dist/modules/contractspec-workspace/dist/templates/handler.js +95 -0
  166. package/dist/modules/contractspec-workspace/dist/templates/integration-utils.js +104 -0
  167. package/dist/modules/contractspec-workspace/dist/templates/integration.js +62 -0
  168. package/dist/modules/contractspec-workspace/dist/templates/knowledge.js +68 -0
  169. package/dist/modules/contractspec-workspace/dist/templates/migration.js +60 -0
  170. package/dist/modules/contractspec-workspace/dist/templates/operation.js +100 -0
  171. package/dist/modules/contractspec-workspace/dist/templates/presentation.js +78 -0
  172. package/dist/modules/contractspec-workspace/dist/templates/telemetry.js +89 -0
  173. package/dist/modules/contractspec-workspace/dist/templates/utils.js +38 -0
  174. package/dist/modules/contractspec-workspace/dist/templates/workflow-runner.js +48 -0
  175. package/dist/modules/contractspec-workspace/dist/templates/workflow.js +67 -0
  176. package/dist/modules/contractspec-workspace/dist/types/generation-types.js +20 -0
  177. package/dist/services/agent-guide/adapters/claude-code.js +144 -3
  178. package/dist/services/agent-guide/adapters/cursor-cli.js +135 -3
  179. package/dist/services/agent-guide/adapters/generic-mcp.js +159 -3
  180. package/dist/services/agent-guide/adapters/index.js +30 -1
  181. package/dist/services/agent-guide/agent-guide-service.js +148 -1
  182. package/dist/services/agent-guide/index.js +5 -1
  183. package/dist/services/build.js +140 -1
  184. package/dist/services/ci-check/ci-check-service.js +393 -1
  185. package/dist/services/ci-check/index.js +2 -1
  186. package/dist/services/ci-check/types.js +28 -1
  187. package/dist/services/clean.js +71 -1
  188. package/dist/services/config.js +76 -1
  189. package/dist/services/deps.js +62 -1
  190. package/dist/services/diff.js +33 -1
  191. package/dist/services/doctor/checks/ai.js +118 -2
  192. package/dist/services/doctor/checks/cli.js +146 -1
  193. package/dist/services/doctor/checks/config.js +170 -1
  194. package/dist/services/doctor/checks/deps.js +180 -1
  195. package/dist/services/doctor/checks/index.js +6 -1
  196. package/dist/services/doctor/checks/mcp.js +144 -1
  197. package/dist/services/doctor/checks/workspace.js +243 -1
  198. package/dist/services/doctor/doctor-service.js +115 -2
  199. package/dist/services/doctor/index.js +2 -1
  200. package/dist/services/doctor/types.js +26 -1
  201. package/dist/services/implementation/discovery.js +143 -2
  202. package/dist/services/implementation/index.js +2 -1
  203. package/dist/services/implementation/resolver.js +223 -1
  204. package/dist/services/index.js +53 -1
  205. package/dist/services/integrity-diagram.js +274 -6
  206. package/dist/services/integrity.js +272 -1
  207. package/dist/services/list.js +35 -1
  208. package/dist/services/openapi/export-service.js +51 -2
  209. package/dist/services/openapi/import-service.js +75 -1
  210. package/dist/services/openapi/index.js +4 -1
  211. package/dist/services/openapi/sync-service.js +121 -1
  212. package/dist/services/openapi/validate-service.js +130 -1
  213. package/dist/services/regenerator.js +23 -1
  214. package/dist/services/registry.js +73 -1
  215. package/dist/services/setup/config-generators.js +113 -26
  216. package/dist/services/setup/file-merger.js +60 -2
  217. package/dist/services/setup/index.js +4 -1
  218. package/dist/services/setup/setup-service.js +95 -1
  219. package/dist/services/setup/targets/agents-md.js +46 -1
  220. package/dist/services/setup/targets/cli-config.js +59 -1
  221. package/dist/services/setup/targets/cursor-rules.js +47 -1
  222. package/dist/services/setup/targets/mcp-claude.js +59 -1
  223. package/dist/services/setup/targets/mcp-cursor.js +58 -1
  224. package/dist/services/setup/targets/vscode-settings.js +62 -1
  225. package/dist/services/setup/types.js +26 -1
  226. package/dist/services/sync.js +62 -1
  227. package/dist/services/test.js +30 -1
  228. package/dist/services/validate-implementation.js +69 -1
  229. package/dist/services/validate.js +47 -1
  230. package/dist/services/verification-cache/adapters/filesystem.js +121 -1
  231. package/dist/services/verification-cache/adapters/in-memory.js +45 -1
  232. package/dist/services/verification-cache/adapters/index.js +3 -1
  233. package/dist/services/verification-cache/adapters/workspace-state.js +90 -1
  234. package/dist/services/verification-cache/cache-service.js +255 -1
  235. package/dist/services/verification-cache/index.js +6 -1
  236. package/dist/services/verification-cache/types.js +15 -1
  237. package/dist/services/verify/ai-verifier.js +336 -9
  238. package/dist/services/verify/behavior-verifier.js +185 -1
  239. package/dist/services/verify/index.js +4 -1
  240. package/dist/services/verify/structure-verifier.js +195 -2
  241. package/dist/services/verify/verify-service.js +203 -3
  242. package/dist/services/watch.js +31 -1
  243. package/dist/services/workspace-info.js +102 -2
  244. package/dist/templates/app-config.template.js +101 -28
  245. package/dist/templates/data-view.template.js +42 -27
  246. package/dist/templates/event.template.js +29 -14
  247. package/dist/templates/experiment.template.js +77 -51
  248. package/dist/templates/handler.template.js +53 -17
  249. package/dist/templates/index.js +36 -1
  250. package/dist/templates/integration.template.js +134 -50
  251. package/dist/templates/knowledge.template.js +62 -21
  252. package/dist/templates/migration.template.js +50 -26
  253. package/dist/templates/operation.template.js +44 -28
  254. package/dist/templates/presentation.template.js +46 -20
  255. package/dist/templates/telemetry.template.js +74 -53
  256. package/dist/templates/workflow-runner.template.js +12 -6
  257. package/dist/templates/workflow.template.js +51 -24
  258. package/package.json +13 -9
  259. package/dist/adapters/index.d.ts +0 -7
  260. package/dist/ports/index.d.ts +0 -5
  261. package/dist/services/agent-guide/index.d.ts +0 -6
  262. package/dist/services/ci-check/index.d.ts +0 -2
  263. package/dist/services/doctor/index.d.ts +0 -2
  264. package/dist/services/implementation/index.d.ts +0 -3
  265. package/dist/services/index.d.ts +0 -56
  266. package/dist/services/openapi/index.d.ts +0 -5
  267. package/dist/services/verification-cache/adapters/index.d.ts +0 -3
  268. package/dist/services/verification-cache/index.d.ts +0 -6
  269. package/dist/services/verify/index.d.ts +0 -5
@@ -0,0 +1,16 @@
1
+ import { registerDocBlocks } from "../registry.js";
2
+
3
+ //#region ../../libs/contracts/dist/docs/tech/PHASE_1_QUICKSTART.docblock.js
4
+ const tech_PHASE_1_QUICKSTART_DocBlocks = [{
5
+ id: "docs.tech.PHASE_1_QUICKSTART",
6
+ title: "Phase 1: API Reference Index",
7
+ summary: "Quick reference for all new Phase 1 APIs.",
8
+ kind: "reference",
9
+ visibility: "public",
10
+ route: "/docs/tech/PHASE_1_QUICKSTART",
11
+ tags: ["tech", "PHASE_1_QUICKSTART"],
12
+ 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"
13
+ }];
14
+ registerDocBlocks(tech_PHASE_1_QUICKSTART_DocBlocks);
15
+
16
+ //#endregion
@@ -0,0 +1,16 @@
1
+ import { registerDocBlocks } from "../registry.js";
2
+
3
+ //#region ../../libs/contracts/dist/docs/tech/PHASE_2_AI_NATIVE_OPERATIONS.docblock.js
4
+ const tech_PHASE_2_AI_NATIVE_OPERATIONS_DocBlocks = [{
5
+ id: "docs.tech.PHASE_2_AI_NATIVE_OPERATIONS",
6
+ title: "Phase 2: AI-Native Operations",
7
+ summary: "_Last updated: 2025-11-20_",
8
+ kind: "reference",
9
+ visibility: "public",
10
+ route: "/docs/tech/PHASE_2_AI_NATIVE_OPERATIONS",
11
+ tags: ["tech", "PHASE_2_AI_NATIVE_OPERATIONS"],
12
+ 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"
13
+ }];
14
+ registerDocBlocks(tech_PHASE_2_AI_NATIVE_OPERATIONS_DocBlocks);
15
+
16
+ //#endregion
@@ -0,0 +1,16 @@
1
+ import { registerDocBlocks } from "../registry.js";
2
+
3
+ //#region ../../libs/contracts/dist/docs/tech/PHASE_3_AUTO_EVOLUTION.docblock.js
4
+ const tech_PHASE_3_AUTO_EVOLUTION_DocBlocks = [{
5
+ id: "docs.tech.PHASE_3_AUTO_EVOLUTION",
6
+ title: "Phase 3: Auto-Evolution Technical Notes",
7
+ summary: "**Status**: In progress",
8
+ kind: "reference",
9
+ visibility: "public",
10
+ route: "/docs/tech/PHASE_3_AUTO_EVOLUTION",
11
+ tags: ["tech", "PHASE_3_AUTO_EVOLUTION"],
12
+ 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"
13
+ }];
14
+ registerDocBlocks(tech_PHASE_3_AUTO_EVOLUTION_DocBlocks);
15
+
16
+ //#endregion
@@ -0,0 +1,16 @@
1
+ import { registerDocBlocks } from "../registry.js";
2
+
3
+ //#region ../../libs/contracts/dist/docs/tech/PHASE_4_PERSONALIZATION_ENGINE.docblock.js
4
+ const tech_PHASE_4_PERSONALIZATION_ENGINE_DocBlocks = [{
5
+ id: "docs.tech.PHASE_4_PERSONALIZATION_ENGINE",
6
+ title: "Phase 4: Personalization Engine",
7
+ summary: "**Status**: Complete",
8
+ kind: "reference",
9
+ visibility: "public",
10
+ route: "/docs/tech/PHASE_4_PERSONALIZATION_ENGINE",
11
+ tags: ["tech", "PHASE_4_PERSONALIZATION_ENGINE"],
12
+ 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"
13
+ }];
14
+ registerDocBlocks(tech_PHASE_4_PERSONALIZATION_ENGINE_DocBlocks);
15
+
16
+ //#endregion
@@ -0,0 +1,16 @@
1
+ import { registerDocBlocks } from "../registry.js";
2
+
3
+ //#region ../../libs/contracts/dist/docs/tech/PHASE_5_ZERO_TOUCH_OPERATIONS.docblock.js
4
+ const tech_PHASE_5_ZERO_TOUCH_OPERATIONS_DocBlocks = [{
5
+ id: "docs.tech.PHASE_5_ZERO_TOUCH_OPERATIONS",
6
+ title: "Phase 5: Zero-Touch Operations",
7
+ summary: "**Status**: In progress",
8
+ kind: "reference",
9
+ visibility: "public",
10
+ route: "/docs/tech/PHASE_5_ZERO_TOUCH_OPERATIONS",
11
+ tags: ["tech", "PHASE_5_ZERO_TOUCH_OPERATIONS"],
12
+ 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"
13
+ }];
14
+ registerDocBlocks(tech_PHASE_5_ZERO_TOUCH_OPERATIONS_DocBlocks);
15
+
16
+ //#endregion
@@ -0,0 +1,80 @@
1
+ import { registerDocBlocks } from "../../registry.js";
2
+
3
+ //#region ../../libs/contracts/dist/docs/tech/auth/better-auth-nextjs.docblock.js
4
+ const tech_auth_better_auth_nextjs_DocBlocks = [{
5
+ id: "docs.tech.auth.better-auth-nextjs",
6
+ title: "Better Auth + Next.js integration (ContractSpec)",
7
+ summary: "How ContractSpec wires Better Auth into Next.js (server config, client singleton, and proxy cookie-only redirects).",
8
+ kind: "reference",
9
+ visibility: "public",
10
+ route: "/docs/tech/auth/better-auth-nextjs",
11
+ tags: [
12
+ "auth",
13
+ "better-auth",
14
+ "nextjs",
15
+ "cookies",
16
+ "proxy",
17
+ "hmr"
18
+ ],
19
+ body: `# Better Auth + Next.js integration (ContractSpec)
20
+
21
+ This repo uses Better Auth as the primary auth layer (sessions, organizations, teams, API keys, and OAuth).
22
+
23
+ ## Server config (Better Auth)
24
+
25
+ - Source: \`packages/bundles/contractspec-studio/src/application/services/auth.ts\`
26
+ - Important: \`nextCookies()\` must be the **last** plugin in the Better Auth plugin list so \`Set-Cookie\` is applied correctly in Next.js environments.
27
+
28
+ ## Better Auth Admin plugin
29
+
30
+ ContractSpec Studio enables the Better Auth **Admin plugin** to support platform-admin user operations (list users, impersonation, etc.).
31
+
32
+ - Server: \`admin()\` plugin in \`packages/bundles/contractspec-studio/src/application/services/auth.ts\`
33
+ - Client: \`adminClient()\` in \`packages/bundles/contractspec-studio/src/presentation/providers/auth/client.ts\`
34
+
35
+ ### PLATFORM_ADMIN ⇒ Better Auth admin role
36
+
37
+ Better Auth Admin endpoints authorize via \`user.role\`. ContractSpec enforces an org-driven rule:
38
+
39
+ - If the **active organization** has \`type = PLATFORM_ADMIN\`, the signed-in user is ensured to have \`User.role\` containing \`admin\`.
40
+ - This is applied in the session creation hook and re-checked in \`assertsPlatformAdmin()\`.
41
+
42
+ This keeps admin enablement deterministic and avoids manual role backfills.
43
+
44
+ ## Client config (React web + Expo)
45
+
46
+ To avoid duplicate background refresh/polling loops in dev (Fast Refresh/HMR), the Better Auth client is implemented as a singleton cached on \`globalThis\`.
47
+
48
+ - Web client: \`packages/bundles/contractspec-studio/src/presentation/providers/auth/client.ts\`
49
+ - Native client: \`packages/bundles/contractspec-studio/src/presentation/providers/auth/client.native.ts\`
50
+
51
+ Import guidance:
52
+
53
+ - If you only need the context/hook, prefer importing from \`@lssm/bundle.contractspec-studio/presentation/providers/auth\`.
54
+ - 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\`.
55
+
56
+ ## Public routes (login / signup)
57
+
58
+ Public auth pages should avoid eager \`authClient\` initialization.
59
+
60
+ Pattern used:
61
+
62
+ - In the submit handler, dynamically import \`@lssm/bundle.contractspec-studio/presentation/providers/auth/index.web\` and call \`authClient.signIn.*\` / \`authClient.signUp.*\`.
63
+
64
+ This prevents session refresh behavior from starting just because a public page rendered.
65
+
66
+ ## Next.js proxy auth (web-landing)
67
+
68
+ The Next.js proxy/middleware is used for **redirect decisions only**. It must not perform DB-backed session reads on every request.
69
+
70
+ - Source: \`packages/apps/web-landing/src/proxy.ts\`
71
+ - Approach: cookie-only checks via Better Auth cookies helpers:
72
+ - \`getSessionCookie(request)\`
73
+ - \`getCookieCache(request)\`
74
+
75
+ These checks are intentionally optimistic and should only gate routing. Full authorization must still be enforced on server-side actions/routes and GraphQL resolvers.
76
+ `
77
+ }];
78
+ registerDocBlocks(tech_auth_better_auth_nextjs_DocBlocks);
79
+
80
+ //#endregion
@@ -0,0 +1,57 @@
1
+ import { registerDocBlocks } from "../../registry.js";
2
+
3
+ //#region ../../libs/contracts/dist/docs/tech/contracts/openapi-export.docblock.js
4
+ const tech_contracts_openapi_export_DocBlocks = [{
5
+ id: "docs.tech.contracts.openapi-export",
6
+ title: "OpenAPI export (OpenAPI 3.1) from SpecRegistry",
7
+ summary: "Generate a deterministic OpenAPI document from a SpecRegistry using jsonSchemaForSpec + REST transport metadata.",
8
+ kind: "reference",
9
+ visibility: "public",
10
+ route: "/docs/tech/contracts/openapi-export",
11
+ tags: [
12
+ "contracts",
13
+ "openapi",
14
+ "rest"
15
+ ],
16
+ body: `## OpenAPI export (OpenAPI 3.1) from SpecRegistry
17
+
18
+ ### Purpose
19
+
20
+ ContractSpec specs can be exported into an **OpenAPI 3.1** document for tooling (SDK generation, docs, gateways).
21
+
22
+ The export is **spec-first**:
23
+
24
+ - Uses \`jsonSchemaForSpec(spec)\` for input/output JSON Schema (from SchemaModel → zod → JSON Schema)
25
+ - Uses \`spec.transport.rest.method/path\` when present
26
+ - Falls back to deterministic defaults:
27
+ - Method: \`POST\` for commands, \`GET\` for queries
28
+ - Path: \`defaultRestPath(name, version)\` → \`/<dot/name>/v<version>\`
29
+
30
+ ### Library API
31
+
32
+ - Function: \`openApiForRegistry(registry, options?)\`
33
+ - Location: \`@lssm/lib.contracts/openapi\`
34
+
35
+ ### CLI
36
+
37
+ Export OpenAPI from a registry module:
38
+
39
+ \`\`\`bash
40
+ contractspec openapi --registry ./src/registry.ts --out ./openapi.json
41
+ \`\`\`
42
+
43
+ The registry module must export one of:
44
+
45
+ - \`registry: SpecRegistry\`
46
+ - \`default(): SpecRegistry | Promise<SpecRegistry>\`
47
+ - \`createRegistry(): SpecRegistry | Promise<SpecRegistry>\`
48
+
49
+ ### Notes / limitations (current)
50
+
51
+ - Responses are generated as a basic \`200\` response (plus schemas when available).
52
+ - Query (GET) inputs are currently represented as a JSON request body when an input schema exists.
53
+ - Errors are not yet expanded into OpenAPI responses; that will be added when we standardize error envelopes.`
54
+ }];
55
+ registerDocBlocks(tech_contracts_openapi_export_DocBlocks);
56
+
57
+ //#endregion
@@ -0,0 +1,16 @@
1
+ import { registerDocBlocks } from "../registry.js";
2
+
3
+ //#region ../../libs/contracts/dist/docs/tech/lifecycle-stage-system.docblock.js
4
+ const tech_lifecycle_stage_system_DocBlocks = [{
5
+ id: "docs.tech.lifecycle-stage-system",
6
+ title: "ContractSpec Lifecycle Stage System – Technical Design",
7
+ 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.",
8
+ kind: "reference",
9
+ visibility: "public",
10
+ route: "/docs/tech/lifecycle-stage-system",
11
+ tags: ["tech", "lifecycle-stage-system"],
12
+ 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"
13
+ }];
14
+ registerDocBlocks(tech_lifecycle_stage_system_DocBlocks);
15
+
16
+ //#endregion
@@ -0,0 +1,357 @@
1
+ import { registerDocBlocks } from "../../registry.js";
2
+
3
+ //#region ../../libs/contracts/dist/docs/tech/llm/llm-integration.docblock.js
4
+ const tech_llm_integration_DocBlocks = [
5
+ {
6
+ id: "docs.tech.llm.overview",
7
+ title: "LLM Integration Overview",
8
+ summary: "Export specs to LLM-friendly formats, generate implementation guides, and verify implementations.",
9
+ kind: "reference",
10
+ visibility: "public",
11
+ route: "/docs/tech/llm/overview",
12
+ tags: [
13
+ "llm",
14
+ "ai",
15
+ "export",
16
+ "guide",
17
+ "verify"
18
+ ],
19
+ body: `# LLM Integration
20
+
21
+ ContractSpec provides first-class LLM integration to bridge specifications and AI coding agents.
22
+
23
+ ## Core Features
24
+
25
+ ### 1. Multi-Format Export
26
+
27
+ Export specs to markdown in formats optimized for LLM consumption:
28
+
29
+ - **Context format**: Summary for understanding (goal, context, acceptance criteria)
30
+ - **Full format**: Complete spec with all details (I/O schemas, policy, events)
31
+ - **Prompt format**: Actionable prompt with implementation instructions
32
+
33
+ ### 2. Implementation Guidance
34
+
35
+ Generate agent-specific implementation plans:
36
+
37
+ - **Claude Code**: Extended thinking mode with structured prompts
38
+ - **Cursor CLI**: Background/composer mode with .mdc rules generation
39
+ - **Generic MCP**: Standard format for any MCP-compatible agent
40
+
41
+ ### 3. Tiered Verification
42
+
43
+ Verify implementations against specs:
44
+
45
+ - **Tier 1 (Structure)**: Types, exports, imports validation
46
+ - **Tier 2 (Behavior)**: Scenario coverage, error handling, events
47
+ - **Tier 3 (AI Review)**: Semantic compliance analysis via LLM
48
+
49
+ ## Access Points
50
+
51
+ | Surface | Commands/Tools |
52
+ |---------|---------------|
53
+ | CLI | \`contractspec llm export\`, \`guide\`, \`verify\`, \`copy\` |
54
+ | MCP | \`llm.export\`, \`llm.guide\`, \`llm.verify\` tools |
55
+ | VSCode | Export to LLM, Generate Guide, Verify, Copy commands |
56
+
57
+ ## Quick Start
58
+
59
+ ### CLI Usage
60
+
61
+ \`\`\`bash
62
+ # Export spec as markdown
63
+ contractspec llm export path/to/my.spec.ts --format full
64
+
65
+ # Generate implementation guide
66
+ contractspec llm guide path/to/my.spec.ts --agent claude-code
67
+
68
+ # Verify implementation
69
+ contractspec llm verify path/to/my.spec.ts path/to/impl.ts --tier 2
70
+
71
+ # Copy spec to clipboard
72
+ contractspec llm copy path/to/my.spec.ts --format context
73
+ \`\`\`
74
+
75
+ ### MCP Usage
76
+
77
+ \`\`\`
78
+ # Export spec
79
+ llm.export { specPath: "path/to/my.spec.ts", format: "full" }
80
+
81
+ # Generate guide
82
+ llm.guide { specPath: "path/to/my.spec.ts", agent: "cursor-cli" }
83
+
84
+ # Verify implementation
85
+ llm.verify { specPath: "path/to/my.spec.ts", implementationPath: "path/to/impl.ts", tier: "2" }
86
+ \`\`\`
87
+
88
+ ### Programmatic Usage
89
+
90
+ \`\`\`typescript
91
+ import { specToFullMarkdown, specToAgentPrompt } from '@lssm/lib.contracts/llm';
92
+ import { createAgentGuideService, createVerifyService } from '@lssm/bundle.contractspec-workspace';
93
+
94
+ // Export
95
+ const markdown = specToFullMarkdown(mySpec);
96
+
97
+ // Generate guide
98
+ const guideService = createAgentGuideService({ defaultAgent: 'claude-code' });
99
+ const guide = guideService.generateGuide(mySpec);
100
+
101
+ // Verify
102
+ const verifyService = createVerifyService();
103
+ const result = await verifyService.verify(mySpec, implementationCode, {
104
+ tiers: ['structure', 'behavior']
105
+ });
106
+ \`\`\`
107
+ `
108
+ },
109
+ {
110
+ id: "docs.tech.llm.export-formats",
111
+ title: "LLM Export Formats",
112
+ summary: "Detailed explanation of the three export formats for LLM consumption.",
113
+ kind: "reference",
114
+ visibility: "public",
115
+ route: "/docs/tech/llm/export-formats",
116
+ tags: [
117
+ "llm",
118
+ "export",
119
+ "markdown"
120
+ ],
121
+ body: `# LLM Export Formats
122
+
123
+ ContractSpec provides three export formats optimized for different LLM use cases.
124
+
125
+ ## Context Format
126
+
127
+ Best for: Understanding what a spec does, providing background to LLMs.
128
+
129
+ Includes:
130
+ - Spec name, version, type
131
+ - Goal and context
132
+ - Description
133
+ - Acceptance scenarios
134
+
135
+ Example:
136
+
137
+ \`\`\`markdown
138
+ # users.createUser (v1)
139
+
140
+ > Create a new user account with email verification.
141
+
142
+ **Type:** command | **Stability:** stable
143
+
144
+ ## Goal
145
+ Create a new user in the system and trigger email verification.
146
+
147
+ ## Context
148
+ Part of the user onboarding flow. Called after signup form submission.
149
+
150
+ ## Acceptance Criteria
151
+ ### Happy path
152
+ **Given:** Valid email and password
153
+ **When:** User submits registration
154
+ **Then:** Account is created, verification email is sent
155
+ \`\`\`
156
+
157
+ ## Full Format
158
+
159
+ Best for: Complete documentation, implementation reference.
160
+
161
+ Includes everything:
162
+ - All metadata
163
+ - JSON schemas for I/O
164
+ - Error definitions
165
+ - Policy (auth, rate limits, PII)
166
+ - Events emitted
167
+ - Examples
168
+ - Transport configuration
169
+
170
+ ## Prompt Format
171
+
172
+ Best for: Feeding directly to coding agents.
173
+
174
+ Includes:
175
+ - Task header with clear instructions
176
+ - Full spec context
177
+ - Implementation requirements
178
+ - Task-specific guidance (implement/test/refactor/review)
179
+ - Expected output format
180
+
181
+ The prompt format adapts based on task type:
182
+ - **implement**: Full implementation with tests
183
+ - **test**: Test generation for existing code
184
+ - **refactor**: Refactoring while maintaining behavior
185
+ - **review**: Code review against spec
186
+ `
187
+ },
188
+ {
189
+ id: "docs.tech.llm.agent-adapters",
190
+ title: "Agent Adapters",
191
+ summary: "Adapters for different AI coding agents (Claude, Cursor, MCP).",
192
+ kind: "reference",
193
+ visibility: "public",
194
+ route: "/docs/tech/llm/agent-adapters",
195
+ tags: [
196
+ "llm",
197
+ "agents",
198
+ "claude",
199
+ "cursor",
200
+ "mcp"
201
+ ],
202
+ body: `# Agent Adapters
203
+
204
+ ContractSpec provides specialized adapters for different AI coding agents.
205
+
206
+ ## Claude Code Adapter
207
+
208
+ Optimized for Anthropic Claude's extended thinking and code generation.
209
+
210
+ Features:
211
+ - Structured markdown with clear sections
212
+ - Checklists for steps and verification
213
+ - Icons for file operations (📝 create, ✏️ modify)
214
+ - System prompt for ContractSpec context
215
+
216
+ Usage:
217
+ \`\`\`typescript
218
+ const guideService = createAgentGuideService({ defaultAgent: 'claude-code' });
219
+ const result = guideService.generateGuide(spec, { agent: 'claude-code' });
220
+ // result.prompt.systemPrompt - Claude system context
221
+ // result.prompt.taskPrompt - Task-specific instructions
222
+ \`\`\`
223
+
224
+ ## Cursor CLI Adapter
225
+
226
+ Optimized for Cursor's background/composer mode.
227
+
228
+ Features:
229
+ - Compact format for context efficiency
230
+ - .mdc cursor rules generation
231
+ - Integration with Cursor's file system
232
+ - Concise step lists
233
+
234
+ Generate Cursor Rules:
235
+ \`\`\`typescript
236
+ const cursorRules = guideService.generateAgentConfig(spec, 'cursor-cli');
237
+ // Save to .cursor/rules/my-spec.mdc
238
+ \`\`\`
239
+
240
+ ## Generic MCP Adapter
241
+
242
+ Works with any MCP-compatible agent (Cline, Aider, etc.).
243
+
244
+ Features:
245
+ - Standard markdown format
246
+ - Table-based metadata
247
+ - JSON resource format support
248
+ - Prompt message format
249
+
250
+ The generic adapter is the default and works across all agents.
251
+
252
+ ## Choosing an Adapter
253
+
254
+ | Agent | Best For | Key Features |
255
+ |-------|----------|--------------|
256
+ | Claude Code | Complex implementations | Extended thinking, detailed steps |
257
+ | Cursor CLI | IDE-integrated work | Cursor rules, compact format |
258
+ | Generic MCP | Any MCP agent | Universal compatibility |
259
+ `
260
+ },
261
+ {
262
+ id: "docs.tech.llm.verification",
263
+ title: "Implementation Verification",
264
+ summary: "Tiered verification of implementations against specifications.",
265
+ kind: "reference",
266
+ visibility: "public",
267
+ route: "/docs/tech/llm/verification",
268
+ tags: [
269
+ "llm",
270
+ "verify",
271
+ "validation",
272
+ "testing"
273
+ ],
274
+ body: `# Implementation Verification
275
+
276
+ ContractSpec provides tiered verification to check if implementations comply with specs.
277
+
278
+ ## Verification Tiers
279
+
280
+ ### Tier 1: Structure (Fast)
281
+
282
+ Checks TypeScript structure against spec requirements:
283
+
284
+ | Check | What it validates |
285
+ |-------|------------------|
286
+ | Handler export | Function is properly exported |
287
+ | Contracts import | Imports from @lssm/lib.contracts |
288
+ | Schema import | Imports from @lssm/lib.schema |
289
+ | No \`any\` type | TypeScript strict compliance |
290
+ | Error handling | Error codes are referenced |
291
+ | Event emission | Event patterns exist |
292
+ | Input validation | Validation patterns used |
293
+ | Async patterns | Async/await for commands |
294
+
295
+ ### Tier 2: Behavior (Comprehensive)
296
+
297
+ Checks implementation coverage of spec behaviors:
298
+
299
+ | Check | What it validates |
300
+ |-------|------------------|
301
+ | Scenario coverage | Acceptance scenarios implemented |
302
+ | Example coverage | Example I/O values referenced |
303
+ | Error cases | All error conditions handled |
304
+ | Event conditions | Events emitted correctly |
305
+ | Idempotency | Idempotent patterns (if required) |
306
+
307
+ ### Tier 3: AI Review (Deep)
308
+
309
+ Uses LLM for semantic analysis:
310
+
311
+ - Does the implementation fulfill the spec's intent?
312
+ - Are edge cases properly handled?
313
+ - Is the code quality acceptable?
314
+ - Are there any subtle violations?
315
+
316
+ Requires AI API key configuration.
317
+
318
+ ## Running Verification
319
+
320
+ \`\`\`typescript
321
+ const verifyService = createVerifyService({
322
+ aiApiKey: process.env.ANTHROPIC_API_KEY, // Optional, for Tier 3
323
+ aiProvider: 'anthropic',
324
+ });
325
+
326
+ const result = await verifyService.verify(spec, implementationCode, {
327
+ tiers: ['structure', 'behavior'],
328
+ failFast: false,
329
+ includeSuggestions: true,
330
+ });
331
+
332
+ console.log(result.passed); // true/false
333
+ console.log(result.score); // 0-100
334
+ console.log(result.summary); // Human-readable summary
335
+ \`\`\`
336
+
337
+ ## Verification Report
338
+
339
+ The report includes:
340
+
341
+ - **passed**: Overall compliance
342
+ - **score**: 0-100 score
343
+ - **issues**: Array of problems found
344
+ - **suggestions**: Recommended fixes
345
+ - **coverage**: Metrics on scenario/error/field coverage
346
+
347
+ Each issue has:
348
+ - **severity**: error, warning, or info
349
+ - **category**: type, export, import, scenario, error_handling, semantic
350
+ - **message**: Description of the issue
351
+ - **suggestion**: How to fix it
352
+ `
353
+ }
354
+ ];
355
+ registerDocBlocks(tech_llm_integration_DocBlocks);
356
+
357
+ //#endregion