// @bun
import j from"@contractspec/lib.ui-link";import{jsx as L,jsxs as ee}from"react/jsx-runtime";function v({title:i="Need the operating layer on top of OSS ContractSpec?",body:X="ContractSpec Studio helps teams turn evidence into proposed spec changes, governed delivery loops, and execution-ready task packs while keeping the open contract system as the source of truth.",ctaLabel:Z="See what Studio adds",href:x="https://www.contractspec.studio/docs"}){return ee("div",{className:"card-subtle space-y-3 p-6",children:[L("h3",{className:"font-semibold text-lg",children:i}),L("p",{className:"text-muted-foreground text-sm",children:X}),L(j,{href:x,className:"btn-primary",children:Z})]})}import{CodeBlock as A}from"@contractspec/lib.design-system";import _ from"@contractspec/lib.ui-link";import{ChevronRight as te}from"lucide-react";import{jsx as l,jsxs as S}from"react/jsx-runtime";function ae(){return S("div",{className:"space-y-8",children:[S("div",{className:"space-y-3",children:[l("h1",{className:"font-bold text-4xl",children:"CI gating with deterministic diffs"}),l("p",{className:"text-lg text-muted-foreground",children:"Add ContractSpec CI checks that validate specs, detect drift, and gate breaking changes before merge."})]}),S("div",{className:"card-subtle space-y-4 p-6",children:[l("h2",{className:"font-bold text-2xl",children:"What you'll build"}),S("ul",{className:"space-y-2 text-muted-foreground text-sm",children:[l("li",{children:"CI workflow running ContractSpec validation and drift checks."}),l("li",{children:"Machine-readable output for PR annotations."}),l("li",{children:"Deterministic contract diffs in review."})]})]}),S("div",{className:"space-y-6",children:[S("div",{className:"space-y-3",children:[l("h2",{className:"font-bold text-2xl",children:"1) Add the CI workflow"}),l("p",{className:"text-muted-foreground text-sm",children:"Copy the template from the CLI package."}),l(A,{language:"bash",filename:"ci-copy",code:"cp node_modules/@contractspec/app.cli-contractspec/templates/github-action.yml .github/workflows/contractspec.yml"}),S("p",{className:"text-muted-foreground text-sm",children:["Expected output: new workflow file in ",l("code",{children:".github/workflows"}),"."]})]}),S("div",{className:"space-y-3",children:[l("h2",{className:"font-bold text-2xl",children:"2) Run CI locally"}),l(A,{language:"bash",filename:"ci-local",code:"contractspec ci --format json --check-drift"}),l("p",{className:"text-muted-foreground text-sm",children:"Expected output: JSON summary including pass/fail counts and drift status (if configured)."})]}),S("div",{className:"space-y-3",children:[l("h2",{className:"font-bold text-2xl",children:"3) Add a diff check"}),l("p",{className:"text-muted-foreground text-sm",children:"Use the diff command to inspect breaking changes in PRs."}),l(A,{language:"bash",filename:"ci-diff",code:"contractspec diff src/contracts/spec-v1.ts src/contracts/spec-v2.ts --breaking"}),l("p",{className:"text-muted-foreground text-sm",children:"Expected output: deterministic diff with breaking change hints."})]}),S("div",{className:"card-subtle space-y-3 p-6",children:[l("h3",{className:"font-semibold text-lg",children:"Example package"}),l("p",{className:"text-muted-foreground text-sm",children:"The CRM pipeline example is already wired in the quickstart smoke test. Use it as a CI-ready template."}),l(A,{language:"bash",filename:"crm-ci",code:`cd packages/examples/crm-pipeline
bun run build
bun run validate`})]}),l(v,{title:"Need continuous checks tied to outcomes?",body:"Studio closes the loop with post-change verification and learning dividends that improve future decisions."})]}),S("div",{className:"flex items-center gap-4 pt-4",children:[S(_,{href:"/docs/guides",className:"btn-primary",children:["Back to guides ",l(te,{size:16})]}),l(_,{href:"/docs",className:"btn-ghost",children:"Docs home"})]})]})}import{CodeBlock as R}from"@contractspec/lib.design-system";import H from"@contractspec/lib.ui-link";import{ChevronRight as oe}from"lucide-react";import{jsx as n,jsxs as b}from"react/jsx-runtime";var ne=[".contractspec/connect/context-pack.json",".contractspec/connect/plan-packet.json",".contractspec/connect/patch-verdict.json",".contractspec/connect/audit.ndjson",".contractspec/connect/decisions/<decisionId>/",".contractspec/adoption/catalog.json",".contractspec/adoption/overrides.json"];function re(){return b("div",{className:"space-y-8",children:[b("div",{className:"space-y-3",children:[n("h1",{className:"font-bold text-4xl",children:"Use Connect in a repo"}),n("p",{className:"text-lg text-muted-foreground",children:"Put coding-agent edits and shell commands behind task-scoped context, plan compilation, verification, and local review evidence without introducing a second control plane."})]}),b("div",{className:"card-subtle space-y-4 p-6",children:[n("h2",{className:"font-bold text-2xl",children:"What you'll build"}),b("ul",{className:"space-y-2 text-muted-foreground text-sm",children:[n("li",{children:"A workspace-level Connect config in `.contractsrc.json`."}),n("li",{children:"A reuse-first adoption check before new implementation work."}),n("li",{children:"A context and plan flow for one task."}),n("li",{children:"Verified file and shell mutations with local review/replay evidence."})]})]}),b("div",{className:"space-y-6",children:[b("div",{className:"space-y-3",children:[n("h2",{className:"font-bold text-2xl",children:"1) Enable Connect"}),n("p",{className:"text-muted-foreground text-sm",children:"Start by making the safety policy explicit. Protected paths, generated paths, review thresholds, and command rules live in the workspace config, not in editor-specific hooks."}),n(R,{language:"json",filename:".contractsrc.json",code:`{
  "connect": {
    "enabled": true,
    "storage": {
      "root": ".contractspec/connect",
      "contextPack": ".contractspec/connect/context-pack.json",
      "planPacket": ".contractspec/connect/plan-packet.json",
      "patchVerdict": ".contractspec/connect/patch-verdict.json",
      "auditFile": ".contractspec/connect/audit.ndjson",
      "reviewPacketsDir": ".contractspec/connect/review-packets"
    },
    "policy": {
      "protectedPaths": ["packages/libs/contracts-spec/**"],
      "generatedPaths": ["generated/**"],
      "smokeChecks": ["bun run typecheck"],
      "reviewThresholds": {
        "protectedPathWrite": "require_review",
        "breakingChange": "require_review",
        "destructiveCommand": "deny"
      }
    },
    "commands": {
      "allow": ["bun run typecheck"],
      "review": ["git push"],
      "deny": ["git reset --hard", "git push --force", "rm -rf"]
    },
    "adoption": {
      "enabled": true,
      "catalog": {
        "indexPath": ".contractspec/adoption/catalog.json",
        "overrideManifestPath": ".contractspec/adoption/overrides.json"
      },
      "workspaceScan": {
        "include": ["packages/**", "docs/**"],
        "exclude": ["generated/**", "dist/**"]
      },
      "families": {
        "contracts": true,
        "runtime": true,
        "sharedLibs": true
      },
      "thresholds": {
        "workspaceReuse": "permit",
        "contractspecReuse": "permit",
        "ambiguous": "require_review",
        "newImplementation": "require_review"
      }
    }
  }
}`}),n("p",{className:"text-muted-foreground text-sm",children:"Expected output: Connect has enough policy to classify writes, commands, drift, and review thresholds deterministically."})]}),b("div",{className:"space-y-3",children:[n("h2",{className:"font-bold text-2xl",children:"2) Initialize storage"}),n(R,{language:"bash",filename:"connect-init",code:"contractspec connect init --scope workspace"}),n("p",{className:"text-muted-foreground text-sm",children:"Expected output: `.contractsrc.json` is updated if needed and `.contractspec/connect/` is created."})]}),b("div",{className:"space-y-3",children:[n("h2",{className:"font-bold text-2xl",children:"3) Mirror the adoption catalog and resolve reuse first"}),n("p",{className:"text-muted-foreground text-sm",children:"Connect adoption is the reuse-first layer for authoring. Mirror the local catalog, then resolve the best existing surface for the family you are about to touch before you scaffold or invent anything new."}),n(R,{language:"bash",filename:"connect-adoption",code:`contractspec connect adoption sync --json

printf '{"goal":"Prefer an existing release helper before adding a new one"}' | \\
  contractspec connect adoption resolve --family sharedLibs --stdin --json`}),n("p",{className:"text-muted-foreground text-sm",children:"Expected output: a mirrored local adoption catalog plus a reuse recommendation that can point to an existing workspace package or a ContractSpec surface before the task reaches file mutation."})]}),b("div",{className:"space-y-3",children:[n("h2",{className:"font-bold text-2xl",children:"4) Project context and compile a plan"}),n("p",{className:"text-muted-foreground text-sm",children:"Use the task id as the thread that connects context, plan, verdict, and replay artifacts."}),n(R,{language:"bash",filename:"connect-plan",code:`contractspec connect context \\
  --task docs-connect \\
  --paths packages/libs/contracts-spec/src/control-plane/contracts.ts \\
  --json

printf '{"objective":"Document the control-plane contract surface","commands":["bun run typecheck"]}' | \\
  contractspec connect plan --task docs-connect --stdin --json`}),n("p",{className:"text-muted-foreground text-sm",children:"Expected output: a `ContextPack` and `PlanPacket` that point back to `controlPlane.intent.submit`, `controlPlane.plan.compile`, and `controlPlane.plan.verify`."})]}),b("div",{className:"space-y-3",children:[n("h2",{className:"font-bold text-2xl",children:"5) Verify file and shell mutations"}),n(R,{language:"bash",filename:"connect-verify",code:`printf '{"operation":"edit","path":"packages/libs/contracts-spec/src/control-plane/contracts.ts"}' | \\
  contractspec connect verify --task docs-connect --tool acp.fs.access --stdin --json

printf 'bun run typecheck' | \\
  contractspec connect verify --task docs-connect --tool acp.terminal.exec --stdin --json`}),n("p",{className:"text-muted-foreground text-sm",children:"Expected output: a `PatchVerdict` with `permit`, `rewrite`, `require_review`, or `deny`, plus a runtime-linked control-plane state when that linkage is available."})]}),b("div",{className:"card-subtle space-y-3 p-6",children:[n("h3",{className:"font-semibold text-lg",children:"Artifacts to inspect"}),n("ul",{className:"space-y-2 text-muted-foreground text-sm",children:ne.map((i)=>n("li",{children:n("code",{children:i})},i))})]}),b("div",{className:"space-y-3",children:[n("h2",{className:"font-bold text-2xl",children:"6) Review, replay, and optional Studio sync"}),n(R,{language:"bash",filename:"connect-review-replay",code:`contractspec connect review list --json
contractspec connect replay <decisionId> --json
contractspec connect eval <decisionId> --registry ./harness-registry.ts --scenario connect.safe-refactor --json

# Optional when Studio review-bridge mode is enabled
contractspec connect review sync --decision <decisionId> --json`}),n("p",{className:"text-muted-foreground text-sm",children:"Local review packets remain authoritative. Studio sync is an operator convenience layer, not a requirement for baseline OSS safety."})]})]}),b("div",{className:"flex items-center gap-4 pt-4",children:[b(H,{href:"/docs/specs/connect",className:"btn-primary",children:["Back to Connect spec ",n(oe,{size:16})]}),n(H,{href:"/docs/architecture/control-plane",className:"btn-ghost",children:"Control-plane runtime"})]})]})}import{CodeBlock as T}from"@contractspec/lib.design-system";import V from"@contractspec/lib.ui-link";import{ChevronRight as ie,Globe as ce,Layers as se,Shield as de,Zap as le}from"lucide-react";import{jsx as t,jsxs as r}from"react/jsx-runtime";var pe=[{name:"Operations",factory:"defineCommand / defineQuery",description:"API endpoints with input/output schemas, validation, and policy.",icon:le,color:"text-blue-400"},{name:"Events",factory:"defineEvent",description:"Domain events with typed payloads and PII handling.",icon:se,color:"text-green-400"},{name:"Capabilities",factory:"defineCapability",description:"Feature groupings that link operations, events, and UIs.",icon:de,color:"text-purple-400"},{name:"Presentations",factory:"definePresentation",description:"UI specifications for rendering data and handling interactions.",icon:ce,color:"text-orange-400"}];function me(){return r("div",{className:"space-y-8",children:[r("div",{className:"space-y-3",children:[t("h1",{className:"font-bold text-4xl",children:"Contract Types Overview"}),t("p",{className:"text-lg text-muted-foreground",children:"Learn about the different contract types in ContractSpec and when to use each one when you are making the system boundary explicit."})]}),r("div",{className:"card-subtle space-y-4 p-6",children:[t("h2",{className:"font-bold text-2xl",children:"Core Contract Types"}),t("div",{className:"grid gap-3 md:grid-cols-2",children:pe.map((i)=>r("div",{className:"flex items-start gap-3 rounded-lg border border-white/10 p-4",children:[t(i.icon,{className:i.color,size:20}),r("div",{className:"space-y-1",children:[t("h3",{className:"font-semibold",children:i.name}),t("p",{className:"text-muted-foreground text-xs",children:i.description}),t("code",{className:"text-violet-400 text-xs",children:i.factory})]})]},i.name))})]}),r("div",{className:"space-y-6",children:[r("div",{className:"space-y-3",children:[t("h2",{className:"font-bold text-2xl",children:"1) Operations (Commands & Queries)"}),t("p",{className:"text-muted-foreground text-sm",children:"Operations are the backbone of your API. Commands mutate state, queries read state. Both have typed input/output schemas."}),t(T,{language:"typescript",filename:"src/contracts/user.operation.ts",code:`import { defineCommand, defineQuery } from "@contractspec/lib.contracts-spec";
import { SchemaModel, ScalarTypeEnum } from "@contractspec/lib.schema";

// Command: Mutates state (creates a user)
export const CreateUserCommand = defineCommand({
  meta: {
    key: "user.create",
    version: "1.0.0",
    description: "Create a new user account",
    stability: "stable",
    owners: ["platform.core"],
    tags: ["users", "auth"],
  },
  io: {
    input: new SchemaModel({
      name: "CreateUserInput",
      fields: {
        email: { type: ScalarTypeEnum.Email(), isOptional: false },
        name: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
      },
    }),
    output: new SchemaModel({
      name: "CreateUserOutput",
      fields: {
        id: { type: ScalarTypeEnum.UUID(), isOptional: false },
        email: { type: ScalarTypeEnum.Email(), isOptional: false },
      },
    }),
    errors: {
      EMAIL_EXISTS: {
        description: "Email already registered",
        http: 409,
        when: "User with this email already exists",
      },
    },
  },
  policy: { auth: "admin" },
});

// Query: Reads state (gets user by ID)
export const GetUserQuery = defineQuery({
  meta: {
    key: "user.get",
    version: "1.0.0",
    description: "Get user by ID",
    stability: "stable",
    owners: ["platform.core"],
    tags: ["users"],
  },
  io: {
    input: new SchemaModel({
      name: "GetUserInput",
      fields: {
        id: { type: ScalarTypeEnum.UUID(), isOptional: false },
      },
    }),
    output: new SchemaModel({
      name: "GetUserOutput",
      fields: {
        id: { type: ScalarTypeEnum.UUID(), isOptional: false },
        email: { type: ScalarTypeEnum.Email(), isOptional: false },
        name: { type: ScalarTypeEnum.String(), isOptional: false },
      },
    }),
  },
  policy: { auth: "user" },
});`})]}),r("div",{className:"space-y-3",children:[t("h2",{className:"font-bold text-2xl",children:"2) Events"}),t("p",{className:"text-muted-foreground text-sm",children:"Events represent domain occurrences. They have typed payloads with PII field marking for compliance."}),t(T,{language:"typescript",filename:"src/contracts/user.event.ts",code:`import { defineEvent } from "@contractspec/lib.contracts-spec";
import { SchemaModel, ScalarTypeEnum } from "@contractspec/lib.schema";

export const UserCreatedEvent = defineEvent({
  meta: {
    key: "user.created",
    version: "1.0.0",
    description: "Emitted when a new user is created",
    stability: "stable",
    owners: ["platform.core"],
    tags: ["users", "auth"],
  },
  // Mark PII fields for redaction in logs/exports
  pii: ["email"],
  payload: new SchemaModel({
    name: "UserCreatedPayload",
    fields: {
      userId: { type: ScalarTypeEnum.UUID(), isOptional: false },
      email: { type: ScalarTypeEnum.Email(), isOptional: false },
      createdAt: { type: ScalarTypeEnum.DateTime(), isOptional: false },
    },
  }),
});

export const UserDeletedEvent = defineEvent({
  meta: {
    key: "user.deleted",
    version: "1.0.0",
    description: "Emitted when a user is deleted",
    stability: "stable",
    owners: ["platform.core"],
    tags: ["users"],
  },
  payload: new SchemaModel({
    name: "UserDeletedPayload",
    fields: {
      userId: { type: ScalarTypeEnum.UUID(), isOptional: false },
      deletedAt: { type: ScalarTypeEnum.DateTime(), isOptional: false },
      reason: { type: ScalarTypeEnum.String(), isOptional: true },
    },
  }),
});`})]}),r("div",{className:"space-y-3",children:[t("h2",{className:"font-bold text-2xl",children:"3) Capabilities"}),t("p",{className:"text-muted-foreground text-sm",children:"Capabilities group related operations, events, and presentations. They define feature boundaries and dependencies."}),t(T,{language:"typescript",filename:"src/contracts/user-management.capability.ts",code:`import { defineCapability } from "@contractspec/lib.contracts-spec";

export const UserManagementCapability = defineCapability({
  meta: {
    key: "user.management",
    version: "1.0.0",
    description: "User account management features",
    stability: "stable",
    owners: ["platform.core"],
    tags: ["users", "core"],
    kind: "api",
  },
  // Operations/events this capability provides
  provides: [
    { surface: "operation", key: "user.create", version: "1.0.0" },
    { surface: "operation", key: "user.get", version: "1.0.0" },
    { surface: "operation", key: "user.delete", version: "1.0.0" },
    { surface: "event", key: "user.created", version: "1.0.0" },
    { surface: "event", key: "user.deleted", version: "1.0.0" },
  ],
  // Dependencies on other capabilities
  requires: [
    { key: "auth.core", reason: "Needs authentication for user operations" },
  ],
});

// Capabilities can extend other capabilities
export const AdminUserCapability = defineCapability({
  meta: {
    key: "user.admin",
    version: "1.0.0",
    description: "Admin-only user management features",
    stability: "stable",
    owners: ["platform.core"],
    tags: ["users", "admin"],
    kind: "api",
  },
  // Inherit from base capability
  extends: { key: "user.management", version: "1.0.0" },
  provides: [
    { surface: "operation", key: "user.ban", version: "1.0.0" },
    { surface: "operation", key: "user.impersonate", version: "1.0.0" },
  ],
});`})]}),r("div",{className:"space-y-3",children:[t("h2",{className:"font-bold text-2xl",children:"4) Presentations"}),t("p",{className:"text-muted-foreground text-sm",children:"Presentations define UI specifications. They link to capabilities and specify how data should be displayed."}),t(T,{language:"typescript",filename:"src/contracts/user-list.presentation.ts",code:`import { definePresentation } from "@contractspec/lib.contracts-spec";

export const UserListPresentation = definePresentation({
  meta: {
    key: "users.list",
    version: "1.0.0",
    description: "Display a list of users with search and pagination",
    stability: "stable",
    owners: ["platform.core"],
    tags: ["users", "ui"],
  },
  // Link to capability that provides data
  capability: { key: "user.management", version: "1.0.0" },
  // UI specifications
  config: {
    title: "Users",
    layout: "table",
    columns: ["name", "email", "createdAt", "status"],
    actions: ["view", "edit", "delete"],
    pagination: { defaultPageSize: 25 },
    search: { fields: ["name", "email"] },
  },
});`})]}),r("div",{className:"space-y-3",children:[t("h2",{className:"font-bold text-2xl",children:"5) Additional Contract Types"}),t("p",{className:"text-muted-foreground text-sm",children:"ContractSpec provides specialized contracts for different concerns:"}),r("div",{className:"grid gap-4 md:grid-cols-2",children:[r("div",{className:"card-subtle space-y-2 p-4",children:[t("h3",{className:"font-semibold",children:"Policy"}),t("code",{className:"text-violet-400 text-xs",children:"definePolicy"}),t("p",{className:"text-muted-foreground text-xs",children:"RBAC/ABAC rules, rate limits, and access control."})]}),r("div",{className:"card-subtle space-y-2 p-4",children:[t("h3",{className:"font-semibold",children:"Workflow"}),t("code",{className:"text-violet-400 text-xs",children:"defineWorkflow"}),t("p",{className:"text-muted-foreground text-xs",children:"Multi-step processes with states, transitions, and SLAs."})]}),r("div",{className:"card-subtle space-y-2 p-4",children:[t("h3",{className:"font-semibold",children:"Translation"}),t("code",{className:"text-violet-400 text-xs",children:"defineTranslation"}),t("p",{className:"text-muted-foreground text-xs",children:"i18n messages with ICU format and locale fallbacks."})]}),r("div",{className:"card-subtle space-y-2 p-4",children:[t("h3",{className:"font-semibold",children:"Integration"}),t("code",{className:"text-violet-400 text-xs",children:"defineIntegration"}),t("p",{className:"text-muted-foreground text-xs",children:"External service connections and API adapters."})]}),r("div",{className:"card-subtle space-y-2 p-4",children:[t("h3",{className:"font-semibold",children:"Form"}),t("code",{className:"text-violet-400 text-xs",children:"defineFormSpec"}),t("p",{className:"text-muted-foreground text-xs",children:"Form definitions with fields, validation, and layouts."})]}),r("div",{className:"card-subtle space-y-2 p-4",children:[t("h3",{className:"font-semibold",children:"Data View"}),t("code",{className:"text-violet-400 text-xs",children:"defineDataView"}),t("p",{className:"text-muted-foreground text-xs",children:"Read-only data projections and aggregations."})]}),r("div",{className:"card-subtle space-y-2 p-4",children:[t("h3",{className:"font-semibold",children:"Feature"}),t("code",{className:"text-violet-400 text-xs",children:"defineFeature"}),t("p",{className:"text-muted-foreground text-xs",children:"Feature flags and progressive rollout configurations."})]}),r("div",{className:"card-subtle space-y-2 p-4",children:[t("h3",{className:"font-semibold",children:"Test"}),t("code",{className:"text-violet-400 text-xs",children:"defineTestSpec"}),t("p",{className:"text-muted-foreground text-xs",children:"Contract-driven test scenarios and fixtures."})]})]})]}),r("div",{className:"space-y-3",children:[t("h2",{className:"font-bold text-2xl",children:"6) Registering Contracts"}),t("p",{className:"text-muted-foreground text-sm",children:"Each contract type has a registry for lookup and validation."}),t(T,{language:"typescript",filename:"src/contracts/registry.ts",code:`import {
  OperationSpecRegistry,
  installOp,
} from "@contractspec/lib.contracts-spec/operations";
import { EventRegistry } from "@contractspec/lib.contracts-spec";
import { CapabilityRegistry } from "@contractspec/lib.contracts-spec/capabilities";

// Import your contracts
import { CreateUserCommand, GetUserQuery } from "./user.operation";
import { UserCreatedEvent } from "./user.event";
import { UserManagementCapability } from "./user-management.capability";

// Create registries
export const operationRegistry = new OperationSpecRegistry();
export const eventRegistry = new EventRegistry();
export const capabilityRegistry = new CapabilityRegistry();

// Register operations with handlers
installOp(operationRegistry, CreateUserCommand, async (input) => {
  // Your implementation here
  return { id: "uuid", email: input.email };
});

installOp(operationRegistry, GetUserQuery, async (input) => {
  // Your implementation here
  return { id: input.id, email: "user@example.com", name: "User" };
});

// Register events and capabilities
eventRegistry.register(UserCreatedEvent);
capabilityRegistry.register(UserManagementCapability);`})]}),r("div",{className:"card-subtle space-y-3 p-6",children:[t("h3",{className:"font-semibold text-lg",children:"Contract Type Decision Guide"}),r("table",{className:"w-full text-sm",children:[t("thead",{children:r("tr",{className:"border-white/10 border-b",children:[t("th",{className:"py-2 text-left",children:"When you need..."}),t("th",{className:"py-2 text-left",children:"Use this contract"})]})}),r("tbody",{className:"text-muted-foreground",children:[r("tr",{className:"border-white/5 border-b",children:[t("td",{className:"py-2",children:"An API endpoint that changes data"}),t("td",{className:"py-2",children:t("code",{children:"defineCommand"})})]}),r("tr",{className:"border-white/5 border-b",children:[t("td",{className:"py-2",children:"An API endpoint that reads data"}),t("td",{className:"py-2",children:t("code",{children:"defineQuery"})})]}),r("tr",{className:"border-white/5 border-b",children:[t("td",{className:"py-2",children:"Async notification of something that happened"}),t("td",{className:"py-2",children:t("code",{children:"defineEvent"})})]}),r("tr",{className:"border-white/5 border-b",children:[t("td",{className:"py-2",children:"Group related specs under a feature"}),t("td",{className:"py-2",children:t("code",{children:"defineCapability"})})]}),r("tr",{className:"border-white/5 border-b",children:[t("td",{className:"py-2",children:"Define UI rendering specifications"}),t("td",{className:"py-2",children:t("code",{children:"definePresentation"})})]}),r("tr",{className:"border-white/5 border-b",children:[t("td",{className:"py-2",children:"Access control and rate limiting"}),t("td",{className:"py-2",children:t("code",{children:"definePolicy"})})]}),r("tr",{children:[t("td",{className:"py-2",children:"Multi-step business processes"}),t("td",{className:"py-2",children:t("code",{children:"defineWorkflow"})})]})]})]})]}),t(v,{title:"Need to decide which contract should change next?",body:"Studio uses evidence and focus constraints to generate decision briefs, patch intents, and execution-ready task packs."})]}),r("div",{className:"flex items-center gap-4 pt-4",children:[r(V,{href:"/docs/guides/nextjs-one-endpoint",className:"btn-primary",children:["Next: Add your first endpoint ",t(ie,{size:16})]}),t(V,{href:"/docs/guides",className:"btn-ghost",children:"Back to guides"})]})]})}import{CodeBlock as M}from"@contractspec/lib.design-system";import z from"@contractspec/lib.ui-link";import{ChevronRight as ue}from"lucide-react";import{jsx as m,jsxs as y}from"react/jsx-runtime";function he(){return y("div",{className:"space-y-8",children:[y("div",{className:"space-y-3",children:[m("h1",{className:"font-bold text-4xl",children:"Build the docs pipeline"}),m("p",{className:"text-lg text-muted-foreground",children:"Generate reference docs, chunk the index, and wire the docs pages the same way this repo does."})]}),y("div",{className:"card-subtle space-y-4 p-6",children:[m("h2",{className:"font-bold text-2xl",children:"What you'll build"}),y("ul",{className:"space-y-2 text-muted-foreground text-sm",children:[m("li",{children:"Generated Markdown and a chunked index manifest."}),m("li",{children:"Reference routes powered by the docs loader."}),m("li",{children:"Versioned outputs you can publish per release."})]})]}),y("div",{className:"space-y-6",children:[y("div",{className:"space-y-3",children:[m("h2",{className:"font-bold text-2xl",children:"1) Generate contract docs"}),m(M,{language:"bash",filename:"generate-contract-docs",code:"contractspec generate"}),y("p",{className:"text-muted-foreground text-sm",children:["Expected output: Markdown in ",m("code",{children:"generated/docs"}),"."]})]}),y("div",{className:"space-y-3",children:[m("h2",{className:"font-bold text-2xl",children:"2) Build the docs index"}),m(M,{language:"bash",filename:"docs-generate",code:`bun docs:generate
# versioned output
bun docs:generate -- --version v1.0.0`}),y("p",{className:"text-muted-foreground text-sm",children:["This writes ",m("code",{children:"docs-index.manifest.json"})," and chunked",m("code",{children:"docs-index.*.json"})," files in the generated docs bundle."]})]}),y("div",{className:"space-y-3",children:[m("h2",{className:"font-bold text-2xl",children:"3) Wire reference routes"}),m(M,{language:"tsx",filename:"docs-reference-route",code:`import { notFound } from "next/navigation";
import {
  DocsReferenceIndexPage,
  DocsReferencePage,
  getGeneratedDocById,
  listGeneratedDocs,
} from "@contractspec/bundle.library";

export async function generateStaticParams() {
  const docs = await listGeneratedDocs();
  return docs.map((doc) => ({ slug: doc.id.split("/") }));
}

export default async function Page({ params }: { params: { slug?: string[] } }) {
  const slug = params.slug?.join("/") ?? "";
  const doc = await getGeneratedDocById(slug);
  if (!doc) notFound();
  return <DocsReferencePage entry={doc.entry} content={doc.content} />;
}`}),y("p",{className:"text-muted-foreground text-sm",children:["Use the index page on ",m("code",{children:"/docs/reference"})," to render the searchable list."]})]}),y("div",{className:"card-subtle space-y-3 p-6",children:[m("h3",{className:"font-semibold text-lg",children:"Repo reference"}),y("p",{className:"text-muted-foreground text-sm",children:["This repo wires docs under"," ",m("code",{children:"packages/apps/web-landing/src/app/docs/reference"}),"."]})]}),m(v,{title:"Need decision-to-export automation?",body:"Studio exports evidence-backed spec changes and task packs to Linear, Jira, Notion, and GitHub."})]}),y("div",{className:"flex items-center gap-4 pt-4",children:[y(z,{href:"/docs/guides/ci-contract-diff-gating",className:"btn-primary",children:["Next: CI gating ",m(ue,{size:16})]}),m(z,{href:"/docs/guides",className:"btn-ghost",children:"Back to guides"})]})]})}import{CodeBlock as G}from"@contractspec/lib.design-system";import q from"@contractspec/lib.ui-link";import{ChevronRight as fe}from"lucide-react";import{jsx as s,jsxs as E}from"react/jsx-runtime";function ge(){return E("div",{className:"space-y-8",children:[E("div",{className:"space-y-3",children:[s("h1",{className:"font-bold text-4xl",children:"Build a first module bundle"}),s("p",{className:"text-lg text-muted-foreground",children:"Define one bundle spec, resolve it for a real route and preference profile, then render the resulting surface plan through the React host layer."})]}),E("div",{className:"card-subtle space-y-4 p-6",children:[s("h2",{className:"font-bold text-2xl",children:"What you'll build"}),E("ul",{className:"space-y-2 text-muted-foreground text-sm",children:[s("li",{children:"One `ModuleBundleSpec` with a route and workbench surface."}),s("li",{children:"One `ResolvedSurfacePlan` from `resolveBundle`."}),s("li",{children:"One React host using `BundleProvider` and `BundleRenderer`."})]})]}),E("div",{className:"space-y-6",children:[E("div",{className:"space-y-3",children:[s("h2",{className:"font-bold text-2xl",children:"1) Define the bundle spec"}),s("p",{className:"text-muted-foreground text-sm",children:"The bundle spec is the durable contract. It owns route selection, surface shape, layouts, data recipes, and verification coverage for all seven preference dimensions."}),s(G,{language:"typescript",filename:"src/bundles/support.workbench.bundle.ts",code:`import { defineModuleBundle } from "@contractspec/lib.surface-runtime/spec/define-module-bundle";

export const SupportWorkbenchBundle = defineModuleBundle({
  meta: {
    key: "support.workbench",
    version: "0.1.0",
    title: "Support Workbench",
  },
  routes: [
    {
      routeId: "support-ticket",
      path: "/operate/support/tickets/:ticketId",
      defaultSurface: "ticket-workbench",
    },
  ],
  surfaces: {
    "ticket-workbench": {
      surfaceId: "ticket-workbench",
      kind: "workbench",
      slots: [
        { slotId: "primary", role: "primary", accepts: ["entity-section"], cardinality: "many" },
        { slotId: "assistant", role: "assistant", accepts: ["assistant-panel"], cardinality: "many", mutableByAi: true, mutableByUser: true },
      ],
      layouts: [
        { layoutId: "balanced", title: "Balanced", root: { type: "slot", slotId: "primary" } },
      ],
      data: [
        { recipeId: "ticket-core", source: { kind: "entity", entityType: "support.ticket" }, hydrateInto: "ticket" },
      ],
      verification: {
        dimensions: {
          guidance: "Surface can reveal walkthrough or inline help states.",
          density: "Layout supports compact and balanced detail modes.",
          dataDepth: "Resolver can hydrate summary or detailed ticket context.",
          control: "Advanced actions stay policy-gated.",
          media: "Surface supports text-first and hybrid assist modes.",
          pace: "Transitions and confirmations adapt to operator pace.",
          narrative: "Summary and evidence ordering stay explicit.",
        },
      },
    },
  },
});`}),s("p",{className:"text-muted-foreground text-sm",children:"Expected output: `defineModuleBundle` validates the route, surface, and verification dimensions at runtime."})]}),E("div",{className:"space-y-3",children:[s("h2",{className:"font-bold text-2xl",children:"2) Resolve the plan"}),s("p",{className:"text-muted-foreground text-sm",children:"Resolve against a real route, device, and preference profile. This is where the runtime chooses the surface, layout, bindings, and audit reasons."}),s(G,{language:"typescript",filename:"src/runtime/resolve-support-workbench.ts",code:`import { resolveBundle } from "@contractspec/lib.surface-runtime/runtime/resolve-bundle";

export const supportWorkbenchPlan = await resolveBundle(
  SupportWorkbenchBundle,
  {
    tenantId: "tenant_demo",
    workspaceId: "workspace_ops",
    actorId: "user_42",
    route: "/operate/support/tickets/123",
    params: { ticketId: "123" },
    query: {},
    device: "desktop",
    locale: "en",
    preferences: {
      guidance: "hints",
      density: "compact",
      dataDepth: "detailed",
      control: "advanced",
      media: "hybrid",
      pace: "balanced",
      narrative: "top-down",
    },
    capabilities: ["tickets.read", "tickets.update"],
  }
);`}),s("p",{className:"text-muted-foreground text-sm",children:"Expected output: a `ResolvedSurfacePlan` with `bundleKey`, `surfaceId`, `layoutId`, `bindings`, `adaptation`, and audit reasons."})]}),E("div",{className:"space-y-3",children:[s("h2",{className:"font-bold text-2xl",children:"3) Render the plan"}),s("p",{className:"text-muted-foreground text-sm",children:"The host app renders the resolved plan, not the raw spec. That keeps layout selection, overlays, and AI proposals downstream of the declared bundle contract."}),s(G,{language:"tsx",filename:"src/app/support/SurfaceHost.tsx",code:`import { BundleProvider, BundleRenderer } from "@contractspec/lib.surface-runtime/react";

export function SurfaceHost() {
  return (
    <BundleProvider plan={supportWorkbenchPlan}>
      <BundleRenderer assistantSlotId="assistant" />
    </BundleProvider>
  );
}`}),s("p",{className:"text-muted-foreground text-sm",children:"Expected output: the route renders according to the resolved layout root and slot plan instead of bespoke page assembly."})]}),E("div",{className:"card-subtle space-y-3 p-6",children:[s("h3",{className:"font-semibold text-lg",children:"Verification checks"}),E("ul",{className:"space-y-2 text-muted-foreground text-sm",children:[s("li",{children:"The resolved `surfaceId` matches the route you expected."}),s("li",{children:"The `layoutId` is stable for the active view and preferences."}),s("li",{children:"The plan carries audit reasons and all seven adaptation dimensions."}),s("li",{children:"Assistant or overlay work stays within declared slots."})]})]})]}),E("div",{className:"flex items-center gap-4 pt-4",children:[E(q,{href:"/docs/specs/module-bundles",className:"btn-primary",children:["Back to module bundles ",s(fe,{size:16})]}),s(q,{href:"/docs/specs/overlays",className:"btn-ghost",children:"Next: overlays"})]})]})}import{CodeBlock as O}from"@contractspec/lib.design-system";import Q from"@contractspec/lib.ui-link";import{ChevronRight as ye}from"lucide-react";import{jsx as p,jsxs as N}from"react/jsx-runtime";function ve(){return N("div",{className:"space-y-8",children:[N("div",{className:"space-y-3",children:[p("h1",{className:"font-bold text-4xl",children:"Generate docs + client schemas"}),p("p",{className:"text-lg text-muted-foreground",children:"Generate docs and OpenAPI output from ContractSpec operations to power SDKs, docs sites, and tooling."})]}),N("div",{className:"card-subtle space-y-4 p-6",children:[p("h2",{className:"font-bold text-2xl",children:"What you'll build"}),N("ul",{className:"space-y-2 text-muted-foreground text-sm",children:[p("li",{children:"Export docs from your specs."}),p("li",{children:"Emit OpenAPI 3.1 for client SDK generation."}),p("li",{children:"Keep outputs deterministic with CI validation."})]})]}),N("div",{className:"space-y-6",children:[N("div",{className:"space-y-3",children:[p("h2",{className:"font-bold text-2xl",children:"1) Generate docs"}),p("p",{className:"text-muted-foreground text-sm",children:"Use the generator to emit docs from your contracts."}),p(O,{language:"bash",filename:"generate-docs",code:"contractspec generate"}),N("p",{className:"text-muted-foreground text-sm",children:["Expected output: ",p("code",{children:"Generate X doc files in generated/docs"}),"."]})]}),N("div",{className:"space-y-3",children:[p("h2",{className:"font-bold text-2xl",children:"2) Export OpenAPI"}),p("p",{className:"text-muted-foreground text-sm",children:"Export an OpenAPI document from your registry module."}),p(O,{language:"bash",filename:"openapi-export",code:"contractspec openapi export --registry ./src/contracts/registry.ts --out ./generated/openapi.json"}),N("p",{className:"text-muted-foreground text-sm",children:["Expected output:"," ",p("code",{children:"OpenAPI written to .../generated/openapi.json"}),"."]})]}),N("div",{className:"space-y-3",children:[p("h2",{className:"font-bold text-2xl",children:"3) Validate specs"}),p(O,{language:"bash",filename:"validate-specs",code:"contractspec validate"}),N("p",{className:"text-muted-foreground text-sm",children:["Expected output: ",p("code",{children:"Validation passed"}),"."]})]}),N("div",{className:"card-subtle space-y-3 p-6",children:[p("h3",{className:"font-semibold text-lg",children:"Example package"}),p("p",{className:"text-muted-foreground text-sm",children:"The Integration Hub example provides a full registry of operations and is a good source for OpenAPI exports."}),p(O,{language:"bash",filename:"integration-hub-example",code:`contractspec examples show integration-hub

# openapi export against your registry module
contractspec openapi export --registry ./src/contracts/registry.ts --out ./generated/openapi.json`})]}),p(v,{title:"Want exports tied to product decisions?",body:"Studio compiles approved changes into deliverables and pushes them to your execution stack with full evidence context."})]}),N("div",{className:"flex items-center gap-4 pt-4",children:[N(Q,{href:"/docs/guides/docs-generation-pipeline",className:"btn-primary",children:["Next: Docs pipeline ",p(ye,{size:16})]}),p(Q,{href:"/docs/guides",className:"btn-ghost",children:"Back to guides"})]})]})}import{CodeBlock as I}from"@contractspec/lib.design-system";import F from"@contractspec/lib.ui-link";import{ChevronRight as be}from"lucide-react";import{jsx as o,jsxs as f}from"react/jsx-runtime";var Ne=["builder.workspace.bootstrap","builder.channel.receiveInbound","builder.blueprint.generate","builder.plan.compile","builder.preview.create","builder.preview.runHarness","builder.export.prepare","builder.export.approve","builder.export.execute"],ke=["local runtime trust and lease details","channel-action posture for mobile/operator follow-up","comparison posture and export readiness from the shared snapshot"];function we(){return f("div",{className:"space-y-8",children:[f("div",{className:"space-y-3",children:[o("h1",{className:"font-bold text-4xl",children:"Host the Builder workbench"}),o("p",{className:"text-lg text-muted-foreground",children:"Use the reusable Builder workbench as the desktop control surface for snapshot loading, guided authoring, preview, readiness, export, and mobile review handoff."})]}),f("div",{className:"card-subtle space-y-4 p-6",children:[o("h2",{className:"font-bold text-2xl",children:"What you'll build"}),f("ul",{className:"space-y-2 text-muted-foreground text-sm",children:[o("li",{children:"A workspace snapshot fetch path."}),o("li",{children:"A `BuilderWorkbench` host with action callbacks."}),o("li",{children:"Runtime-mode aware preview/export controls plus mobile review links."})]})]}),f("div",{className:"space-y-6",children:[f("div",{className:"space-y-3",children:[o("h2",{className:"font-bold text-2xl",children:"1) Fetch the workspace snapshot"}),o("p",{className:"text-muted-foreground text-sm",children:"The web shell already exposes a query path for the current Builder workspace snapshot. Your host should load it first, then refresh it after each successful command."}),o(I,{language:"typescript",filename:"builder-workbench-controller.ts",code:`export async function fetchBuilderSnapshot(workspaceId: string) {
  const response = await fetch(
    \`/api/operate/builder/queries/builder.workspace.snapshot?workspaceId=\${encodeURIComponent(workspaceId)}\`,
    { cache: "no-store" }
  );
  if (!response.ok) {
    throw new Error("Failed to fetch Builder workspace snapshot.");
  }
  const payload = await response.json() as {
    ok: boolean;
    result: BuilderWorkspaceSnapshot;
  };
  if (!payload.ok) {
    throw new Error("Builder workspace snapshot query returned an error.");
  }
  return payload.result;
}`}),o("p",{className:"text-muted-foreground text-sm",children:"Expected output: one `BuilderWorkspaceSnapshot` containing workspace, plan, providers, runtime targets, preview, export, mobile review state, and the operator posture needed for local trust, lease, and comparison status."})]}),f("div",{className:"space-y-3",children:[o("h2",{className:"font-bold text-2xl",children:"2) Host the workbench and refresh on action"}),o("p",{className:"text-muted-foreground text-sm",children:"The simplest host pattern is local state plus a small action wrapper that executes one Builder command and then refreshes the snapshot."}),o(I,{language:"tsx",filename:"BuilderWorkbenchHost.tsx",code:`import {
  BuilderWorkbench,
  useBuilderWorkbenchState,
} from "@contractspec/module.builder-workbench/presentation";

const { snapshot, setSnapshot, promptDraft, setPromptDraft } =
  useBuilderWorkbenchState({
    workspace: initialSnapshot.workspace,
    initialSnapshot,
  });

async function runAction(commandKey: string, payload?: Record<string, unknown>) {
  await executeBuilderCommand({ commandKey, workspaceId, payload });
  setSnapshot(await fetchBuilderSnapshot(workspaceId));
}

<BuilderWorkbench
  snapshot={snapshot}
  promptDraft={promptDraft}
  onPromptDraftChange={setPromptDraft}
  onCapturePrompt={() =>
    runAction("builder.channel.receiveInbound", createPromptEnvelope(workspaceId, promptDraft))
  }
  onGenerateBlueprint={() => runAction("builder.blueprint.generate")}
  onCompilePlan={() => runAction("builder.plan.compile")}
  onCreatePreview={() => runAction("builder.preview.create", { runtimeMode: "hybrid" })}
  onRunReadiness={() => runAction("builder.preview.runHarness")}
  onPrepareExport={() => runAction("builder.export.prepare", { runtimeMode: "hybrid" })}
  onApproveExport={() => runAction("builder.export.approve")}
  onExecuteExport={() => runAction("builder.export.execute")}
  selectedExportRuntimeMode="hybrid"
/>;`}),o("p",{className:"text-muted-foreground text-sm",children:"Expected output: each successful action leaves the host with a fresh snapshot and keeps the workbench tabs aligned with current runtime state."})]}),f("div",{className:"space-y-3",children:[o("h2",{className:"font-bold text-2xl",children:"3) Persist Builder defaults in workspace config"}),o("p",{className:"text-muted-foreground text-sm",children:"The host should agree with the CLI and setup flows on the same control-plane defaults. For local or hybrid setups, keep the Builder API base URL, token env var, and local runtime metadata in `.contractsrc.json`."}),o(I,{language:"json",filename:".contractsrc.json",code:`{
  "builder": {
    "enabled": true,
    "runtimeMode": "local",
    "bootstrapPreset": "local_daemon_mvp",
    "api": {
      "baseUrl": "https://api.contractspec.io",
      "controlPlaneTokenEnvVar": "CONTROL_PLANE_API_TOKEN"
    },
    "localRuntime": {
      "runtimeId": "rt_local_daemon",
      "grantedTo": "local:operator",
      "providerIds": ["provider.codex", "provider.local.model"]
    }
  }
}`})]}),f("div",{className:"space-y-3",children:[o("h2",{className:"font-bold text-2xl",children:"4) Bootstrap providers and routing policy explicitly"}),o("p",{className:"text-muted-foreground text-sm",children:"Builder v3 treats provider routing as policy, not heuristic. Use the workspace bootstrap command as the single managed-first setup path instead of orchestrating provider registration in the app shell."}),o(I,{language:"typescript",filename:"builder-bootstrap.ts",code:`await executeBuilderCommand({
  commandKey: "builder.workspace.bootstrap",
  workspaceId,
  payload: {
    preset: "managed_mvp",
    includeLocalHelperProvider: true,
  },
});`})]}),f("div",{className:"card-subtle space-y-3 p-6",children:[o("h3",{className:"font-semibold text-lg",children:"Common command keys"}),o("ul",{className:"space-y-2 text-muted-foreground text-sm",children:Ne.map((i)=>o("li",{children:o("code",{children:i})},i))})]}),f("div",{className:"card-subtle space-y-3 p-6",children:[o("h3",{className:"font-semibold text-lg",children:"Snapshot-backed operator details"}),o("ul",{className:"space-y-2 text-muted-foreground text-sm",children:ke.map((i)=>o("li",{children:i},i))})]}),f("div",{className:"space-y-3",children:[o("h2",{className:"font-bold text-2xl",children:"5) Keep runtime mode explicit"}),o("p",{className:"text-muted-foreground text-sm",children:"Preview and export flows are runtime-mode aware. The host chooses between `managed`, `local`, and `hybrid` and passes that choice into preview or export commands instead of hiding it behind provider selection heuristics."}),o(I,{language:"typescript",filename:"runtime-mode",code:`const [selectedExportRuntimeMode, setSelectedExportRuntimeMode] =
  React.useState(resolveBuilderExportRuntimeMode(initialSnapshot));

await executeBuilderCommand({
  commandKey: "builder.preview.create",
  workspaceId,
  payload: {
    runtimeMode: selectedExportRuntimeMode,
  },
	});`})]}),f("div",{className:"space-y-3",children:[o("h2",{className:"font-bold text-2xl",children:"6) Link mobile review flows"}),o("p",{className:"text-muted-foreground text-sm",children:"When a patch proposal, approval ticket, or incident needs operator follow-up away from the desktop workbench, deep-link into the mobile review route instead of inventing a separate data model."}),o(I,{language:"typescript",filename:"mobile-review-path.ts",code:`export function buildBuilderMobileReviewPath(
  workspaceId: string,
  cardId: string
) {
  return \`/operate/builder/workspaces/\${encodeURIComponent(workspaceId)}/mobile-review/\${encodeURIComponent(cardId)}\`;
}`}),o("p",{className:"text-muted-foreground text-sm",children:"Expected output: the same Builder workspace state stays visible from desktop workbench and mobile review surfaces."})]}),f("div",{className:"space-y-3",children:[o("h2",{className:"font-bold text-2xl",children:"7) Keep Connect adjacent, not embedded"}),o("p",{className:"text-muted-foreground text-sm",children:"Builder owns the authoring control plane. When Builder delegates into coding repositories, enable Connect in those target workspaces for context packs, mutation verification, replay, and review packets, but do not replace Builder contracts with Connect artifacts."}),o(I,{language:"bash",filename:"connect-init.sh",code:"contractspec connect init --scope workspace"})]})]}),f("div",{className:"flex items-center gap-4 pt-4",children:[f(F,{href:"/docs/specs/builder-control-plane",className:"btn-primary",children:["Back to Builder control plane ",o(be,{size:16})]}),o(F,{href:"/docs/studio",className:"btn-ghost",children:"Studio overview"})]})]})}import{CodeBlock as P}from"@contractspec/lib.design-system";import K from"@contractspec/lib.ui-link";import{AlertCircle as Ce,ChevronRight as Se,FileCode as Ee,Scan as W,Settings as Ie}from"lucide-react";import{jsx as e,jsxs as a}from"react/jsx-runtime";var Pe=[{name:"NestJS",flag:"nestjs",description:"Controllers, decorators, DTOs"},{name:"Express",flag:"express",description:"Router methods, middleware"},{name:"Fastify",flag:"fastify",description:"Route definitions, schemas"},{name:"Hono",flag:"hono",description:"Route handlers, validators"},{name:"Elysia",flag:"elysia",description:"Type-safe routes, schemas"},{name:"tRPC",flag:"trpc",description:"Procedure definitions"},{name:"Next.js",flag:"next-api",description:"API routes (app/api, pages/api)"}];function Re(){return a("div",{className:"space-y-8",children:[a("div",{className:"space-y-3",children:[e("h1",{className:"font-bold text-4xl",children:"Import Existing Codebases"}),e("p",{className:"text-lg text-muted-foreground",children:"Convert your existing API endpoints into ContractSpec contracts. Auto-detect frameworks, extract schemas, and generate explicit contract definitions from your code."})]}),a("div",{className:"card-subtle space-y-4 p-6",children:[e("h2",{className:"font-bold text-2xl",children:"What you'll learn"}),a("ul",{className:"space-y-2 text-muted-foreground text-sm",children:[e("li",{children:"How to import existing API endpoints as ContractSpec contracts."}),e("li",{children:"Framework-specific patterns and auto-detection."}),e("li",{children:"Customizing imports with scopes, dry-run, and output options."}),e("li",{children:"Registering imported contracts and adding handlers."})]})]}),a("div",{className:"space-y-6",children:[a("div",{className:"space-y-3",children:[e("h2",{className:"font-bold text-2xl",children:"Why import existing code?"}),e("p",{className:"text-muted-foreground text-sm",children:"Instead of writing contracts from scratch, the import command extracts endpoint patterns from your existing codebase. This gives you:"}),a("ul",{className:"list-disc space-y-1 pl-5 text-muted-foreground text-sm",children:[e("li",{children:"Instant spec coverage for existing APIs"}),e("li",{children:"Type-safe schemas derived from your existing types"}),e("li",{children:"A foundation to iterate and refine contracts"}),e("li",{children:"Gradual adoption without rewriting code"})]})]}),a("div",{className:"space-y-3",children:[e("h2",{className:"font-bold text-2xl",children:"Supported frameworks"}),e("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-3",children:Pe.map((i)=>a("div",{className:"flex items-start gap-3 rounded-lg border border-white/10 p-4",children:[e(Ee,{className:"text-violet-400",size:18}),a("div",{className:"space-y-1",children:[e("h3",{className:"font-semibold",children:i.name}),e("p",{className:"text-muted-foreground text-xs",children:i.description}),a("code",{className:"text-violet-400 text-xs",children:["--framework ",i.flag]})]})]},i.flag))})]}),a("div",{className:"space-y-3",children:[e("h2",{className:"font-bold text-2xl",children:"1) Quick start"}),e("p",{className:"text-muted-foreground text-sm",children:"Run the import command to auto-detect your framework and extract endpoints:"}),e(P,{language:"bash",filename:"import-quickstart",code:`# Auto-detect framework and import all endpoints
contractspec import ./src

# Preview what would be imported (dry-run)
contractspec import ./src --dry-run

# Force a specific framework
contractspec import ./src --framework nestjs`}),e("p",{className:"text-muted-foreground text-sm",children:"Expected output: A summary of endpoints found, schemas extracted, and files generated."})]}),a("div",{className:"space-y-3",children:[e("h2",{className:"font-bold text-2xl",children:"2) Framework-specific patterns"}),e("p",{className:"text-muted-foreground text-sm",children:"The import command recognizes these patterns in each framework:"})]}),a("div",{className:"space-y-3",children:[a("h3",{className:"flex items-center gap-2 font-semibold text-xl",children:[e(W,{size:18,className:"text-blue-400"}),"NestJS"]}),e(P,{language:"typescript",filename:"src/users/users.controller.ts (before)",code:`@Controller('users')
export class UsersController {
  @Get(':id')
  async getUser(@Param('id') id: string): Promise<UserDto> {
    return this.usersService.findOne(id);
  }

  @Post()
  @UseGuards(AuthGuard)
  async createUser(@Body() dto: CreateUserDto): Promise<UserDto> {
    return this.usersService.create(dto);
  }
}`}),a("p",{className:"text-muted-foreground text-sm",children:["Detected: ",e("code",{children:"@Controller"}),", ",e("code",{children:"@Get"}),","," ",e("code",{children:"@Post"}),", ",e("code",{children:"@Body"}),", ",e("code",{children:"@Param"}),","," ",e("code",{children:"@UseGuards"})," decorators."]})]}),a("div",{className:"space-y-3",children:[a("h3",{className:"flex items-center gap-2 font-semibold text-xl",children:[e(W,{size:18,className:"text-green-400"}),"Express"]}),e(P,{language:"typescript",filename:"src/routes/users.ts (before)",code:`const router = express.Router();

router.get('/users/:id', async (req, res) => {
  const user = await getUserById(req.params.id);
  res.json(user);
});

router.post('/users', validateBody(CreateUserSchema), async (req, res) => {
  const user = await createUser(req.body);
  res.status(201).json(user);
});`}),a("p",{className:"text-muted-foreground text-sm",children:["Detected: ",e("code",{children:"router.get"}),", ",e("code",{children:"router.post"}),", validation middleware, Zod schemas."]})]}),a("div",{className:"space-y-3",children:[a("h3",{className:"flex items-center gap-2 font-semibold text-xl",children:[e(W,{size:18,className:"text-purple-400"}),"Next.js API Routes"]}),e(P,{language:"typescript",filename:"app/api/users/[id]/route.ts (before)",code:`export async function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
  const user = await getUserById(params.id);
  return Response.json(user);
}

export async function POST(request: Request) {
  const body = await request.json();
  const user = await createUser(body);
  return Response.json(user, { status: 201 });
}`}),a("p",{className:"text-muted-foreground text-sm",children:["Detected: ",e("code",{children:"GET"}),", ",e("code",{children:"POST"})," exports in"," ",e("code",{children:"app/api/**/route.ts"})," and ",e("code",{children:"pages/api/**/*.ts"}),"."]})]}),a("div",{className:"space-y-3",children:[e("h2",{className:"font-bold text-2xl",children:"3) Understanding generated contracts"}),e("p",{className:"text-muted-foreground text-sm",children:"The import command generates ContractSpec operations with TODO placeholders for fields it cannot infer:"}),e(P,{language:"typescript",filename:".contractspec/generated/users.operation.ts",code:`import { defineQuery, defineCommand } from "@contractspec/lib.contracts-spec";
import { SchemaModel, ScalarTypeEnum } from "@contractspec/lib.schema";

export const GetUserQuery = defineQuery({
  meta: {
    key: "users.get",
    version: "1.0.0",
    description: "TODO: Add description",
    stability: "draft",
    owners: ["TODO"],
    tags: ["users"],
  },
  io: {
    input: new SchemaModel({
      name: "GetUserInput",
      fields: {
        id: { type: ScalarTypeEnum.String(), isOptional: false },
      },
    }),
    output: new SchemaModel({
      name: "GetUserOutput",
      fields: {
        // TODO: Add output fields based on your UserDto
        id: { type: ScalarTypeEnum.String(), isOptional: false },
      },
    }),
  },
  policy: { auth: "user" }, // Inferred from @UseGuards
  transport: {
    rest: { method: "GET", path: "/users/:id" },
  },
});

export const CreateUserCommand = defineCommand({
  meta: {
    key: "users.create",
    version: "1.0.0",
    description: "TODO: Add description",
    stability: "draft",
    owners: ["TODO"],
    tags: ["users"],
  },
  io: {
    input: new SchemaModel({
      name: "CreateUserInput",
      fields: {
        // TODO: Add fields from CreateUserDto
      },
    }),
    output: new SchemaModel({
      name: "CreateUserOutput",
      fields: {
        id: { type: ScalarTypeEnum.String(), isOptional: false },
      },
    }),
  },
  policy: { auth: "admin" },
  transport: {
    rest: { method: "POST", path: "/users" },
  },
});`})]}),a("div",{className:"space-y-3",children:[e("h2",{className:"font-bold text-2xl",children:"4) Customizing imports"}),a("div",{className:"flex items-center gap-2",children:[e(Ie,{size:18,className:"text-violet-400"}),e("h3",{className:"font-semibold text-lg",children:"Available options"})]}),e("div",{className:"overflow-x-auto",children:a("table",{className:"w-full text-sm",children:[e("thead",{children:a("tr",{className:"border-white/10 border-b",children:[e("th",{className:"py-2 pr-4 text-left",children:"Option"}),e("th",{className:"py-2 pr-4 text-left",children:"Description"}),e("th",{className:"py-2 text-left",children:"Example"})]})}),a("tbody",{className:"text-muted-foreground",children:[a("tr",{className:"border-white/5 border-b",children:[e("td",{className:"py-2 pr-4",children:e("code",{children:"--scope"})}),e("td",{className:"py-2 pr-4",children:"Limit to specific directories"}),e("td",{className:"py-2",children:e("code",{children:"--scope src/users src/auth"})})]}),a("tr",{className:"border-white/5 border-b",children:[e("td",{className:"py-2 pr-4",children:e("code",{children:"--framework"})}),e("td",{className:"py-2 pr-4",children:"Force a specific framework"}),e("td",{className:"py-2",children:e("code",{children:"--framework express"})})]}),a("tr",{className:"border-white/5 border-b",children:[e("td",{className:"py-2 pr-4",children:e("code",{children:"--output"})}),e("td",{className:"py-2 pr-4",children:"Output directory"}),e("td",{className:"py-2",children:e("code",{children:"--output ./contracts"})})]}),a("tr",{className:"border-white/5 border-b",children:[e("td",{className:"py-2 pr-4",children:e("code",{children:"--dry-run"})}),e("td",{className:"py-2 pr-4",children:"Preview without writing files"}),e("td",{className:"py-2",children:e("code",{children:"--dry-run"})})]}),a("tr",{className:"border-white/5 border-b",children:[e("td",{className:"py-2 pr-4",children:e("code",{children:"--analyze"})}),e("td",{className:"py-2 pr-4",children:"Analysis only, no code generation"}),e("td",{className:"py-2",children:e("code",{children:"--analyze"})})]}),a("tr",{children:[e("td",{className:"py-2 pr-4",children:e("code",{children:"--json"})}),e("td",{className:"py-2 pr-4",children:"Output as JSON for scripting"}),e("td",{className:"py-2",children:e("code",{children:"--json"})})]})]})]})}),e(P,{language:"bash",filename:"import-options",code:`# Import only specific modules
contractspec import ./src --scope src/users src/orders

# Preview with analysis
contractspec import ./src --dry-run --analyze

# Output to custom directory
contractspec import ./src --output ./src/contracts/generated

# Get JSON for CI/scripting
contractspec import ./src --json > import-result.json`})]}),a("div",{className:"space-y-3",children:[e("h2",{className:"font-bold text-2xl",children:"5) Registering imported contracts"}),e("p",{className:"text-muted-foreground text-sm",children:"After import, register contracts and add handlers:"}),e(P,{language:"typescript",filename:"src/contracts/registry.ts",code:`import {
  OperationSpecRegistry,
  installOp,
} from "@contractspec/lib.contracts-spec/operations";
import {
  GetUserQuery,
  CreateUserCommand,
} from "./.contractspec/generated/users.operation";

export const registry = new OperationSpecRegistry();

// Add handlers to imported operations
installOp(registry, GetUserQuery, async (input) => {
  const user = await db.user.findUnique({ where: { id: input.id } });
  return user;
});

installOp(registry, CreateUserCommand, async (input) => {
  const user = await db.user.create({ data: input });
  return { id: user.id };
});`})]}),a("div",{className:"space-y-3",children:[e("h2",{className:"font-bold text-2xl",children:"6) After importing"}),a("ol",{className:"list-decimal space-y-2 pl-5 text-muted-foreground text-sm",children:[a("li",{children:[e("strong",{children:"Review generated contracts"})," \u2014 Check the TODO placeholders and fill in descriptions, owners, and tags."]}),a("li",{children:[e("strong",{children:"Refine schemas"})," \u2014 Add proper types, validation rules, and error definitions."]}),a("li",{children:[e("strong",{children:"Run validation"})," \u2014"," ",e("code",{children:"contractspec validate"})," to ensure contracts are valid."]}),a("li",{children:[e("strong",{children:"Register and wire handlers"})," \u2014 Connect contracts to your existing business logic."]}),a("li",{children:[e("strong",{children:"Iterate"})," \u2014 The imported contracts are a starting point. Refine them as your spec matures."]})]})]}),a("div",{className:"space-y-3",children:[a("h2",{className:"flex items-center gap-2 font-bold text-2xl",children:[e(Ce,{size:20,className:"text-yellow-400"}),"Troubleshooting"]}),a("div",{className:"space-y-4",children:[a("div",{className:"card-subtle space-y-2 p-4",children:[e("h3",{className:"font-semibold",children:"Framework not detected"}),a("p",{className:"text-muted-foreground text-sm",children:["Use ",e("code",{children:"--framework <name>"})," to force a specific framework. Check that your entry files follow standard patterns."]})]}),a("div",{className:"card-subtle space-y-2 p-4",children:[e("h3",{className:"font-semibold",children:"Missing schemas"}),a("p",{className:"text-muted-foreground text-sm",children:["Schema inference works best with explicit types. If using"," ",e("code",{children:"any"})," or dynamic types, you'll see TODO placeholders. Fill them in manually."]})]}),a("div",{className:"card-subtle space-y-2 p-4",children:[e("h3",{className:"font-semibold",children:"Partial imports"}),a("p",{className:"text-muted-foreground text-sm",children:["Some endpoints may not be detected if they use unconventional patterns. Use ",e("code",{children:"--analyze"})," to see what was found, then add missing contracts manually."]})]})]})]}),e(v,{title:"Want evidence-driven migration priorities?",body:"Studio clusters product signals into scored patterns, then proposes contract changes and execution-ready work for the highest-impact areas."})]}),a("div",{className:"flex items-center gap-4 pt-4",children:[a(K,{href:"/docs/guides/spec-validation-and-typing",className:"btn-primary",children:["Next: Spec validation + typing ",e(Se,{size:16})]}),e(K,{href:"/docs/guides",className:"btn-ghost",children:"Back to guides"})]})]})}import{CodeBlock as B}from"@contractspec/lib.design-system";import Y from"@contractspec/lib.ui-link";import{ChevronRight as Be}from"lucide-react";import{jsx as c,jsxs as h}from"react/jsx-runtime";function Te(){return h("div",{className:"space-y-8",children:[h("div",{className:"space-y-3",children:[c("h1",{className:"font-bold text-4xl",children:"Next.js: add one endpoint"}),c("p",{className:"text-lg text-muted-foreground",children:"Add ContractSpec to an existing Next.js App Router project by wiring a single operation end-to-end with validation and types."})]}),h("div",{className:"card-subtle space-y-4 p-6",children:[c("h2",{className:"font-bold text-2xl",children:"What you'll build"}),h("ul",{className:"space-y-2 text-muted-foreground text-sm",children:[c("li",{children:"One OperationSpec with SchemaModel validation."}),c("li",{children:"A registry wiring the operation to its handler."}),c("li",{children:"A Next.js route handler that exposes the operation."})]})]}),h("div",{className:"space-y-6",children:[h("div",{className:"space-y-3",children:[c("h2",{className:"font-bold text-2xl",children:"1) Install core packages"}),c(B,{language:"bash",filename:"nextjs-install",code:`bun add -D contractspec
bun add @contractspec/lib.contracts-spec @contractspec/lib.contracts-runtime-server-rest @contractspec/lib.schema`}),h("p",{className:"text-muted-foreground text-sm",children:["Expected output: ",c("code",{children:"added 3 packages"})," and a lockfile update."]})]}),h("div",{className:"space-y-3",children:[c("h2",{className:"font-bold text-2xl",children:"2) Define the operation spec"}),h("p",{className:"text-muted-foreground text-sm",children:["Create ",c("code",{children:"src/contracts/healthcheck.operation.ts"}),":"]}),c(B,{language:"typescript",filename:"src/contracts/healthcheck.operation.ts",code:`import { defineQuery } from "@contractspec/lib.contracts-spec/operations";
import { SchemaModel, ScalarTypeEnum } from "@contractspec/lib.schema";

const HealthcheckOutput = new SchemaModel({
  name: "HealthcheckOutput",
  fields: {
    status: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
    checkedAt: { type: ScalarTypeEnum.DateTime(), isOptional: false },
  },
});

export const HealthcheckQuery = defineQuery({
  meta: {
    key: "healthcheck.get",
    version: "1.0.0",
    description: "Return service health status",
    owners: ["@platform.core"],
    tags: ["health", "observability"],
  },
  io: {
    input: null,
    output: HealthcheckOutput,
  },
  policy: {
    auth: "public",
  },
  transport: {
    rest: { method: "GET" },
    gql: { field: "healthcheck_get" },
    mcp: { toolName: "healthcheck_get-v1" },
  },
});`})]}),h("div",{className:"space-y-3",children:[c("h2",{className:"font-bold text-2xl",children:"3) Register the operation"}),h("p",{className:"text-muted-foreground text-sm",children:["Create ",c("code",{children:"src/contracts/registry.ts"}),":"]}),c(B,{language:"typescript",filename:"src/contracts/registry.ts",code:`import {
  OperationSpecRegistry,
  installOp,
} from "@contractspec/lib.contracts-spec/operations";
import { HealthcheckQuery } from "./healthcheck.operation";

export const registry = new OperationSpecRegistry();

installOp(registry, HealthcheckQuery, async () => ({
  status: "ok",
  checkedAt: new Date().toISOString(),
}));`})]}),h("div",{className:"space-y-3",children:[c("h2",{className:"font-bold text-2xl",children:"4) Add the Next.js handler"}),h("p",{className:"text-muted-foreground text-sm",children:["Create ",c("code",{children:"app/api/ops/[...route]/route.ts"}),":"]}),c(B,{language:"typescript",filename:"app/api/ops/[...route]/route.ts",code:`import { makeNextAppHandler } from "@contractspec/lib.contracts-runtime-server-rest/rest-next-app";
import { registry } from "@/contracts/registry";

const handler = makeNextAppHandler(registry, async () => ({
  actor: "public",
  tenantId: "public",
}));

export { handler as GET, handler as POST };`}),h("p",{className:"text-muted-foreground text-sm",children:["Expected output: the route responds at",c("code",{children:" /api/ops/healthcheck.get"}),"."]})]}),h("div",{className:"space-y-3",children:[c("h2",{className:"font-bold text-2xl",children:"5) Validate the spec"}),c(B,{language:"bash",filename:"nextjs-validate",code:"contractspec validate src/contracts/healthcheck.operation.ts"}),h("p",{className:"text-muted-foreground text-sm",children:["Expected output: ",c("code",{children:"Validation passed"}),"."]})]}),h("div",{className:"card-subtle space-y-3 p-6",children:[c("h3",{className:"font-semibold text-lg",children:"Example package"}),h("p",{className:"text-muted-foreground text-sm",children:["Use ",c("code",{children:"@contractspec/example.lifecycle-dashboard"})," as a lightweight Next.js snippet reference."]}),c(B,{language:"bash",filename:"nextjs-example",code:`# Inspect the example docs
contractspec examples show lifecycle-dashboard

# Validate all example manifests in this repo
contractspec examples validate --repo-root .`})]}),c(v,{title:"Want real product evidence behind endpoint changes?",body:"Studio correlates meetings, support, analytics, and code signals before compiling endpoint decisions into spec diffs."})]}),h("div",{className:"flex items-center gap-4 pt-4",children:[h(Y,{href:"/docs/guides/spec-validation-and-typing",className:"btn-primary",children:["Next: Spec validation + typing ",c(Be,{size:16})]}),c(Y,{href:"/docs/guides",className:"btn-ghost",children:"Back to guides"})]})]})}import{CodeBlock as U}from"@contractspec/lib.design-system";import J from"@contractspec/lib.ui-link";import{ChevronRight as Ae}from"lucide-react";import{jsx as d,jsxs as k}from"react/jsx-runtime";var Oe=["root `README.md` and generated root `AGENTS.md` inputs when contributor or operator workflow changes","the nearest package `README.md` and `AGENTS.md` for any touched public package surface","website docs and `/llms*` summaries when the release changes how users or contributors should work"];function Ue(){return k("div",{className:"space-y-8",children:[k("div",{className:"space-y-3",children:[d("h1",{className:"font-bold text-4xl",children:"Author release capsules"}),d("p",{className:"text-lg text-muted-foreground",children:"Pair each publishable changeset with a structured release capsule so changelog, upgrade, and docs surfaces all read from the same release source of truth."})]}),k("div",{className:"card-subtle space-y-4 p-6",children:[d("h2",{className:"font-bold text-2xl",children:"What you'll build"}),k("ul",{className:"space-y-2 text-muted-foreground text-sm",children:[k("li",{children:["A ",d("code",{children:".changeset/<slug>.md"})," file for package/version intent."]}),k("li",{children:["A ",d("code",{children:".changeset/<slug>.release.yaml"})," companion for audiences, migrations, validation, and evidence."]}),d("li",{children:"Generated release artifacts that the website changelog and upgrade flows can consume safely."})]})]}),k("div",{className:"space-y-6",children:[k("div",{className:"space-y-3",children:[d("h2",{className:"font-bold text-2xl",children:"1) Create the paired changeset files"}),d("p",{className:"text-muted-foreground text-sm",children:"The Markdown file states the package bumps and reader-facing change intent. The YAML file carries the structured release metadata."}),d(U,{language:"yaml",filename:".changeset/contract-dx-first-slice.release.yaml",code:`schemaVersion: "1"
slug: contract-dx-first-slice
summary: Improve app-config, theme, and feature authoring with explicit validation and shared setup alignment.
isBreaking: false
packages:
  - name: "@contractspec/lib.contracts-spec"
    releaseType: minor
validation:
  commands:
    - "cd packages/libs/contracts-spec && bun run test && bun run typecheck"
  evidence:
    - "Package-level validation entrypoints now back setup, docs, and CLI authoring flows."`}),d("p",{className:"text-muted-foreground text-sm",children:"Expected output: every publishable slug has both the human-facing changeset and the structured release capsule beside it."})]}),k("div",{className:"space-y-3",children:[d("h2",{className:"font-bold text-2xl",children:"2) Use the release authoring commands instead of raw drift-prone edits"}),d(U,{language:"bash",filename:"release-authoring",code:`contractspec release init --summary "Improve app-config, theme, and feature authoring"

# Or revise an existing capsule with the guided flow
contractspec release edit contract-dx-first-slice`}),d("p",{className:"text-muted-foreground text-sm",children:"Expected output: the CLI scaffolds or revises the paired files with the current release schema instead of leaving maintainers to hand-roll YAML structure."})]}),k("div",{className:"space-y-3",children:[d("h2",{className:"font-bold text-2xl",children:"3) Build the generated release artifacts before consuming them"}),d(U,{language:"bash",filename:"release-build",code:"contractspec release build"}),d("p",{className:"text-muted-foreground text-sm",children:"Expected output: `generated/releases/manifest.json`, `generated/releases/upgrade-manifest.json`, and the related customer/maintainer guidance files are refreshed from the release capsules."})]}),k("div",{className:"space-y-3",children:[d("h2",{className:"font-bold text-2xl",children:"4) Enforce completeness before publishing or building the changelog"}),d(U,{language:"bash",filename:"release-check",code:"contractspec release check --strict"}),d("p",{className:"text-muted-foreground text-sm",children:"Expected output: missing capsules, incomplete migration guidance, or stale generated release artifacts are flagged before the website changelog or publish workflow treats the release data as canonical."})]}),k("div",{className:"card-subtle space-y-3 p-6",children:[d("h3",{className:"font-semibold text-lg",children:"5) Sync the public docs if workflow expectations changed"}),d("ul",{className:"space-y-2 text-muted-foreground text-sm",children:Oe.map((i)=>d("li",{children:i},i))})]})]}),k("div",{className:"flex items-center gap-4 pt-4",children:[k(J,{href:"/docs/guides/connect-in-a-repo",className:"btn-primary",children:["Connect guide ",d(Ae,{size:16})]}),d(J,{href:"/changelog",className:"btn-ghost",children:"Website changelog"})]})]})}import{CodeBlock as D}from"@contractspec/lib.design-system";import $ from"@contractspec/lib.ui-link";import{ChevronRight as De}from"lucide-react";import{jsx as u,jsxs as w}from"react/jsx-runtime";function Le(){return w("div",{className:"space-y-8",children:[w("div",{className:"space-y-3",children:[u("h1",{className:"font-bold text-4xl",children:"Spec-driven validation + typing"}),u("p",{className:"text-lg text-muted-foreground",children:"Define a single operation with SchemaModel, generate validation, and keep your existing handler logic."})]}),w("div",{className:"card-subtle space-y-4 p-6",children:[u("h2",{className:"font-bold text-2xl",children:"What you'll build"}),w("ul",{className:"space-y-2 text-muted-foreground text-sm",children:[u("li",{children:"One command spec with explicit input/output models."}),u("li",{children:"Validation + typing without rewriting your service layer."}),u("li",{children:"Clear acceptance scenarios for regression safety."})]})]}),w("div",{className:"space-y-6",children:[w("div",{className:"space-y-3",children:[u("h2",{className:"font-bold text-2xl",children:"1) Define the spec"}),w("p",{className:"text-muted-foreground text-sm",children:["Create ",u("code",{children:"src/contracts/contact-create.operation.ts"}),":"]}),u(D,{language:"typescript",filename:"src/contracts/contact-create.operation.ts",code:`import { defineCommand } from "@contractspec/lib.contracts-spec/operations";
import { SchemaModel, ScalarTypeEnum } from "@contractspec/lib.schema";

const ContactInput = new SchemaModel({
  name: "ContactInput",
  fields: {
    email: { type: ScalarTypeEnum.Email(), isOptional: false },
    firstName: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
    lastName: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
  },
});

const ContactOutput = new SchemaModel({
  name: "ContactOutput",
  fields: {
    id: { type: ScalarTypeEnum.String(), isOptional: false },
    email: { type: ScalarTypeEnum.Email(), isOptional: false },
    createdAt: { type: ScalarTypeEnum.DateTime(), isOptional: false },
  },
});

export const ContactCreateCommand = defineCommand({
  meta: {
    key: "contact.create",
    version: "1.0.0",
    description: "Create a CRM contact",
    owners: ["@sales"],
    tags: ["crm", "contacts"],
  },
  io: {
    input: ContactInput,
    output: ContactOutput,
  },
  policy: {
    auth: "user",
  },
  acceptance: {
    scenarios: [
      {
        key: "create-contact",
        given: ["User is authenticated"],
        when: ["ContactCreateCommand executes"],
        then: ["Contact is persisted", "Email is validated"],
      },
    ],
  },
});`})]}),w("div",{className:"space-y-3",children:[u("h2",{className:"font-bold text-2xl",children:"2) Wire the handler"}),u("p",{className:"text-muted-foreground text-sm",children:"Keep your existing code. Just ensure the handler returns the output shape defined above."}),u(D,{language:"typescript",filename:"src/handlers/contact-create.ts",code:`import { ContactCreateCommand } from "@/contracts/contact-create.operation";
 
 export async function handleContactCreate(
   input: (typeof ContactCreateCommand)["io"]["input"],
   ctx: { userId: string }
 ) {
   // Your existing persistence logic
   return {
     id: "contact_123",
     email: input.email,
     createdAt: new Date().toISOString(),
   };
 }`})]}),w("div",{className:"space-y-3",children:[u("h2",{className:"font-bold text-2xl",children:"3) Validate"}),u(D,{language:"bash",filename:"spec-validation",code:"contractspec validate src/contracts/contact-create.operation.ts"}),w("p",{className:"text-muted-foreground text-sm",children:["Expected output: ",u("code",{children:"Validation passed"}),"."]})]}),w("div",{className:"card-subtle space-y-3 p-6",children:[u("h3",{className:"font-semibold text-lg",children:"Example package"}),u("p",{className:"text-muted-foreground text-sm",children:"The CRM Pipeline example includes real specs, handlers, and presentations for contact + deal flows."}),u(D,{language:"bash",filename:"crm-example",code:`# Build + validate the CRM pipeline example
cd packages/examples/crm-pipeline
bun install
bun run build
bun run validate`})]}),u(v,{title:"Need validation tied to real outcomes?",body:"Studio links checks to evidence, focus decisions, and post-release verification so specs evolve with product truth."})]}),w("div",{className:"flex items-center gap-4 pt-4",children:[w($,{href:"/docs/guides/generate-docs-clients-schemas",className:"btn-primary",children:["Next: Generate docs + clients ",u(De,{size:16})]}),u($,{href:"/docs/guides",className:"btn-ghost",children:"Back to guides"})]})]})}import{CodeBlock as Me}from"@contractspec/lib.design-system";import Ge from"@contractspec/lib.ui-link";import{ArrowRight as We,CheckCircle2 as _e,GitBranch as He}from"lucide-react";import{jsx as g,jsxs as C}from"react/jsx-runtime";var Ve=[{title:"Adopt one endpoint in Next.js",description:"Start inside a live app with one operation, one generated surface, and one clearly bounded change.",href:"/docs/guides/nextjs-one-endpoint",time:"25 min"},{title:"Import an existing codebase",description:"Stabilize what already exists instead of treating adoption as a rewrite project.",href:"/docs/guides/import-existing-codebases",time:"20 min"},{title:"Validation and typing",description:"Keep runtime validation and TypeScript behavior aligned from the same source definitions.",href:"/docs/guides/spec-validation-and-typing",time:"20 min"},{title:"Generate docs and clients",description:"Publish stable docs, schemas, and client-facing artifacts from the contract layer.",href:"/docs/guides/generate-docs-clients-schemas",time:"20 min"},{title:"Docs pipeline",description:"Feed generated reference material into the docs site without confusing ownership.",href:"/docs/guides/docs-generation-pipeline",time:"20 min"},{title:"Build a first module bundle",description:"Define one bundle spec, resolve a surface plan, and render it through the React host layer.",href:"/docs/guides/first-module-bundle",time:"20 min"},{title:"Host the Builder workbench",description:"Wire a Builder workspace snapshot, common commands, runtime modes, and mobile review links into the reusable host.",href:"/docs/guides/host-builder-workbench",time:"20 min"},{title:"Use Connect in a repo",description:"Enable Connect, verify agent actions locally, and inspect the resulting review and replay artifacts.",href:"/docs/guides/connect-in-a-repo",time:"15 min"},{title:"Author release capsules",description:"Pair changesets with structured release capsules and generate the artifacts that changelog and upgrade flows consume.",href:"/docs/guides/release-capsules",time:"15 min"},{title:"CI diff gating",description:"Use deterministic checks to catch drift and risky changes before they ship.",href:"/docs/guides/ci-contract-diff-gating",time:"15 min"}];function ze(){return C("div",{className:"space-y-10",children:[C("div",{className:"space-y-3",children:[g("p",{className:"editorial-kicker",children:"Build"}),g("h1",{className:"font-serif text-4xl tracking-[-0.04em] md:text-5xl",children:"Adoption guides for teams that want to keep their code."}),g("p",{className:"max-w-3xl text-lg text-muted-foreground leading-8",children:"These guides assume you are introducing ContractSpec into a real code base. Start with a narrow surface, verify the generated outputs, and expand only after the contract loop feels trustworthy."})]}),g("div",{className:"grid gap-4 md:grid-cols-2",children:Ve.map((i)=>C(Ge,{href:i.href,className:"editorial-panel",children:[C("div",{className:"flex items-start justify-between gap-4",children:[C("div",{children:[g("h2",{className:"font-semibold text-xl",children:i.title}),g("p",{className:"mt-2 text-muted-foreground text-sm leading-7",children:i.description})]}),g(We,{className:"mt-1 shrink-0",size:18})]}),C("div",{className:"mt-4 flex items-center gap-2 text-muted-foreground text-xs",children:[g(_e,{size:14}),C("span",{children:["Target time: ",i.time]})]})]},i.href))}),C("div",{className:"editorial-panel space-y-4",children:[C("div",{className:"flex items-center gap-2 font-semibold text-[color:var(--rust)] text-sm uppercase tracking-[0.2em]",children:[g(He,{size:16}),"Working style"]}),C("ul",{className:"editorial-list",children:[C("li",{children:[g("span",{className:"editorial-list-marker"}),g("span",{children:"Run each guide in a branch or sandboxed workspace."})]}),C("li",{children:[g("span",{className:"editorial-list-marker"}),g("span",{children:"Prefer one bounded surface at a time: one endpoint, one workflow, one integration, one unsafe module."})]}),C("li",{children:[g("span",{className:"editorial-list-marker"}),g("span",{children:"Use the example and reference outputs to verify what changed, not just the narrative page."})]})]}),g(Me,{language:"bash",filename:"guides-quickstart",code:`# list example systems
contractspec examples list

# validate the examples in this workspace
contractspec examples validate --repo-root .`})]})]})}import{registerDocBlocks as qe}from"@contractspec/lib.contracts-spec/docs";var Qe=[{id:"docs.guides.index",title:"Guides",summary:"Hands-on guides for adopting ContractSpec in real workflows.",kind:"goal",visibility:"public",route:"/docs/guides",tags:["guides","adoption"],body:`# Guides

Hands-on, runnable guides that map to real adoption scenarios. Each guide includes commands, expected output, and a CI-verified example package.`},{id:"docs.guides.nextjs-one-endpoint",title:"Next.js one endpoint",summary:"Add ContractSpec to an existing Next.js app with one endpoint.",kind:"usage",visibility:"public",route:"/docs/guides/nextjs-one-endpoint",tags:["guides","nextjs","operations"],body:`# Add ContractSpec to a Next.js app (one endpoint)

Create a single OperationSpec, register it, and expose it through a Next.js App Router handler.`},{id:"docs.guides.spec-validation-typing",title:"Spec validation and typing",summary:"Define an operation spec with validation and types, no rewrites.",kind:"usage",visibility:"public",route:"/docs/guides/spec-validation-and-typing",tags:["guides","validation","typing"],body:`# Spec-driven validation and typing

Define command/query specs that enforce validation and generate types without rewriting your app.`},{id:"docs.guides.docs-clients-schemas",title:"Generate docs, clients, schemas",summary:"Generate docs and OpenAPI for client SDKs from specs.",kind:"usage",visibility:"public",route:"/docs/guides/generate-docs-clients-schemas",tags:["guides","docs","openapi"],body:`# Generate docs and client schemas

Use ContractSpec to generate documentation and OpenAPI exports for client SDKs.

## Generate reference docs

1. Regenerate contract artifacts:

\`\`\`bash
bun contractspec generate
\`\`\`

2. Build docs output (index + markdown):

\`\`\`bash
bun docs:generate
# or versioned output
bun docs:generate -- --version v1.0.0
\`\`\``},{id:"docs.guides.docs-generation-pipeline",title:"Docs generation pipeline",summary:"Wire generated docs into a reference site with chunked indexes.",kind:"usage",visibility:"public",route:"/docs/guides/docs-generation-pipeline",tags:["guides","docs","pipeline"],body:`# Build the docs pipeline

Use ContractSpec to generate reference markdown, build a chunked index, and wire it into your docs routes.

## Generate contract docs

\`\`\`bash
contractspec generate
\`\`\`

## Build the docs index

\`\`\`bash
bun docs:generate
# versioned output
bun docs:generate -- --version v1.0.0
\`\`\`

## Reference wiring

Use the generated manifest and chunks under \`docs-index.manifest.json\` and \`docs-index.*.json\` to load the index at runtime.`},{id:"docs.guides.ci-contract-diff-gating",title:"CI gating for contract diffs",summary:"Gate changes with deterministic diffs and CI checks.",kind:"usage",visibility:"public",route:"/docs/guides/ci-contract-diff-gating",tags:["guides","ci","diff"],body:`# CI gating with deterministic diffs

Run ContractSpec CI checks to detect drift and breaking changes before merge.`}];qe(Qe);export{ze as GuidesIndexPage,Le as GuideSpecValidationTypingPage,Ue as GuideReleaseCapsulesPage,Te as GuideNextjsOneEndpointPage,Re as GuideImportExistingCodebasesPage,we as GuideHostBuilderWorkbenchPage,ve as GuideGenerateDocsClientsSchemasPage,ge as GuideFirstModuleBundlePage,he as GuideDocsPipelinePage,me as GuideContractTypesPage,re as GuideConnectInRepoPage,ae as GuideCIDiffGatingPage};
