import{CodeBlock as w}from"@contractspec/lib.design-system";import P from"@contractspec/lib.ui-link";import{jsx as o,jsxs as u}from"react/jsx-runtime";var A=[{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."}],D=["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."],R=["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 W(){return u("div",{className:"space-y-10",children:[u("section",{className:"space-y-3",children:[o("p",{className:"editorial-kicker",children:"Spec pack"}),o("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"," ",o("code",{children:"@contractspec/lib.builder-spec"}),","," ",o("code",{children:"@contractspec/lib.builder-runtime"}),","," ",o("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:[o("span",{className:"editorial-label",children:"What Builder owns"}),o("span",{className:"editorial-stat-value",children:"fusion, routing, readiness, export"})]}),o("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:[o("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Implemented stack and entrypoints"}),o("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."})]}),o(w,{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`})]}),o("section",{className:"grid gap-4 md:grid-cols-3",children:A.map((i)=>u("article",{className:"editorial-panel space-y-3",children:[o("h2",{className:"font-semibold text-xl",children:i.title}),o("p",{className:"text-muted-foreground text-sm leading-7",children:i.body})]},i.title))}),u("section",{className:"grid gap-5 lg:grid-cols-2",children:[u("article",{className:"editorial-panel space-y-4",children:[o("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Typical Builder loop"}),o("ol",{className:"list-inside list-decimal space-y-3 text-muted-foreground text-sm leading-7",children:D.map((i)=>o("li",{children:i},i))})]}),u("article",{className:"editorial-panel space-y-4",children:[o("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"What Builder should not become"}),u("ul",{className:"editorial-list",children:[u("li",{children:[o("span",{className:"editorial-list-marker"}),o("span",{children:"Not a competitor to specialized coding agents such as Codex or Claude Code."})]}),u("li",{children:[o("span",{className:"editorial-list-marker"}),o("span",{children:"Not a managed-only product that traps teams away from OSS-local runtime paths."})]}),u("li",{children:[o("span",{className:"editorial-list-marker"}),o("span",{children:"Not a hidden routing layer that obscures provider provenance, receipts, or runtime mode."})]}),u("li",{children:[o("span",{className:"editorial-list-marker"}),o("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:[o("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Workspace config carries the current Builder defaults"}),o("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."})]}),o(w,{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:[o("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Operator posture stays visible"}),o("ul",{className:"editorial-list",children:R.map((i)=>u("li",{children:[o("span",{className:"editorial-list-marker"}),o("span",{children:i})]},i))})]}),u("section",{className:"editorial-panel space-y-5",children:[u("div",{className:"space-y-2",children:[o("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Use the workbench UI as the host surface"}),o("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."})]}),o(w,{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:[o("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Read this with the Studio bridge in mind"}),o("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:[o(P,{href:"/docs/studio",className:"btn-primary",children:"Studio overview"}),o(P,{href:"/docs/architecture/control-plane",className:"btn-ghost",children:"Control-plane runtime"})]})]})]})}import M from"@contractspec/lib.ui-link";import{ChevronRight as U}from"lucide-react";import{jsx as y,jsxs as v}from"react/jsx-runtime";function _(){return v("div",{className:"space-y-8",children:[v("div",{className:"space-y-2",children:[y("h1",{className:"font-bold text-4xl",children:"Capabilities"}),y("p",{className:"text-lg text-muted-foreground",children:"Capabilities are the core building block of ContractSpec. They define what your app can do."})]}),v("div",{className:"space-y-6",children:[v("div",{className:"space-y-3",children:[y("h2",{className:"font-bold text-2xl",children:"Overview"}),y("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."})]}),v("div",{className:"space-y-3",children:[y("h2",{className:"font-bold text-2xl",children:"Defining a Command (Write)"}),y("div",{className:"overflow-x-auto rounded-lg border border-border bg-background/50 p-4 font-mono text-muted-foreground text-sm",children:y("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'],
  },
});`})})]}),v("div",{className:"space-y-3",children:[y("h2",{className:"font-bold text-2xl",children:"Schema Types"}),v("p",{className:"text-muted-foreground",children:["ContractSpec uses ",y("code",{children:"@contractspec/lib.schema"})," for I/O definitions. This provides Zod validation, GraphQL types, and JSON Schema from a single source."]}),v("ul",{className:"space-y-2 text-muted-foreground",children:[v("li",{children:["•"," ",y("code",{className:"rounded bg-background/50 px-2 py-1",children:"ScalarTypeEnum.NonEmptyString()"})," ","- Non-empty text"]}),v("li",{children:["•"," ",y("code",{className:"rounded bg-background/50 px-2 py-1",children:"ScalarTypeEnum.PositiveNumber()"})," ","- Positive numbers"]}),v("li",{children:["•"," ",y("code",{className:"rounded bg-background/50 px-2 py-1",children:"ScalarTypeEnum.DateTime()"})," ","- ISO 8601 timestamps"]}),v("li",{children:["•"," ",y("code",{className:"rounded bg-background/50 px-2 py-1",children:"ScalarTypeEnum.Email()"})," ","- Valid email addresses"]}),v("li",{children:["•"," ",y("code",{className:"rounded bg-background/50 px-2 py-1",children:"defineEnum(...)"})," ","- Type-safe enums"]})]})]}),y("div",{className:"flex items-center gap-4 pt-4",children:v(M,{href:"/docs/specs/dataviews",className:"btn-primary",children:["Next: DataViews ",y(U,{size:16})]})})]})]})}import{CodeBlock as z}from"@contractspec/lib.design-system";import B from"@contractspec/lib.ui-link";import{jsx as d,jsxs as f}from"react/jsx-runtime";var E=[{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."}],q=["`.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"],G=["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."],H=["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 K(){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:"ContractSpec Connect puts coding-agent actions behind explicit, local-first governance."}),d("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."})]}),f("section",{className:"editorial-proof-strip",children:[f("div",{className:"editorial-stat",children:[d("span",{className:"editorial-label",children:"Authoritative surfaces"}),d("span",{className:"editorial-stat-value",children:"control plane, ACP, workspace, harness"})]}),d("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."})]}),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:"What you use in practice"}),d("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."})]}),d(z,{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`})]}),f("section",{className:"space-y-5",children:[f("div",{className:"space-y-2",children:[d("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"The four core artifacts"}),d("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/*`."})]}),d("div",{className:"grid gap-4 md:grid-cols-2",children:E.map((i)=>f("article",{className:"editorial-panel space-y-3",children:[d("h3",{className:"font-semibold text-xl",children:i.title}),d("p",{className:"text-muted-foreground text-sm leading-7",children:i.body})]},i.title))})]}),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:"Reuse-first adoption is part of the workflow"}),d("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."})]}),d("ul",{className:"editorial-list",children:q.map((i)=>f("li",{children:[d("span",{className:"editorial-list-marker"}),d("span",{children:i})]},i))})]}),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:"Adopt Connect in this order"}),d("ol",{className:"list-inside list-decimal space-y-3 text-muted-foreground text-sm leading-7",children:G.map((i)=>d("li",{children:i},i))})]}),f("article",{className:"editorial-panel space-y-4",children:[d("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Boundaries that keep it trustworthy"}),d("ul",{className:"editorial-list",children:H.map((i)=>f("li",{children:[d("span",{className:"editorial-list-marker"}),d("span",{children:i})]},i))})]})]}),f("section",{className:"editorial-panel space-y-4",children:[d("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Where Connect fits in the rest of the docs"}),d("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."}),f("div",{className:"flex flex-wrap gap-3",children:[d(B,{href:"/docs/architecture/control-plane",className:"btn-primary",children:"Control-plane runtime"}),d(B,{href:"/docs/studio",className:"btn-ghost",children:"Studio bridge"})]})]})]})}import N from"@contractspec/lib.ui-link";import{ChevronRight as V}from"lucide-react";import{jsx as n,jsxs as m}from"react/jsx-runtime";var Y=`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: 'notes', label: 'Notes', dataPath: 'notes' },
    ],
  },
});`;function F(){return m("div",{className:"space-y-8",children:[m("div",{className:"space-y-4",children:[n("h1",{className:"font-bold text-4xl",children:"DataViews"}),m("p",{className:"text-muted-foreground",children:["A ",n("strong",{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."]})]}),m("div",{className:"space-y-4",children:[n("h2",{className:"font-bold text-2xl",children:"Core concepts"}),m("div",{className:"space-y-3",children:[m("div",{children:[n("h3",{className:"font-semibold text-lg",children:"Data sources"}),n("p",{className:"text-muted-foreground",children:"A DataView connects to one or more data sources—databases, APIs, or other capabilities. You specify the source and the fields you want to expose."})]}),m("div",{children:[n("h3",{className:"font-semibold text-lg",children:"Filtering"}),n("p",{className:"text-muted-foreground",children:`Define filters that users can apply to narrow down results. Filters can be simple (e.g., "status equals 'active'") or complex (e.g., "created within the last 30 days AND assigned to current user").`})]}),m("div",{children:[n("h3",{className:"font-semibold text-lg",children:"Sorting"}),n("p",{className:"text-muted-foreground",children:"Specify which fields can be sorted and the default sort order. ContractSpec generates efficient database queries with proper indexes."})]}),m("div",{children:[n("h3",{className:"font-semibold text-lg",children:"Pagination"}),n("p",{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."})]}),m("div",{children:[n("h3",{className:"font-semibold text-lg",children:"Aggregations"}),n("p",{className:"text-muted-foreground",children:"Compute aggregates like counts, sums, averages, and group-by operations. These are useful for dashboards and summary views."})]})]})]}),m("div",{className:"space-y-4",children:[n("h2",{className:"font-bold text-2xl",children:"Example DataViewSpec"}),m("p",{className:"text-muted-foreground",children:["Here is the canonical table contract used by the live"," ",n(N,{href:"/docs/examples/data-grid-showcase",className:"text-[color:var(--rust)] underline underline-offset-4",children:"Data Grid Showcase"}),":"]}),n("div",{className:"overflow-x-auto rounded-lg border border-border bg-background/50 p-4 font-mono text-muted-foreground text-sm",children:n("pre",{children:Y})}),n("p",{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."})]}),m("div",{className:"space-y-4",children:[n("h2",{className:"font-bold text-2xl",children:"Policy integration"}),m("p",{className:"text-muted-foreground",children:["DataViews automatically enforce"," ",n(N,{href:"/docs/specs/policy",className:"text-violet-400 hover:text-violet-300",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."]}),n("p",{className:"text-muted-foreground",children:"This means you define the data view once, and it works correctly for all users based on their permissions—no need to write separate queries for different roles."})]}),m("div",{className:"space-y-4",children:[n("h2",{className:"font-bold text-2xl",children:"Served outputs"}),n("p",{className:"text-muted-foreground",children:"From a DataViewSpec, ContractSpec serves:"}),m("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[m("li",{children:[n("strong",{children:"Database queries"})," – Optimized SQL or NoSQL queries executed at runtime"]}),m("li",{children:[n("strong",{children:"API endpoints"})," – RESTful or GraphQL endpoints for fetching data"]}),m("li",{children:[n("strong",{children:"UI components"})," – List views, tables, cards, and detail views"]}),m("li",{children:[n("strong",{children:"Search interfaces"})," – Full-text search with autocomplete"]}),m("li",{children:[n("strong",{children:"Export functions"})," – CSV, JSON, or Excel exports"]})]})]}),m("div",{className:"space-y-4",children:[n("h2",{className:"font-bold text-2xl",children:"Best practices"}),m("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[n("li",{children:"Only expose fields that users actually need—this improves performance and security."}),n("li",{children:"Use appropriate indexes for sortable and filterable fields."}),n("li",{children:"Set reasonable pagination limits to prevent performance issues."}),n("li",{children:"Use aggregations sparingly—they can be expensive on large datasets."}),n("li",{children:"Test DataViews with realistic data volumes to ensure they perform well."})]})]}),m("div",{className:"flex items-center gap-4 pt-4",children:[n(N,{href:"/docs/specs/capabilities",className:"btn-ghost",children:"Previous: Capabilities"}),m(N,{href:"/docs/specs/workflows",className:"btn-primary",children:["Next: Workflows ",n(V,{size:16})]})]})]})}import{CodeBlock as C}from"@contractspec/lib.design-system";import I from"@contractspec/lib.ui-link";import{jsx as l,jsxs as h}from"react/jsx-runtime";var J=["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"],Q=["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 X(){return h("div",{className:"space-y-10",children:[h("section",{className:"space-y-3",children:[l("p",{className:"editorial-kicker",children:"Spec pack"}),l("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."}),h("p",{className:"max-w-3xl text-lg text-muted-foreground leading-8",children:["The implemented package is"," ",l("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."]})]}),h("section",{className:"editorial-proof-strip",children:[h("div",{className:"editorial-stat",children:[l("span",{className:"editorial-label",children:"Runtime promise"}),l("span",{className:"editorial-stat-value",children:"bundle spec → resolved surface plan"})]}),l("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."})]}),l("section",{className:"grid gap-4 md:grid-cols-2",children:J.map((i)=>h("article",{className:"editorial-panel space-y-3",children:[l("h2",{className:"font-semibold text-xl",children:"Bundle capability"}),l("p",{className:"text-muted-foreground text-sm leading-7",children:i})]},i))}),h("section",{className:"editorial-panel space-y-5",children:[h("div",{className:"space-y-2",children:[l("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"1) Define the bundle"}),l("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."})]}),l(C,{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.",
        },
      },
    },
  },
});`})]}),h("section",{className:"editorial-panel space-y-5",children:[h("div",{className:"space-y-2",children:[l("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"2) Resolve and render the plan"}),l("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."})]}),l(C,{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>
  );
}`})]}),h("section",{className:"grid gap-5 lg:grid-cols-2",children:[h("article",{className:"editorial-panel space-y-4",children:[l("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Adoption loop"}),l("ol",{className:"list-inside list-decimal space-y-3 text-muted-foreground text-sm leading-7",children:Q.map((i)=>l("li",{children:i},i))})]}),h("article",{className:"editorial-panel space-y-4",children:[l("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Guardrails that matter"}),h("ul",{className:"editorial-list",children:[h("li",{children:[l("span",{className:"editorial-list-marker"}),l("span",{children:"Do not stuff this behavior back into `lib.ui-kit`."})]}),h("li",{children:[l("span",{className:"editorial-list-marker"}),l("span",{children:"Do not let AI invent undeclared components or mutate raw DOM state."})]}),h("li",{children:[l("span",{className:"editorial-list-marker"}),l("span",{children:"Keep third-party UI libraries behind adapter subpaths only."})]}),h("li",{children:[l("span",{className:"editorial-list-marker"}),l("span",{children:"Every surface still needs explicit verification coverage for the seven preference dimensions."})]})]})]})]}),h("section",{className:"editorial-panel space-y-4",children:[l("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Continue with overlays and runtime architecture"}),l("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."}),h("div",{className:"flex flex-wrap gap-3",children:[l(I,{href:"/docs/specs/overlays",className:"btn-primary",children:"Overlays"}),l(I,{href:"/docs/architecture",className:"btn-ghost",children:"Architecture overview"})]})]})]})}import b from"@contractspec/lib.ui-link";import{ChevronRight as Z}from"lucide-react";import{jsx as a,jsxs as r}from"react/jsx-runtime";function $(){return r("div",{className:"space-y-8",children:[r("div",{className:"space-y-4",children:[a("h1",{className:"font-bold text-4xl",children:"Overlays"}),r("p",{className:"text-muted-foreground",children:["An ",a("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."]})]}),r("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Why overlays matter"}),a("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."}),a("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."})]}),r("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"What overlays can do"}),r("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[r("li",{children:[a("strong",{children:"Hide or show fields"})," – Remove fields from forms or detail views (but only if the user has permission to see them in the first place)"]}),r("li",{children:[a("strong",{children:"Reorder fields"})," – Change the order in which fields appear"]}),r("li",{children:[a("strong",{children:"Rename labels"})," – Use different terminology that's more familiar to the user"]}),r("li",{children:[a("strong",{children:"Change layouts"})," – Switch between list, grid, or card views"]}),r("li",{children:[a("strong",{children:"Add help text"})," – Provide context-specific guidance"]}),r("li",{children:[a("strong",{children:"Set default values"})," – Pre-fill forms with tenant-specific defaults"]}),r("li",{children:[a("strong",{children:"Apply branding"})," – Customize colors, logos, and styling (within approved themes)"]})]})]}),r("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Example OverlaySpec"}),a("p",{className:"text-muted-foreground",children:"Here's an overlay that customizes an order form:"}),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:`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"`})})]}),r("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Safety guarantees"}),a("p",{className:"text-muted-foreground",children:"Overlays are powerful, but they must not compromise security or data integrity. ContractSpec enforces several guarantees:"}),r("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[r("li",{children:[a("strong",{children:"Overlays cannot grant new permissions"})," – They can only hide or rearrange what the user is already allowed to see"]}),r("li",{children:[a("strong",{children:"Overlays cannot bypass validation"})," – Field types, constraints, and business rules from the underlying spec still apply"]}),r("li",{children:[a("strong",{children:"Overlays must be signed"})," – Only authorized parties (typically tenant admins) can create overlays"]}),r("li",{children:[a("strong",{children:"Overlays are versioned"})," – Changes to overlays are tracked and can be rolled back"]}),r("li",{children:[a("strong",{children:"Overlays are audited"})," – Every overlay application is logged"]})]})]}),r("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Creating overlays"}),a("p",{className:"text-muted-foreground",children:"Overlays can be created through:"}),r("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[r("li",{children:[a("strong",{children:"Visual editor"})," – A drag-and-drop interface for non-technical users"]}),r("li",{children:[a("strong",{children:"TypeScript/JSON"})," – For developers who prefer code"]}),r("li",{children:[a("strong",{children:"API"})," – Programmatically create overlays for automation"]})]}),a("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."}),r("p",{className:"text-muted-foreground",children:["See"," ",a(b,{href:"/docs/libraries/overlay-engine",className:"text-violet-400 underline",children:"Overlay Engine docs"})," ","and the"," ",a(b,{href:"/docs/advanced/overlay-editor",className:"text-violet-400 underline",children:"Overlay Editor guide"})," ","for end-to-end workflows."]})]}),r("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Overlay scope"}),a("p",{className:"text-muted-foreground",children:"Overlays can be scoped to:"}),r("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[r("li",{children:[a("strong",{children:"Tenant"})," – All users in a tenant see the same overlay"]}),r("li",{children:[a("strong",{children:"User"})," – Individual users can have personal overlays"]}),r("li",{children:[a("strong",{children:"Role"})," – All users with a specific role see the overlay"]}),r("li",{children:[a("strong",{children:"Device"})," – Different overlays for mobile vs desktop"]})]}),a("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)."})]}),r("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Best practices"}),r("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[a("li",{children:"Start with the default UI and only create overlays when users request specific changes."}),a("li",{children:"Document why each overlay modification was made—this helps when reviewing or updating overlays."}),a("li",{children:"Test overlays thoroughly to ensure they don't break workflows or confuse users."}),a("li",{children:"Use tenant-level overlays for organizational customizations and user-level overlays for personal preferences."}),a("li",{children:"Regularly review overlays to remove ones that are no longer needed."}),a("li",{children:"Protect overlay signing keys carefully—they control what customizations are allowed."})]})]}),r("div",{className:"space-y-4",children:[a("h2",{className:"font-bold text-2xl",children:"Where overlays fit in the runtime"}),a("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."}),r("div",{className:"flex flex-wrap gap-3",children:[a(b,{href:"/docs/specs/module-bundles",className:"btn-primary",children:"Module bundles"}),a(b,{href:"/docs/guides/first-module-bundle",className:"btn-ghost",children:"Build a first module bundle"})]})]}),r("div",{className:"flex items-center gap-4 pt-4",children:[a(b,{href:"/docs/specs/policy",className:"btn-ghost",children:"Previous: Policy"}),r(b,{href:"/docs/safety",className:"btn-primary",children:["Next: Safety ",a(Z,{size:16})]})]})]})}import T from"@contractspec/lib.ui-link";import{ChevronRight as O}from"lucide-react";import{jsx as s,jsxs as g}from"react/jsx-runtime";var L=[{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"}],x=[{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 j(){return g("div",{className:"space-y-10",children:[g("div",{className:"space-y-3",children:[s("p",{className:"editorial-kicker",children:"Core model"}),s("h1",{className:"font-serif text-4xl tracking-[-0.04em] md:text-5xl",children:"Contracts are the durable system boundary."}),s("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."})]}),g("div",{className:"editorial-proof-strip",children:[g("div",{className:"editorial-stat",children:[s("span",{className:"editorial-label",children:"System promise"}),s("span",{className:"editorial-stat-value",children:"one contract → many surfaces"})]}),s("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."})]}),s("section",{className:"editorial-panel space-y-5",children:g("div",{className:"space-y-2",children:[s("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"What the contract layer owns"}),g("ul",{className:"editorial-list",children:[g("li",{children:[s("span",{className:"editorial-list-marker"}),s("span",{children:"Behavior: operations, events, presentations, workflows."})]}),g("li",{children:[s("span",{className:"editorial-list-marker"}),s("span",{children:"Validation: input, output, and schema boundaries."})]}),g("li",{children:[s("span",{className:"editorial-list-marker"}),s("span",{children:"Governance: policy, auditability, and migration rules."})]}),g("li",{children:[s("span",{className:"editorial-list-marker"}),s("span",{children:"Surface alignment: generated or served behavior across API, UI, data, and agent-facing interfaces."})]})]})]})}),g("section",{className:"space-y-5",children:[g("div",{className:"space-y-2",children:[s("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Specification types"}),s("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."})]}),s("div",{className:"grid gap-4 md:grid-cols-2",children:L.map((i)=>g(T,{href:i.href,className:"editorial-panel",children:[s("h3",{className:"font-semibold text-xl",children:i.title}),s("p",{className:"mt-2 text-muted-foreground text-sm leading-7",children:i.body}),g("div",{className:"mt-4 flex items-center gap-2 text-[color:var(--rust)] text-sm",children:["Open section ",s(O,{size:14})]})]},i.title))})]}),g("section",{className:"space-y-5",children:[g("div",{className:"space-y-2",children:[s("h2",{className:"font-serif text-3xl tracking-[-0.03em]",children:"Implemented spec packs"}),s("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."})]}),s("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:x.map((i)=>g(T,{href:i.href,className:"editorial-panel",children:[s("h3",{className:"font-semibold text-xl",children:i.title}),s("p",{className:"mt-2 text-muted-foreground text-sm leading-7",children:i.body}),g("div",{className:"mt-4 flex items-center gap-2 text-[color:var(--rust)] text-sm",children:["Open pack ",s(O,{size:14})]})]},i.title))})]})]})}import k from"@contractspec/lib.ui-link";import{ChevronRight as ee}from"lucide-react";import{jsx as e,jsxs as c}from"react/jsx-runtime";function ae(){return c("div",{className:"space-y-8",children:[c("div",{className:"space-y-4",children:[e("h1",{className:"font-bold text-4xl",children:"Policy"}),c("p",{className:"text-muted-foreground",children:["A ",e("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—from API endpoints to UI components."]})]}),c("div",{className:"space-y-4",children:[e("h2",{className:"font-bold text-2xl",children:"Why policies matter"}),e("p",{className:"text-muted-foreground",children:"Traditional access control relies on roles (RBAC), which can become unwieldy as applications grow. ABAC is more flexible—it 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—the"," ",e(k,{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:[e("h2",{className:"font-bold text-2xl",children:"Policy structure"}),e("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:[e("strong",{children:"Effect"})," – PERMIT, DENY, or REDACT"]}),c("li",{children:[e("strong",{children:"Condition"})," – A boolean expression that determines when the rule applies"]}),c("li",{children:[e("strong",{children:"Scope"})," – Which resources, actions, or fields the rule applies to"]}),c("li",{children:[e("strong",{children:"Priority"})," – Rules are evaluated in priority order; the first matching rule wins"]})]})]}),c("div",{className:"space-y-4",children:[e("h2",{className:"font-bold text-2xl",children:"Example PolicySpec"}),e("p",{className:"text-muted-foreground",children:"Here's a policy that controls access to customer data in TypeScript:"}),e("div",{className:"overflow-x-auto rounded-lg border border-border bg-background/50 p-4 font-mono text-muted-foreground text-sm",children:e("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:[e("h2",{className:"font-bold text-2xl",children:"Attributes"}),e("p",{className:"text-muted-foreground",children:"Policy conditions can reference attributes from four categories:"}),c("div",{className:"space-y-3",children:[c("div",{children:[e("h3",{className:"font-semibold text-lg",children:"User attributes"}),c("p",{className:"text-muted-foreground",children:[e("code",{className:"rounded bg-background/50 px-2 py-1",children:"user.id"}),","," ",e("code",{className:"rounded bg-background/50 px-2 py-1",children:"user.role"}),","," ",e("code",{className:"rounded bg-background/50 px-2 py-1",children:"user.groups"}),","," ",e("code",{className:"rounded bg-background/50 px-2 py-1",children:"user.department"}),", custom attributes"]})]}),c("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Resource attributes"}),c("p",{className:"text-muted-foreground",children:[e("code",{className:"rounded bg-background/50 px-2 py-1",children:"resource.type"}),","," ",e("code",{className:"rounded bg-background/50 px-2 py-1",children:"resource.owner"}),","," ",e("code",{className:"rounded bg-background/50 px-2 py-1",children:"resource.sensitivity"}),", custom attributes"]})]}),c("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Action attributes"}),c("p",{className:"text-muted-foreground",children:[e("code",{className:"rounded bg-background/50 px-2 py-1",children:"action"})," ","(read, write, delete, execute, export, etc.)"]})]}),c("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Context attributes"}),c("p",{className:"text-muted-foreground",children:[e("code",{className:"rounded bg-background/50 px-2 py-1",children:"time.hour"}),","," ",e("code",{className:"rounded bg-background/50 px-2 py-1",children:"time.dayOfWeek"}),","," ",e("code",{className:"rounded bg-background/50 px-2 py-1",children:"request.ipAddress"}),","," ",e("code",{className:"rounded bg-background/50 px-2 py-1",children:"request.userAgent"})]})]})]})]}),c("div",{className:"space-y-4",children:[e("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"," ",e(k,{href:"/docs/specs/capabilities",className:"text-violet-400 hover:text-violet-300",children:"CapabilitySpecs"})," ","and"," ",e(k,{href:"/docs/specs/dataviews",className:"text-violet-400 hover:text-violet-300",children:"DataViewSpecs"}),":"]}),e("div",{className:"overflow-x-auto rounded-lg border border-border bg-background/50 p-4 font-mono text-muted-foreground text-sm",children:e("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`})}),e("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:[e("h2",{className:"font-bold text-2xl",children:"Testing policies"}),e("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:[e("strong",{children:"Policy simulator"})," – Test how policies evaluate for different users and scenarios"]}),c("li",{children:[e("strong",{children:"Coverage analysis"})," – Identify resources or actions that aren't covered by any policy"]}),c("li",{children:[e("strong",{children:"Conflict detection"})," – Find rules that might conflict or produce unexpected results"]}),c("li",{children:[e("strong",{children:"Audit mode"})," – Run policies in audit-only mode to see what would be blocked without actually blocking it"]})]})]}),c("div",{className:"space-y-4",children:[e("h2",{className:"font-bold text-2xl",children:"Best practices"}),c("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[e("li",{children:"Start with a deny-by-default policy—explicitly permit what should be allowed."}),e("li",{children:"Use clear, descriptive rule IDs that explain what the rule does."}),e("li",{children:"Set priorities carefully to ensure rules are evaluated in the right order."}),e("li",{children:"Test policies thoroughly with realistic user scenarios before deploying."}),c("li",{children:["Monitor policy decisions in production using"," ",e(k,{href:"/docs/safety/auditing",className:"text-violet-400 hover:text-violet-300",children:"audit logs"}),"."]}),e("li",{children:"Review and update policies regularly as your application and requirements evolve."})]})]}),c("div",{className:"flex items-center gap-4 pt-4",children:[e(k,{href:"/docs/specs/workflows",className:"btn-ghost",children:"Previous: Workflows"}),c(k,{href:"/docs/specs/overlays",className:"btn-primary",children:["Next: Overlays ",e(ee,{size:16})]})]})]})}import S from"@contractspec/lib.ui-link";import{ChevronRight as te}from"lucide-react";import{jsx as t,jsxs as p}from"react/jsx-runtime";function oe(){return p("div",{className:"space-y-8",children:[p("div",{className:"space-y-4",children:[t("h1",{className:"font-bold text-4xl",children:"Workflows"}),p("p",{className:"text-muted-foreground",children:["A ",t("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."]})]}),p("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"Core concepts"}),p("div",{className:"space-y-3",children:[p("div",{children:[t("h3",{className:"font-semibold text-lg",children:"Identifiers"}),p("p",{className:"text-muted-foreground",children:["Each workflow has a unique"," ",t("code",{className:"rounded bg-background/50 px-2 py-1",children:"workflowId"})," ","and a"," ",t("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."]})]}),p("div",{children:[t("h3",{className:"font-semibold text-lg",children:"Steps"}),p("p",{className:"text-muted-foreground",children:["A workflow is composed of ",t("strong",{children:"steps"}),". Each step invokes a"," ",t(S,{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."]})]}),p("div",{children:[t("h3",{className:"font-semibold text-lg",children:"Transitions"}),p("p",{className:"text-muted-foreground",children:[t("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.']})]}),p("div",{children:[t("h3",{className:"font-semibold text-lg",children:"Retries"}),t("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."})]}),p("div",{children:[t("h3",{className:"font-semibold text-lg",children:"Compensation"}),p("p",{className:"text-muted-foreground",children:["When a workflow fails partway through,"," ",t("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."]})]}),p("div",{children:[t("h3",{className:"font-semibold text-lg",children:"SLAs"}),t("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."})]})]})]}),p("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"Example WorkflowSpec (TypeScript)"}),t("p",{className:"text-muted-foreground",children:"Here's a simplified example of a payment workflow in TypeScript:"}),p("p",{className:"text-muted-foreground text-sm",children:["For Vercel Workflow and other VM-evaluated runtimes, author workflow specs from"," ",t("code",{className:"rounded bg-background/50 px-2 py-1",children:"@contractspec/lib.contracts-spec/workflow/spec"})," ","rather than the broad workflow barrel."]}),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:`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,
  },
});`})})]}),p("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"Triggers"}),t("p",{className:"text-muted-foreground",children:"Workflows can be triggered in several ways:"}),p("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[p("li",{children:[t("strong",{children:"Manual invocation"})," – A user or system calls the workflow via an API endpoint."]}),p("li",{children:[t("strong",{children:"Event-driven"})," – The workflow starts automatically when a specific event occurs (e.g., a new order is created)."]}),p("li",{children:[t("strong",{children:"Scheduled"})," – The workflow runs on a cron schedule (e.g., nightly batch processing)."]}),p("li",{children:[t("strong",{children:"Chained"})," – One workflow can invoke another as a step."]})]})]}),p("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"Monitoring and versioning"}),t("p",{className:"text-muted-foreground",children:"ContractSpec automatically instruments workflows with telemetry. You can view:"}),p("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[t("li",{children:"Real-time execution status for each step"}),t("li",{children:"Historical run data and success/failure rates"}),t("li",{children:"Latency distributions and SLA compliance"}),t("li",{children:"Compensation events and retry attempts"})]}),t("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."})]}),p("div",{className:"space-y-4",children:[t("h2",{className:"font-bold text-2xl",children:"Best practices"}),p("ul",{className:"list-inside list-disc space-y-2 text-muted-foreground",children:[t("li",{children:"Keep steps idempotent – they should be safe to retry without side effects."}),t("li",{children:"Define compensation for any step that modifies external state."}),t("li",{children:"Use meaningful step IDs that describe the operation."}),t("li",{children:"Set realistic SLAs and monitor them in production."}),t("li",{children:"Test failure scenarios locally before deploying."})]})]}),p("div",{className:"flex items-center gap-4 pt-4",children:[t(S,{href:"/docs/specs/capabilities",className:"btn-ghost",children:"Previous: Capabilities"}),p(S,{href:"/docs/safety",className:"btn-primary",children:["Next: Safety Features ",t(te,{size:16})]})]})]})}export{oe as SpecsWorkflowsPage,ae as SpecsPolicyPage,j as SpecsOverviewPage,$ as SpecsOverlaysPage,X as SpecsModuleBundlesPage,F as SpecsDataViewsPage,K as SpecsConnectPage,_ as SpecsCapabilitiesPage,W as SpecsBuilderControlPlanePage};
