// Isolated local preview fixture provider for the unified adaptive shell.
// Follow-on OpenSpec changes replace this module with live server RPC contracts.

///|
/// Canned SDLC workflow presets and custom diagram option.
#derive(Eq, Debug)
pub(all) enum WorkflowPreset {
  OpenSpecSdlcV1
  RegulatedBpmnV1
  LightweightRfcV1
  CustomProjectFile
}

///|
pub extend WorkflowPreset with Eq::{equal, not_equal}

///|
pub extend WorkflowPreset with @debug.Debug::{to_repr}

///|
/// Returns all selectable workflow presets in display order.
pub fn WorkflowPreset::all() -> ReadOnlyArray[WorkflowPreset] {
  [OpenSpecSdlcV1, RegulatedBpmnV1, LightweightRfcV1, CustomProjectFile]
}

///|
/// Returns the stable machine identifier of a workflow preset.
pub fn WorkflowPreset::id(self : WorkflowPreset) -> String {
  match self {
    OpenSpecSdlcV1 => "openspec-sdlc-v1"
    RegulatedBpmnV1 => "regulated-bpmn-v1"
    LightweightRfcV1 => "lightweight-rfc-v1"
    CustomProjectFile => "custom-file"
  }
}

///|
/// Returns the display title of a workflow preset.
pub fn WorkflowPreset::title(self : WorkflowPreset) -> String {
  match self {
    OpenSpecSdlcV1 => "OpenSpec SDLC v1"
    RegulatedBpmnV1 => "Regulated / PCI BPMN 2.0"
    LightweightRfcV1 => "Lightweight RFC -> Ship"
    CustomProjectFile => "Custom Project Diagram"
  }
}

///|
/// Returns the status badge text for a workflow preset.
pub fn WorkflowPreset::badge(self : WorkflowPreset) -> String {
  match self {
    OpenSpecSdlcV1 => "Canned Default"
    RegulatedBpmnV1 | LightweightRfcV1 => "Canned Preset"
    CustomProjectFile => "Project File"
  }
}

///|
/// Returns the diagram notation label for a workflow preset.
pub fn WorkflowPreset::diagram_kind(self : WorkflowPreset) -> String {
  match self {
    OpenSpecSdlcV1 | LightweightRfcV1 => "Mermaid stateDiagram-v2"
    RegulatedBpmnV1 => "BPMN 2.0 XML"
    CustomProjectFile => "Mermaid / BPMN 2.0"
  }
}

///|
/// Returns a short description of a workflow preset.
pub fn WorkflowPreset::summary(self : WorkflowPreset) -> String {
  match self {
    OpenSpecSdlcV1 =>
      "Explore -> Propose -> Implement -> Verify Gate -> Archived. Selected when openspec/ exists."
    RegulatedBpmnV1 =>
      "Adds a mandatory Security and Data Dictionary sign-off gateway before Implementation."
    LightweightRfcV1 =>
      "Four-stage flow (Explore -> Propose -> Implement -> Archived) for personal workspaces or spikes."
    CustomProjectFile =>
      "Repository .mmd or .bpmn diagram rendered with moonrockz/diagrams.mbt."
  }
}

///|
/// A typed stage in the SDLC workflow state machine.
#derive(Eq, Debug)
pub(all) enum StageId {
  Explore
  Propose
  SecurityGate
  Implement
  VerifyGate
  Archived
}

///|
pub extend StageId with Eq::{equal, not_equal}

///|
pub extend StageId with @debug.Debug::{to_repr}

///|
/// Returns the display label of a workflow stage.
pub fn StageId::label(self : StageId) -> String {
  match self {
    Explore => "Explore"
    Propose => "Propose"
    SecurityGate => "Security Gate"
    Implement => "Implement"
    VerifyGate => "Verify Gate"
    Archived => "Archived"
  }
}

///|
/// Returns the stable machine key of a workflow stage.
pub fn StageId::key(self : StageId) -> String {
  match self {
    Explore => "explore"
    Propose => "propose"
    SecurityGate => "security"
    Implement => "implement"
    VerifyGate => "verify"
    Archived => "archived"
  }
}

///|
/// Reports whether this stage acts as a verification or security gate.
pub fn StageId::is_gate(self : StageId) -> Bool {
  self is (SecurityGate | VerifyGate)
}

///|
/// Required artifact verification status.
#derive(Eq, Debug)
pub(all) enum ArtifactStatus {
  Clean
  Warning
  Missing
}

///|
pub extend ArtifactStatus with Eq::{equal, not_equal}

///|
pub extend ArtifactStatus with @debug.Debug::{to_repr}

///|
/// Typed artifact file slot attached to a workflow item.
#derive(Eq, Debug)
pub(all) enum ArtifactKind {
  ProposalMd
  DesignMd
  SpecMd
  TasksMd
  Adr0015
  Adr0014
  ExploreMd
  SpecsSynced
}

///|
pub extend ArtifactKind with Eq::{equal, not_equal}

///|
pub extend ArtifactKind with @debug.Debug::{to_repr}

///|
/// Returns the display name of an artifact slot.
pub fn ArtifactKind::label(self : ArtifactKind) -> String {
  match self {
    ProposalMd => "proposal.md"
    DesignMd => "design.md"
    SpecMd => "spec.md"
    TasksMd => "tasks.md"
    Adr0015 => "ADR-0015"
    Adr0014 => "ADR-0014"
    ExploreMd => "explore.md"
    SpecsSynced => "specs synced"
  }
}

///|
/// Adapter source that owns a workflow item.
#derive(Eq, Debug)
pub(all) enum WorkflowAdapter {
  OpenSpec
  CompanionOkf
  NativeOkf
}

///|
pub extend WorkflowAdapter with Eq::{equal, not_equal}

///|
pub extend WorkflowAdapter with @debug.Debug::{to_repr}

///|
/// Returns the display label of a workflow adapter.
pub fn WorkflowAdapter::label(self : WorkflowAdapter) -> String {
  match self {
    OpenSpec => "OpenSpec"
    CompanionOkf => "Companion OKF"
    NativeOkf => "Native OKF"
  }
}

///|
/// Whether a workflow item tracks a top-level Intent or an OpenSpec Change.
#derive(Eq, Debug)
pub(all) enum WorkflowItemKind {
  Intent
  Change
}

///|
pub extend WorkflowItemKind with Eq::{equal, not_equal}

///|
pub extend WorkflowItemKind with @debug.Debug::{to_repr}

///|
/// Kind of document inside the Review reading packet.
#derive(Eq, Debug)
pub(all) enum DocKind {
  ProposalDoc
  DesignDoc
  SpecDeltaDoc
  AdrDoc
  MountedKbDoc
  TasksDoc
}

///|
pub extend DocKind with Eq::{equal, not_equal}

///|
pub extend DocKind with @debug.Debug::{to_repr}

///|
/// Returns the display label of a reading packet document kind.
pub fn DocKind::label(self : DocKind) -> String {
  match self {
    ProposalDoc => "Proposal"
    DesignDoc => "Design"
    SpecDeltaDoc => "Spec Delta"
    AdrDoc => "ADR"
    MountedKbDoc => "Mounted KB"
    TasksDoc => "Tasks"
  }
}

///|
/// Policy or artifact source of a transition gate check.
#derive(Eq, Debug)
pub(all) enum GateSource {
  Artifact
  OkfGraph
  Ears
  RegoAndDict
  DocumentScorer
  InputContract
  TasksCheck
  OkfAndRego
  Terminal
}

///|
pub extend GateSource with Eq::{equal, not_equal}

///|
pub extend GateSource with @debug.Debug::{to_repr}

///|
/// Returns the display label of a gate check source.
pub fn GateSource::label(self : GateSource) -> String {
  match self {
    Artifact => "Artifact"
    OkfGraph => "OKF Graph"
    Ears => "EARS"
    RegoAndDict => "Rego + Dict"
    DocumentScorer => "DocumentScorer"
    InputContract => "Input Contract"
    TasksCheck => "Tasks"
    OkfAndRego => "OKF + Rego"
    Terminal => "Terminal"
  }
}

///|
/// Recorded editorial review outcome for the active workflow item.
#derive(Eq, Debug)
pub(all) enum ReviewDecision {
  Pending
  Approved(StageId)
  ChangesRequested(StageId)
}

///|
pub extend ReviewDecision with Eq::{equal, not_equal}

///|
pub extend ReviewDecision with @debug.Debug::{to_repr}

///|
/// Returns display text for a recorded review decision, if any.
pub fn ReviewDecision::banner(self : ReviewDecision) -> String? {
  match self {
    Pending => None
    Approved(stage) => Some("Approved -> \{stage.label()}")
    ChangesRequested(stage) => Some("Sent Back -> \{stage.label()}")
  }
}

///|
/// Source format displayed inside the Workflow Studio editor.
#derive(Eq, Debug)
pub(all) enum StudioFormat {
  Mermaid
  BpmnXml
  ArtifactYaml
}

///|
pub extend StudioFormat with Eq::{equal, not_equal}

///|
pub extend StudioFormat with @debug.Debug::{to_repr}

///|
/// Diagram rendering style inside the Workflow Studio preview.
#derive(Eq, Debug)
pub(all) enum StudioDiagramKind {
  MermaidState
  BpmnFlow
}

///|
pub extend StudioDiagramKind with Eq::{equal, not_equal}

///|
pub extend StudioDiagramKind with @debug.Debug::{to_repr}

///|
/// Active tab of the Review perspective Reading Companion.
#derive(Eq, Debug)
pub(all) enum ReviewTab {
  ConceptPeek
  ScoreReview
}

///|
pub extend ReviewTab with Eq::{equal, not_equal}

///|
pub extend ReviewTab with @debug.Debug::{to_repr}

///|
/// Preview RDF Data Dictionary concepts referenced in prose and the Knowledge workbench.
#derive(Eq, Debug)
pub(all) enum ConceptId {
  Pan
  MaskedPan
  PaymentMethod
  DeprecatedCc
  AuditEvent
  IdempotencyKey
  LocalConcept(LocalConceptId)
}

///|
pub extend ConceptId with Eq::{equal, not_equal}

///|
pub extend ConceptId with @debug.Debug::{to_repr}

///|
/// Optional extra artifact requirement that can be toggled onto a stage in
/// Workflow Studio.
#derive(Eq, Debug)
pub(all) enum ExtraArtifactInput {
  ThreatModel
  DictionaryAudit
  RunbookSignoff
}

///|
pub extend ExtraArtifactInput with Eq::{equal, not_equal}

///|
pub extend ExtraArtifactInput with @debug.Debug::{to_repr}

///|
/// Returns the display label of an optional stage input artifact.
pub fn ExtraArtifactInput::label(self : ExtraArtifactInput) -> String {
  match self {
    ThreatModel => "Threat Model"
    DictionaryAudit => "Data Dictionary Audit"
    RunbookSignoff => "Runbook Sign-off"
  }
}

///|
/// An artifact slot attached to a workflow item.
#derive(Eq, Debug)
pub struct WorkflowArtifact {
  kind : ArtifactKind
  status : ArtifactStatus
}

///|
pub extend WorkflowArtifact with Eq::{equal, not_equal}

///|
pub extend WorkflowArtifact with @debug.Debug::{to_repr}

///|
/// A workflow item flowing through the SDLC state machine.
#derive(Eq, Debug)
pub struct WorkflowItem {
  id : WorkflowItemId
  title : String
  kind : WorkflowItemKind
  adapter : WorkflowAdapter
  intent : String
  stage : StageId
  score : Score
  progress : TaskProgress
  warnings : WarningCount
  artifacts : ReadOnlyArray[WorkflowArtifact]
}

///|
pub extend WorkflowItem with Eq::{equal, not_equal}

///|
pub extend WorkflowItem with @debug.Debug::{to_repr}

///|
/// Returns the letter grade of this workflow item's scorecard score.
pub fn WorkflowItem::grade(self : WorkflowItem) -> Grade {
  self.score.grade()
}

