// @bun
var l=Object.defineProperty;var c=(e)=>e;function d(e,o){this[e]=c.bind(null,o)}var p=(e,o)=>{for(var t in o)l(e,t,{get:o[t],enumerable:!0,configurable:!0,set:d.bind(o,t)})};var u=(e,o)=>()=>(e&&(o=e(e=0)),o);var s=[{id:"docs.ops.lifecycle-operations.goal",title:"Lifecycle operations goal",summary:"Keep managed lifecycle assessments timely, auditable, and low-risk per tenant.",kind:"goal",visibility:"public",route:"/docs/ops/lifecycle-operations/goal",tags:["ops","lifecycle"],body:"Operate lifecycle assessments with predictable cadence, clear observability, and reversible customizations so tenants stay aligned to milestones without risking data access."},{id:"docs.ops.lifecycle-operations.usage",title:"Lifecycle operations usage guide",summary:"Quick checklist for running lifecycle managed ops.",kind:"usage",visibility:"public",route:"/docs/ops/lifecycle-operations/usage",tags:["ops","lifecycle"],body:`- Run weekly auto-refresh per tenant; allow manual reruns behind \`LIFECYCLE_DETECTION_ALPHA\`.
- Publish top 3 actions + milestone checklist to Studio UI; emit lifecycle events.
- Monitor P95 < 500ms; alert on confidence < 0.5 or stage churn.
- Version overrides (weights, milestones, playbooks); never edit compiled JS.
- Log incidents for detection gaps or bad recommendations; gate ceremony output via flag if broken.`},{id:"docs.ops.lifecycle-operations.how",title:"Lifecycle operations runbook",summary:"Full runbook for lifecycle assessments, customization, and alerts.",kind:"how",visibility:"public",route:"/docs/ops/lifecycle-operations/how",tags:["ops","lifecycle"],body:`## Lifecycle Operations Runbook (ContractSpec Managed)

This runbook guides ContractSpec operators who run the lifecycle managed service (bundle + Studio surfaces). It focuses on cadence, monitoring, customization, and escalation without touching tenant-specific databases.

---

### 1. Responsibilities

1. **Assessment Cadence**
   - Default: weekly auto-refresh per tenant (using latest telemetry + questionnaires).
   - Manual rerun allowed any time via Studio admin (flag \`LIFECYCLE_DETECTION_ALPHA\` must be on).
2. **Guidance Delivery**
   - Publish top 3 recommended actions + milestone checklist to Studio UI.
   - Trigger ceremony payload when stage changes (Stage N \u2192 N+1 or N-1).
3. **Observability**
   - Ensure lifecycle events hit analytics pipeline (\`lifecycle_assessment_run\`, \`lifecycle_stage_changed\`, \`lifecycle_guidance_consumed\`).
   - Monitor error budget for orchestrator runtime (<500ms P95 on synthetic data).

---

### 2. Operational Flow

1. **Collect Signals**
   - Kick \`StageSignalCollector\` with adapters:
     - Analytics adapter pulls synthetic/aggregated metrics (no raw tenant data).
     - Questionnaire adapter reads stored JSON answers (per customer).
     - Intent adapter listens to observability events (optional).
2. **Score & Assess**
   - \`LifecycleOrchestrator\` returns \`LifecycleAssessment\` + confidence.
   - Persist assessment snapshot via Studio storage abstraction (file or KV).
3. **Generate Guidance**
   - \`LifecycleRecommendationEngine\` + \`LifecycleCeremonyDesigner\`.
   - Queue AI advisor agent call if \`LIFECYCLE_ADVISOR_ALPHA\` enabled.
4. **Publish**
   - Update Studio dashboard caches.
   - Emit lifecycle events.
   - Notify support (Slack/Webhook) when confidence < 0.5 or stage regresses.

---

### 3. Customization Guide

| What | How | Notes |
| --- | --- | --- |
| Stage weights | Update \`modules/lifecycle-core/configs/stage-weights.json\` via bundle config layer | Keep doc changes in sync; re-run unit tests |
| Milestones | Edit \`milestones-catalog.json\`, re-run CLI fixtures | Do not remove IDs used in history |
| Playbooks / ceremonies | Update \`modules/lifecycle-advisor/src/data/*.json\` | Provide localized copy if required |
| Feature flags | Toggle via progressive-delivery library (per tenant) | Document rationale and expiration date |

All overrides must be versioned; operators should never edit compiled JS.

---

### 4. Monitoring & Alerts

- **Dashboards** (Grafana or equivalent):
  - Stage distribution (per tenant / aggregated)
  - Assessment latency (trigger \u2192 completion)
  - Adoption metrics (guidance consumed events)
- **Alerts**:
  - \`LifecycleAssessmentFailed\` (error > 3 in 5m)
  - \`LifecycleConfidenceLow\` (confidence < 0.4 for 2 consecutive runs)
  - \`LifecycleStageChurn\` (stage oscillates >2 times in 7 days)

Alert recipients: lifecycle ops squad + product owner.

---

### 5. Escalation Playbook

1. **Detection gap** (signals missing):
   - Check analytics adapter health.
   - Fall back to questionnaire-only mode.
   - Log incident in lifecycle ops channel.
2. **Inaccurate recommendation**:
   - Capture assessment payload + manual notes.
   - File issue referencing \`LifecycleRecommendationEngine\`.
   - Update playbook JSON + add regression test.
3. **Ceremony assets broken**:
   - Disable \`LifecycleCeremonyDesigner\` output via feature flag.
   - Notify design systems to refresh assets.

---

### 6. Data Handling

- Managed bundle uses Studio storage; no direct access to tenant DBs.
- Retain last 10 assessments per tenant for comparison (configurable).
- Delete assessments on tenant request (flag \`lifecycle_data_retention_days\`).
- Questionnaire answers treated as customer data; store encrypted if possible.

---

### 7. Run / Maintenance Tasks

| Task | Cadence | Owner |
| --- | --- | --- |
| Review staged weight adjustments | Monthly | Lifecycle PM + Ops |
| Refresh milestone catalog with new learnings | Quarterly | Lifecycle strategist |
| Validate CLI + dashboard examples still work | Release cycle | DevRel |
| Audit analytics events coverage | Monthly | Data team |

---

### 8. Tooling References

- \`packages/bundles/lifecycle-managed/\` for managed runtime code.
- \`packages/modules/lifecycle-core/\` for detection logic.
- \`packages/modules/lifecycle-advisor/\` for playbooks and ceremonies.
- Progressive delivery config for lifecycle feature flags.

Maintain this runbook alongside code changes; every bundle release must document operational impact and flag defaults.`}];var i=[{id:"docs.ops.anomaly-detection.goal",title:"Anomaly detection goal",summary:"Why anomaly detection matters for ops stability.",kind:"goal",visibility:"public",route:"/docs/ops/anomaly-detection/goal",tags:["ops","observability"],body:"Ensure anomalies are detected early to protect latency, error rate, and throughput SLAs; keep rollback hooks ready and audits reproducible."},{id:"docs.ops.anomaly-detection.usage",title:"Anomaly detection usage guide",summary:"How to run and consume anomaly detection in operations.",kind:"usage",visibility:"public",route:"/docs/ops/anomaly-detection/usage",tags:["ops","observability"],body:`- Enable tracing middleware; emit latency/error/throughput samples.
- Configure thresholds per capability when bursty traffic exists.
- Wire rollback hook in DeploymentCoordinator for error spikes.
- Export anomaly JSON into incidents; update MetricBaseline post-fix.
- Run chaos/load checks to validate signals within 30s.`},{id:"docs.ops.anomaly-detection.how",title:"Anomaly detection runbook",summary:"Step-by-step runbook for anomaly signals and rollback hooks.",kind:"how",visibility:"public",route:"/docs/ops/anomaly-detection/how",tags:["ops","observability"],body:`# Anomaly Detection Runbook

## 1. Pipeline Overview
1. \`createTracingMiddleware({ onSample })\` emits metric points (latency, errors, throughput).
2. Feed points into \`AnomalyDetector.evaluate\` after enriching with timestamps.
3. On signal, run \`RootCauseAnalyzer.analyze(signal, recentDeployments)\`.
4. Send deduplicated alerts via \`AlertManager\` (cooldown default 60s).

## 2. Configuration
- Baseline: exponential moving average with \`alpha=0.2\`, 10-sample warmup.
- Thresholds (default):
  - Error rate delta 50%
  - Latency delta 35%
  - Throughput drop 40%
- Override per capability when traffic is bursty (e.g., nightly batch jobs).

## 3. Auto-Rollback Hook
- When anomaly type = \`error_rate_spike\` AND \`DeploymentCoordinator\` is active, trigger rollback immediately.
- Record an \`AnomalyEvent\` pointing to \`deploymentId\` for auditability.

## 4. Postmortem Checklist
- Export anomaly JSON (metrics + baseline) into the incident doc.
- Verify \`MetricBaseline\` updated after fix; burn rate should fall < 2x.
- Backfill \`AnomalyEvent.notes\` with RCA outcome for future training.

## 5. Testing
- Use load test harness to inject latency and verify detector emits signals within 30 seconds.
- Chaos suite should simulate upstream outages to ensure throughput-drop detection fires.`},{id:"docs.ops.cost-optimization.goal",title:"Cost optimization goal",summary:"Keep spend predictable and actionable for ops and finance.",kind:"goal",visibility:"public",route:"/docs/ops/cost-optimization/goal",tags:["ops","cost"],body:"Align telemetry, budgets, and rollback levers so cost spikes are detected early, communicated clearly, and mitigated without breaking SLAs."},{id:"docs.ops.cost-optimization.usage",title:"Cost optimization usage guide",summary:"Quick checklist to run cost tracking and optimization.",kind:"usage",visibility:"public",route:"/docs/ops/cost-optimization/usage",tags:["ops","cost"],body:"- Emit `CostSample` via wrapped DB/HTTP clients; include provider/invoice cost.\n- Batch into `OperationCost` every 5m; alert at 80% of monthlyLimit.\n- Nightly run `OptimizationRecommender.generate`; push tickets with evidence.\n- Use regional overrides for `defaultCostModel` when infra prices differ.\n- Send proactive alerts for \xB120% deviations to enterprise tenants."},{id:"docs.ops.cost-optimization.how",title:"Cost optimization runbook",summary:"Step-by-step cost tracking, alerting, and communication.",kind:"how",visibility:"public",route:"/docs/ops/cost-optimization/how",tags:["ops","cost"],body:"# Cost Tracking & Optimization Runbook\n\n## 1. Instrumentation\n- Wrap DB client and HTTP adapters to emit `CostSample`s to `CostTracker.recordSample`.\n- For external APIs, attach provider name + actual invoice cost when available.\n- Persist aggregate rows into `OperationCost` (batch job every 5 minutes).\n\n## 2. Budgets\n- Insert/update `TenantBudget` per workspace.\n- Default alert threshold: 80% of `monthlyLimit`.\n- `BudgetAlertManager.track(summary)` emits Slack + email payloads including breakdown JSON.\n\n## 3. Optimization Suggestions\n- Nightly job reads `OperationCost` and creates `OptimizationSuggestion` records via `OptimizationRecommender.generate`.\n- Auto-file tickets or push to Growth Agent backlog with the evidence (avg reads, compute share, external spend).\n\n## 4. Forecasting\n- Cost model inputs live in `@contractspec/lib.cost-tracking` (`defaultCostModel`). Override per region if infra prices differ.\n- Keep a history of `OperationCost` to render spark lines in Ops Console; highlight slopes > 15% week-over-week.\n\n## 5. Customer Communication\n- For enterprise tenants offer proactive alerts when spend deviates \xB120% from plan.\n- Connect `TenantBudget` alerts to CRM notes so Success teams see when automation saved costs."}];var a=[{id:"docs.ops.profile-settings.goal",title:"Profile settings goal",summary:"Keep identity/profile flows reliable and debuggable.",kind:"goal",visibility:"public",route:"/docs/ops/profile-settings/goal",tags:["ops","auth"],body:"Ensure profile linking/unlinking stays stable across FC+ and SMS flows, with clear monitoring and quick recovery steps."},{id:"docs.ops.profile-settings.usage",title:"Profile settings usage guide",summary:"Quick checklist for profile settings operations.",kind:"usage",visibility:"public",route:"/docs/ops/profile-settings/usage",tags:["ops","auth"],body:"- Verify Better Auth config in `src/lib/auth.ts`; JWKS for FC+.\n- Monitor Sentry spans `profile.*`; PostHog events connection_linked/unlinked.\n- On unlink failures: check `/api/auth/connections/unlink` logs.\n- FC+ issues: validate discovery URL and partner redirects.\n- OTP throttling: confirm SMS service rate limiter is active."},{id:"docs.ops.profile-settings.how",title:"Profile settings runbook",summary:"Detailed runbook for profile/settings operations.",kind:"how",visibility:"public",route:"/docs/ops/profile-settings/how",tags:["ops","auth"],body:`## Runbook \u2013 Profile Settings

### Feature flags / Env

- Better Auth configured in \`src/lib/auth.ts\`
- FC+ envs and JWKS exposed (see specs_france_connect_plus.md)

### Monitoring

- Sentry spans: profile.* ops
- PostHog events: connection_linked / connection_unlinked

### Troubleshooting

- Unlink failures \u2192 check \`/api/auth/connections/unlink\` logs
- FC+ link issues \u2192 verify discovery URL and partner console redirects
- Phone OTP rate limit \u2192 server-side limiter in SMS service`},{id:"docs.ops.progressive-delivery.goal",title:"Progressive delivery goal",summary:"Roll out safely with fast rollback and clear guardrails.",kind:"goal",visibility:"public",route:"/docs/ops/progressive-delivery/goal",tags:["ops","delivery"],body:"Use canary/blue-green with metrics guardrails so deployments can be halted or rolled back before customer impact."},{id:"docs.ops.progressive-delivery.usage",title:"Progressive delivery usage guide",summary:"Quick checklist for canary/blue-green runs.",kind:"usage",visibility:"public",route:"/docs/ops/progressive-delivery/usage",tags:["ops","delivery"],body:"- Register `DeploymentStrategy`; wire telemetry via observability middleware.\n- Define rollback actions (flag toggle/spec revert/infrastructure swap) in `RollbackManager`.\n- Use canary thresholds (err 1%, P99 500ms) or stricter per domain.\n- Pipe stage events to Ops Slack + Ops Console timeline.\n- For blue-green, run smoke tests before swap; freeze old env 24h post-swap."},{id:"docs.ops.progressive-delivery.how",title:"Progressive delivery runbook",summary:"Step-by-step for canary and blue-green rollouts.",kind:"how",visibility:"public",route:"/docs/ops/progressive-delivery/how",tags:["ops","delivery"],body:`# Progressive Delivery Runbook

**Scope**: Contracts runtime deployments running on ContractSpec infrastructure.

## 1. Prerequisites
- Register a \`DeploymentStrategy\` via \`@contractspec/lib.progressive-delivery\`.
- Ensure adapters emit telemetry through \`@contractspec/lib.observability\` (HTTP middleware + custom metrics).
- Define rollback actions (feature flag toggle, spec revert, infrastructure switch) and wire them to \`RollbackManager\`.

## 2. Standard Canary
\`\`\`ts
const strategy: DeploymentStrategy = {
  target: { name: 'billing.createInvoice', version: 7 },
  mode: 'canary',
  thresholds: {
    errorRate: 0.01,
    latencyP99: 500,
    latencyP95: 250,
  },
};
\`\`\`

1. Run \`DeploymentCoordinator.run()\` from CLI or CI job.
2. Watch emitted events (\`stage_started\`, \`stage_passed\`, \`stage_failed\`). Pipe them to Ops Slack and the Ops Console timeline.
3. On failure the coordinator triggers \`RollbackManager.execute\` automatically; the runbook owner only validates post-rollback metrics.

## 3. Blue-Green Swap
- Use mode \`blue-green\` with two stages: \`0%\` warmup and \`100%\` swap.
- Attach smoke tests to \`stage_started\` events before sending any traffic.
- After \`blue_green_swapped\`, freeze the old environment for 24h before decommissioning.

## 4. Guardrails
- Default thresholds: error rate 1%, P99 500ms, throughput drop 40%.
- Add custom evaluator for domain-specific metrics:
\`\`\`ts
thresholds: {
  errorRate: 0.005,
  customEvaluator: (metrics) => metrics.throughput > 200,
}
\`\`\`

## 5. Incident Hooks
- \`Deployment\`, \`DeploymentStage\`, and \`RollbackEvent\` tables store the full history.
- Tag rollbacks with incident ID to keep Ops Console synchronized.
- Auto-resolve the incident once \`status === 'completed'\` and SLO burn rate returns < 2x.`}];var n=[{id:"docs.ops.slo-management.goal",title:"SLO management goal",summary:"Keep availability/latency SLOs observable and enforceable.",kind:"goal",visibility:"public",route:"/docs/ops/slo-management/goal",tags:["ops","slo"],body:"Ensure every capability has a versioned SLO with alerts, burn-rate workflows, and incident cross-links so rollbacks are justified and auditable."},{id:"docs.ops.slo-management.usage",title:"SLO management usage guide",summary:"Quick checklist for defining and operating SLOs.",kind:"usage",visibility:"public",route:"/docs/ops/slo-management/usage",tags:["ops","slo"],body:"- Define `SLODefinition` per capability; tag tenant/tier for filtering.\n- Deploy `SLOMonitor`; pipe incidents to PagerDuty + Ops Slack.\n- Fast burn 14x -> page; slow burn 6x -> create ticket.\n- Use `SLOSnapshot` for dashboards; include deployment IDs in incidents.\n- Reset or advance error budgets after resolution when appropriate."},{id:"docs.ops.slo-management.how",title:"SLO management runbook",summary:"Detailed runbook for SLO lifecycle and incident handling.",kind:"how",visibility:"public",route:"/docs/ops/slo-management/how",tags:["ops","slo"],body:`# SLO Management Runbook

## 1. Definition Lifecycle
1. Create an entry in \`SLODefinition\` via migration or the Ops Console.
2. Map capabilities to specs: e.g. \`orders.create\` availability 99.9%, P99 500ms.
3. Store tags (\`tenant:enterprise\`, \`tier:mission-critical\`) for filtering dashboards.

## 2. Monitoring
- Deploy \`SLOMonitor\` alongside each critical service.
- Pipe \`IncidentManager.createIncident\` into PagerDuty + Ops Slack.
- Fast burn threshold (14x) -> page immediately; slow burn (6x) -> create ticket.

\`\`\`ts
const monitor = new SLOMonitor({
  definition,
  incidentManager,
});
monitor.recordWindow({ good, bad, latencyP99, latencyP95 });
\`\`\`

## 3. Error Budget Workflow
- \`ErrorBudget\` rows track rolling windows (default 7d).
- Add runbooks for "burn > 50%" (freeze deploys) and "burn > 80%" (roll back latest change).
- Use \`SLOSnapshot\` to regenerate dashboards (no warehouse needed).

## 4. Incident Triage
- Every incident includes snapshot JSON (availability, latency, burn rate).
- Attach deployment IDs from \`Deployment\` table to cross-link incidents & rollouts.
- After resolution set \`acknowledgedAt\` and reset error budget (new period) if needed.

## 5. Reporting
- Weekly summary = AVG burn rate, # incidents, # auto-rollbacks triggered by SLO monitor.
- Feed \`SLOIncident\` into Growth Agent for customer comms when SLAs impact tenants.`},{id:"docs.ops.tenant-customization.goal",title:"Tenant customization goal",summary:"Let tenants customize overlays/workflows safely with audit and rollback.",kind:"goal",visibility:"public",route:"/docs/ops/tenant-customization/goal",tags:["ops","tenant"],body:"Provide controlled overlays and workflow extensions per tenant with signed assets, versioning, and observability so UI/flow tweaks stay safe and reversible."},{id:"docs.ops.tenant-customization.usage",title:"Tenant customization usage guide",summary:"Quick steps for onboarding a tenant customization.",kind:"usage",visibility:"public",route:"/docs/ops/tenant-customization/usage",tags:["ops","tenant"],body:"- Capture fields to hide/rename and workflow deviations.\n- Build overlay in overlay editor; sign JSON with tenant key.\n- Persist in `Overlay` table; register via `OverlayRegistry` or admin API.\n- Compose `WorkflowExtension`; store alongside overlay metadata.\n- Run sandbox smoke tests; ensure audit logs capture overlay events."},{id:"docs.ops.tenant-customization.how",title:"Tenant customization runbook",summary:"Detailed runbook for overlays and workflow extensions.",kind:"how",visibility:"public",route:"/docs/ops/tenant-customization/how",tags:["ops","tenant"],body:`# Tenant Customization Runbook

Phase 4 introduces managed overlays and workflow extensions. Ops teams should follow this flow when onboarding a tenant that requests UI tweaks or workflow changes.

1. **Collect requirements**
   - List fields to hide/show or rename.
   - Capture workflow deviations (extra approvals, reordered steps).
2. **Create overlay**
   - Use the overlay editor app (\`packages/apps/overlay-editor\`) to draft the overlay.
   - Export JSON and sign with the tenant\u2019s registered key (store keys in \`OverlaySigningKey\`).
3. **Register overlay**
   - Persist the signed payload in the \`Overlay\` table via provisioning scripts.
   - Register with \`OverlayRegistry\` at boot or push via admin API.
4. **Compose workflows**
   - Define a \`WorkflowExtension\` for the tenant (see \`@contractspec/lib.workflow-composer\` docs).
   - Store extension config alongside overlay metadata.
5. **Verify**
   - Run smoke tests in the tenant sandbox.
   - Ensure audit logs capture overlay application events.
6. **Monitor**
   - Use behavior tracking dashboards to confirm adoption or trigger cleanup when overlays become obsolete.

---

## Lifecycle customization

Managed tenants can override lifecycle playbooks without touching database schemas:

1. **Stage definitions**
   - Add overrides in \`packages/modules/lifecycle-core/src/data/stage-weights.json\`.
   - Keep the canonical doc (\`docs/product/lifecycle-stages.md\`) in sync with any new stage or axis.
2. **Milestones**
   - Extend \`milestones-catalog.json\` with tenant-specific IDs. Prefix with the tenant or vertical slug (e.g., \`tenant-acme-stage3-retention\`).
   - Use feature flag \`lifecycle_managed_service\` to gate access while new milestones are validated.
3. **Playbooks & ceremonies**
   - Customize \`packages/modules/lifecycle-advisor/src/data/stage-playbooks.ts\`.
   - Use Studio\u2019s localization hooks to translate ceremony copy for low-tech flows.
4. **Event routing**
   - Subscribe to \`LifecycleKpiPipeline\` events (see \`@contractspec/bundle.lifecycle-managed\`) to forward stage changes into tenant-specific analytics.

All lifecycle overrides must be versioned alongside the tenant\u2019s overlay and workflow extensions so ops can rollback safely.`}];var r=[{id:"docs.ops.index",title:"Operations docs index",summary:"Entry point for operations runbooks and guides.",kind:"goal",visibility:"public",route:"/docs/ops",tags:["ops"],body:`# Operations

Browse runbooks and guides for ops workflows:
- Anomaly detection (goal/usage/how)
- Cost optimization (goal/usage/how)
- Lifecycle operations (goal/usage/how)
- Profile settings (goal/usage/how)
- Progressive delivery (goal/usage/how)
- SLO management (goal/usage/how)
- Tenant customization (goal/usage/how)`}];var C=[...r,...i,...s,...a,...n];export{C as opsDocBlocks};
