// @bun
var Y=Object.defineProperty;var F=(o)=>o;function J(o,S){this[o]=F.bind(null,S)}var Ne=(o,S)=>{for(var D in S)Y(o,D,{get:S[D],enumerable:!0,configurable:!0,set:J.bind(S,D)})};var ke=(o,S)=>()=>(o&&(S=o(o=0)),S);import{CodeBlock as R}from"@contractspec/lib.design-system";import M from"@contractspec/lib.ui-link";import{jsx as n,jsxs as u}from"react/jsx-runtime";var Q=[{title:"Managed",body:"Best when the team wants the platform to own setup, routing, readiness, API defaults, and mobile-safe operator flows."},{title:"Local",body:"Best for power users who want local-daemon registration, tenant-local execution providers, and tighter data-locality control."},{title:"Hybrid",body:"Best when some work should stay local while preview, review, export, or mobile operator flows still use managed coordination."}],X=["Bootstrap managed, local-daemon, or hybrid presets explicitly instead of inventing provider posture ad hoc per host.","Capture prompts, files, voice, and other inbound sources into a typed workspace instead of relying on a single chat transcript.","Fuse the sources into decisions, assumptions, and blueprint updates with provenance and approval memory.","Compile authoring work into execution lanes, then route the work to explicit provider profiles and runtime targets.","Create previews, run readiness gates, and record receipts before export becomes an operator action.","Keep mobile review parity so approvals, incidents, and patch proposals can be inspected away from the desktop workbench."],Z=["local trust and lease posture for registered local runtimes","channel-action and comparison posture data in the shared Builder snapshot","preview, readiness, export, and mobile-review state derived from the same workspace snapshot"];function $(){return u("div",{className:"space-y-10",children:[u("section",{className:"space-y-3",children:[n("p",{className:"editorial-kicker",children:"Spec pack"}),n("h1",{className:"font-serif text-4xl tracking-[-0.04em] md:text-5xl",children:"Builder is a governed authoring control plane, not a frontier coding agent."}),u("p",{className:"max-w-3xl text-lg text-muted-foreground leading-8",children:["The implemented Builder stack sits across"," ",n("code",{children:"@contractspec/lib.builder-spec"}),","," ",n("code",{children:"@contractspec/lib.builder-runtime"}),","," ",n("code",{children:"@contractspec/lib.provider-spec"}),", and the reusable workbench/mobile modules. It orchestrates inputs, provider routing, readiness, and export decisions on top of the OSS ContractSpec foundation and the Studio operating layer."]})]}),u("section",{className:"editorial-proof-strip",children:[u("div",{className:"editorial-stat",children:[n("span",{className:"editorial-label",children:"What Builder owns"}),n("span",{className:"editorial-stat-value",children:"fusion, routing, readiness, export"})]}),n("p",{className:"max-w-2xl text-muted-foreground text-sm leading-7",children:"Builder delegates synthesis and coding to external execution providers. Its job is to keep those runs policy-aware, provenance-rich, and usable from both desktop and mobile operator surfaces."})]}),u("section",{className:"editorial-panel space-y-5",children:[u("div",{className:"space-y-2",children:[n("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Implemented stack and entrypoints"}),n("p",{className:"text-muted-foreground text-sm leading-7",children:"You can use the type surfaces directly in code, or start from the already wired workbench and mobile review routes in the public app shell."})]}),n(R,{language:"text",filename:"builder-stack",code:`Packages
- @contractspec/lib.builder-spec
- @contractspec/lib.builder-runtime
- @contractspec/lib.provider-spec
- @contractspec/module.builder-workbench
- @contractspec/module.mobile-review

Web app routes
- /operate/builder/workspaces/:workspaceId
- /operate/builder/workspaces/:workspaceId/mobile-review/:cardId

Operate API proxy
- /api/operate/builder/queries/builder.workspace.snapshot
- /api/operate/builder/commands/builder.blueprint.patch
- /api/operate/builder/commands/builder.export.execute`})]}),n("section",{className:"grid gap-4 md:grid-cols-3",children:Q.map((o)=>u("article",{className:"editorial-panel space-y-3",children:[n("h2",{className:"font-semibold text-xl",children:o.title}),n("p",{className:"text-muted-foreground text-sm leading-7",children:o.body})]},o.title))}),u("section",{className:"grid gap-5 lg:grid-cols-2",children:[u("article",{className:"editorial-panel space-y-4",children:[n("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Typical Builder loop"}),n("ol",{className:"list-inside list-decimal space-y-3 text-muted-foreground text-sm leading-7",children:X.map((o)=>n("li",{children:o},o))})]}),u("article",{className:"editorial-panel space-y-4",children:[n("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"What Builder should not become"}),u("ul",{className:"editorial-list",children:[u("li",{children:[n("span",{className:"editorial-list-marker"}),n("span",{children:"Not a competitor to specialized coding agents such as Codex or Claude Code."})]}),u("li",{children:[n("span",{className:"editorial-list-marker"}),n("span",{children:"Not a managed-only product that traps teams away from OSS-local runtime paths."})]}),u("li",{children:[n("span",{className:"editorial-list-marker"}),n("span",{children:"Not a hidden routing layer that obscures provider provenance, receipts, or runtime mode."})]}),u("li",{children:[n("span",{className:"editorial-list-marker"}),n("span",{children:"Not a desktop-only surface. Mobile review parity is part of the control-plane contract."})]})]})]})]}),u("section",{className:"editorial-panel space-y-5",children:[u("div",{className:"space-y-2",children:[n("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Workspace config carries the current Builder defaults"}),n("p",{className:"text-muted-foreground text-sm leading-7",children:"Builder setup is no longer just an app-shell concern. The shared workspace config now carries runtime mode, bootstrap preset, control plane API defaults, and local runtime registration metadata so the CLI, editors, and web shells resolve the same posture."})]}),n(R,{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"]
    }
  }
}`})]}),u("section",{className:"editorial-panel space-y-4",children:[n("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Operator posture stays visible"}),n("ul",{className:"editorial-list",children:Z.map((o)=>u("li",{children:[n("span",{className:"editorial-list-marker"}),n("span",{children:o})]},o))})]}),u("section",{className:"editorial-panel space-y-5",children:[u("div",{className:"space-y-2",children:[n("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Use the workbench UI as the host surface"}),n("p",{className:"text-muted-foreground text-sm leading-7",children:"The reusable module already exposes the desktop workbench shell. Your host app keeps control of action wiring, runtime mode selection, and approval flows."})]}),n(R,{language:"tsx",filename:"BuilderWorkbenchHost.tsx",code:`import { BuilderWorkbench, useBuilderWorkbenchState } from "@contractspec/module.builder-workbench";

const state = useBuilderWorkbenchState({
  workspace: initialSnapshot.workspace,
  initialSnapshot,
});

<BuilderWorkbench
  snapshot={state.snapshot}
  promptDraft={state.promptDraft}
  onPromptDraftChange={state.setPromptDraft}
  onCapturePrompt={capturePrompt}
  onGenerateBlueprint={generateBlueprint}
  onCompilePlan={compilePlan}
  onCreatePreview={createPreview}
  onRunReadiness={runReadiness}
  onExecuteExport={executeExport}
  selectedExportRuntimeMode="hybrid"
/>;`})]}),u("section",{className:"editorial-panel space-y-4",children:[n("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Read this with the Studio bridge in mind"}),n("p",{className:"text-muted-foreground text-sm leading-7",children:"Builder is where the OSS foundation meets the richer operating layer. Use the Studio overview when you want the higher-level product posture and team workflows on top of these contracts."}),u("div",{className:"flex flex-wrap gap-3",children:[n(M,{href:"/docs/studio",className:"btn-primary",children:"Studio overview"}),n(M,{href:"/docs/architecture/control-plane",className:"btn-ghost",children:"Control-plane runtime"})]})]})]})}import T from"@contractspec/lib.ui-link";import{ChevronRight as H}from"lucide-react";import{jsx as v,jsxs as N}from"react/jsx-runtime";function V(){return N("div",{className:"space-y-8",children:[N("div",{className:"space-y-2",children:[v("h1",{className:"font-bold text-4xl",children:"Capabilities"}),v("p",{className:"text-lg text-muted-foreground",children:"Capabilities are the core building block of ContractSpec. They define what your app can do."})]}),N("div",{className:"space-y-6",children:[N("div",{className:"space-y-3",children:[v("h2",{className:"font-bold text-2xl",children:"Overview"}),v("p",{className:"text-muted-foreground",children:"A ContractSpec (or Capability) is a typed, declarative description of an operation. It defines the operation's name, version, inputs, outputs, policies, and side effects. Runtime adapters automatically serve these as REST/GraphQL/MCP endpoints with full validation and policy enforcement."})]}),N("div",{className:"space-y-3",children:[v("h2",{className:"font-bold text-2xl",children:"Defining a Command (Write)"}),v("div",{className:"overflow-x-auto rounded-lg border border-border bg-background/50 p-4 font-mono text-muted-foreground text-sm",children:v("pre",{children:`import { defineCommand } from '@contractspec/lib.contracts-spec';
import { SchemaModel, ScalarTypeEnum } from '@contractspec/lib.schema';

const TransferFundsInput = new SchemaModel({
  name: 'TransferFundsInput',
  fields: {
    recipient: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
    amount: { type: ScalarTypeEnum.PositiveNumber(), isOptional: false },
  },
});

const TransferFundsOutput = new SchemaModel({
  name: 'TransferFundsOutput',
  fields: {
    transactionId: { type: ScalarTypeEnum.String(), isOptional: false },
    timestamp: { type: ScalarTypeEnum.DateTime(), isOptional: false },
  },
});

export const TransferFunds = defineCommand({
  meta: {
    key: 'wallet.transferFunds',
    version: '1.0.0',
    description: 'Transfer funds to another user',
    goal: 'Enable peer-to-peer payments',
    context: 'Requires sufficient balance',
    owners: ['team-payments'],
    tags: ['payments'],
    stability: 'stable',
  },
  io: {
    input: TransferFundsInput,
    output: TransferFundsOutput,
  },
  policy: {
    auth: 'user',
    flags: ['payments_enabled'],
  },
});`})})]}),N("div",{className:"space-y-3",children:[v("h2",{className:"font-bold text-2xl",children:"Schema Types"}),N("p",{className:"text-muted-foreground",children:["ContractSpec uses ",v("code",{children:"@contractspec/lib.schema"})," for I/O definitions. This provides Zod validation, GraphQL types, and JSON Schema from a single source."]}),N("ul",{className:"space-y-2 text-muted-foreground",children:[N("li",{children:["\u2022"," ",v("code",{className:"rounded bg-background/50 px-2 py-1",children:"ScalarTypeEnum.NonEmptyString()"})," ","- Non-empty text"]}),N("li",{children:["\u2022"," ",v("code",{className:"rounded bg-background/50 px-2 py-1",children:"ScalarTypeEnum.PositiveNumber()"})," ","- Positive numbers"]}),N("li",{children:["\u2022"," ",v("code",{className:"rounded bg-background/50 px-2 py-1",children:"ScalarTypeEnum.DateTime()"})," ","- ISO 8601 timestamps"]}),N("li",{children:["\u2022"," ",v("code",{className:"rounded bg-background/50 px-2 py-1",children:"ScalarTypeEnum.Email()"})," ","- Valid email addresses"]}),N("li",{children:["\u2022"," ",v("code",{className:"rounded bg-background/50 px-2 py-1",children:"defineEnum(...)"})," ","- Type-safe enums"]})]})]}),v("div",{className:"flex items-center gap-4 pt-4",children:N(T,{href:"/docs/specs/dataviews",className:"btn-primary",children:["Next: DataViews ",v(H,{size:16})]})})]})]})}import{CodeBlock as L}from"@contractspec/lib.design-system";import U from"@contractspec/lib.ui-link";import{jsx as p,jsxs as g}from"react/jsx-runtime";var x=[{title:"ContextPack",body:"Projects the current repo state, impacted contracts, canon packs, policy bindings, and acceptance checks into one task-scoped envelope."},{title:"PlanPacket",body:"Compiles a candidate objective into ACP-aware steps plus explicit refs back to control-plane intent, plan compile, and plan verify contracts."},{title:"PatchVerdict",body:"Classifies one file edit or shell command as permit, rewrite, require_review, or deny, with runtime-linked control-plane state when available."},{title:"ReviewPacket",body:"Persists the evidence a human needs when Connect escalates, while keeping the local artifact trail authoritative in OSS mode."}],j=["`.contractspec/adoption/catalog.json` mirrored from the bundled ContractSpec catalog","family-aware reuse recommendations for `ui`, `contracts`, `integrations`, `runtime`, `sharedLibs`, and `solutions`","verdict thresholds that can prefer workspace reuse, ContractSpec reuse, review, or explicit denial before a new implementation starts"],ee=["Enable `connect` in `.contractsrc.json` and keep your protected, immutable, generated, and smoke-check policies explicit.","Run `contractspec connect context` and `contractspec connect plan` before risky work so the agent is operating on task-scoped evidence, not ambient repo assumptions.","Gate file and shell mutations through `contractspec connect verify` or the host hook commands instead of inventing editor-specific approval logic.","Inspect pending review packets locally first, then sync them to the Studio bridge only if your team wants centralized operator workflows.","Use replay and harness evaluation to prove whether a prior decision stayed safe when the workspace changed."],ae=["Connect is not a second control plane or a second package family.","Verdicts are projections over existing `controlPlane.*`, ACP, workspace, and harness primitives.","Studio is optional for baseline enforcement. Local artifacts remain the OSS source of truth.","Destructive commands, protected paths, drift, and unknown impact stay visible instead of being hidden behind adapter magic."];function te(){return g("div",{className:"space-y-10",children:[g("section",{className:"space-y-3",children:[p("p",{className:"editorial-kicker",children:"Spec pack"}),p("h1",{className:"font-serif text-4xl tracking-[-0.04em] md:text-5xl",children:"ContractSpec Connect puts coding-agent actions behind explicit, local-first governance."}),p("p",{className:"max-w-3xl text-lg text-muted-foreground leading-8",children:"Connect is the adapter layer between agent-native actions and the existing ContractSpec stack. It reuses control-plane, ACP, workspace, knowledge, and harness primitives to explain what the agent is trying to do before a file edit or shell command lands."})]}),g("section",{className:"editorial-proof-strip",children:[g("div",{className:"editorial-stat",children:[p("span",{className:"editorial-label",children:"Authoritative surfaces"}),p("span",{className:"editorial-stat-value",children:"control plane, ACP, workspace, harness"})]}),p("p",{className:"max-w-2xl text-muted-foreground text-sm leading-7",children:"Connect stays narrow on purpose. It projects local evidence, maps its verdicts back to runtime semantics, and leaves the canonical system contracts where they already live."})]}),g("section",{className:"editorial-panel space-y-5",children:[g("div",{className:"space-y-2",children:[p("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"What you use in practice"}),p("p",{className:"text-muted-foreground text-sm leading-7",children:"The CLI and the workspace service already implement the pack. The main workflow is local initialization, task projection, verification, then optional review sync."})]}),p(L,{language:"bash",filename:"contractspec-connect",code:`contractspec connect init --scope workspace
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
contractspec connect context --task refactor-docs --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 refactor-docs --stdin --json
printf '{"operation":"edit","path":"packages/libs/contracts-spec/src/control-plane/contracts.ts"}' | contractspec connect verify --task refactor-docs --tool acp.fs.access --stdin --json
printf 'bun run typecheck' | contractspec connect verify --task refactor-docs --tool acp.terminal.exec --stdin --json
contractspec connect review list --json
contractspec connect replay <decisionId> --json`})]}),g("section",{className:"space-y-5",children:[g("div",{className:"space-y-2",children:[p("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"The four core artifacts"}),p("p",{className:"text-muted-foreground text-sm leading-7",children:"Every Connect command is there to emit or inspect one of these reviewable objects under `.contractspec/connect/*`."})]}),p("div",{className:"grid gap-4 md:grid-cols-2",children:x.map((o)=>g("article",{className:"editorial-panel space-y-3",children:[p("h3",{className:"font-semibold text-xl",children:o.title}),p("p",{className:"text-muted-foreground text-sm leading-7",children:o.body})]},o.title))})]}),g("section",{className:"editorial-panel space-y-5",children:[g("div",{className:"space-y-2",children:[p("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Reuse-first adoption is part of the workflow"}),p("p",{className:"text-muted-foreground text-sm leading-7",children:"Connect adoption keeps reuse guidance in the same local control surface. Before a new contract family, helper, or runtime abstraction lands, Connect can mirror the bundled catalog and resolve the best reuse candidate by family."})]}),p("ul",{className:"editorial-list",children:j.map((o)=>g("li",{children:[p("span",{className:"editorial-list-marker"}),p("span",{children:o})]},o))})]}),g("section",{className:"grid gap-5 lg:grid-cols-2",children:[g("article",{className:"editorial-panel space-y-4",children:[p("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Adopt Connect in this order"}),p("ol",{className:"list-inside list-decimal space-y-3 text-muted-foreground text-sm leading-7",children:ee.map((o)=>p("li",{children:o},o))})]}),g("article",{className:"editorial-panel space-y-4",children:[p("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Boundaries that keep it trustworthy"}),p("ul",{className:"editorial-list",children:ae.map((o)=>g("li",{children:[p("span",{className:"editorial-list-marker"}),p("span",{children:o})]},o))})]})]}),g("section",{className:"editorial-panel space-y-4",children:[p("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Where Connect fits in the rest of the docs"}),p("p",{className:"text-muted-foreground text-sm leading-7",children:"Read the control-plane runtime page when you want the underlying governance contracts, then use the Studio bridge only if your team wants centralized review queues on top of the OSS-local evidence path."}),g("div",{className:"flex flex-wrap gap-3",children:[p(U,{href:"/docs/architecture/control-plane",className:"btn-primary",children:"Control-plane runtime"}),p(U,{href:"/docs/studio",className:"btn-ghost",children:"Studio bridge"})]})]})]})}import{CodeBlock as _}from"@contractspec/lib.design-system";import{HStack as oe,VStack as b}from"@contractspec/lib.design-system/layout";import{List as z,ListItem as B}from"@contractspec/lib.design-system/list";import{Code as k,H1 as re,H2 as P,H3 as C,P as w,Text as h}from"@contractspec/lib.design-system/typography";import A from"@contractspec/lib.ui-link";import{ChevronRight as ne}from"lucide-react";import{jsx as e,jsxs as l}from"react/jsx-runtime";var ie=`import { defineDataView } from '@contractspec/lib.contracts-spec/data-views';
import { ListDataGridShowcaseRowsQuery } from '@contractspec/example.data-grid-showcase/contracts/data-grid-showcase.operation';

export const DataGridShowcaseDataView = defineDataView({
  meta: {
    key: 'examples.data-grid-showcase.table',
    version: '1.0.0',
    entity: 'account',
    title: 'Data Grid Showcase Table',
    description:
      'Declarative DataViewSpec for the ContractSpec table showcase.',
    domain: 'examples',
    owners: ['@platform.core'],
    tags: ['examples', 'table', 'data-grid'],
    stability: 'experimental',
  },
  source: {
    primary: {
      key: ListDataGridShowcaseRowsQuery.meta.key,
      version: ListDataGridShowcaseRowsQuery.meta.version,
    },
  },
  view: {
    kind: 'table',
    executionMode: 'client',
    selection: 'multiple',
    columnVisibility: true,
    columnResizing: true,
    columnPinning: true,
    rowExpansion: {
      fields: ['notes', 'renewalDate', 'lastActivityAt'],
    },
    initialState: {
      pageSize: 4,
      hiddenColumns: ['notes'],
      pinnedColumns: {
        left: ['account'],
      },
      sorting: [{ field: 'arr', desc: true }],
    },
    fields: [
      { key: 'account', label: 'Account', dataPath: 'account', sortable: true },
      { key: 'owner', label: 'Owner', dataPath: 'owner', sortable: true },
      { key: 'status', label: 'Status', dataPath: 'status', sortable: true },
      {
        key: 'arr',
        label: 'ARR',
        dataPath: 'arr',
        sortable: true,
        format: { type: 'currency', currency: 'USD', rounded: true },
      },
      {
        key: 'healthScore',
        label: 'Health score',
        dataPath: 'healthScore',
        format: { type: 'percent', valueScale: 'fraction', maximumFractionDigits: 1 },
      },
      {
        key: 'lastActivityAt',
        label: 'Last activity',
        dataPath: 'lastActivityAt',
        format: { type: 'datetime', dateStyle: 'medium', timeStyle: 'short' },
      },
      {
        key: 'notes',
        label: 'Notes',
        dataPath: 'notes',
        visibility: { minDataDepth: 'detailed' },
      },
    ],
    collection: {
      viewModes: {
        defaultMode: 'table',
        allowedModes: ['list', 'grid', 'table'],
      },
      pagination: {
        pageSize: 25,
        pageSizeOptions: [10, 25, 50],
      },
      toolbar: {
        search: true,
        viewMode: true,
        filters: true,
        density: true,
        dataDepth: true,
      },
      density: 'comfortable',
      dataDepth: 'standard',
      personalization: {
        enabled: true,
        persist: {
          viewMode: true,
          density: true,
          dataDepth: true,
          pageSize: true,
        },
      },
    },
    filters: [
      { key: 'status', label: 'Status', field: 'status', type: 'enum' },
      {
        key: 'arr',
        label: 'ARR',
        field: 'arr',
        type: 'currency',
        valueMode: 'range',
      },
      {
        key: 'lastActivityAt',
        label: 'Last activity',
        field: 'lastActivityAt',
        type: 'datetime',
        valueMode: 'range',
      },
    ],
  },
});`;function ce(){return l(b,{className:"space-y-8",children:[l(b,{className:"space-y-4",children:[e(re,{className:"font-bold text-4xl",children:"DataViews"}),l(w,{className:"text-muted-foreground",children:["A ",e(h,{className:"font-semibold",children:"DataViewSpec"})," describes how data should be queried, filtered, sorted, and presented to users. Runtime adapters execute optimized database queries and serve list views, detail views, and search interfaces while respecting policy constraints."]})]}),l(b,{className:"space-y-4",children:[e(P,{className:"font-bold text-2xl",children:"Core concepts"}),l(b,{className:"space-y-3",children:[l(b,{children:[e(C,{className:"font-semibold text-lg",children:"Data sources"}),e(w,{className:"text-muted-foreground",children:"A DataView connects to one or more data sources\u2014databases, APIs, or other capabilities. You specify the source and the fields you want to expose."})]}),l(b,{children:[e(C,{className:"font-semibold text-lg",children:"Filtering"}),e(w,{className:"text-muted-foreground",children:"Define filters that users can apply to narrow down results. Filters are typed as search, enum, number, percent, currency, date, time, datetime, duration, or boolean so renderers and query helpers can validate values before execution."})]}),l(b,{children:[e(C,{className:"font-semibold text-lg",children:"Sorting"}),e(w,{className:"text-muted-foreground",children:"Specify which fields can be sorted and the default sort order. ContractSpec generates efficient database queries with proper indexes."})]}),l(b,{children:[e(C,{className:"font-semibold text-lg",children:"Pagination"}),e(w,{className:"text-muted-foreground",children:"DataViews automatically support pagination to handle large datasets. You can configure page size limits and cursor-based or offset-based pagination."})]}),l(b,{children:[e(C,{className:"font-semibold text-lg",children:"Collection modes and data depth"}),l(w,{className:"text-muted-foreground",children:["List, grid, and table views can share a single"," ",e(k,{children:"view.collection"})," contract. It declares allowed view modes, toolbar controls, page-size defaults, density, data depth, and persistence hints. Fields can use"," ",e(k,{children:"visibility.minDataDepth"})," so summary views stay light while detailed views expose richer context."]})]}),l(b,{children:[e(C,{className:"font-semibold text-lg",children:"Personalization hints"}),l(w,{className:"text-muted-foreground",children:["The contract layer stays neutral: it can opt into persistence with"," ",e(k,{children:"view.collection.personalization"}),", but it does not import the personalization runtime. Host apps resolve preferences and behavior insights into renderer props."]})]})]})]}),l(b,{className:"space-y-4",children:[e(P,{className:"font-bold text-2xl",children:"Example DataViewSpec"}),l(w,{className:"text-muted-foreground",children:["Here is the canonical table contract used by the live"," ",e(A,{href:"/docs/examples/data-grid-showcase",className:"text-[color:var(--rust)] underline underline-offset-4",children:e(h,{children:"Data Grid Showcase"})}),":"]}),e(_,{language:"typescript",code:ie}),e(w,{className:"text-muted-foreground text-sm",children:"This one contract drives the DataView lane, while the same rows and controller also feed the raw web primitive, native-first primitive, and composed design-system demos."})]}),l(b,{className:"space-y-4",children:[e(P,{className:"font-bold text-2xl",children:"Policy integration"}),l(w,{className:"text-muted-foreground",children:["DataViews automatically enforce"," ",e(A,{href:"/docs/specs/policy",className:"text-violet-400 hover:text-violet-300",children:e(h,{children:"PolicySpecs"})}),". If a user doesn't have permission to see certain fields, those fields are automatically filtered out or redacted. If a user can only see their own data, the query is automatically scoped."]}),e(w,{className:"text-muted-foreground",children:"This means you define the data view once, and it works correctly for all users based on their permissions\u2014no need to write separate queries for different roles."})]}),l(b,{className:"space-y-4",children:[e(P,{className:"font-bold text-2xl",children:"Personalized Rendering Pattern"}),l(w,{className:"text-muted-foreground",children:["To personalize a DataView, keep the spec declarative and resolve user-specific defaults at the app boundary. Use"," ",e(k,{children:"resolveDataViewPreferences"})," from"," ",e(k,{children:"@contractspec/lib.personalization/data-view-preferences"}),"to compute ",e(k,{children:"viewMode"}),", ",e(k,{children:"density"}),","," ",e(k,{children:"dataDepth"}),", and ",e(k,{children:"pageSize"}),". Pass those values to ",e(k,{children:"DataViewRenderer"})," as controlled or default props, then record UI changes with ",e(k,{children:"trackDataViewInteraction"}),"."]}),e(_,{language:"tsx",code:`const resolved = resolveDataViewPreferences({
  spec: DataGridShowcaseDataView,
  preferences: profile.canonical,
  insights,
  record: savedPreference,
});

<DataViewRenderer
  spec={DataGridShowcaseDataView}
  items={rows}
  defaultViewMode={resolved.viewMode}
  defaultDensity={resolved.density}
  defaultDataDepth={resolved.dataDepth}
/>;`})]}),l(b,{className:"space-y-4",children:[e(P,{className:"font-bold text-2xl",children:"Served outputs"}),e(w,{className:"text-muted-foreground",children:"From a DataViewSpec, ContractSpec serves:"}),l(z,{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[e(B,{children:l(h,{children:[e(h,{className:"font-semibold",children:"Database queries"})," \u2013 Optimized SQL or NoSQL queries executed at runtime"]})}),e(B,{children:l(h,{children:[e(h,{className:"font-semibold",children:"API endpoints"})," \u2013 RESTful or GraphQL endpoints for fetching data"]})}),e(B,{children:l(h,{children:[e(h,{className:"font-semibold",children:"UI components"})," \u2013 List views, tables, cards, and detail views"]})}),e(B,{children:l(h,{children:[e(h,{className:"font-semibold",children:"Personalized defaults"})," \u2013 Plain renderer props for preferred mode, density, data depth, and page size"]})}),e(B,{children:l(h,{children:[e(h,{className:"font-semibold",children:"Search interfaces"})," \u2013 Full-text search with autocomplete"]})}),e(B,{children:l(h,{children:[e(h,{className:"font-semibold",children:"Export functions"})," \u2013 CSV, JSON, or Excel exports"]})})]})]}),l(b,{className:"space-y-4",children:[e(P,{className:"font-bold text-2xl",children:"Best practices"}),l(z,{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[e(B,{children:e(h,{children:"Only expose fields that users actually need\u2014this improves performance and security."})}),e(B,{children:e(h,{children:"Use appropriate indexes for sortable and filterable fields."})}),e(B,{children:e(h,{children:"Set reasonable pagination limits to prevent performance issues."})}),e(B,{children:l(h,{children:["Use ",e(k,{children:"allowedModes"})," to constrain mode switching to layouts that the fields and row actions can support."]})}),e(B,{children:l(h,{children:["Store preferences only for dimensions enabled by"," ",e(k,{children:"view.collection.personalization.persist"}),"."]})}),e(B,{children:e(h,{children:"Test DataViews with realistic data volumes to ensure they perform well."})})]})]}),l(oe,{className:"items-center gap-4 pt-4",children:[e(A,{href:"/docs/specs/capabilities",className:"btn-ghost",children:e(h,{children:"Previous: Capabilities"})}),l(A,{href:"/docs/specs/workflows",className:"btn-primary",children:[e(h,{children:"Next: Workflows"})," ",e(ne,{size:16})]})]})]})}import{CodeBlock as E}from"@contractspec/lib.design-system";import q from"@contractspec/lib.ui-link";import{jsx as d,jsxs as f}from"react/jsx-runtime";var le=["declared routes, surfaces, layouts, slots, actions, and data recipes","entity registries and field renderers for relation-heavy workbenches","preference-aware adaptation across guidance, density, data depth, control, media, pace, and narrative","auditable overlays and bounded AI patch proposals instead of free-form JSX generation"],de=["Define one `ModuleBundleSpec` with `defineModuleBundle` and keep the route and surface map explicit.","Resolve the bundle with `resolveBundle` for a real user, route, device, and preference profile.","Render the plan through `BundleProvider` and `BundleRenderer` so the UI stays downstream of the resolved spec.","Add overlays, policy hooks, planner proposals, and telemetry only after the base route resolves cleanly.","Pilot one dense domain first, such as a PM or operations workbench, before expanding the abstraction across the app."];function pe(){return f("div",{className:"space-y-10",children:[f("section",{className:"space-y-3",children:[d("p",{className:"editorial-kicker",children:"Spec pack"}),d("h1",{className:"font-serif text-4xl tracking-[-0.04em] md:text-5xl",children:"Module bundles turn surface composition into a typed ContractSpec runtime instead of a pile of bespoke page code."}),f("p",{className:"max-w-3xl text-lg text-muted-foreground leading-8",children:["The implemented package is"," ",d("code",{children:"@contractspec/lib.surface-runtime"}),". It lets you define a bundle spec once, resolve it into a personalized surface plan, then render that plan through React without letting AI or per-route custom code bypass the declared system boundary."]})]}),f("section",{className:"editorial-proof-strip",children:[f("div",{className:"editorial-stat",children:[d("span",{className:"editorial-label",children:"Runtime promise"}),d("span",{className:"editorial-stat-value",children:"bundle spec \u2192 resolved surface plan"})]}),d("p",{className:"max-w-2xl text-muted-foreground text-sm leading-7",children:"The bundle spec owns what can render, where it can render, which preferences matter, and how overlays and AI proposals stay bounded."})]}),d("section",{className:"grid gap-4 md:grid-cols-2",children:le.map((o)=>f("article",{className:"editorial-panel space-y-3",children:[d("h2",{className:"font-semibold text-xl",children:"Bundle capability"}),d("p",{className:"text-muted-foreground text-sm leading-7",children:o})]},o))}),f("section",{className:"editorial-panel space-y-5",children:[f("div",{className:"space-y-2",children:[d("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"1) Define the bundle"}),d("p",{className:"text-muted-foreground text-sm leading-7",children:"Start with a typed route and one surface. The runtime validates that you declared routes, surfaces, and verification coverage for all seven preference dimensions."})]}),d(E,{language:"typescript",filename:"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" }],
      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.",
        },
      },
    },
  },
});`})]}),f("section",{className:"editorial-panel space-y-5",children:[f("div",{className:"space-y-2",children:[d("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"2) Resolve and render the plan"}),d("p",{className:"text-muted-foreground text-sm leading-7",children:"The app renders the resolved plan, not the raw spec. That keeps layout choice, data hydration, overlays, and AI proposals auditable."})]}),d(E,{language:"tsx",filename:"SurfaceHost.tsx",code:`import { BundleProvider, BundleRenderer } from "@contractspec/lib.surface-runtime/react";
import { resolveBundle } from "@contractspec/lib.surface-runtime/runtime/resolve-bundle";

const plan = 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"],
});

export function SurfaceHost() {
  return (
    <BundleProvider plan={plan}>
      <BundleRenderer assistantSlotId="assistant" />
    </BundleProvider>
  );
}`})]}),f("section",{className:"grid gap-5 lg:grid-cols-2",children:[f("article",{className:"editorial-panel space-y-4",children:[d("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Adoption loop"}),d("ol",{className:"list-inside list-decimal space-y-3 text-muted-foreground text-sm leading-7",children:de.map((o)=>d("li",{children:o},o))})]}),f("article",{className:"editorial-panel space-y-4",children:[d("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Guardrails that matter"}),f("ul",{className:"editorial-list",children:[f("li",{children:[d("span",{className:"editorial-list-marker"}),d("span",{children:"Do not stuff this behavior back into `lib.ui-kit`."})]}),f("li",{children:[d("span",{className:"editorial-list-marker"}),d("span",{children:"Do not let AI invent undeclared components or mutate raw DOM state."})]}),f("li",{children:[d("span",{className:"editorial-list-marker"}),d("span",{children:"Keep third-party UI libraries behind adapter subpaths only."})]}),f("li",{children:[d("span",{className:"editorial-list-marker"}),d("span",{children:"Every surface still needs explicit verification coverage for the seven preference dimensions."})]})]})]})]}),f("section",{className:"editorial-panel space-y-4",children:[d("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Continue with overlays and runtime architecture"}),d("p",{className:"text-muted-foreground text-sm leading-7",children:"Once the bundle resolves deterministically, move into safe customization and the wider architecture that surrounds it."}),f("div",{className:"flex flex-wrap gap-3",children:[d(q,{href:"/docs/specs/overlays",className:"btn-primary",children:"Overlays"}),d(q,{href:"/docs/architecture",className:"btn-ghost",children:"Architecture overview"})]})]})]})}import I from"@contractspec/lib.ui-link";import{ChevronRight as se}from"lucide-react";import{jsx as t,jsxs as i}from"react/jsx-runtime";function me(){return i("div",{className:"space-y-8",children:[i("div",{className:"space-y-4",children:[t("h1",{className:"font-bold text-4xl",children:"Overlays"}),i("p",{className:"text-muted-foreground",children:["An ",t("strong",{children:"OverlaySpec"})," allows tenants or users to customize UI layouts and field visibility without modifying the underlying application code. Overlays are cryptographically signed to ensure they respect policy boundaries and cannot introduce security vulnerabilities."]})]}),i("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"Why overlays matter"}),t("p",{className:"text-muted-foreground",children:"Different users have different needs. A power user might want to see all available fields and actions, while a casual user prefers a simplified interface. A tenant in a multi-tenant application might want to brand the UI or hide features they don't use."}),t("p",{className:"text-muted-foreground",children:"Traditional approaches require either building multiple UIs or adding complex configuration logic throughout the codebase. OverlaySpecs provide a safer, more maintainable solution: users can customize their experience, but only within the bounds allowed by the underlying specs and policies."})]}),i("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"What overlays can do"}),i("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[i("li",{children:[t("strong",{children:"Hide or show fields"})," \u2013 Remove fields from forms or detail views (but only if the user has permission to see them in the first place)"]}),i("li",{children:[t("strong",{children:"Reorder fields"})," \u2013 Change the order in which fields appear"]}),i("li",{children:[t("strong",{children:"Rename labels"})," \u2013 Use different terminology that's more familiar to the user"]}),i("li",{children:[t("strong",{children:"Change layouts"})," \u2013 Switch between list, grid, or card views"]}),i("li",{children:[t("strong",{children:"Add help text"})," \u2013 Provide context-specific guidance"]}),i("li",{children:[t("strong",{children:"Set default values"})," \u2013 Pre-fill forms with tenant-specific defaults"]}),i("li",{children:[t("strong",{children:"Apply branding"})," \u2013 Customize colors, logos, and styling (within approved themes)"]})]})]}),i("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"Example OverlaySpec"}),t("p",{className:"text-muted-foreground",children:"Here's an overlay that customizes an order form:"}),t("div",{className:"overflow-x-auto rounded-lg border border-border bg-background/50 p-4 font-mono text-muted-foreground text-sm",children:t("pre",{children:`overlayId: acme-order-form
version: '1.0.0'.0.0
appliesTo:
  capability: createOrder
  tenantId: acme-corp
  
modifications:
  - type: hideField
    field: internalNotes
    reason: "ACME doesn't use internal notes"
    
  - type: renameLabel
    field: customerReference
    newLabel: "PO Number"
    
  - type: reorderFields
    fields:
      - customerReference
      - items
      - shippingAddress
      - billingAddress
      - paymentMethod
      
  - type: setDefault
    field: paymentMethod
    value: "net30"
    
  - type: addHelpText
    field: customerReference
    text: "Enter your purchase order number from your procurement system"
    
  - type: makeRequired
    field: customerReference
    
signature:
  algorithm: EdDSA
  publicKey: "acme-corp-overlay-key"
  signature: "base64-encoded-signature"`})})]}),i("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"Safety guarantees"}),t("p",{className:"text-muted-foreground",children:"Overlays are powerful, but they must not compromise security or data integrity. ContractSpec enforces several guarantees:"}),i("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[i("li",{children:[t("strong",{children:"Overlays cannot grant new permissions"})," \u2013 They can only hide or rearrange what the user is already allowed to see"]}),i("li",{children:[t("strong",{children:"Overlays cannot bypass validation"})," \u2013 Field types, constraints, and business rules from the underlying spec still apply"]}),i("li",{children:[t("strong",{children:"Overlays must be signed"})," \u2013 Only authorized parties (typically tenant admins) can create overlays"]}),i("li",{children:[t("strong",{children:"Overlays are versioned"})," \u2013 Changes to overlays are tracked and can be rolled back"]}),i("li",{children:[t("strong",{children:"Overlays are audited"})," \u2013 Every overlay application is logged"]})]})]}),i("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"Creating overlays"}),t("p",{className:"text-muted-foreground",children:"Overlays can be created through:"}),i("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[i("li",{children:[t("strong",{children:"Visual editor"})," \u2013 A drag-and-drop interface for non-technical users"]}),i("li",{children:[t("strong",{children:"TypeScript/JSON"})," \u2013 For developers who prefer code"]}),i("li",{children:[t("strong",{children:"API"})," \u2013 Programmatically create overlays for automation"]})]}),t("p",{className:"text-muted-foreground",children:"Once created, overlays must be signed using a private key. The corresponding public key is registered with ContractSpec, which verifies the signature before applying the overlay."}),i("p",{className:"text-muted-foreground",children:["See"," ",t(I,{href:"/docs/libraries/overlay-engine",className:"text-violet-400 underline",children:"Overlay Engine docs"})," ","and the"," ",t(I,{href:"/docs/advanced/overlay-editor",className:"text-violet-400 underline",children:"Overlay Editor guide"})," ","for end-to-end workflows."]})]}),i("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"Overlay scope"}),t("p",{className:"text-muted-foreground",children:"Overlays can be scoped to:"}),i("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[i("li",{children:[t("strong",{children:"Tenant"})," \u2013 All users in a tenant see the same overlay"]}),i("li",{children:[t("strong",{children:"User"})," \u2013 Individual users can have personal overlays"]}),i("li",{children:[t("strong",{children:"Role"})," \u2013 All users with a specific role see the overlay"]}),i("li",{children:[t("strong",{children:"Device"})," \u2013 Different overlays for mobile vs desktop"]})]}),t("p",{className:"text-muted-foreground",children:"If multiple overlays apply to the same user, they are merged in order of specificity (user overlays override role overlays, which override tenant overlays)."})]}),i("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"Best practices"}),i("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[t("li",{children:"Start with the default UI and only create overlays when users request specific changes."}),t("li",{children:"Document why each overlay modification was made\u2014this helps when reviewing or updating overlays."}),t("li",{children:"Test overlays thoroughly to ensure they don't break workflows or confuse users."}),t("li",{children:"Use tenant-level overlays for organizational customizations and user-level overlays for personal preferences."}),t("li",{children:"Regularly review overlays to remove ones that are no longer needed."}),t("li",{children:"Protect overlay signing keys carefully\u2014they control what customizations are allowed."})]})]}),i("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"Where overlays fit in the runtime"}),t("p",{className:"text-muted-foreground",children:"Overlays are safest when they sit on top of a declared bundle surface instead of ad hoc page code. Use the module-bundles docs first, then apply overlays as auditable customization on top of the resolved surface plan."}),i("div",{className:"flex flex-wrap gap-3",children:[t(I,{href:"/docs/specs/module-bundles",className:"btn-primary",children:"Module bundles"}),t(I,{href:"/docs/guides/first-module-bundle",className:"btn-ghost",children:"Build a first module bundle"})]})]}),i("div",{className:"flex items-center gap-4 pt-4",children:[t(I,{href:"/docs/specs/policy",className:"btn-ghost",children:"Previous: Policy"}),i(I,{href:"/docs/safety",className:"btn-primary",children:["Next: Safety ",t(se,{size:16})]})]})]})}import G from"@contractspec/lib.ui-link";import{ChevronRight as K}from"lucide-react";import{jsx as m,jsxs as y}from"react/jsx-runtime";var ue=[{title:"Capabilities",body:"Model operations, events, and presentations as explicit system behavior.",href:"/docs/specs/capabilities"},{title:"Data views",body:"Describe query, filtering, and presentation behavior from the same source model.",href:"/docs/specs/dataviews"},{title:"Workflows",body:"Coordinate multi-step execution, retries, monitoring, and hand-offs.",href:"/docs/specs/workflows"},{title:"Policy",body:"Carry governance and access rules through every generated and runtime-served surface.",href:"/docs/specs/policy"},{title:"Overlays",body:"Customize generated surfaces safely instead of forking them permanently.",href:"/docs/specs/overlays"},{title:"Safety and migration",body:"Keep change safe with signing, audits, rollbacks, and explicit migration behavior.",href:"/docs/safety"}],he=[{title:"Module bundles",body:"Define typed surface bundles that resolve into auditable runtime plans instead of hand-built page logic.",href:"/docs/specs/module-bundles"},{title:"ContractSpec Connect",body:"Put coding-agent edits and commands behind local-first context, verification, replay, and review artifacts.",href:"/docs/specs/connect"},{title:"Builder control plane",body:"Coordinate multimodal authoring, provider routing, readiness, export, and mobile review on top of OSS and Studio.",href:"/docs/specs/builder-control-plane"}];function fe(){return y("div",{className:"space-y-10",children:[y("div",{className:"space-y-3",children:[m("p",{className:"editorial-kicker",children:"Core model"}),m("h1",{className:"font-serif text-4xl tracking-[-0.04em] md:text-5xl",children:"Contracts are the durable system boundary."}),m("p",{className:"max-w-3xl text-lg text-muted-foreground leading-8",children:"ContractSpec uses explicit TypeScript specs to describe behavior before it spreads across APIs, UI, data models, events, and operator flows. The goal is not to hide implementation. The goal is to make the system boundary explicit enough that generation, validation, runtime enforcement, and regeneration can stay coherent."})]}),y("div",{className:"editorial-proof-strip",children:[y("div",{className:"editorial-stat",children:[m("span",{className:"editorial-label",children:"System promise"}),m("span",{className:"editorial-stat-value",children:"one contract \u2192 many surfaces"})]}),m("p",{className:"max-w-2xl text-muted-foreground text-sm leading-7",children:"Use the contract layer to keep surface behavior aligned, then let runtimes and generators do the repetitive work without inventing a closed platform."})]}),m("section",{className:"editorial-panel space-y-5",children:y("div",{className:"space-y-2",children:[m("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"What the contract layer owns"}),y("ul",{className:"editorial-list",children:[y("li",{children:[m("span",{className:"editorial-list-marker"}),m("span",{children:"Behavior: operations, events, presentations, workflows."})]}),y("li",{children:[m("span",{className:"editorial-list-marker"}),m("span",{children:"Validation: input, output, and schema boundaries."})]}),y("li",{children:[m("span",{className:"editorial-list-marker"}),m("span",{children:"Governance: policy, auditability, and migration rules."})]}),y("li",{children:[m("span",{className:"editorial-list-marker"}),m("span",{children:"Surface alignment: generated or served behavior across API, UI, data, and agent-facing interfaces."})]})]})]})}),y("section",{className:"space-y-5",children:[y("div",{className:"space-y-2",children:[m("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Specification types"}),m("p",{className:"text-muted-foreground text-sm leading-7",children:"You can adopt the model one part at a time. Not every system needs every spec type on day one."})]}),m("div",{className:"grid gap-4 md:grid-cols-2",children:ue.map((o)=>y(G,{href:o.href,className:"editorial-panel",children:[m("h3",{className:"font-semibold text-xl",children:o.title}),m("p",{className:"mt-2 text-muted-foreground text-sm leading-7",children:o.body}),y("div",{className:"mt-4 flex items-center gap-2 text-[color:var(--rust)] text-sm",children:["Open section ",m(K,{size:14})]})]},o.title))})]}),y("section",{className:"space-y-5",children:[y("div",{className:"space-y-2",children:[m("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Implemented spec packs"}),m("p",{className:"text-muted-foreground text-sm leading-7",children:"These packs combine multiple contract surfaces into higher-order systems you can use directly today: agent enforcement, AI-native surface runtime, and governed Builder authoring."})]}),m("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:he.map((o)=>y(G,{href:o.href,className:"editorial-panel",children:[m("h3",{className:"font-semibold text-xl",children:o.title}),m("p",{className:"mt-2 text-muted-foreground text-sm leading-7",children:o.body}),y("div",{className:"mt-4 flex items-center gap-2 text-[color:var(--rust)] text-sm",children:["Open pack ",m(K,{size:14})]})]},o.title))})]})]})}import O from"@contractspec/lib.ui-link";import{ChevronRight as ge}from"lucide-react";import{jsx as a,jsxs as c}from"react/jsx-runtime";function ye(){return c("div",{className:"space-y-8",children:[c("div",{className:"space-y-4",children:[a("h1",{className:"font-bold text-4xl",children:"Policy"}),c("p",{className:"text-muted-foreground",children:["A ",a("strong",{children:"PolicySpec"})," defines who can do what, when, and under what conditions. ContractSpec uses attribute-based access control (ABAC) to enforce policies across your entire application\u2014from API endpoints to UI components."]})]}),c("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Why policies matter"}),a("p",{className:"text-muted-foreground",children:"Traditional access control relies on roles (RBAC), which can become unwieldy as applications grow. ABAC is more flexible\u2014it evaluates policies based on attributes of the user, resource, action, and context."}),c("p",{className:"text-muted-foreground",children:["ContractSpec's policy engine ensures that access control is consistent across all surfaces. You don't have to remember to add authorization checks in every API endpoint or UI component\u2014the"," ",a(O,{href:"/docs/safety/pdp",className:"text-violet-400 hover:text-violet-300",children:"Policy Decision Point"})," ","enforces policies automatically."]})]}),c("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Policy structure"}),a("p",{className:"text-muted-foreground",children:"A PolicySpec contains one or more rules. Each rule has:"}),c("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[c("li",{children:[a("strong",{children:"Effect"})," \u2013 PERMIT, DENY, or REDACT"]}),c("li",{children:[a("strong",{children:"Condition"})," \u2013 A boolean expression that determines when the rule applies"]}),c("li",{children:[a("strong",{children:"Scope"})," \u2013 Which resources, actions, or fields the rule applies to"]}),c("li",{children:[a("strong",{children:"Priority"})," \u2013 Rules are evaluated in priority order; the first matching rule wins"]})]})]}),c("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Example PolicySpec"}),a("p",{className:"text-muted-foreground",children:"Here's a policy that controls access to customer data in TypeScript:"}),a("div",{className:"overflow-x-auto rounded-lg border border-border bg-background/50 p-4 font-mono text-muted-foreground text-sm",children:a("pre",{children:`import { definePolicy } from '@contractspec/lib.contracts-spec';

export const CustomerDataAccess = definePolicy({
  meta: {
    key: 'customer.data.access',
    version: '1.0.0',
  },
  rules: [
    {
      id: 'admin-full-access',
      priority: 100,
      effect: 'PERMIT',
      condition: (ctx) => ctx.user.role === 'admin',
      scope: {
        resources: ['customer'],
        actions: ['read', 'write', 'delete'],
      },
    },
    {
      id: 'sales-read-assigned',
      priority: 200,
      effect: 'PERMIT',
      condition: (ctx) => 
        ctx.user.role === 'sales' && 
        ctx.resource.assignedTo === ctx.user.id,
      scope: {
        resources: ['customer'],
        actions: ['read', 'write'],
      },
    },
    {
      id: 'support-read-redacted',
      priority: 300,
      effect: 'REDACT',
      condition: (ctx) => ctx.user.role === 'support',
      scope: {
        resources: ['customer'],
        actions: ['read'],
      },
      redactFields: ['creditCard', 'ssn', 'bankAccount'],
    },
  ],
});`})})]}),c("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Attributes"}),a("p",{className:"text-muted-foreground",children:"Policy conditions can reference attributes from four categories:"}),c("div",{className:"space-y-3",children:[c("div",{children:[a("h3",{className:"font-semibold text-lg",children:"User attributes"}),c("p",{className:"text-muted-foreground",children:[a("code",{className:"rounded bg-background/50 px-2 py-1",children:"user.id"}),","," ",a("code",{className:"rounded bg-background/50 px-2 py-1",children:"user.role"}),","," ",a("code",{className:"rounded bg-background/50 px-2 py-1",children:"user.groups"}),","," ",a("code",{className:"rounded bg-background/50 px-2 py-1",children:"user.department"}),", custom attributes"]})]}),c("div",{children:[a("h3",{className:"font-semibold text-lg",children:"Resource attributes"}),c("p",{className:"text-muted-foreground",children:[a("code",{className:"rounded bg-background/50 px-2 py-1",children:"resource.type"}),","," ",a("code",{className:"rounded bg-background/50 px-2 py-1",children:"resource.owner"}),","," ",a("code",{className:"rounded bg-background/50 px-2 py-1",children:"resource.sensitivity"}),", custom attributes"]})]}),c("div",{children:[a("h3",{className:"font-semibold text-lg",children:"Action attributes"}),c("p",{className:"text-muted-foreground",children:[a("code",{className:"rounded bg-background/50 px-2 py-1",children:"action"})," ","(read, write, delete, execute, export, etc.)"]})]}),c("div",{children:[a("h3",{className:"font-semibold text-lg",children:"Context attributes"}),c("p",{className:"text-muted-foreground",children:[a("code",{className:"rounded bg-background/50 px-2 py-1",children:"time.hour"}),","," ",a("code",{className:"rounded bg-background/50 px-2 py-1",children:"time.dayOfWeek"}),","," ",a("code",{className:"rounded bg-background/50 px-2 py-1",children:"request.ipAddress"}),","," ",a("code",{className:"rounded bg-background/50 px-2 py-1",children:"request.userAgent"})]})]})]})]}),c("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Data classification"}),c("p",{className:"text-muted-foreground",children:["You can tag fields with sensitivity levels in your"," ",a(O,{href:"/docs/specs/capabilities",className:"text-violet-400 hover:text-violet-300",children:"CapabilitySpecs"})," ","and"," ",a(O,{href:"/docs/specs/dataviews",className:"text-violet-400 hover:text-violet-300",children:"DataViewSpecs"}),":"]}),a("div",{className:"overflow-x-auto rounded-lg border border-border bg-background/50 p-4 font-mono text-muted-foreground text-sm",children:a("pre",{children:`fields:
  - name: email
    type: string
    sensitivity: PII
  - name: creditCard
    type: string
    sensitivity: PII
    encrypted: true
  - name: diagnosis
    type: string
    sensitivity: PHI
  - name: salary
    type: number
    sensitivity: confidential`})}),a("p",{className:"text-muted-foreground",children:'Policies can then reference these tags to enforce blanket rules like "support staff cannot see PII" or "PHI can only be accessed from approved IP addresses."'})]}),c("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Testing policies"}),a("p",{className:"text-muted-foreground",children:"ContractSpec provides tools for testing policies before deployment:"}),c("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[c("li",{children:[a("strong",{children:"Policy simulator"})," \u2013 Test how policies evaluate for different users and scenarios"]}),c("li",{children:[a("strong",{children:"Coverage analysis"})," \u2013 Identify resources or actions that aren't covered by any policy"]}),c("li",{children:[a("strong",{children:"Conflict detection"})," \u2013 Find rules that might conflict or produce unexpected results"]}),c("li",{children:[a("strong",{children:"Audit mode"})," \u2013 Run policies in audit-only mode to see what would be blocked without actually blocking it"]})]})]}),c("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Best practices"}),c("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[a("li",{children:"Start with a deny-by-default policy\u2014explicitly permit what should be allowed."}),a("li",{children:"Use clear, descriptive rule IDs that explain what the rule does."}),a("li",{children:"Set priorities carefully to ensure rules are evaluated in the right order."}),a("li",{children:"Test policies thoroughly with realistic user scenarios before deploying."}),c("li",{children:["Monitor policy decisions in production using"," ",a(O,{href:"/docs/safety/auditing",className:"text-violet-400 hover:text-violet-300",children:"audit logs"}),"."]}),a("li",{children:"Review and update policies regularly as your application and requirements evolve."})]})]}),c("div",{className:"flex items-center gap-4 pt-4",children:[a(O,{href:"/docs/specs/workflows",className:"btn-ghost",children:"Previous: Workflows"}),c(O,{href:"/docs/specs/overlays",className:"btn-primary",children:["Next: Overlays ",a(ge,{size:16})]})]})]})}import W from"@contractspec/lib.ui-link";import{ChevronRight as ve}from"lucide-react";import{jsx as r,jsxs as s}from"react/jsx-runtime";function be(){return s("div",{className:"space-y-8",children:[s("div",{className:"space-y-4",children:[r("h1",{className:"font-bold text-4xl",children:"Workflows"}),s("p",{className:"text-muted-foreground",children:["A ",r("strong",{children:"WorkflowSpec"})," orchestrates multi-step processes. It defines the sequence of operations, handles failures with retries and compensation, and provides observability into long-running tasks."]})]}),s("div",{className:"space-y-4",children:[r("h2",{className:"font-bold text-2xl",children:"Core concepts"}),s("div",{className:"space-y-3",children:[s("div",{children:[r("h3",{className:"font-semibold text-lg",children:"Identifiers"}),s("p",{className:"text-muted-foreground",children:["Each workflow has a unique"," ",r("code",{className:"rounded bg-background/50 px-2 py-1",children:"workflowId"})," ","and a"," ",r("code",{className:"rounded bg-background/50 px-2 py-1",children:"version"}),". This allows you to run multiple versions of the same workflow simultaneously during migrations or A/B tests."]})]}),s("div",{children:[r("h3",{className:"font-semibold text-lg",children:"Steps"}),s("p",{className:"text-muted-foreground",children:["A workflow is composed of ",r("strong",{children:"steps"}),". Each step invokes a"," ",r(W,{href:"/docs/specs/capabilities",className:"text-violet-400 hover:text-violet-300",children:"CapabilitySpec"}),", passes inputs, and receives outputs. Steps can run sequentially or in parallel."]})]}),s("div",{children:[r("h3",{className:"font-semibold text-lg",children:"Transitions"}),s("p",{className:"text-muted-foreground",children:[r("strong",{children:"Transitions"}),' define the flow between steps. They can be conditional (e.g., "if payment succeeds, go to step 3; otherwise, go to step 5") or unconditional.']})]}),s("div",{children:[r("h3",{className:"font-semibold text-lg",children:"Retries"}),r("p",{className:"text-muted-foreground",children:"If a step fails, the workflow can retry it with exponential backoff. You specify the maximum number of retries and the backoff strategy in the spec."})]}),s("div",{children:[r("h3",{className:"font-semibold text-lg",children:"Compensation"}),s("p",{className:"text-muted-foreground",children:["When a workflow fails partway through,"," ",r("strong",{children:"compensation"})," steps undo the effects of completed steps (e.g., refunding a payment, releasing a reservation). This ensures consistency even in failure scenarios."]})]}),s("div",{children:[r("h3",{className:"font-semibold text-lg",children:"SLAs"}),r("p",{className:"text-muted-foreground",children:"You can define Service Level Agreements (SLAs) for each step or the entire workflow. If a step exceeds its SLA, the system can trigger alerts or escalations."})]})]})]}),s("div",{className:"space-y-4",children:[r("h2",{className:"font-bold text-2xl",children:"Example WorkflowSpec (TypeScript)"}),r("p",{className:"text-muted-foreground",children:"Here's a simplified example of a payment workflow in TypeScript:"}),s("p",{className:"text-muted-foreground text-sm",children:["For Vercel Workflow and other VM-evaluated runtimes, author workflow specs from"," ",r("code",{className:"rounded bg-background/50 px-2 py-1",children:"@contractspec/lib.contracts-spec/workflow/spec"})," ","rather than the broad workflow barrel."]}),r("div",{className:"overflow-x-auto rounded-lg border border-border bg-background/50 p-4 font-mono text-muted-foreground text-sm",children:r("pre",{children:`import { defineWorkflow } from '@contractspec/lib.contracts-spec/workflow/spec';
import { ValidatePaymentMethod, ChargePayment, SendEmail } from './specs';

export const PaymentFlow = defineWorkflow({
  meta: {
    key: 'payment.flow',
    version: '1.0.0',
    description: 'End-to-end payment processing',
    owners: ['team-payments'],
    tags: ['payments'],
    stability: 'stable',
  },
  steps: [
    {
      id: 'validate-payment',
      operation: ValidatePaymentMethod,
      inputs: (ctx, input) => ({
        userId: ctx.userId,
        paymentMethodId: input.paymentMethodId,
      }),
      retry: {
        maxAttempts: 3,
        backoff: 'exponential',
      },
      onSuccess: 'charge-payment',
      onFailure: 'notify-user',
    },
    {
      id: 'charge-payment',
      operation: ChargePayment,
      inputs: (ctx, input, steps) => ({
        amount: input.amount,
        paymentMethodId: input.paymentMethodId,
      }),
      compensation: 'refund-payment',
      onSuccess: 'send-receipt',
      onFailure: 'notify-admin',
    },
    {
      id: 'send-receipt',
      operation: SendEmail,
      inputs: (ctx, input, steps) => ({
        to: ctx.userEmail,
        template: 'payment-receipt',
        data: steps['charge-payment'].output,
      }),
    },
  ],
  sla: {
    maxDuration: 30000, // milliseconds
    alertOnBreach: true,
  },
});`})})]}),s("div",{className:"space-y-4",children:[r("h2",{className:"font-bold text-2xl",children:"Triggers"}),r("p",{className:"text-muted-foreground",children:"Workflows can be triggered in several ways:"}),s("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[s("li",{children:[r("strong",{children:"Manual invocation"})," \u2013 A user or system calls the workflow via an API endpoint."]}),s("li",{children:[r("strong",{children:"Event-driven"})," \u2013 The workflow starts automatically when a specific event occurs (e.g., a new order is created)."]}),s("li",{children:[r("strong",{children:"Scheduled"})," \u2013 The workflow runs on a cron schedule (e.g., nightly batch processing)."]}),s("li",{children:[r("strong",{children:"Chained"})," \u2013 One workflow can invoke another as a step."]})]})]}),s("div",{className:"space-y-4",children:[r("h2",{className:"font-bold text-2xl",children:"Monitoring and versioning"}),r("p",{className:"text-muted-foreground",children:"ContractSpec automatically instruments workflows with telemetry. You can view:"}),s("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[r("li",{children:"Real-time execution status for each step"}),r("li",{children:"Historical run data and success/failure rates"}),r("li",{children:"Latency distributions and SLA compliance"}),r("li",{children:"Compensation events and retry attempts"})]}),r("p",{className:"text-muted-foreground",children:"When you update a workflow, you increment its version. Running workflows continue on their original version, while new invocations use the latest version. This allows safe, zero-downtime deployments."})]}),s("div",{className:"space-y-4",children:[r("h2",{className:"font-bold text-2xl",children:"Best practices"}),s("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[r("li",{children:"Keep steps idempotent \u2013 they should be safe to retry without side effects."}),r("li",{children:"Define compensation for any step that modifies external state."}),r("li",{children:"Use meaningful step IDs that describe the operation."}),r("li",{children:"Set realistic SLAs and monitor them in production."}),r("li",{children:"Test failure scenarios locally before deploying."})]})]}),s("div",{className:"flex items-center gap-4 pt-4",children:[r(W,{href:"/docs/specs/capabilities",className:"btn-ghost",children:"Previous: Capabilities"}),s(W,{href:"/docs/safety",className:"btn-primary",children:["Next: Safety Features ",r(ve,{size:16})]})]})]})}export{be as SpecsWorkflowsPage,ye as SpecsPolicyPage,fe as SpecsOverviewPage,me as SpecsOverlaysPage,pe as SpecsModuleBundlesPage,ce as SpecsDataViewsPage,te as SpecsConnectPage,V as SpecsCapabilitiesPage,$ as SpecsBuilderControlPlanePage};