///|
/// Contract describing a state's required inputs, expected outputs, and edges.
#derive(Eq, Debug)
pub struct StageSpec {
  id : StageId
  inputs : ReadOnlyArray[String]
  outputs : ReadOnlyArray[String]
  next : StageId?
  back : StageId?
}

///|
pub extend StageSpec with Eq::{equal, not_equal}

///|
pub extend StageSpec with @debug.Debug::{to_repr}

///|
/// A single evaluated transition guard check.
#derive(Eq, Debug)
pub struct GateCheck {
  passed : Bool
  label : String
  source : GateSource
}

///|
pub extend GateCheck with Eq::{equal, not_equal}

///|
pub extend GateCheck with @debug.Debug::{to_repr}

///|
/// The transition gate evaluation for a workflow item.
#derive(Eq, Debug)
pub struct GateEvaluation {
  target : StageId?
  checks : ReadOnlyArray[GateCheck]
}

///|
pub extend GateEvaluation with Eq::{equal, not_equal}

///|
pub extend GateEvaluation with @debug.Debug::{to_repr}

///|
/// Reports whether every gate check in this evaluation passed.
pub fn GateEvaluation::all_passed(self : GateEvaluation) -> Bool {
  self.checks.iter().all(check => check.passed)
}

///|
/// Returns the count of gate checks that have not passed.
pub fn GateEvaluation::open_count(self : GateEvaluation) -> Int32 {
  self.checks.iter().filter(check => !check.passed).count()
}

///|
/// Backlink connecting a dictionary concept to a workflow item and Review document.
#derive(Eq, Debug)
pub struct ConceptBacklink {
  item : WorkflowItemId
  doc : ReviewDocId
  label : String
}

///|
pub extend ConceptBacklink with Eq::{equal, not_equal}

///|
pub extend ConceptBacklink with @debug.Debug::{to_repr}

///|
/// Lifecycle status of a SKOS dictionary concept.
#derive(Eq, Debug)
pub(all) enum ConceptStatus {
  ActiveConcept
  DeprecatedConcept(replaced_by~ : ConceptId)
}

///|
pub extend ConceptStatus with Eq::{equal, not_equal}

///|
pub extend ConceptStatus with @debug.Debug::{to_repr}

///|
/// Reports whether a concept status marks the term as deprecated.
pub fn ConceptStatus::is_deprecated(self : ConceptStatus) -> Bool {
  match self {
    ActiveConcept => false
    DeprecatedConcept(..) => true
  }
}

///|
/// An RDF concept displayed in Review's Concept Peek and the Knowledge Data Dictionary.
#derive(Eq, Debug)
pub struct ConceptCard {
  id : ConceptId
  label : ConceptLabel
  status : ConceptStatus
  iri : ConceptIri
  graph : NamedGraph
  alt_labels : ReadOnlyArray[String]
  broader : ReadOnlyArray[ConceptId]
  narrower : ReadOnlyArray[ConceptId]
  related : ReadOnlyArray[ConceptId]
  shacl : String
  definition : ConceptDefinition
  backlinks : ReadOnlyArray[ConceptBacklink]
}

///|
pub extend ConceptCard with Eq::{equal, not_equal}

///|
pub extend ConceptCard with @debug.Debug::{to_repr}

///|
/// Reports whether this concept card is deprecated.
pub fn ConceptCard::is_deprecated(self : ConceptCard) -> Bool {
  self.status.is_deprecated()
}

///|
/// Returns the access policy derived from this concept's named graph.
pub fn ConceptCard::access(self : ConceptCard) -> GraphAccess {
  self.graph.access()
}

///|
/// Returns the formatted named graph line for display and Turtle headers.
pub fn ConceptCard::graph_display(self : ConceptCard) -> String {
  match self.status {
    DeprecatedConcept(..) => " · skos:altLabel (deprecated)"
    ActiveConcept => self.graph.uri_label()
  }
}

///|
/// Identifier of a Prose Term Audit finding in the Data Dictionary workbench.
#derive(Eq, Debug)
pub(all) enum TermAuditId {
  AuditDeprecatedCc
  AuditUnlinkedMaskedPan
  AuditUnlinkedIdempotency
}

///|
pub extend TermAuditId with Eq::{equal, not_equal}

///|
pub extend TermAuditId with @debug.Debug::{to_repr}

///|
/// Classification of a Prose Term Audit item.
#derive(Eq, Debug)
pub(all) enum AuditKind {
  DeprecatedSynonym(target~ : ConceptId)
  UnlinkedMention(target~ : ConceptId)
}

///|
pub extend AuditKind with Eq::{equal, not_equal}

///|
pub extend AuditKind with @debug.Debug::{to_repr}

///|
/// Lifecycle status of a Prose Term Audit finding.
#derive(Eq, Debug)
pub(all) enum AuditStatus {
  OpenAudit
  ResolvedAudit
}

///|
pub extend AuditStatus with Eq::{equal, not_equal}

///|
pub extend AuditStatus with @debug.Debug::{to_repr}

///|
/// Reports whether an audit finding has been resolved.
pub fn AuditStatus::is_resolved(self : AuditStatus) -> Bool {
  match self {
    OpenAudit => false
    ResolvedAudit => true
  }
}

///|
/// One Prose Term Audit item surfaced in the Data Dictionary companion.
#derive(Eq, Debug)
pub struct TermAuditItem {
  id : TermAuditId
  mention : String
  location : String
  item : WorkflowItemId
  doc : ReviewDocId
  kind : AuditKind
  status : AuditStatus
}

///|
pub extend TermAuditItem with Eq::{equal, not_equal}

///|
pub extend TermAuditItem with @debug.Debug::{to_repr}

///|
/// Identifier of a preview OKF Knowledge Base document.
#derive(Eq, Debug)
pub(all) enum KbDocId {
  KbPciRunbook
  KbAdrMasking
  KbLedgerSpec
  KbSddPolicy
}

///|
pub extend KbDocId with Eq::{equal, not_equal}

///|
pub extend KbDocId with @debug.Debug::{to_repr}

///|
/// Classification of a Knowledge Base document.
#derive(Eq, Debug)
pub(all) enum KbDocKind {
  KbRunbook
  KbAdr
  KbSpec
  KbPolicy
}

///|
pub extend KbDocKind with Eq::{equal, not_equal}

///|
pub extend KbDocKind with @debug.Debug::{to_repr}

///|
/// Returns the short display label of a Knowledge Base document kind.
pub fn KbDocKind::label(self : KbDocKind) -> String {
  match self {
    KbRunbook => "Runbook"
    KbAdr => "ADR"
    KbSpec => "Spec"
    KbPolicy => "Policy"
  }
}

///|
/// One local or mounted OKF Knowledge Base document.
#derive(Eq, Debug)
pub struct KbDocument {
  id : KbDocId
  title : String
  path : String
  kind : KbDocKind
  source : KbSource
  trust_tier : String
  summary : String
  paragraphs : ReadOnlyArray[ReadOnlyArray[ProseSpan]]
  source_lines : ReadOnlyArray[String]
  links : ReadOnlyArray[KbDocId]
  concepts : ReadOnlyArray[ConceptId]
}

///|
pub extend KbDocument with Eq::{equal, not_equal}

///|
pub extend KbDocument with @debug.Debug::{to_repr}

///|
/// A document inside the Review narrative reading packet.
#derive(Eq, Debug)
pub struct ReadDoc {
  id : ReviewDocId
  step : StepNumber
  title : String
  kind : DocKind
  file : String
  score : Score
  read : Bool
}

///|
pub extend ReadDoc with Eq::{equal, not_equal}

///|
pub extend ReadDoc with @debug.Debug::{to_repr}

///|
/// Inline segment of prose or requirement text shared across Review modes.
#derive(Eq, Debug)
pub(all) enum ProseSpan {
  Plain(String)
  Keyword(String)
  Term(ConceptId, String, deprecated~ : Bool)
}

///|
pub extend ProseSpan with Eq::{equal, not_equal}

///|
pub extend ProseSpan with @debug.Debug::{to_repr}

///|
/// Plain text of one prose span.
pub fn ProseSpan::text(self : ProseSpan) -> String {
  match self {
    Plain(s) | Keyword(s) | Term(_, s, ..) => s
  }
}

///|
/// Renders a sequence of prose spans into plain text.
pub fn spans_plain_text(spans : ReadOnlyArray[ProseSpan]) -> String {
  let buf = StringBuilder()
  for span in spans {
    buf.write_string(span.text())
  }
  buf.to_string()
}

///|
/// Whether a requirement delta clause is newly added or modifies an earlier clause.
#derive(Eq, Debug)
pub(all) enum ClauseChange {
  Added
  Modified(previous~ : String)
}

///|
pub extend ClauseChange with Eq::{equal, not_equal}

///|
pub extend ClauseChange with @debug.Debug::{to_repr}

///|
pub fn ClauseChange::label(self : ClauseChange) -> String {
  match self {
    Added => "ADDED"
    Modified(..) => "MODIFIED"
  }
}

///|
/// Closed set of EARS requirement pattern classifications.
#derive(Eq, Debug)
pub(all) enum EarsKind {
  Ubiquitous
  EventDriven
  StateDriven
  UnwantedBehavior
}

///|
pub extend EarsKind with Eq::{equal, not_equal}

///|
pub extend EarsKind with @debug.Debug::{to_repr}

///|
pub fn EarsKind::label(self : EarsKind) -> String {
  match self {
    Ubiquitous => "EARS: Ubiquitous"
    EventDriven => "EARS: Event-Driven"
    StateDriven => "EARS: State-Driven"
    UnwantedBehavior => "EARS: Unwanted Behavior"
  }
}

///|
/// Whether a requirement clause carries an active or resolved policy finding banner.
#derive(Eq, Debug)
pub(all) enum ClauseFinding {
  NoFinding
  DeprecatedTermOpen
  DeprecatedTermResolved
}

///|
pub extend ClauseFinding with Eq::{equal, not_equal}

///|
pub extend ClauseFinding with @debug.Debug::{to_repr}

///|
/// One structured EARS requirement delta shared by Structured, Preview, and Source modes.
#derive(Eq, Debug)
pub struct RequirementClause {
  id : String
  change : ClauseChange
  ears_kind : EarsKind
  spans : ReadOnlyArray[ProseSpan]
  finding : ClauseFinding
}

///|
pub extend RequirementClause with Eq::{equal, not_equal}

///|
pub extend RequirementClause with @debug.Debug::{to_repr}

///|
/// Plain requirement text projected directly from this clause's shared spans.
pub fn RequirementClause::plain_text(self : RequirementClause) -> String {
  spans_plain_text(self.spans)
}

///|
/// Per-document reading body for Structured, Preview, and Source modes.
#derive(Eq, Debug)
pub struct DocContent {
  summary : String
  preview_paragraphs : ReadOnlyArray[ReadOnlyArray[ProseSpan]]
  clauses : ReadOnlyArray[RequirementClause]
  source_lines : ReadOnlyArray[String]
}

///|
pub extend DocContent with Eq::{equal, not_equal}

///|
pub extend DocContent with @debug.Debug::{to_repr}

///|
/// Pure local preview state scoped to one open `@app.Project`.
/// Fields are private so every transition preserves invariants.
#derive(Eq, Debug)
pub struct MockupWorkspace {
  priv preset : WorkflowPreset
  priv min_scorecard : Score
  priv policy_floor : Score
  priv has_security_gate : Bool
  priv include_verify : Bool
  priv studio_diagram : StudioDiagramKind
  priv studio_format : StudioFormat
  priv studio_stage : StageId
  priv extra_inputs : ReadOnlyArray[(StageId, ExtraArtifactInput)]
  priv studio_drafts : ReadOnlyArray[(StudioFormat, String)]
  priv studio_parse_error : String?
  priv selected_item : WorkflowItemId
  priv inspector_open : Bool
  priv items : ReadOnlyArray[WorkflowItem]
  priv docs_by_item : ReadOnlyArray[(WorkflowItemId, ReadOnlyArray[ReadDoc])]
  priv active_concept : ConceptId
  priv review_tab : ReviewTab
  priv review_decisions : ReadOnlyArray[(WorkflowItemId, ReviewDecision)]
  priv local_concepts : ReadOnlyArray[ConceptCard]
  priv accepted_audits : ReadOnlyArray[TermAuditId]
}

///|
pub extend MockupWorkspace with Eq::{equal, not_equal}

///|
pub extend MockupWorkspace with @debug.Debug::{to_repr}

///|
fn seed_progress(done : Int32, total : Int32) -> TaskProgress {
  try! TaskProgress(done, total)
}

///|
fn seed_warnings(count : Int32) -> WarningCount {
  try! WarningCount(count)
}

///|
fn seed_step(value : Int32) -> StepNumber {
  try! StepNumber(value)
}

///|
/// Builds the deterministic seed preview workspace for any real open project.
pub fn MockupWorkspace::seed() -> MockupWorkspace {
  {
    preset: OpenSpecSdlcV1,
    min_scorecard: Score::clamped(85),
    policy_floor: Score::clamped(85),
    has_security_gate: false,
    include_verify: true,
    studio_diagram: MermaidState,
    studio_format: Mermaid,
    studio_stage: Implement,
    extra_inputs: [],
    studio_drafts: [],
    studio_parse_error: None,
    selected_item: ChgMask,
    inspector_open: false,
    items: [
      {
        id: ChgMask,
        title: "mask-card-numbers-in-logs",
        kind: Change,
        adapter: OpenSpec,
        intent: "INT-004 · Zero Raw PAN",
        stage: Implement,
        score: Score::clamped(83),
        progress: seed_progress(3, 5),
        warnings: seed_warnings(2),
        artifacts: [
          { kind: ProposalMd, status: Clean, },
          { kind: DesignMd, status: Clean, },
          { kind: SpecMd, status: Warning, },
          { kind: TasksMd, status: Warning, },
          { kind: Adr0015, status: Clean, },
        ],
      },
      {
        id: ChgRefund,
        title: "idempotent-refund-posting",
        kind: Change,
        adapter: OpenSpec,
        intent: "INT-007 · Exactly-Once",
        stage: VerifyGate,
        score: Score::clamped(94),
        progress: seed_progress(6, 6),
        warnings: WarningCount::zero(),
        artifacts: [
          { kind: ProposalMd, status: Clean, },
          { kind: DesignMd, status: Clean, },
          { kind: SpecMd, status: Clean, },
          { kind: TasksMd, status: Clean, },
        ],
      },
      {
        id: Int3ds,
        title: "3ds2-challenge-orchestration",
        kind: Intent,
        adapter: CompanionOkf,
        intent: "INT-009 · PSD2 SCA",
        stage: Propose,
        score: Score::clamped(86),
        progress: seed_progress(0, 4),
        warnings: WarningCount::zero(),
        artifacts: [
          { kind: ProposalMd, status: Clean, },
          { kind: DesignMd, status: Clean, },
          { kind: SpecMd, status: Missing, },
          { kind: TasksMd, status: Missing, },
        ],
      },
      {
        id: IntBmad,
        title: "q3-bmad-migration-spike",
        kind: Intent,
        adapter: NativeOkf,
        intent: "INT-011 · SDD Portability",
        stage: Explore,
        score: Score::clamped(74),
        progress: seed_progress(0, 0),
        warnings: WarningCount::zero(),
        artifacts: [{ kind: ExploreMd, status: Clean, }],
      },
      {
        id: ChgVault,
        title: "pci-vault-bootstrap",
        kind: Change,
        adapter: OpenSpec,
        intent: "INT-004 · Zero Raw PAN",
        stage: Archived,
        score: Score::clamped(96),
        progress: seed_progress(8, 8),
        warnings: WarningCount::zero(),
        artifacts: [
          { kind: SpecsSynced, status: Clean, },
          { kind: Adr0014, status: Clean, },
        ],
      },
    ],
    docs_by_item: [
      (
        ChgMask,
        [
          {
            id: Proposal,
            step: seed_step(1),
            title: "Proposal: Why & Scope",
            kind: ProposalDoc,
            file: "openspec/changes/mask-card-numbers-in-logs/proposal.md",
            score: Score::clamped(92),
            read: true,
          },
          {
            id: Design,
            step: seed_step(2),
            title: "Design: Token Boundary",
            kind: DesignDoc,
            file: "openspec/changes/mask-card-numbers-in-logs/design.md",
            score: Score::clamped(88),
            read: true,
          },
          {
            id: Spec,
            step: seed_step(3),
            title: "Spec Delta: Log Redaction (EARS)",
            kind: SpecDeltaDoc,
            file: "openspec/changes/mask-card-numbers-in-logs/specs/logging/spec.md",
            score: Score::clamped(74),
            read: false,
          },
          {
            id: Adr,
            step: seed_step(4),
            title: "ADR-0015: Tokenize Before Log",
            kind: AdrDoc,
            file: "intent/decisions/ADR-0015-tokenize-before-log.md",
            score: Score::clamped(95),
            read: false,
          },
          {
            id: Kb,
            step: seed_step(5),
            title: "KB: PCI Logging Runbook",
            kind: MountedKbDoc,
            file: "mounted://platform-runbooks/pci-logging.md",
            score: Score::clamped(91),
            read: false,
          },
          {
            id: Tasks,
            step: seed_step(6),
            title: "Tasks & Verification",
            kind: TasksDoc,
            file: "openspec/changes/mask-card-numbers-in-logs/tasks.md",
            score: Score::clamped(82),
            read: false,
          },
        ],
      ),
      (
        ChgRefund,
        [
          {
            id: Proposal,
            step: seed_step(1),
            title: "Proposal: Idempotent Refund Posting",
            kind: ProposalDoc,
            file: "openspec/changes/idempotent-refund-posting/proposal.md",
            score: Score::clamped(95),
            read: true,
          },
          {
            id: Design,
            step: seed_step(2),
            title: "Design: Ledger Deduplication Key",
            kind: DesignDoc,
            file: "openspec/changes/idempotent-refund-posting/design.md",
            score: Score::clamped(94),
            read: true,
          },
          {
            id: Spec,
            step: seed_step(3),
            title: "Spec Delta: Refund Ledger (EARS)",
            kind: SpecDeltaDoc,
            file: "openspec/changes/idempotent-refund-posting/specs/refunds/spec.md",
            score: Score::clamped(94),
            read: true,
          },
          {
            id: Adr,
            step: seed_step(4),
            title: "ADR-0018: Deterministic Refund Keys",
            kind: AdrDoc,
            file: "intent/decisions/ADR-0018-deterministic-refund-keys.md",
            score: Score::clamped(93),
            read: false,
          },
          {
            id: Kb,
            step: seed_step(5),
            title: "KB: Ledger Reconciliation Guide",
            kind: MountedKbDoc,
            file: "mounted://platform-runbooks/ledger-reconciliation.md",
            score: Score::clamped(92),
            read: false,
          },
          {
            id: Tasks,
            step: seed_step(6),
            title: "Tasks & Verification",
            kind: TasksDoc,
            file: "openspec/changes/idempotent-refund-posting/tasks.md",
            score: Score::clamped(96),
            read: true,
          },
        ],
      ),
      (
        Int3ds,
        [
          {
            id: Proposal,
            step: seed_step(1),
            title: "Proposal: 3DS2 Challenge Flow",
            kind: ProposalDoc,
            file: "intent/3ds2-challenge-orchestration/proposal.md",
            score: Score::clamped(89),
            read: true,
          },
          {
            id: Design,
            step: seed_step(2),
            title: "Design: Frictionless Fallback",
            kind: DesignDoc,
            file: "intent/3ds2-challenge-orchestration/design.md",
            score: Score::clamped(86),
            read: false,
          },
          {
            id: Spec,
            step: seed_step(3),
            title: "Spec Draft: SCA Challenge (EARS)",
            kind: SpecDeltaDoc,
            file: "intent/3ds2-challenge-orchestration/specs/sca/spec.md",
            score: Score::clamped(84),
            read: false,
          },
          {
            id: Tasks,
            step: seed_step(4),
            title: "Tasks & Verification",
            kind: TasksDoc,
            file: "intent/3ds2-challenge-orchestration/tasks.md",
            score: Score::clamped(82),
            read: false,
          },
        ],
      ),
      (
        IntBmad,
        [
          {
            id: Proposal,
            step: seed_step(1),
            title: "Explore Note: BMAD Adapter Spike",
            kind: ProposalDoc,
            file: "intent/q3-bmad-migration-spike/explore.md",
            score: Score::clamped(76),
            read: false,
          },
          {
            id: Spec,
            step: seed_step(2),
            title: "Draft Requirements: SDD Portability",
            kind: SpecDeltaDoc,
            file: "intent/q3-bmad-migration-spike/specs/portability/spec.md",
            score: Score::clamped(72),
            read: false,
          },
          {
            id: Tasks,
            step: seed_step(3),
            title: "Spike Checklist",
            kind: TasksDoc,
            file: "intent/q3-bmad-migration-spike/tasks.md",
            score: Score::clamped(74),
            read: false,
          },
        ],
      ),
      (
        ChgVault,
        [
          {
            id: Proposal,
            step: seed_step(1),
            title: "Proposal: PCI Vault Bootstrap",
            kind: ProposalDoc,
            file: "openspec/changes/archive/pci-vault-bootstrap/proposal.md",
            score: Score::clamped(97),
            read: true,
          },
          {
            id: Spec,
            step: seed_step(2),
            title: "Synced Spec: Vault Storage (EARS)",
            kind: SpecDeltaDoc,
            file: "openspec/specs/vault/spec.md",
            score: Score::clamped(96),
            read: true,
          },
          {
            id: Adr,
            step: seed_step(3),
            title: "ADR-0014: Isolated Vault Keys",
            kind: AdrDoc,
            file: "intent/decisions/ADR-0014-isolated-vault-keys.md",
            score: Score::clamped(96),
            read: true,
          },
          {
            id: Tasks,
            step: seed_step(4),
            title: "Archived Verification Log",
            kind: TasksDoc,
            file: "openspec/changes/archive/pci-vault-bootstrap/tasks.md",
            score: Score::clamped(96),
            read: true,
          },
        ],
      ),
    ],
    active_concept: DeprecatedCc,
    review_tab: ConceptPeek,
    review_decisions: [],
    local_concepts: [],
    accepted_audits: [],
  }
}

///|
/// Returns the selected workflow preset.
pub fn MockupWorkspace::preset(self : MockupWorkspace) -> WorkflowPreset {
  self.preset
}

///|
/// Returns the active minimum scorecard score gate.
pub fn MockupWorkspace::min_scorecard(self : MockupWorkspace) -> Score {
  self.min_scorecard
}

///|
/// Returns the organization policy floor that limits the minimum score gate.
pub fn MockupWorkspace::policy_floor(self : MockupWorkspace) -> Score {
  self.policy_floor
}

///|
/// Reports whether the optional Security Gate stage is enabled.
pub fn MockupWorkspace::has_security_gate(self : MockupWorkspace) -> Bool {
  self.has_security_gate
}

///|
/// Returns the active Workflow Studio diagram kind.
pub fn MockupWorkspace::studio_diagram(
  self : MockupWorkspace,
) -> StudioDiagramKind {
  self.studio_diagram
}

///|
/// Returns the active Workflow Studio source format.
pub fn MockupWorkspace::studio_format(self : MockupWorkspace) -> StudioFormat {
  self.studio_format
}

///|
/// Returns the stage selected in Workflow Studio.
pub fn MockupWorkspace::studio_stage(self : MockupWorkspace) -> StageId {
  self.studio_stage
}

///|
/// Returns the selected workflow item identifier.
pub fn MockupWorkspace::selected_item(self : MockupWorkspace) -> WorkflowItemId {
  self.selected_item
}

///|
/// Reports whether the gate inspector drawer is open.
pub fn MockupWorkspace::inspector_open(self : MockupWorkspace) -> Bool {
  self.inspector_open
}

///|
/// Returns the immutable list of workflow items.
pub fn MockupWorkspace::items(
  self : MockupWorkspace,
) -> ReadOnlyArray[WorkflowItem] {
  self.items
}

///|
/// Returns the immutable list of reading packet documents for the selected workflow item.
pub fn MockupWorkspace::docs(self : MockupWorkspace) -> ReadOnlyArray[ReadDoc] {
  match
    self.docs_by_item.iter().find_first(pair => pair.0 == self.selected_item) {
    Some((_, docs)) => docs
    None => []
  }
}

///|
fn MockupWorkspace::update_item_docs(
  self : MockupWorkspace,
  item_id : WorkflowItemId,
  f : (ReadDoc) -> ReadDoc,
) -> ReadOnlyArray[(WorkflowItemId, ReadOnlyArray[ReadDoc])] {
  self.docs_by_item.map(pair => {
    if pair.0 == item_id {
      (pair.0, pair.1.map(f))
    } else {
      pair
    }
  })
}

///|
/// Returns the active RDF concept in the Reading Companion.
pub fn MockupWorkspace::active_concept(self : MockupWorkspace) -> ConceptId {
  self.active_concept
}

///|
/// Returns the active tab in the Reading Companion.
pub fn MockupWorkspace::review_tab(self : MockupWorkspace) -> ReviewTab {
  self.review_tab
}

///|
/// Returns the recorded editorial review decision for the selected workflow item.
pub fn MockupWorkspace::review_decision(
  self : MockupWorkspace,
) -> ReviewDecision {
  match
    self.review_decisions
    .iter()
    .find_first(pair => pair.0 == self.selected_item) {
    Some((_, decision)) => decision
    None => Pending
  }
}

///|
/// Returns the current Workflow Studio source parse error, if the edited draft
/// is invalid.
pub fn MockupWorkspace::studio_error(self : MockupWorkspace) -> String? {
  self.studio_parse_error
}

///|
/// Reports whether `extra` is enabled as an input requirement on `stage`.
pub fn MockupWorkspace::has_extra_input(
  self : MockupWorkspace,
  stage : StageId,
  extra : ExtraArtifactInput,
) -> Bool {
  self.extra_inputs.iter().any(pair => pair.0 == stage && pair.1 == extra)
}

///|
/// Returns the ordered stages for this workspace preset and gate configuration.
pub fn MockupWorkspace::stages(
  self : MockupWorkspace,
) -> ReadOnlyArray[StageSpec] {
  let extras_for = (stage : StageId, base : Array[String]) => {
    let out : Array[String] = [..base]
    for pair in self.extra_inputs {
      if pair.0 == stage {
        out.push(pair.1.label())
      }
    }
    ReadOnlyArray::from_array(out)
  }
  let include_verify = self.include_verify
  let explore : StageSpec = {
    id: Explore,
    inputs: extras_for(Explore, ["Intent or Problem Note"]),
    outputs: ["Exploration notes", "Scope decisions"],
    next: Some(Propose),
    back: None,
  }
  let propose : StageSpec = {
    id: Propose,
    inputs: extras_for(Propose, ["Linked Intent (INT-*)"]),
    outputs: ["proposal.md", "design.md", "EARS specs", "tasks.md"],
    next: Some(if self.has_security_gate { SecurityGate } else { Implement }),
    back: Some(Explore),
  }
  let security : StageSpec = {
    id: SecurityGate,
    inputs: extras_for(SecurityGate, [
      "ADR", "Data Dictionary Terms", "PCI Classification",
    ]),
    outputs: ["Security Sign-Off", "Threat Checklist"],
    next: Some(Implement),
    back: Some(Propose),
  }
  let implement : StageSpec = {
    id: Implement,
    inputs: extras_for(Implement, [
      "Approved Proposal", "Design", "EARS Specs", "Tasks",
    ]),
    outputs: ["Code & Tests", "Dictionary/ADR updates", "Tasks checked"],
    next: Some(if include_verify { VerifyGate } else { Archived }),
    back: Some(if self.has_security_gate { SecurityGate } else { Propose }),
  }
  let verify : StageSpec = {
    id: VerifyGate,
    inputs: extras_for(VerifyGate, [
      "100% Tasks", "0 Warnings", "Scorecard >= Floor",
    ]),
    outputs: ["Verification Sign-off", "Spec Sync Plan"],
    next: Some(Archived),
    back: Some(Implement),
  }
  let archived : StageSpec = {
    id: Archived,
    inputs: extras_for(Archived, [
      if include_verify {
        "Verification Sign-off"
      } else {
        "Tasks checked"
      },
    ]),
    outputs: ["Merged Canonical OKF Specs"],
    next: None,
    back: None,
  }
  let list : Array[StageSpec] = [explore, propose]
  if self.has_security_gate {
    list.push(security)
  }
  list.push(implement)
  if include_verify {
    list.push(verify)
  }
  list.push(archived)
  ReadOnlyArray::from_array(list)
}

///|
/// Finds the stage contract for `id`, or falls back to `Explore`.
pub fn MockupWorkspace::stage_spec(
  self : MockupWorkspace,
  id : StageId,
) -> StageSpec {
  let stages = self.stages()
  match stages.iter().find_first(spec => spec.id == id) {
    Some(spec) => spec
    None =>
      // `Explore` is always the first stage in `stages()`.
      match stages.get(0) {
        Some(first) => first
        None =>
          { id: Explore, inputs: [], outputs: [], next: None, back: None, }
      }
  }
}

///|
/// Looks up a workflow item by identifier.
pub fn MockupWorkspace::item(
  self : MockupWorkspace,
  id : WorkflowItemId,
) -> WorkflowItem? {
  self.items.iter().find_first(item => item.id == id)
}

///|
/// Looks up a reading packet document by identifier.
pub fn MockupWorkspace::doc(
  self : MockupWorkspace,
  id : ReviewDocId,
) -> ReadDoc? {
  self.docs().iter().find_first(doc => doc.id == id)
}

///|
/// Returns the currently selected workflow item, if present.
pub fn MockupWorkspace::selected(self : MockupWorkspace) -> WorkflowItem? {
  match self.item(self.selected_item) {
    Some(found) => Some(found)
    None => self.items.get(0)
  }
}

///|
/// Computes the average scorecard score across all workflow items.
pub fn MockupWorkspace::rollup_score(self : MockupWorkspace) -> Score {
  if self.items.is_empty() {
    return Score::clamped(0)
  }
  let mut total = 0
  for item in self.items {
    total += item.score.value()
  }
  Score::clamped(total / self.items.length())
}

///|
/// Computes the letter grade for the workspace rollup score.
pub fn MockupWorkspace::rollup_grade(self : MockupWorkspace) -> Grade {
  self.rollup_score().grade()
}

///|
/// Evaluates transition guards for one workflow item under this workspace's rules.
pub fn MockupWorkspace::evaluate_gates(
  self : MockupWorkspace,
  item : WorkflowItem,
) -> GateEvaluation {
  let floor = self.min_scorecard.value()
  let stage_spec = self.stage_spec(item.stage)
  match item.stage {
    Explore =>
      {
        target: stage_spec.next,
        checks: [
          { passed: true, label: "Problem note present", source: Artifact, },
          { passed: true, label: "Linked to \{item.intent}", source: OkfGraph, },
        ],
      }
    Propose => {
      let has_spec = item.artifacts
        .iter()
        .any(a => a.kind == SpecMd && a.status == Clean)
      let has_tasks = item.artifacts
        .iter()
        .any(a => a.kind == TasksMd && a.status == Clean)
      {
        target: stage_spec.next,
        checks: [
          {
            passed: true,
            label: "Proposal & design present",
            source: Artifact,
          },
          {
            passed: has_spec,
            label: "EARS spec deltas authored",
            source: Ears,
          },
          {
            passed: has_tasks,
            label: "Tasks checklist created",
            source: Artifact,
          },
        ],
      }
    }
    SecurityGate =>
      {
        target: stage_spec.next,
        checks: [
          {
            passed: item.warnings.is_zero(),
            label: "PCI / Data Dictionary terms clean",
            source: RegoAndDict,
          },
          {
            passed: item.score.value() >= floor,
            label: "Scorecard >= \{floor} (current: \{item.score.value()})",
            source: DocumentScorer,
          },
        ],
      }
    Implement => {
      let tasks_ok = item.progress.is_complete()
      let warnings_ok = item.warnings.is_zero()
      let score_ok = item.score.value() >= floor
      {
        target: stage_spec.next,
        checks: [
          {
            passed: true,
            label: "Required inputs satisfied (Proposal, Design, ADR)",
            source: InputContract,
          },
          {
            passed: tasks_ok,
            label: "All tasks complete (\{item.progress.done()}/\{item.progress.total()})",
            source: TasksCheck,
          },
          {
            passed: warnings_ok,
            label: if warnings_ok {
              "0 Rego / Dictionary warnings"
            } else {
              "\{item.warnings.count()} warnings (deprecated CC# + Rego PCI rule)"
            },
            source: RegoAndDict,
          },
          {
            passed: score_ok,
            label: "Scorecard >= \{floor} (current: \{item.score.value()} · Grade \{item.grade().label()})",
            source: DocumentScorer,
          },
        ],
      }
    }
    VerifyGate =>
      {
        target: stage_spec.next,
        checks: [
          {
            passed: item.warnings.is_zero(),
            label: "Validation passing (0 errors)",
            source: OkfAndRego,
          },
          {
            passed: item.score.value() >= floor,
            label: "Scorecard >= \{floor} (current: \{item.score.value()})",
            source: DocumentScorer,
          },
        ],
      }
    Archived =>
      {
        target: None,
        checks: [
          {
            passed: true,
            label: "Synced to canonical OKF & archived",
            source: Terminal,
          },
        ],
      }
  }
}

///|
fn seed_iri(text : String) -> ConceptIri {
  try! ConceptIri(text)
}

///|
fn seed_concept_label(raw : String) -> ConceptLabel {
  try! ConceptLabel(raw)
}

///|
fn seed_concept_def(raw : String) -> ConceptDefinition {
  try! ConceptDefinition(raw)
}

///|
/// Returns the default fallback built-in concept (`Pan`).
pub fn default_concept_card() -> ConceptCard {
  {
    id: Pan,
    label: seed_concept_label("Credit Card Number (PAN)"),
    status: ActiveConcept,
    iri: seed_iri("https://org.example/dict#CreditCardNumber"),
    graph: MountedPci,
    alt_labels: ["Primary Account Number", "PAN"],
    broader: [PaymentMethod],
    narrower: [MaskedPan],
    related: [AuditEvent],
    shacl: "Must be tokenized via Vault or masked to last 4 digits before logging or telemetry export.",
    definition: seed_concept_def(
      "Primary Account Number identifying a payment card. Raw PAN digits must never appear in logs.",
    ),
    backlinks: [
      {
        item: ChgMask,
        doc: Spec,
        label: "mask-card-numbers-in-logs · LOG-014",
      },
      {
        item: Int3ds,
        doc: Spec,
        label: "3ds2-challenge-orchestration · SCA-002",
      },
      { item: ChgVault, doc: Spec, label: "pci-vault-bootstrap · VLT-001", },
    ],
  }
}

///|
/// Returns RDF concept metadata for built-in concepts, or `None` for workspace-local concepts.
pub fn concept_card(id : ConceptId) -> ConceptCard? {
  match id {
    Pan => Some(default_concept_card())
    MaskedPan =>
      Some({
        id: MaskedPan,
        label: seed_concept_label("Masked PAN"),
        status: ActiveConcept,
        iri: seed_iri("https://org.example/dict#MaskedPan"),
        graph: MountedPci,
        alt_labels: ["Last-4 PAN", "Redacted PAN"],
        broader: [Pan],
        narrower: [],
        related: [AuditEvent],
        shacl: "Pattern ^\\*{12}[0-9]{4}$ or [REDACTED-PAN] literal; never stores BIN + trailing digits together.",
        definition: seed_concept_def(
          "Non-reversible representation of a Credit Card Number retaining at most the final four digits for support diagnostics.",
        ),
        backlinks: [
          {
            item: ChgMask,
            doc: Adr,
            label: "mask-card-numbers-in-logs · ADR-0015",
          },
        ],
      })
    PaymentMethod =>
      Some({
        id: PaymentMethod,
        label: seed_concept_label("Payment Method"),
        status: ActiveConcept,
        iri: seed_iri("https://org.example/dict#PaymentMethod"),
        graph: MountedPci,
        alt_labels: ["Funding Instrument"],
        broader: [],
        narrower: [Pan],
        related: [IdempotencyKey],
        shacl: "Every payment instrument must declare PCI sensitivity tier and tokenization strategy.",
        definition: seed_concept_def(
          "Customer-authorized instrument used to settle or refund a payment transaction.",
        ),
        backlinks: [
          {
            item: ChgRefund,
            doc: Proposal,
            label: "idempotent-refund-posting · Proposal",
          },
        ],
      })
    DeprecatedCc =>
      Some({
        id: DeprecatedCc,
        label: seed_concept_label("CC# (Deprecated Alias)"),
        status: DeprecatedConcept(replaced_by=Pan),
        iri: seed_iri("https://org.example/dict#DeprecatedCcAlias"),
        graph: MountedPci,
        alt_labels: ["CC#", "Card #"],
        broader: [],
        narrower: [],
        related: [Pan],
        shacl: "Rego rule org/pci-dict flags 'CC#' and offers a one-click fix to canonical 'Credit Card Number'.",
        definition: seed_concept_def(
          "Legacy shorthand replaced by Credit Card Number (PAN) in Data Dictionary v2.1.",
        ),
        backlinks: [
          {
            item: ChgMask,
            doc: Spec,
            label: "mask-card-numbers-in-logs · LOG-019",
          },
        ],
      })
    AuditEvent =>
      Some({
        id: AuditEvent,
        label: seed_concept_label("Redaction Audit Event"),
        status: ActiveConcept,
        iri: seed_iri("https://org.example/local/payments#RedactionAuditEvent"),
        graph: LocalPayments,
        alt_labels: ["Sanitization Event"],
        broader: [],
        narrower: [],
        related: [Pan, MaskedPan],
        shacl: "Structured log event recording field path and redaction policy version without sensitive payload.",
        definition: seed_concept_def(
          "Tamper-evident record emitted whenever the gateway intercepts a PCI-classified token.",
        ),
        backlinks: [
          {
            item: ChgMask,
            doc: Spec,
            label: "mask-card-numbers-in-logs · LOG-014",
          },
          {
            item: ChgRefund,
            doc: Spec,
            label: "idempotent-refund-posting · REF-004",
          },
        ],
      })
    IdempotencyKey =>
      Some({
        id: IdempotencyKey,
        label: seed_concept_label("Idempotency Key"),
        status: ActiveConcept,
        iri: seed_iri("https://org.example/local/payments#IdempotencyKey"),
        graph: LocalPayments,
        alt_labels: ["Deduplication Key"],
        broader: [],
        narrower: [],
        related: [PaymentMethod, AuditEvent],
        shacl: "UUIDv7 or 32..64 hex token scoped per merchant + endpoint, retained for >= 24 hours.",
        definition: seed_concept_def(
          "Client-supplied key ensuring retried refund or capture commands execute at most once.",
        ),
        backlinks: [
          {
            item: ChgRefund,
            doc: Spec,
            label: "idempotent-refund-posting · REF-004",
          },
        ],
      })
    LocalConcept(_) => None
  }
}

///|
fn slugify_concept_label(label : String) -> String {
  let buf = StringBuilder()
  let mut last_dash = false
  for ch in label {
    if (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') {
      buf.write_char(ch)
      last_dash = false
    } else if ch >= 'A' && ch <= 'Z' {
      buf.write_char(Int32::unsafe_to_char(ch.to_int() + 32))
      last_dash = false
    } else if !last_dash && buf.to_string().length() > 0 {
      buf.write_char('-')
      last_dash = true
    }
  }
  let raw = buf.to_string().trim_end(chars="-").to_owned()
  if raw.is_empty() {
    "concept"
  } else {
    raw
  }
}

///|
fn escape_rdf_literal(text : String) -> String {
  text.replace_all(old="\\", new="\\\\").replace_all(old="\"", new="\\\"")
}

///|
/// Serializes one dictionary concept into valid Turtle (TTL).
pub fn ConceptCard::to_turtle(
  self : ConceptCard,
  lookup : (ConceptId) -> ConceptCard?,
) -> String {
  let lines : Array[String] = [
    "@prefix skos:  .",
    "@prefix owl:  .",
    "@prefix sh:  .",
    "",
    "# Graph: \{self.graph_display()}",
    "<\{self.iri.as_str()}> a skos:Concept ;",
    "  skos:prefLabel \"\{escape_rdf_literal(self.label.as_str())}\"@en ;",
    "  skos:definition \"\{escape_rdf_literal(self.definition.as_str())}\"@en ;",
  ]
  for alt in self.alt_labels {
    lines.push("  skos:altLabel \"\{escape_rdf_literal(alt)}\"@en ;")
  }
  for b in self.broader {
    if lookup(b) is Some(target) {
      lines.push("  skos:broader <\{target.iri.as_str()}> ;")
    }
  }
  for n in self.narrower {
    if lookup(n) is Some(target) {
      lines.push("  skos:narrower <\{target.iri.as_str()}> ;")
    }
  }
  for r in self.related {
    if lookup(r) is Some(target) {
      lines.push("  skos:related <\{target.iri.as_str()}> ;")
    }
  }
  if self.is_deprecated() {
    lines.push("  owl:deprecated true ;")
  }
  lines.push("  sh:description \"\{escape_rdf_literal(self.shacl)}\"@en .")
  lines.join("\n")
}

///|
/// Serializes one dictionary concept into JSON-LD matching the Structured and
/// Turtle representations.
pub fn ConceptCard::to_json_ld(
  self : ConceptCard,
  lookup : (ConceptId) -> ConceptCard?,
) -> String {
  let iri_array = (ids : ReadOnlyArray[ConceptId]) => {
    ids
    .iter()
    .filter_map(id => lookup(id).map(c => "\"\{c.iri.as_str()}\""))
    .to_array()
    .join(", ")
  }
  let alt_literals = self.alt_labels
    .iter()
    .map(alt => "\"\{escape_rdf_literal(alt)}\"")
    .to_array()
    .join(", ")
  let lines : Array[String] = [
    "{",
    "  \"@context\": {",
    "    \"skos\": \"http://www.w3.org/2004/02/skos/core#\",",
    "    \"sh\": \"http://www.w3.org/ns/shacl#\",",
    "    \"owl\": \"http://www.w3.org/2002/07/owl#\"",
    "  },",
    "  \"@id\": \"\{self.iri.as_str()}\",",
    "  \"@type\": \"skos:Concept\",",
    "  \"skos:prefLabel\": \"\{escape_rdf_literal(self.label.as_str())}\",",
    "  \"skos:definition\": \"\{escape_rdf_literal(self.definition.as_str())}\",",
    "  \"skos:altLabel\": [\{alt_literals}],",
    "  \"skos:broader\": [\{iri_array(self.broader)}],",
    "  \"skos:narrower\": [\{iri_array(self.narrower)}],",
    "  \"skos:related\": [\{iri_array(self.related)}],",
    "  \"owl:deprecated\": \{self.is_deprecated()},",
    "  \"sh:description\": \"\{escape_rdf_literal(self.shacl)}\"",
    "}",
  ]
  lines.join("\n")
}

///|
/// All seeded plus user-authored local concepts in this workspace.
pub fn MockupWorkspace::all_concepts(
  self : MockupWorkspace,
) -> ReadOnlyArray[ConceptCard] {
  let seeded : Array[ConceptCard] = [
    Pan,
    MaskedPan,
    PaymentMethod,
    DeprecatedCc,
    AuditEvent,
    IdempotencyKey,
  ].filter_map(concept_card)
  for local_c in self.local_concepts {
    seeded.push(local_c)
  }
  ReadOnlyArray::from_array(seeded)
}

///|
/// Looks up a concept card by ID, including local workspace concepts.
pub fn MockupWorkspace::concept(
  self : MockupWorkspace,
  id : ConceptId,
) -> ConceptCard? {
  self.all_concepts().iter().find_first(c => c.id == id)
}

///|
/// Adds a validated local concept to `` and focuses it.
pub fn MockupWorkspace::add_local_concept(
  self : MockupWorkspace,
  label : ConceptLabel,
  definition : ConceptDefinition,
) -> MockupWorkspace {
  let next_idx = self.local_concepts.length() + 1
  let local_id = try! LocalConceptId(next_idx)
  let id = LocalConcept(local_id)
  let slug = slugify_concept_label(label.as_str())
  let iri = seed_iri("https://org.example/local/payments#\{slug}-\{next_idx}")
  let card : ConceptCard = {
    id,
    label,
    status: ActiveConcept,
    iri,
    graph: LocalPayments,
    alt_labels: [],
    broader: [],
    narrower: [],
    related: [AuditEvent],
    shacl: "Local workspace SKOS term authored in preview state.",
    definition,
    backlinks: [],
  }
  {
    ..self,
    local_concepts: ReadOnlyArray::from_array([..self.local_concepts, card]),
    active_concept: id,
  }
}

///|
/// Returns the live Prose Term Audit items synced with workspace findings.
pub fn MockupWorkspace::term_audits(
  self : MockupWorkspace,
) -> ReadOnlyArray[TermAuditItem] {
  let cc_status : AuditStatus = match self.item(ChgMask) {
    Some(item) if !item.warnings.is_zero() => OpenAudit
    _ => ResolvedAudit
  }
  let accepted = (id : TermAuditId) => {
    if self.accepted_audits.contains(id) {
      AuditStatus::ResolvedAudit
    } else {
      OpenAudit
    }
  }
  [
    {
      id: AuditDeprecatedCc,
      mention: "CC#",
      location: "mask-card-numbers-in-logs · LOG-019",
      item: ChgMask,
      doc: Spec,
      kind: DeprecatedSynonym(target=Pan),
      status: cc_status,
    },
    {
      id: AuditUnlinkedMaskedPan,
      mention: "last four digits",
      location: "mask-card-numbers-in-logs · ADR-0015",
      item: ChgMask,
      doc: Adr,
      kind: UnlinkedMention(target=MaskedPan),
      status: accepted(AuditUnlinkedMaskedPan),
    },
    {
      id: AuditUnlinkedIdempotency,
      mention: "idempotency key",
      location: "idempotent-refund-posting · REF-004",
      item: ChgRefund,
      doc: Spec,
      kind: UnlinkedMention(target=IdempotencyKey),
      status: accepted(AuditUnlinkedIdempotency),
    },
  ]
}

///|
/// Resolves one Prose Term Audit item without changing the selected workflow item.
pub fn MockupWorkspace::resolve_term_audit(
  self : MockupWorkspace,
  audit_id : TermAuditId,
) -> MockupWorkspace {
  match audit_id {
    AuditDeprecatedCc => self.normalize_deprecated_term_for(ChgMask)
    AuditUnlinkedMaskedPan | AuditUnlinkedIdempotency =>
      if self.accepted_audits.contains(audit_id) {
        self
      } else {
        {
          ..self,
          accepted_audits: ReadOnlyArray::from_array(
            [..self.accepted_audits, audit_id],
          ),
        }
      }
  }
}

///|
/// Returns the seeded OKF Knowledge Base documents (local + mounted read-only).
pub fn kb_documents() -> ReadOnlyArray[KbDocument] {
  let pci_p1 : ReadOnlyArray[ProseSpan] = [
    Plain("PCI-DSS 3.4 prohibits storing raw "),
    Term(Pan, "Credit Card Number", deprecated=false),
    Plain(" values in application or gateway logs. Services must emit a "),
    Term(MaskedPan, "Masked PAN", deprecated=false),
    Plain(" alongside a "),
    Term(AuditEvent, "Redaction Audit Event", deprecated=false),
    Plain("."),
  ]
  let adr_p1 : ReadOnlyArray[ProseSpan] = [
    Plain("ADR-0015 standardizes "),
    Term(MaskedPan, "Masked PAN", deprecated=false),
    Plain(
      " rendering (`************4242`) so on-call engineers correlate gateway retries without exposing ",
    ),
    Term(Pan, "Credit Card Number", deprecated=false),
    Plain(" digits."),
  ]
  let ledger_p1 : ReadOnlyArray[ProseSpan] = [
    Plain("Refund postings require a merchant-scoped "),
    Term(IdempotencyKey, "Idempotency Key", deprecated=false),
    Plain(" bound to the original "),
    Term(PaymentMethod, "Payment Method", deprecated=false),
    Plain(" and audited via "),
    Term(AuditEvent, "Redaction Audit Event", deprecated=false),
    Plain("."),
  ]
  let policy_p1 : ReadOnlyArray[ProseSpan] = [
    Plain(
      "Policy pack `org/pci-dict` enforces canonical terminology from ``, flagging legacy ",
    ),
    Term(DeprecatedCc, "CC#", deprecated=true),
    Plain(" aliases in EARS specs before Verify Gate sign-off."),
  ]
  [
    {
      id: KbPciRunbook,
      title: "PCI Log Redaction Runbook",
      path: "mounts/org-kb/pci-log-redaction.md",
      kind: KbRunbook,
      source: MountedRo,
      trust_tier: "Mounted Org (RO)",
      summary: "Operational standard for sanitizing payment card telemetry across gateway services.",
      paragraphs: [pci_p1],
      source_lines: [
        "---",
        "id: KB-PCI-34",
        "source: urn:acme:kb:pci-v2",
        "trust: mounted-readonly",
        "---",
        "# PCI Log Redaction Runbook",
        "",
        spans_plain_text(pci_p1),
      ],
      links: [KbAdrMasking, KbSddPolicy],
      concepts: [Pan, MaskedPan, AuditEvent],
    },
    {
      id: KbAdrMasking,
      title: "ADR-0015: Last-4 PAN Masking",
      path: "intent/decisions/ADR-0015-last4-masking.md",
      kind: KbAdr,
      source: LocalOkf,
      trust_tier: "Local OKF (Verified)",
      summary: "Records why gateway logs retain last-4 masked PAN tokens rather than opaque hashes.",
      paragraphs: [adr_p1],
      source_lines: [
        "---",
        "id: ADR-0015",
        "status: accepted",
        "---",
        "# ADR-0015: Last-4 PAN Masking",
        "",
        spans_plain_text(adr_p1),
      ],
      links: [KbPciRunbook],
      concepts: [MaskedPan, Pan],
    },
    {
      id: KbLedgerSpec,
      title: "Idempotent Refund Ledger Spec",
      path: "openspec/changes/idempotent-refund-posting/specs/refunds/spec.md",
      kind: KbSpec,
      source: LocalOkf,
      trust_tier: "Local OKF (In Review)",
      summary: "Exactly-once refund posting invariants keyed by Idempotency Key.",
      paragraphs: [ledger_p1],
      source_lines: [
        "---",
        "id: SPEC-REFUND-004",
        "status: verify-gate",
        "---",
        "# Idempotent Refund Ledger Spec",
        "",
        spans_plain_text(ledger_p1),
      ],
      links: [KbSddPolicy],
      concepts: [IdempotencyKey, PaymentMethod, AuditEvent],
    },
    {
      id: KbSddPolicy,
      title: "Org SDD & Rego Policy Pack",
      path: "mounts/org-policy/pci-dict.rego",
      kind: KbPolicy,
      source: MountedRo,
      trust_tier: "Mounted Policy (RO)",
      summary: "Enforces EARS compliance, Scorecard floor >= 85, and canonical SKOS dictionary terms.",
      paragraphs: [policy_p1],
      source_lines: [
        "package org.pci_dict",
        "",
        "# \{spans_plain_text(policy_p1)}",
        "deny[msg] { contains(input.text, \"CC#\") }",
      ],
      links: [KbPciRunbook, KbLedgerSpec],
      concepts: [DeprecatedCc, Pan],
    },
  ]
}

///|
/// Returns the seeded Knowledge Base document matching `id`.
pub fn kb_document(id : KbDocId) -> KbDocument {
  match kb_documents().iter().find_first(doc => doc.id == id) {
    Some(doc) => doc
    None => kb_documents()[0]
  }
}

///|
fn item_spec_clauses(item : WorkflowItem) -> ReadOnlyArray[RequirementClause] {
  let clean = item.warnings.is_zero()
  match item.id {
    ChgMask =>
      [
        {
          id: "LOG-014",
          change: Modified(
            previous="WHEN a payment retry fails, the Gateway Logger SHALL emit the full upstream payload.",
          ),
          ears_kind: EventDriven,
          spans: [
            Keyword("WHEN "),
            Plain("a payment retry fails, the Gateway Logger "),
            Keyword("SHALL "),
            Plain("mask every "),
            Term(Pan, "Credit Card Number", deprecated=false),
            Plain(" to its last four digits before emitting a "),
            Term(AuditEvent, "Redaction Audit Event", deprecated=false),
            Plain("."),
          ],
          finding: NoFinding,
        },
        {
          id: "LOG-019",
          change: Added,
          ears_kind: UnwantedBehavior,
          spans: [
            Keyword("IF "),
            Plain("an unparsed "),
            if clean {
              Term(Pan, "Credit Card Number", deprecated=false)
            } else {
              Term(DeprecatedCc, "CC#", deprecated=true)
            },
            Plain(" matches the Luhn pattern, "),
            Keyword("THEN "),
            Plain("the Sanitizer "),
            Keyword("SHALL "),
            Plain("replace the match with [REDACTED-PAN]."),
          ],
          finding: if clean {
            DeprecatedTermResolved
          } else {
            DeprecatedTermOpen
          },
        },
      ]
    ChgRefund =>
      [
        {
          id: "REF-004",
          change: Added,
          ears_kind: EventDriven,
          spans: [
            Keyword("WHEN "),
            Plain(
              "a duplicate refund request arrives with the same idempotency key, the Refund Ledger ",
            ),
            Keyword("SHALL "),
            Plain("return the original posting receipt and emit a "),
            Term(AuditEvent, "Redaction Audit Event", deprecated=false),
            Plain(" without posting twice."),
          ],
          finding: NoFinding,
        },
      ]
    Int3ds =>
      [
        {
          id: "SCA-002",
          change: Added,
          ears_kind: StateDriven,
          spans: [
            Keyword("WHILE "),
            Plain("a 3DS2 challenge is pending for a "),
            Term(Pan, "Credit Card Number", deprecated=false),
            Plain(", the Orchestrator "),
            Keyword("SHALL "),
            Plain("hold capture until issuer authentication completes."),
          ],
          finding: NoFinding,
        },
      ]
    IntBmad =>
      [
        {
          id: "SDD-001",
          change: Added,
          ears_kind: Ubiquitous,
          spans: [
            Plain("The BMAD adapter "),
            Keyword("SHALL "),
            Plain(
              "project native story files into canonical OKF intent documents while preserving source paths.",
            ),
          ],
          finding: NoFinding,
        },
      ]
    ChgVault =>
      [
        {
          id: "VLT-001",
          change: Added,
          ears_kind: Ubiquitous,
          spans: [
            Plain("The Vault boundary "),
            Keyword("SHALL "),
            Plain("encrypt every stored "),
            Term(Pan, "Credit Card Number", deprecated=false),
            Plain(" using isolated per-tenant data keys and log a "),
            Term(AuditEvent, "Redaction Audit Event", deprecated=false),
            Plain(" on rotation."),
          ],
          finding: NoFinding,
        },
      ]
  }
}

///|
/// Returns distinct Structured, Preview, and Source content for a reading
/// packet document, derived from one shared clause and span model per item.
pub fn doc_content(doc_id : ReviewDocId, item : WorkflowItem) -> DocContent {
  match doc_id {
    Proposal => {
      let summary = "Scope and motivation for \{item.title} under \{item.intent}."
      let p1 : ReadOnlyArray[ProseSpan] = match item.id {
        ChgMask =>
          [
            Plain("This change prevents unmasked "),
            Term(Pan, "Credit Card Number", deprecated=false),
            Plain(
              " payloads from appearing in application logs across retry paths.",
            ),
          ]
        ChgRefund =>
          [
            Plain(
              "This change guarantees exactly-once refund posting using deterministic ledger keys and emits a ",
            ),
            Term(AuditEvent, "Redaction Audit Event", deprecated=false),
            Plain(" for duplicate submissions."),
          ]
        Int3ds =>
          [
            Plain(
              "This intent coordinates PSD2 Strong Customer Authentication challenges for ",
            ),
            Term(Pan, "Credit Card Number", deprecated=false),
            Plain(" payments."),
          ]
        IntBmad =>
          [
            Plain(
              "This exploration spike maps BMAD artifacts onto the canonical OKF intent model without duplicating source files.",
            ),
          ]
        ChgVault =>
          [
            Plain(
              "This archived change bootstrapped isolated envelope encryption for stored ",
            ),
            Term(Pan, "Credit Card Number", deprecated=false),
            Plain(" tokens."),
          ]
      }
      let p2 : ReadOnlyArray[ProseSpan] = [
        Plain(
          "Adapter source: \{item.adapter.label()} · Current stage: \{item.stage.label()} · Scorecard \{item.score.value()} (Grade \{item.grade().label()}).",
        ),
      ]
      {
        summary,
        preview_paragraphs: [p1, p2],
        clauses: [],
        source_lines: [
          "# Proposal: \{item.title}",
          "",
          "## Why",
          spans_plain_text(p1),
          "",
          "## Status",
          spans_plain_text(p2),
        ],
      }
    }
    Design => {
      let summary = "Architecture boundary and key trade-offs for \{item.title}."
      let p1 : ReadOnlyArray[ProseSpan] = match item.id {
        ChgRefund =>
          [
            Plain(
              "Refund requests compute a deterministic key before ledger mutation so retries short-circuit cleanly.",
            ),
          ]
        Int3ds =>
          [
            Plain(
              "Challenge state transitions run inside a pure state machine before calling the issuer ACS gateway.",
            ),
          ]
        _ =>
          [
            Plain(
              "All inbound payloads pass through one pure redaction boundary before structured log serialization.",
            ),
          ]
      }
      let p2 : ReadOnlyArray[ProseSpan] = [
        Plain("Every guarded action emits a "),
        Term(AuditEvent, "Redaction Audit Event", deprecated=false),
        Plain(" carrying policy version and field path, never raw "),
        Term(Pan, "Credit Card Number", deprecated=false),
        Plain(" digits."),
      ]
      {
        summary,
        preview_paragraphs: [p1, p2],
        clauses: [],
        source_lines: [
          "# Design: \{item.title}",
          "",
          "## Decisions",
          "- \{spans_plain_text(p1)}",
          "- \{spans_plain_text(p2)}",
        ],
      }
    }
    Spec => {
      let clauses = item_spec_clauses(item)
      let preview_paragraphs : Array[ReadOnlyArray[ProseSpan]] = []
      let source_lines : Array[String] = []
      for i, clause in clauses {
        let preview_line : Array[ProseSpan] = [
          Keyword("\{clause.id}: "),
          ..clause.spans,
        ]
        preview_paragraphs.push(ReadOnlyArray::from_array(preview_line))
        if i > 0 {
          source_lines.push("")
        }
        source_lines.push(
          "### Requirement: \{clause.id} (\{clause.change.label()} · \{clause.ears_kind.label()})",
        )
        source_lines.push(clause.plain_text())
      }
      {
        summary: "EARS requirements for \{item.title} (\{item.intent}).",
        preview_paragraphs: ReadOnlyArray::from_array(preview_paragraphs),
        clauses,
        source_lines: ReadOnlyArray::from_array(source_lines),
      }
    }
    Adr => {
      let summary = "Architectural decision record linked to \{item.title}."
      let p1 : ReadOnlyArray[ProseSpan] = [
        Plain(
          "Enforcing semantic boundaries before persistence guarantees downstream stores never observe raw ",
        ),
        Term(Pan, "Credit Card Number", deprecated=false),
        Plain(" values."),
      ]
      let p2 : ReadOnlyArray[ProseSpan] = [
        Plain(
          "Post-hoc log scrubbers were rejected because crash dumps could still expose unmasked payloads before collection.",
        ),
      ]
      {
        summary,
        preview_paragraphs: [p1, p2],
        clauses: [],
        source_lines: [
          "# ADR for \{item.title}",
          "",
          "Status: Accepted",
          "Decision: \{spans_plain_text(p1)}",
        ],
      }
    }
    Kb => {
      let summary = "Mounted platform runbook referenced by \{item.title}."
      let p1 : ReadOnlyArray[ProseSpan] = [
        Plain("Operators must verify zero raw "),
        Term(Pan, "Credit Card Number", deprecated=false),
        Plain(" matches in staging telemetry before promoting a release."),
      ]
      let p2 : ReadOnlyArray[ProseSpan] = [
        Plain("Every redaction or deduplication trigger must emit a "),
        Term(AuditEvent, "Redaction Audit Event", deprecated=false),
        Plain(" to the security index."),
      ]
      {
        summary,
        preview_paragraphs: [p1, p2],
        clauses: [],
        source_lines: [
          "# Platform Runbook (\{item.title})",
          "",
          "1. \{spans_plain_text(p1)}",
          "2. \{spans_plain_text(p2)}",
        ],
      }
    }
    Tasks => {
      let summary = "Implementation and verification checklist (\{item.progress.done()}/\{item.progress.total()} complete)."
      let p1 : ReadOnlyArray[ProseSpan] = [
        Plain(
          "Checklist status for \{item.title}: \{item.progress.done()} of \{item.progress.total()} tasks completed with score \{item.score.value()} (Grade \{item.grade().label()}).",
        ),
      ]
      let p2 : ReadOnlyArray[ProseSpan] = [
        Plain(
          "Resolve all open Rego or Data Dictionary findings before Verify Gate approval.",
        ),
      ]
      {
        summary,
        preview_paragraphs: [p1, p2],
        clauses: [],
        source_lines: [
          "# Tasks: \{item.title}",
          "",
          "- [x] 1.1 Implement pure boundary rules",
          "- [x] 1.2 Record structured audit telemetry",
          if item.progress.is_complete() {
            "- [x] 1.3 Run verification suite"
          } else {
            "- [ ] 1.3 Run verification suite"
          },
        ],
      }
    }
  }
}

///|
/// Selects a workflow item and opens the gate inspector.
pub fn MockupWorkspace::open_inspector(
  self : MockupWorkspace,
  item_id : WorkflowItemId,
) -> MockupWorkspace {
  { ..self, selected_item: item_id, inspector_open: true, }
}

///|
/// Selects a workflow item without changing inspector visibility.
pub fn MockupWorkspace::select_item(
  self : MockupWorkspace,
  item_id : WorkflowItemId,
) -> MockupWorkspace {
  { ..self, selected_item: item_id, }
}

///|
/// Closes the floating gate inspector.
pub fn MockupWorkspace::close_inspector(
  self : MockupWorkspace,
) -> MockupWorkspace {
  { ..self, inspector_open: false, }
}

///|
/// Switches the Reading Companion tab in Review.
pub fn MockupWorkspace::with_review_tab(
  self : MockupWorkspace,
  tab : ReviewTab,
) -> MockupWorkspace {
  { ..self, review_tab: tab, }
}

///|
/// Focuses a dictionary concept and switches the Reading Companion to Concept
/// Peek.
pub fn MockupWorkspace::select_concept(
  self : MockupWorkspace,
  concept : ConceptId,
) -> MockupWorkspace {
  { ..self, active_concept: concept, review_tab: ConceptPeek, }
}

///|
/// Switches the Workflow Studio diagram style.
pub fn MockupWorkspace::with_studio_diagram(
  self : MockupWorkspace,
  kind : StudioDiagramKind,
) -> MockupWorkspace {
  { ..self, studio_diagram: kind, }
}

///|
fn MockupWorkspace::draft_for(
  self : MockupWorkspace,
  format : StudioFormat,
) -> String? {
  match self.studio_drafts.iter().find_first(pair => pair.0 == format) {
    Some((_, text)) => Some(text)
    None => None
  }
}

///|
fn MockupWorkspace::with_draft_for(
  self : MockupWorkspace,
  format : StudioFormat,
  source : String,
) -> ReadOnlyArray[(StudioFormat, String)] {
  let next : Array[(StudioFormat, String)] = []
  let mut replaced = false
  for pair in self.studio_drafts {
    if pair.0 == format {
      next.push((format, source))
      replaced = true
    } else {
      next.push(pair)
    }
  }
  if !replaced {
    next.push((format, source))
  }
  ReadOnlyArray::from_array(next)
}

///|
/// Switches the Workflow Studio source format while preserving per-format custom
/// drafts and updating the validation status for the newly selected format.
pub fn MockupWorkspace::with_studio_format(
  self : MockupWorkspace,
  format : StudioFormat,
) -> MockupWorkspace {
  let studio_parse_error = match self.draft_for(format) {
    Some(draft) =>
      match parse_studio_draft(format, draft) {
        Ok(_) => None
        Err(msg) => Some(msg)
      }
    None => None
  }
  { ..self, studio_format: format, studio_parse_error, }
}

///|
/// Selects a stage in Workflow Studio if that stage exists in the active
/// workflow.
pub fn MockupWorkspace::with_studio_stage(
  self : MockupWorkspace,
  stage : StageId,
) -> MockupWorkspace {
  let valid = self.stages().iter().any(spec => spec.id == stage)
  guard valid else { self }
  { ..self, studio_stage: stage, }
}

///|
/// Toggles an optional input artifact requirement on a stage inside Workflow
/// Studio.
pub fn MockupWorkspace::toggle_extra_input(
  self : MockupWorkspace,
  stage : StageId,
  extra : ExtraArtifactInput,
) -> MockupWorkspace {
  let exists = self.has_extra_input(stage, extra)
  let next = if exists {
    self.extra_inputs.filter(pair => !(pair.0 == stage && pair.1 == extra))
  } else {
    ReadOnlyArray::from_array([..self.extra_inputs, (stage, extra)])
  }
  { ..self, extra_inputs: next, studio_drafts: [], studio_parse_error: None, }
}

///|
priv enum MermaidNode {
  Boundary
  Stage(StageId)
}

///|
fn parse_mermaid_node(token : String) -> MermaidNode? {
  match token {
    "[*]" => Some(Boundary)
    "Explore" => Some(Stage(Explore))
    "Propose" => Some(Stage(Propose))
    "SecurityGate" => Some(Stage(SecurityGate))
    "Implement" => Some(Stage(Implement))
    "VerifyGate" => Some(Stage(VerifyGate))
    "Archived" => Some(Stage(Archived))
    _ => None
  }
}

///|
priv struct StudioParseResult {
  has_security_gate : Bool
  include_verify : Bool
}

///|
fn parse_studio_draft(
  format : StudioFormat,
  source : String,
) -> Result[StudioParseResult, String] {
  let trimmed = source.trim()
  if trimmed.is_empty() {
    return Err("source is empty")
  }
  match format {
    Mermaid => {
      let mut saw_header = false
      let mut has_explore = false
      let mut has_propose = false
      let mut has_implement = false
      let mut has_archived = false
      let mut has_security_gate = false
      let mut include_verify = false
      for raw_line in trimmed.split("\n") {
        let line = raw_line.trim().to_owned()
        if line.is_empty() || line.has_prefix("%%") {
          continue
        }
        if !saw_header {
          if line != "stateDiagram-v2" {
            return Err("expected Mermaid header `stateDiagram-v2`")
          }
          saw_header = true
          continue
        }
        let edge_part = match line.split_once(":") {
          Some((before, _)) => before.trim().to_owned()
          None => line
        }
        match edge_part.split_once("-->") {
          None => return Err("invalid transition line `\{line}`")
          Some((lhs_view, rhs_view)) => {
            let lhs_raw = lhs_view.trim().to_owned()
            let rhs_raw = rhs_view.trim().to_owned()
            let lhs = match parse_mermaid_node(lhs_raw) {
              Some(node) => node
              None => return Err("unknown state `\{lhs_raw}`")
            }
            let rhs = match parse_mermaid_node(rhs_raw) {
              Some(node) => node
              None => return Err("unknown state `\{rhs_raw}`")
            }
            for node in [lhs, rhs] {
              match node {
                Stage(Explore) => has_explore = true
                Stage(Propose) => has_propose = true
                Stage(Implement) => has_implement = true
                Stage(Archived) => has_archived = true
                Stage(SecurityGate) => has_security_gate = true
                Stage(VerifyGate) => include_verify = true
                Boundary => ()
              }
            }
          }
        }
      }
      if !saw_header {
        return Err("expected Mermaid header `stateDiagram-v2`")
      }
      if !has_explore || !has_propose || !has_implement || !has_archived {
        return Err(
          "Mermaid workflow requires Explore, Propose, Implement, and Archived transitions",
        )
      }
      Ok({ has_security_gate, include_verify, })
    }
    BpmnXml => {
      if !trimmed.has_prefix("") {
        return Err("expected BPMN `...` block")
      }
      for raw_line in trimmed.split("\n") {
        let line = raw_line.trim().to_owned()
        if line.is_empty() {
          continue
        }
        if !line.has_prefix("<") || !line.has_suffix(">") {
          return Err("malformed BPMN XML line `\{line}`")
        }
      }
      if !trimmed.contains("id=\"Explore\"") ||
        !trimmed.contains("id=\"Propose\"") ||
        !trimmed.contains("id=\"Implement\"") ||
        !trimmed.contains("id=\"Archived\"") {
        return Err(
          "BPMN process requires Explore, Propose, Implement, and Archived elements",
        )
      }
      Ok({
        has_security_gate: trimmed.contains("id=\"SecurityGate\""),
        include_verify: trimmed.contains("id=\"VerifyGate\""),
      })
    }
    ArtifactYaml => {
      for raw_line in trimmed.split("\n") {
        let line = raw_line.trim().to_owned()
        if line.is_empty() || line.has_prefix("#") {
          continue
        }
        if !line.contains(":") && !line.has_prefix("- ") {
          return Err("invalid YAML line `\{line}`")
        }
      }
      if !trimmed.contains("workflow:") || !trimmed.contains("stages:") {
        return Err("expected `workflow:` and `stages:` keys")
      }
      if !trimmed.contains("propose:") || !trimmed.contains("implement:") {
        return Err("Artifact YAML requires `propose:` and `implement:` stages")
      }
      Ok({
        has_security_gate: trimmed.contains("security_gate:"),
        include_verify: trimmed.contains("verify_gate:"),
      })
    }
  }
}

///|
fn MockupWorkspace::reconcile_stages(self : MockupWorkspace) -> MockupWorkspace {
  let valid_stages = self.stages()
  let studio_stage = if valid_stages
    .iter()
    .any(spec => spec.id == self.studio_stage) {
    self.studio_stage
  } else {
    Implement
  }
  let items = self.items.map(item => {
    if valid_stages.iter().any(spec => spec.id == item.stage) {
      item
    } else if item.stage == VerifyGate {
      { ..item, stage: Implement, }
    } else {
      { ..item, stage: Propose, }
    }
  })
  { ..self, studio_stage, items, }
}

///|
/// Parses an edited Workflow Studio source draft and updates the effective
/// workflow preview when valid, or records a parse error when invalid.
pub fn MockupWorkspace::with_studio_source(
  self : MockupWorkspace,
  source : String,
) -> MockupWorkspace {
  let studio_drafts = self.with_draft_for(self.studio_format, source)
  match parse_studio_draft(self.studio_format, source) {
    Ok({ has_security_gate, include_verify, }) =>
      {
        ..self,
        has_security_gate,
        include_verify,
        studio_drafts,
        studio_parse_error: None,
      }.reconcile_stages()
    Err(message) =>
      { ..self, studio_drafts, studio_parse_error: Some(message), }
  }
}

///|
fn required_stage_artifacts(stage : StageId) -> Array[ArtifactKind] {
  match stage {
    Propose => [ProposalMd, DesignMd, SpecMd, TasksMd]
    Explore => [ExploreMd]
    SecurityGate | Implement | VerifyGate | Archived => []
  }
}

///|
fn ensure_clean_stage_artifacts(
  stage : StageId,
  existing : ReadOnlyArray[WorkflowArtifact],
) -> ReadOnlyArray[WorkflowArtifact] {
  let result : Array[WorkflowArtifact] = existing
    .iter()
    .map(a => { ..a, status: Clean, })
    .to_array()
  for kind in required_stage_artifacts(stage) {
    if !result.iter().any(slot => slot.kind == kind) {
      result.push({ kind, status: Clean, })
    }
  }
  ReadOnlyArray::from_array(result)
}

///|
/// Resolves all open gate checks on `item_id` so transition guards pass,
/// creating any missing required stage artifacts as clean.
pub fn MockupWorkspace::resolve_open_gates(
  self : MockupWorkspace,
  item_id : WorkflowItemId,
) -> MockupWorkspace {
  let min_target = if self.min_scorecard.value() > 92 {
    self.min_scorecard.value()
  } else {
    92
  }
  let items = self.items.map(item => {
    if item.id != item_id {
      item
    } else {
      let next_score = if item.score.value() < min_target {
        Score::clamped(min_target)
      } else {
        item.score
      }
      let next_progress = if item.progress.total() > 0 {
        item.progress.complete_all()
      } else {
        match item.stage {
          Propose => seed_progress(0, 3)
          Implement | SecurityGate | VerifyGate => seed_progress(3, 3)
          Explore | Archived => item.progress
        }
      }
      {
        ..item,
        progress: next_progress,
        warnings: WarningCount::zero(),
        score: next_score,
        artifacts: ensure_clean_stage_artifacts(item.stage, item.artifacts),
      }
    }
  })
  let docs_by_item = self.update_item_docs(item_id, doc => {
    if doc.id == Spec {
      let next_doc_score = if doc.score.value() < min_target {
        Score::clamped(min_target)
      } else {
        doc.score
      }
      { ..doc, score: next_doc_score, read: true, }
    } else {
      doc
    }
  })
  { ..self, items, docs_by_item, }
}

///|
/// Normalizes the deprecated `CC#` term on `target`, clearing warnings and
/// raising its spec score without altering `selected_item`.
fn MockupWorkspace::normalize_deprecated_term_for(
  self : MockupWorkspace,
  target : WorkflowItemId,
) -> MockupWorkspace {
  let items = self.items.map(item => {
    if item.id != target {
      item
    } else {
      let next_score = if item.score.value() < 94 {
        Score::clamped(94)
      } else {
        item.score
      }
      {
        ..item,
        warnings: WarningCount::zero(),
        score: next_score,
        progress: item.progress.complete_all(),
        artifacts: ensure_clean_stage_artifacts(item.stage, item.artifacts),
      }
    }
  })
  let docs_by_item = self.update_item_docs(target, doc => {
    if doc.id == Spec {
      { ..doc, score: Score::clamped(94), read: true, }
    } else {
      doc
    }
  })
  { ..self, items, docs_by_item, active_concept: Pan, }
}

///|
/// Normalizes the deprecated `CC#` term on the active item, clearing warnings
/// and raising its spec score.
pub fn MockupWorkspace::normalize_deprecated_term(
  self : MockupWorkspace,
) -> MockupWorkspace {
  self.normalize_deprecated_term_for(self.selected_item)
}

///|
/// Marks a reading packet document as read or unread for the selected item only.
pub fn MockupWorkspace::toggle_doc_read(
  self : MockupWorkspace,
  doc_id : ReviewDocId,
) -> MockupWorkspace {
  let docs_by_item = self.update_item_docs(self.selected_item, doc => {
    if doc.id == doc_id {
      { ..doc, read: !doc.read, }
    } else {
      doc
    }
  })
  { ..self, docs_by_item, }
}

///|
/// Advances `item_id` to its next stage if all transition guards pass.
pub fn MockupWorkspace::advance_item(
  self : MockupWorkspace,
  item_id : WorkflowItemId,
) -> MockupWorkspace {
  match self.item(item_id) {
    None => self
    Some(item) => {
      let eval = self.evaluate_gates(item)
      match eval.target {
        Some(target) if eval.all_passed() => {
          let items = self.items.map(it => {
            if it.id == item_id {
              { ..it, stage: target, }
            } else {
              it
            }
          })
          { ..self, items, }
        }
        _ => self
      }
    }
  }
}

///|
/// Sends `item_id` back to its previous stage when one exists.
pub fn MockupWorkspace::send_back_item(
  self : MockupWorkspace,
  item_id : WorkflowItemId,
) -> MockupWorkspace {
  match self.item(item_id) {
    None => self
    Some(item) =>
      match self.stage_spec(item.stage).back {
        Some(back) => {
          let items = self.items.map(it => {
            if it.id == item_id {
              { ..it, stage: back, }
            } else {
              it
            }
          })
          { ..self, items, }
        }
        None => self
      }
  }
}

///|
fn MockupWorkspace::with_item_decision(
  self : MockupWorkspace,
  item_id : WorkflowItemId,
  decision : ReviewDecision,
) -> MockupWorkspace {
  let mut replaced = false
  let entries : Array[(WorkflowItemId, ReviewDecision)] = []
  for pair in self.review_decisions {
    if pair.0 == item_id {
      entries.push((item_id, decision))
      replaced = true
    } else {
      entries.push(pair)
    }
  }
  if !replaced {
    entries.push((item_id, decision))
  }
  { ..self, review_decisions: ReadOnlyArray::from_array(entries), }
}

///|
/// Approves the currently selected workflow item from Review when all
/// transition gates pass, recording the actual target stage for that item.
pub fn MockupWorkspace::approve_selected_review(
  self : MockupWorkspace,
) -> MockupWorkspace {
  match self.selected() {
    None => self
    Some(item) => {
      let eval = self.evaluate_gates(item)
      match eval.target {
        Some(target) if eval.all_passed() =>
          self
          .advance_item(item.id)
          .with_item_decision(item.id, Approved(target))
        _ => self
      }
    }
  }
}

///|
/// Sends the currently selected workflow item back from Review when a previous
/// stage exists, recording the actual target stage for that item.
pub fn MockupWorkspace::request_changes_selected_review(
  self : MockupWorkspace,
) -> MockupWorkspace {
  match self.selected() {
    None => self
    Some(item) =>
      match self.stage_spec(item.stage).back {
        Some(back) =>
          self
          .send_back_item(item.id)
          .with_item_decision(item.id, ChangesRequested(back))
        None => self
      }
  }
}

///|
/// Updates the selected workflow preset, reconciling stages and studio state.
pub fn MockupWorkspace::with_preset(
  self : MockupWorkspace,
  preset : WorkflowPreset,
) -> MockupWorkspace {
  let has_security_gate = match preset {
    RegulatedBpmnV1 => true
    OpenSpecSdlcV1 | LightweightRfcV1 => false
    CustomProjectFile => self.has_security_gate
  }
  let include_verify = match preset {
    LightweightRfcV1 => false
    OpenSpecSdlcV1 | RegulatedBpmnV1 => true
    CustomProjectFile => self.include_verify
  }
  let studio_diagram = match preset {
    RegulatedBpmnV1 => BpmnFlow
    OpenSpecSdlcV1 | LightweightRfcV1 | CustomProjectFile => self.studio_diagram
  }
  {
    ..self,
    preset,
    has_security_gate,
    include_verify,
    studio_diagram,
    studio_drafts: [],
    studio_parse_error: None,
  }.reconcile_stages()
}

///|
/// Updates the Verify Gate minimum scorecard score while respecting the policy
/// floor.
pub fn MockupWorkspace::with_min_scorecard(
  self : MockupWorkspace,
  score : Score,
) -> MockupWorkspace {
  let clamped = if score.value() < self.policy_floor.value() {
    self.policy_floor
  } else {
    score
  }
  {
    ..self,
    min_scorecard: clamped,
    studio_drafts: [],
    studio_parse_error: None,
  }
}

///|
/// Toggles the optional Security Gate stage in Workflow Studio.
pub fn MockupWorkspace::toggle_security_gate(
  self : MockupWorkspace,
) -> MockupWorkspace {
  let next = !self.has_security_gate
  let studio_stage = if next {
    SecurityGate
  } else if self.studio_stage == SecurityGate {
    Implement
  } else {
    self.studio_stage
  }
  {
    ..self,
    has_security_gate: next,
    studio_stage,
    studio_drafts: [],
    studio_parse_error: None,
  }.reconcile_stages()
}

///|
/// Generates or returns the editable Workflow Studio source text for the active
/// format.
pub fn MockupWorkspace::studio_source(self : MockupWorkspace) -> String {
  match self.draft_for(self.studio_format) {
    Some(custom) => custom
    None =>
      match self.studio_format {
        Mermaid => {
          let sec = if self.has_security_gate {
            "  Propose --> SecurityGate : spec + ADR\n  SecurityGate --> Implement : PCI sign-off\n"
          } else {
            "  Propose --> Implement : spec + tasks\n"
          }
          let verify = if !self.include_verify {
            "  Implement --> Archived : tasks complete\n"
          } else {
            "  Implement --> VerifyGate : 100% tasks + 0 warnings\n  VerifyGate --> Archived : score >= \{self.min_scorecard.value()}\n"
          }
          "stateDiagram-v2\n  [*] --> Explore\n  Explore --> Propose : intent linked\n\{sec}\{verify}  Archived --> [*]"
        }
        BpmnXml => {
          let sec = if self.has_security_gate {
            "  \n"
          } else {
            ""
          }
          let verify = if !self.include_verify {
            ""
          } else {
            "  = \{self.min_scorecard.value()}\"/>\n"
          }
          "\n  \n  \n\{sec}  \n\{verify}  \n"
        }
        ArtifactYaml => {
          let sec_block = if self.has_security_gate {
            "  security_gate:\n    inputs: [adr, data_dictionary, pci_class]\n    outputs: [security_signoff]\n"
          } else {
            ""
          }
          let verify_block = if !self.include_verify {
            ""
          } else {
            "  verify_gate:\n    min_scorecard: \{self.min_scorecard.value()}\n    policy_floor: \{self.policy_floor.value()}\n"
          }
          "workflow: \{self.preset.id()}\nstages:\n  propose:\n    outputs: [proposal.md, design.md, spec.md, tasks.md]\n\{sec_block}  implement:\n    inputs: [proposal.md, design.md, spec.md, tasks.md]\n\{verify_block}"
        }
      }
  }
}

///|
/// Compact preview telemetry displayed on Line 2 of a sidebar workspace card.
#derive(Eq, Debug)
pub struct WorkspaceSummary {
  active_item_title : String
  in_flight : Int32
  open_warnings : Int32
  mounted_sources : Int32
}

///|
pub extend WorkspaceSummary with Eq::{equal, not_equal}

///|
pub extend WorkspaceSummary with @debug.Debug::{to_repr}

///|
/// Projects the active preview context and compact telemetry counts for one workspace.
pub fn MockupWorkspace::summary(self : MockupWorkspace) -> WorkspaceSummary {
  let active_item_title = match self.selected() {
    Some(item) => item.title
    None => "No active change"
  }
  let mut in_flight : Int32 = 0
  let mut open_warnings : Int32 = 0
  for item in self.items {
    if item.stage != Archived {
      in_flight += 1
    }
    open_warnings += item.warnings.count()
  }
  { active_item_title, in_flight, open_warnings, mounted_sources: 2, }
}

///|
/// Generates the preview `.mission-control/workspace.yaml` excerpt shown in
/// Project Settings.
pub fn MockupWorkspace::config_yaml(self : MockupWorkspace) -> String {
  let stages = self.stages().map(s => s.id.key()).join(", ")
  "workspace: \{self.preset.id()}\nworkflow:\n  preset: \{self.preset.id()}\n  stages: [\{stages}]\n  verify_gate:\n    min_scorecard: \{self.min_scorecard.value()}\n    policy_floor: \{self.policy_floor.value()}"
}