schema: lattice.agents/invariants/v1
invariants:
  - id: app-bridge-authority-is-intersection
    name: "App bridge authority is intersected"
    description: "An app bridge data operation succeeds only when the installed app grants it, the operator consented to it, the caller holds the app role by binding, and the caller's own data-plane identity is authorized."
    scope:
      packages:
        - "Orleans.Lattice.Api.Apps"
      components:
        - "LatticeAppBridge"
        - "AppBridgeInstallPlan"
        - "AppRoleGrantEvaluator"
    violation_modes:
      - "A caller's broad non-app-owned rule widens what the app UI can do."
      - "A manifest bridge request is honoured without recorded bridge consent."
      - "A bridge call bypasses the core data path's ordinary authorization."
    detection_signals:
      - type: exception
        name: "AppBridgeException"
        source: "src/lattice.api.abstractions/Apps/Model/AppBridgeException.cs#AppBridgeException"
      - type: source
        name: "LatticeAppBridge.AuthorizeAsync"
        source: "src/lattice.api.apps/LatticeAppBridge.cs#LatticeAppBridge.AuthorizeAsync"
    remediation:
      - step: "Keep app UI data requests behind ILatticeAppBridge rather than calling ILattice directly from the frame broker."
        source: "src/lattice.api.apps/LatticeAppBridge.cs#LatticeAppBridge"
      - step: "Build app-owned grants from the installed record revision and its consented ceiling."
        source: "src/lattice.api.apps/AppBridgeInstallPlan.cs#AppBridgeInstallPlan.Build"
    sources:
      - "src/lattice.api.apps/LatticeAppBridge.cs#LatticeAppBridge"
      - "src/lattice.api.apps/AppBridgeInstallPlan.cs#AppBridgeInstallPlan"
  - id: app-catalog-sources-cannot-impersonate
    name: "App sources cannot impersonate"
    description: "A catalog source result whose provenance source differs from the source descriptor key is refused as a source misconfiguration."
    scope:
      packages:
        - "Orleans.Lattice.Apps"
      components:
        - "AppSourceSet"
        - "IAppCatalogSource"
    violation_modes:
      - "A source returns a manifest while vouching for another source key."
      - "A duplicate source key is treated as a usable source choice."
    detection_signals:
      - type: source
        name: "AppSourceSet.Check"
        source: "src/lattice.apps/Sources/AppSourceSet.cs#AppSourceSet.Check"
    remediation:
      - step: "Give every registered catalog source a unique descriptor key."
        source: "src/lattice.apps/Sources/AppSourceSet.cs#AppSourceSet"
      - step: "Set AppProvenance.Source to the answering source descriptor key."
        source: "src/lattice.apps/Sources/IAppCatalogSource.cs#IAppCatalogSource"
    sources:
      - "src/lattice.apps/Sources/AppSourceSet.cs#AppSourceSet"
      - "src/lattice.apps/Sources/IAppCatalogSource.cs#IAppCatalogSource"
  - id: app-ceiling-bounds-compiled-grants
    name: "App ceiling bounds compiled grants"
    description: "Every app-owned authorization rule is inside the install record's version-pinned ceiling; excess operations or uncovered exception scopes fail activation and emit no rules."
    scope:
      packages:
        - "Orleans.Lattice.Apps"
      components:
        - "AppRoleCompiler"
        - "AppCapabilityCeiling"
        - "AppActivationEngine"
    violation_modes:
      - "A role operation outside AllowedOperations is silently clamped or granted."
      - "A cross-app or adopted-tree scope without an approved exception emits a rule."
      - "A scopeless capability such as AppInstall or Telemetry is emitted by an app role."
    detection_signals:
      - type: test
        name: "AppRoleCompilerTests.Ceiling"
        source: "test/lattice.apps/Compiler/AppRoleCompilerTests.Ceiling.cs"
      - type: test
        name: "AppRoleCompilerTests.Security"
        source: "test/lattice.apps/Compiler/AppRoleCompilerTests.Security.cs"
      - type: exception
        name: "AppActivationFailure.CeilingExceeded"
        source: "src/lattice.apps/Activation/AppActivationFailure.cs#AppActivationFailure.CeilingExceeded"
    remediation:
      - step: "Re-read the installed manifest and consent report, then update the ceiling for the installed version or reduce the manifest request."
        source: "src/lattice.api.abstractions/Apps/ILatticeAppsControl.cs#ILatticeAppsControl.UpdateConsentAsync"
      - step: "Re-run enable or reconcile after consent changes so the compiler replaces the owned rule set."
        source: "src/lattice.apps/Activation/IAppActivationPipeline.cs#IAppActivationPipeline.ReconcileAsync"
    sources:
      - "src/lattice.apps/Compiler/AppRoleCompiler.cs"
      - "test/lattice.apps/Compiler/AppRoleCompilerTests.Ceiling.cs"
  - id: app-enable-reconciles-current-consent
    name: "App enable uses current consent"
    description: "An enable or consent update cannot leave grants compiled from superseded consent after a concurrent registry change."
    scope:
      packages:
        - "Orleans.Lattice.Apps"
        - "Orleans.Lattice.Api.Apps"
      components:
        - "AppRegistry"
        - "LatticeAppsControl"
        - "AppActivationEngine"
    violation_modes:
      - "A consent update racing an upgrade rolls the app back to the version it read earlier."
      - "Enable marks the record enabled while rules compiled from an older revision remain live."
      - "A narrowed ceiling is recorded but stale grants remain after the facade returns failure."
    detection_signals:
      - type: test
        name: "AppRegistryTests.ExpectedVersion"
        source: "test/lattice.apps/Registry/AppRegistryTests.ExpectedVersion.cs"
      - type: test
        name: "LatticeAppsControlUpgradeRaceTests"
        source: "test/lattice.api.apps/LatticeAppsControlUpgradeRaceTests.cs"
      - type: exception
        name: "AppRegistryTransitionError.ConcurrencyConflict"
        source: "src/lattice.apps/Registry/AppRegistryTransitionError.cs#AppRegistryTransitionError.ConcurrencyConflict"
    remediation:
      - step: "Re-read the app record or consent report and retry with the current installed version."
        source: "src/lattice.api.abstractions/Apps/ILatticeAppsControl.cs#ILatticeAppsControl.GetConsentAsync"
      - step: "Run ReconcileAsync on an enabled app after direct registry upgrades or consent writes."
        source: "src/lattice.apps/Registry/IAppRegistry.cs#IAppRegistry.UpgradeAsync"
    sources:
      - "src/lattice.apps/Registry/AppRegistry.cs"
      - "src/lattice.api.apps/LatticeAppsControl.Install.cs"
      - "test/lattice.api.apps/LatticeAppsControlUpgradeRaceTests.cs"
  - id: app-frame-credential-free
    name: "App frames are credential free"
    description: "A Lattice App frame receives verified bundle bytes and consented bridge results but never receives the Explorer credential."
    scope:
      packages:
        - "Orleans.Lattice.Explorer.UI"
        - "Orleans.Lattice.Explorer.AppKit"
      components:
        - "AppFrame"
        - "AppBridgeBroker"
        - "AppKitProtocol"
    violation_modes:
      - "A credential is included in a frame message."
      - "A frame is allowed to fetch its own bundle over HTTP."
      - "A broker relays a data operation after the active tenant changes."
    detection_signals:
      - type: source
        name: "AppFrameBundleLoader.LoadAsync"
        source: "src/lattice.explorer/UI/AppFrame/AppFrameBundleLoader.cs#AppFrameBundleLoader.LoadAsync"
      - type: source
        name: "AppBridgeBroker.RelayAsync"
        source: "src/lattice.explorer/UI/AppFrame/Broker/AppBridgeBroker.cs#AppBridgeBroker.RelayAsync"
    remediation:
      - step: "Fetch app UI assets through ILatticeAppWorkspace on the circuit credential and deliver bytes over the frame port."
        source: "src/lattice.explorer/UI/AppFrame/AppFrameBundleLoader.cs#AppFrameBundleLoader.LoadAsync"
      - step: "Close the broker session when the circuit's asserted tenant differs from the launch tenant."
        source: "src/lattice.explorer/UI/AppFrame/Broker/AppBridgeBroker.cs#AppBridgeBroker.RelayAsync"
    sources:
      - "docs/lattice.explorer/lattice-apps.md"
      - "src/lattice.explorer/UI/AppFrame/AppFrameBundleLoader.cs#AppFrameBundleLoader"
      - "src/lattice.explorer/UI/AppFrame/Broker/AppBridgeBroker.cs#AppBridgeBroker"
  - id: app-lifecycle-retains-data
    name: "App lifecycle retains data"
    description: "Disable removes app authority while keeping trees and data; uninstall removes app authority, skips adopted trees and soft-deletes structural trees without purging them itself, and the core deferred purge removes those trees after their soft-delete window unless the app is installed and enabled again first."
    scope:
      packages:
        - "Orleans.Lattice.Apps"
        - "Orleans.Lattice.Api.Apps"
      components:
        - "AppActivationEngine"
        - "IAppTreeProvisioner"
        - "ILatticeAppsControl"
    violation_modes:
      - "Disable deletes or soft-deletes an app tree."
      - "Uninstall purges a structural tree instead of soft-deleting it."
      - "Uninstall soft-deletes an adopted tree."
    detection_signals:
      - type: test
        name: "AppActivationEngineTests.Lifecycle"
        source: "test/lattice.apps/Activation/AppActivationEngineTests.Lifecycle.cs"
      - type: exception
        name: "AppActivationFailure.TreeProvisioningFailed"
        source: "src/lattice.apps/Activation/AppActivationFailure.cs#AppActivationFailure.TreeProvisioningFailed"
    remediation:
      - step: "Use DisableAsync to withdraw rules while preserving all trees and data."
        source: "src/lattice.api.abstractions/Apps/ILatticeAppsControl.cs#ILatticeAppsControl.DisableAsync"
      - step: "Use UninstallAsync only when soft-deleting structural app trees under their retention window is intended."
        source: "src/lattice.api.abstractions/Apps/ILatticeAppsControl.cs#ILatticeAppsControl.UninstallAsync"
    sources:
      - "src/lattice.apps/Activation/AppActivationEngine.cs"
      - "test/lattice.apps/Activation/AppActivationEngineTests.Lifecycle.cs"
  - id: app-mcp-tools-paired-exactly
    name: "App MCP tools paired exactly"
    description: "An enabled app contributes MCP tools only when every manifest declaration has exactly one implementation and every implementation is declared."
    scope:
      packages:
        - "Orleans.Lattice.Api.Mcp.Apps"
      components:
        - "AppMcpToolActivation"
        - "AppMcpToolSource"
        - "IAppMcpToolProvider"
    violation_modes:
      - "A declared tool without an implementation is skipped while sibling tools are still advertised."
      - "An undeclared implementation is advertised under the app namespace."
      - "Duplicate local tool implementations are resolved by first-wins ordering."
    detection_signals:
      - type: test
        name: "AppMcpToolActivationTests"
        source: "test/lattice.api.mcp.apps/AppMcpToolActivationTests.cs"
      - type: exception
        name: "AppMcpToolActivation.Failure"
        source: "src/lattice.api.mcp.apps/AppMcpToolActivation.cs#AppMcpToolActivation.Failure"
    remediation:
      - step: "Align manifest mcpTools with the provider's app-local tool names, then let the catalog rebuild on the next registry epoch."
        source: "src/lattice.api.mcp.apps/AppMcpToolActivation.cs#AppMcpToolActivation.Pair"
      - step: "Keep reserved slugs lattice and repocontext off the app MCP surface; use a non-reserved app slug."
        source: "src/lattice.api.mcp.apps/AppMcpToolName.cs#AppMcpToolName.IsReservedSlug"
    sources:
      - "src/lattice.api.mcp.apps/AppMcpToolActivation.cs"
      - "test/lattice.api.mcp.apps/AppMcpToolActivationTests.cs"
  - id: app-owned-rules-system-origin-only
    name: "App-owned rules are compiler-owned"
    description: "Authorization rules whose ids are in the app-owned prefix can be written or deleted only by system-origin app activation, not by direct operator policy writes."
    scope:
      packages:
        - "Orleans.Lattice.Apps"
        - "Orleans.Lattice.Auth"
      components:
        - "LatticeAuthorizationPolicyStore"
        - "LatticeAppRuleIds"
        - "AppActivationEngine"
    violation_modes:
      - "An operator PutRuleAsync writes an app: rule id directly."
      - "An operator RemoveRuleAsync deletes an app: rule id directly."
      - "The app compiler writes rules outside its owned prefix or deletes another app's rules."
    detection_signals:
      - type: test
        name: "LatticeAuthorizationPolicyStoreAppOwnedRuleTests"
        source: "test/lattice.auth/LatticeAuthorizationPolicyStoreAppOwnedRuleTests.cs"
      - type: test
        name: "AppRoleCompilerTests.Diff"
        source: "test/lattice.apps/Compiler/AppRoleCompilerTests.Diff.cs"
      - type: exception
        name: "LatticeAppOwnedRuleException"
        source: "src/lattice.auth/LatticeAppOwnedRuleException.cs#LatticeAppOwnedRuleException"
    remediation:
      - step: "Change app authority by updating role bindings, the manifest, or the app consent, then reconcile the app."
        source: "docs/lattice.apps/README.md"
      - step: "Author any operator override as a separate rule id outside the app-owned prefix."
        source: "src/lattice.auth/LatticeAppRuleIds.cs#LatticeAppRuleIds.Prefix"
    sources:
      - "src/lattice.auth/ILatticeAuthorizationPolicyStore.cs"
      - "src/lattice.apps/Compiler/AppRoleCompiler.cs"
      - "test/lattice.auth/LatticeAuthorizationPolicyStoreAppOwnedRuleTests.cs"
  - id: app-physical-tree-ids-not-disclosed
    name: "App control hides physical tree ids"
    description: "App-control responses and sanitized exceptions expose app slugs, app-local tree names and, for an adopted tree, the pre-app tree id, but never composed physical tree ids."
    scope:
      packages:
        - "Orleans.Lattice.Api.Apps"
      components:
        - "LatticeAppsControl"
        - "AppsControlExceptionSanitizer"
        - "AppsControlMapping"
    violation_modes:
      - "Describe, list, or consent responses echo a composed a/{app}/{tree} or t/{tenant}/a/{app}/{tree} id."
      - "A propagated exception message contains a composed app tree id."
      - "A large inner exception graph is forwarded intact after a composed id appears below the inspection budget."
    detection_signals:
      - type: test
        name: "LatticeAppsControlSanitizationTests"
        source: "test/lattice.api.apps/LatticeAppsControlSanitizationTests.cs"
      - type: exception
        name: "InvalidOperationException"
        source: "src/lattice.api.apps/AppsControlExceptionSanitizer.cs#AppsControlExceptionSanitizer.TryRewrite"
    remediation:
      - step: "Sanitize facade exceptions before they cross the app-control boundary."
        source: "src/lattice.api.apps/AppsControlExceptionSanitizer.cs#AppsControlExceptionSanitizer.TryRewrite"
      - step: "Return app-local tree names and AppExceptionScope logical shapes instead of composed physical ids."
        source: "docs/lattice.api.apps/README.md"
    sources:
      - "src/lattice.api.apps/AppsControlExceptionSanitizer.cs"
      - "src/lattice.api.apps/AppsControlMapping.cs"
      - "test/lattice.api.apps/LatticeAppsControlSanitizationTests.cs"
  - id: app-role-binding-is-only-grant
    name: "App role binding is the only grant"
    description: "A caller holds an app role only through a bound membership group, and an access-gate deny can remove that role but cannot add one."
    scope:
      packages:
        - "Orleans.Lattice.Apps"
        - "Orleans.Lattice.Api.Apps"
      components:
        - "AppRoleGate"
        - "AppRoleGrantEvaluator"
        - "LatticeAppWorkspace"
        - "LatticeAppBridge"
    violation_modes:
      - "A caller's non-app-owned allow rule makes the caller hold an app role."
      - "The workspace reports a role that the bridge would refuse for the same caller."
      - "An access-gate allow adds a role before a binding holds."
    detection_signals:
      - type: source
        name: "AppRoleGate.IsHeldAsync"
        source: "src/lattice.apps/Registry/AppRoleGate.cs#AppRoleGate.IsHeldAsync"
      - type: source
        name: "AppRoleGrantEvaluator.EvaluateAsync"
        source: "src/lattice.apps/Registry/AppRoleGrantEvaluator.cs#AppRoleGrantEvaluator.EvaluateAsync"
    remediation:
      - step: "Use the single app role-grant evaluation for workspace, MCP and bridge-facing role decisions."
        source: "src/lattice.apps/Registry/AppRoleGrantEvaluator.cs#AppRoleGrantEvaluator"
      - step: "Ask the access gate only after the caller is shown to hold the app role by binding."
        source: "src/lattice.apps/Registry/AppRoleGate.cs#AppRoleGate.IsHeldAsync"
    sources:
      - "src/lattice.apps/Registry/AppRoleGate.cs#AppRoleGate"
      - "src/lattice.apps/Registry/AppRoleGrantEvaluator.cs#AppRoleGrantEvaluator"
  - id: app-tree-single-owner
    name: "App trees have a single owning install"
    description: "Every structural and adopted tree an app uses belongs to exactly one install at a time, as recorded in the sys-app-trees ownership ledger, so one app's data is never readable or writable under another app's name."
    scope:
      packages:
        - "Orleans.Lattice.Apps"
        - "Orleans.Lattice.Api.Apps"
      components:
        - "AppTreeOwnershipLedger"
        - "AppRegistry"
        - "AppActivationEngine"
        - "AppTreeOwnershipGuard"
    violation_modes:
      - "Two installs hold a claim on the same tree."
      - "An install takes over a pre-existing unowned structural tree, a derived copy, or another tree's alias target."
      - "A structural claim is released while the uninstalled tree is still inside its soft-delete window."
      - "A cross-app role scope or subscription compiles for a tree whose owner is not installed in the same tenant."
    detection_signals:
      - type: exception
        name: "AppActivationFailure.TreeOwnershipConflict"
        source: "src/lattice.apps/Activation/AppActivationFailure.cs#AppActivationFailure.TreeOwnershipConflict"
      - type: test
        name: "AppTreeOwnershipLedgerTests"
        source: "test/lattice.apps/Ownership/AppTreeOwnershipLedgerTests.cs"
      - type: test
        name: "AppActivationEngineTests.Ownership"
        source: "test/lattice.apps/Activation/AppActivationEngineTests.Ownership.cs"
    remediation:
      - step: "Read the conflicts an install would hit with IAppRegistry.GetTreeOwnershipConflictsAsync or DescribeAsync before installing."
        source: "src/lattice.apps/Registry/IAppRegistry.cs#IAppRegistry.GetTreeOwnershipConflictsAsync"
      - step: "Uninstall the owning install, or stop declaring the adopted tree, to release the claim before another install adopts the tree."
        source: "docs/lattice.apps/README.md"
    sources:
      - "docs/lattice.apps/README.md"
      - "src/lattice.apps/Ownership/AppTreeOwnershipLedger.cs"
  - id: atomic-action-compensation-terminal
    name: "Atomic action terminal outcome"
    description: "An atomic action reaches one terminal outcome and compensates prepared participants on failure without exposing a partial plan as successful."
    scope:
      packages:
        - "Orleans.Lattice"
      components:
        - "AtomicActionGrain"
        - "Atomic action handlers"
    violation_modes:
      - "A participant commit is reported successful after a sibling participant failed."
      - "Compensation failure is hidden from the caller as a completed plan."
      - "A crashed coordinator is not resumed to a terminal state."
    detection_signals:
      - type: test
        name: "AtomicActionCoyoteTests"
        source: "test/lattice/BPlusTree/Coyote/AtomicActionCoyoteTests.cs"
      - type: metric
        name: "orleans.lattice.atomic_write.completed"
        source: "src/lattice/LatticeMetrics.cs"
      - type: exception
        name: "CompensationFailedException"
        source: "src/lattice/Sagas/CompensationFailedException.cs"
    remediation:
      - step: "On CompensationFailedException, use the failed step index for operator intervention."
        source: "docs/lattice/atomic-action.md"
      - step: "Allow reminder-driven recovery to resume from persisted state and reach the terminal outcome exactly once."
        source: "docs/lattice/atomic-action.md"
    sources:
      - "docs/lattice/atomic-action.md"
      - "test/lattice/BPlusTree/Coyote/AtomicActionCoyoteTests.cs"
  - id: atomic-batch-all-or-nothing
    name: "Atomic batch all-or-nothing visibility"
    description: "A single-tree atomic batch is either fully visible or fully hidden on every read path and on every replicated cluster."
    scope:
      packages:
        - "Orleans.Lattice"
        - "Orleans.Lattice.Replication"
      components:
        - "AtomicWriteGrain"
        - "TxRegistryGrain"
        - "AtomicVisibilityGate"
        - "ReaderStabilityGate"
    violation_modes:
      - "A reader observes only some keys from an in-flight saga."
      - "A commit decision is recorded after a leaf terminal is applied."
      - "A transaction registry decision flips or is retired before all prepared buckets drain."
      - "A reader serves a prepared or pre-saga value after the transaction registry failed to answer."
    detection_signals:
      - type: test
        name: "AtomicCommitInvariantCoyoteTests"
        source: "test/lattice/BPlusTree/Coyote/AtomicCommitInvariantCoyoteTests.cs"
      - type: test
        name: "TlcModelCheckTests"
        source: "test/lattice/Formal/TlcModelCheckTests.cs"
      - type: metric
        name: "orleans.lattice.atomic_write.completed"
        source: "src/lattice/LatticeMetrics.cs"
      - type: exception
        name: "InvalidOperationException"
        source: "docs/lattice/atomic-writes.md"
      - type: exception
        name: "LatticeTransactionOutcomeUnavailableException"
        source: "src/lattice/LatticeTransactionOutcomeUnavailableException.cs"
    remediation:
      - step: "Retry transport-level failures with the same operation id so the call re-attaches to the original saga."
        source: "docs/lattice/atomic-writes.md"
      - step: "Keep the registry decision recorded until every participant has drained its prepared bucket."
        source: "spec/atomic-commit/AtomicCommit.tla"
      - step: "When several prepared buckets cover one key, select the bucket that can still decide visibility rather than letting an older undecided bucket shadow a newer committed batch or a newer in-flight bucket shadow an older committed one."
        source: "src/lattice/BPlusTree/AtomicVisibilityGate.cs#AtomicVisibilityGate.SelectDecidingPrepare"
      - step: "Run the paired non-vacuous guard when changing a catalogued property."
        source: "docs/lattice/verified-atomic-commit.md"
      - step: "When a read reaches prepared rows and the transaction registry cannot be reached, fail with LatticeTransactionOutcomeUnavailableException rather than guessing visibility."
        source: "docs/lattice/atomic-writes.md"
    sources:
      - "docs/lattice/atomic-writes.md"
      - "docs/lattice/api.md"
      - "docs/lattice/consistency.md"
      - "docs/lattice/verified-atomic-commit.md"
      - "spec/atomic-commit/AtomicCommit.tla"
      - "spec/atomic-commit/README.md"
      - "test/lattice/Formal/TlcModelCheckTests.cs"
  - id: atomic-cross-cluster-receiver-gate
    name: "Cross-cluster atomic receiver gate"
    description: "A receiver does not flip a replicated atomic batch visible until every producer shard terminal for that saga has arrived."
    scope:
      packages:
        - "Orleans.Lattice"
        - "Orleans.Lattice.Replication"
      components:
        - "ReplicationApplier"
        - "TxRegistryGrain"
        - "TerminalArrivalTally"
        - "LatticeGrain.ApplyTxTerminalAsync"
    violation_modes:
      - "The first replicated terminal flips the receiver registry before all source shards arrive."
      - "Prepared records enter the batched visible merge path instead of the pending bucket."
      - "Conflicting terminal outcomes are absorbed instead of rejected."
      - "A terminal arrival that conflicts with a decision whose row was purged after the decision-retention window is recorded rather than rejected, because no row remains to classify against."
    detection_signals:
      - type: metric
        name: "orleans.lattice.replication.apply.duration"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
      - type: test
        name: "TerminalArrivalTallyTests"
        source: "test/lattice/BPlusTree/TerminalArrivalTallyTests.cs"
      - type: exception
        name: "InvalidOperationException"
        source: "docs/lattice/atomic-writes.md"
    remediation:
      - step: "Leave the receiver registry mark unset and pending buckets undrained until the final terminal arrival."
        source: "docs/lattice/atomic-writes.md"
      - step: "Route prepared Set and Delete records through the per-entry prepared apply hops."
        source: "docs/lattice.replication/replication-apply.md"
      - step: "Reject a terminal arrival whose outcome conflicts with a decision row the registry still stores, tombstoned or not; the write-once rule holds within the decision-retention window and is not claimed across a purge."
        source: "src/lattice/BPlusTree/TerminalDecisionGuard.cs#TerminalDecisionGuard"
    sources:
      - "docs/lattice/atomic-writes.md"
      - "docs/lattice.replication/replication-apply.md"
      - "src/lattice/BPlusTree/TerminalDecisionGuard.cs"
      - "src/lattice/BPlusTree/Grains/TxRegistryGrain.cs"
  - id: atomic-cross-tree-global-decision
    name: "Cross-tree global decision"
    description: "A cross-tree atomic write has one coordinator decision that all participating trees resolve before exposing any prepared key."
    scope:
      packages:
        - "Orleans.Lattice"
        - "Orleans.Lattice.Replication"
      components:
        - "LatticeCrossTreeTxGrain"
        - "LatticeCrossTreeReceiverGrain"
        - "TxRegistryGrain"
    violation_modes:
      - "A participating tree commits while a sibling tree aborts or remains in flight."
      - "A delegated registry read returns pre-saga instead of indeterminate when the coordinator is unreachable."
      - "A remote receiver flips one participating tree before the receiver coordinator hears from the rest of its local wait set."
    detection_signals:
      - type: metric
        name: "orleans.lattice.atomic_write.cross_tree.completed"
        source: "src/lattice/LatticeMetrics.cs"
      - type: metric
        name: "orleans.lattice.atomic_write.cross_tree.participants"
        source: "src/lattice/LatticeMetrics.cs"
      - type: exception
        name: "InvalidOperationException"
        source: "docs/lattice/atomic-writes.md"
    remediation:
      - step: "Resolve delegated txids against the coordinator and return Indeterminate when the coordinator cannot be reached."
        source: "docs/lattice/atomic-writes.md"
      - step: "Use a stable operation id for safe retry."
        source: "docs/lattice/atomic-writes.md"
      - step: "Wait for the receiver coordinator decision before finalizing participating trees on the receiver."
        source: "docs/lattice/atomic-writes.md"
    sources:
      - "docs/lattice/atomic-writes.md"
      - "docs/lattice/consistency.md"
      - "spec/atomic-commit/AtomicCommit.tla"
  - id: auth-fail-closed-access-gates
    name: "Authorization fails closed"
    description: "Authorization denies on missing rules, ambiguous security context, or direct external grain calls, and denied mutations leave no partial state."
    scope:
      packages:
        - "Orleans.Lattice.Auth"
        - "Orleans.Lattice.Api.Auth"
        - "Orleans.Lattice"
      components:
        - "ILatticeDecisionEngine"
        - "Access gate"
        - "Incoming grain call filter"
    violation_modes:
      - "A missing allow rule or null collaborator permits a mutation."
      - "A denied mutation writes any leaf, WAL, or coordinator state."
      - "A forged RequestContext capability bypasses the facade gate."
      - "A direct external grain call reaches the tree registry's privileged routing or system-tree access."
    detection_signals:
      - type: metric
        name: "orleans.lattice.auth.decisions"
        source: "src/lattice.auth/LatticeAuthMetrics.cs"
      - type: log
        name: "LatticeAuthDecisionObserver"
        source: "src/lattice.auth/LatticeAuthDecisionObserver.cs"
      - type: exception
        name: "LatticeAuthorizationDeniedException"
        source: "src/lattice/LatticeAuthorizationDeniedException.cs"
    remediation:
      - step: "Deny unmatched decisions by default on the recommended configuration."
        source: "docs/lattice.auth/security-posture.md"
      - step: "Register explicit grants for access that should be allowed."
        source: "docs/lattice.auth/security-posture.md"
      - step: "Keep gate enforcement on the facade grains and internal-origin assertions on physical grains."
        source: "docs/lattice.auth/security-posture.md"
      - step: "Keep the tree registry grain's incoming-call filter asserting internal grain origin for the registry tree before any registry call runs."
        source: "src/lattice/BPlusTree/Grains/LatticeRegistryGrain.InternalOriginGuard.cs#LatticeRegistryGrain"
    sources:
      - ".github/instructions/security.instructions.md"
      - "docs/lattice.auth/security-posture.md"
  - id: backup-content-address-integrity
    name: "Backup content-address integrity"
    description: "A restore verifies every manifest artifact against its recorded content digest before installing any backup data."
    scope:
      packages:
        - "Orleans.Lattice.Backup"
        - "Orleans.Lattice.Api.Backup"
        - "Orleans.Lattice.Api.Backup.Grpc"
      components:
        - "ILatticeBackupRestoreService"
        - "BackupManifest"
        - "BackupContentDescriptor"
        - "BackupHealthReport"
    violation_modes:
      - "A missing or uncommitted artifact is treated as restorable."
      - "An artifact whose bytes no longer match its content hash is installed."
      - "A health report marks a mismatched backup healthy."
    detection_signals:
      - type: health
        name: "BackupHealthReport.Status"
        source: "src/lattice.backup/BackupHealthReport.cs"
      - type: metric
        name: "orleans.lattice.backup.restore.failures"
        source: "src/lattice.backup/LatticeBackupMetrics.cs"
      - type: exception
        name: "LatticeRestoreValidationException"
        source: "src/lattice.backup/LatticeRestoreValidationException.cs"
    remediation:
      - step: "Abort the restore before installing anything when artifact digest verification fails."
        source: "docs/lattice.backup/architecture.md"
      - step: "Read BackupHealthReport to identify missing and hash-mismatched artifact ids."
        source: "docs/lattice.backup/api.md"
    sources:
      - "docs/lattice.backup/api.md"
      - "docs/lattice.backup/architecture.md"
      - "docs/lattice.backup/observability.md"
  - id: backup-cross-tree-fence
    name: "Backup cross-tree fence"
    description: "A cross-tree-consistent backup set captures all member trees at one shared causal fence after in-flight cross-tree sagas touching the set have drained."
    scope:
      packages:
        - "Orleans.Lattice.Backup"
        - "Orleans.Lattice"
      components:
        - "ILatticeBackupCaptureService"
        - "BackupSetFence"
        - "Cross-tree atomic registry"
    violation_modes:
      - "A member backup is stamped into a set while a touching cross-tree saga remains in flight."
      - "A capture set selects different fences for different members."
      - "A fence that cannot stabilize is recorded as a successful selection."
    detection_signals:
      - type: metric
        name: "orleans.lattice.backup.cross_tree_fence.retries"
        source: "src/lattice.backup/BackupMetrics.cs"
      - type: metric
        name: "orleans.lattice.backup.cross_tree_fence.selections"
        source: "src/lattice.backup/BackupMetrics.cs"
      - type: exception
        name: "LatticeBackupCrossTreeFenceException"
        source: "src/lattice.backup/LatticeBackupCrossTreeFenceException.cs"
    remediation:
      - step: "Wait for in-flight cross-tree sagas touching the set to drain before selecting the fence."
        source: "docs/lattice.backup/architecture.md"
      - step: "Retry fence selection up to the configured attempt and timeout bounds."
        source: "docs/lattice.backup/architecture.md"
      - step: "Fail the capture with LatticeBackupCrossTreeFenceException when the fence cannot stabilize."
        source: "docs/lattice.backup/api.md"
    sources:
      - "docs/lattice.backup/architecture.md"
      - "docs/lattice.backup/api.md"
      - "docs/lattice.backup/observability.md"
  - id: backup-operation-runner-liveness
    name: "Backup operation runner liveness"
    description: "A tracked backup or restore operation runs on the accepting silo, heartbeats while active, and is marked Failed rather than left Running when that silo is lost or its lease lapses."
    scope:
      packages:
        - "Orleans.Lattice.Api.Backup"
        - "Orleans.Lattice.Backup"
      components:
        - "ILatticeBackupOperations"
        - "LatticeOperationStatus"
        - "LatticeOperationRunner"
    violation_modes:
      - "An operation remains Running after the accepting silo is declared dead."
      - "A background backup or restore silently resumes without a caller starting a new operation."
      - "A failure reason omits that the runner silo was lost or stopped heartbeating."
    detection_signals:
      - type: status
        name: "LatticeOperationStatus.State"
        source: "src/lattice.api.abstractions/Operations/Model/LatticeOperationStatus.cs"
      - type: status
        name: "LatticeOperationStatus.FailureReason"
        source: "src/lattice.api.abstractions/Operations/Model/LatticeOperationStatus.cs"
    remediation:
      - step: "Treat Failed after silo loss as terminal and start a new tracked operation if the backup or restore is still needed."
        source: "docs/lattice.api.abstractions/operations.md"
      - step: "Use the previous status and backup catalog to decide whether partial work produced an artifact before retrying."
        source: "docs/lattice.api.backup/operations.md"
    sources:
      - "docs/lattice.api.abstractions/operations.md"
      - "docs/lattice.api.backup/operations.md"
  - id: backup-restore-coordinated-cutover
    name: "Coordinated restore cutover"
    description: "A restore of any currently replicated tree or backup set with a replicated member commits the restored cut on every current peer or compensates everywhere."
    scope:
      packages:
        - "Orleans.Lattice.Backup"
        - "Orleans.Lattice.Replication"
      components:
        - "ILatticeCoordinatedRestoreEngine"
        - "IRestoreSagaDispatcher"
        - "Backup sink sharing probe"
    violation_modes:
      - "A replicated restore runs only on the local cluster."
      - "A peer is unreachable but the restore starts anyway."
      - "A prepared participant leaks its write fence after coordinator loss."
      - "A replicated deployment captures to sinks that peers cannot read."
    detection_signals:
      - type: metric
        name: "orleans.lattice.replication.saga.phase.duration"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
      - type: metric
        name: "orleans.lattice.replication.saga.compensations"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
      - type: health
        name: "BackupHealthReport.PeerVisibility"
        source: "src/lattice.backup/BackupHealthReport.cs"
      - type: exception
        name: "LatticeRestoreValidationException"
        source: "src/lattice.backup/LatticeRestoreValidationException.cs"
    remediation:
      - step: "Refuse to start a coordinated restore when any current peer cannot be reached."
        source: "docs/lattice.replication/coordinated-restore.md"
      - step: "Compensate every prepared participant on abort."
        source: "docs/lattice.replication/coordinated-restore.md"
      - step: "Configure replicated clusters to use the same backup sink before relying on coordinated restore."
        source: "docs/lattice.replication/coordinated-restore.md"
    sources:
      - "docs/lattice.replication/coordinated-restore.md"
      - "docs/lattice.backup/architecture.md"
  - id: crdt-buffer-ownership
    name: "CRDT byte-buffer ownership"
    description: "Registers and sequences store caller-authored byte arrays by handoff, set primitives encode them instead of retaining them, peer-folded winners are copied, and every public egress projection is copied."
    scope:
      packages:
        - "Orleans.Lattice"
      components:
        - "ICrdt"
        - "BoundedRegister"
        - "MvRegister"
        - "Rga"
        - "OrMap"
    violation_modes:
      - "A public projection returns a reference into durable CRDT state."
      - "A peer merge aliases a winning candidate buffer into local state."
      - "A losing candidate allocation adds steady-state duplicate-delivery cost."
    detection_signals:
      - type: test
        name: "CrdtBufferOwnershipContractTestsBase"
        source: "test/lattice/Primitives/CrdtBufferOwnershipContractTests.cs"
    remediation:
      - step: "Copy only the winning candidate when folding peer or delta state."
        source: ".github/instructions/primitives.instructions.md"
      - step: "Copy every public egress buffer and keep aliasing views internal."
        source: ".github/instructions/primitives.instructions.md"
      - step: "Register a specimen for every new byte-bearing CRDT in the ownership contract tests."
        source: ".github/instructions/primitives.instructions.md"
    sources:
      - ".github/instructions/primitives.instructions.md"
      - "docs/crdt/readme.md"
  - id: crdt-merge-laws
    name: "CRDT merge laws"
    description: "Every CRDT primitive merge except HLC successor merge is commutative, associative, and idempotent."
    scope:
      packages:
        - "Orleans.Lattice"
        - "Orleans.Lattice.Replication"
      components:
        - "ICrdt"
        - "LwwValue"
        - "VersionVector"
        - "OrSet"
        - "RwSet"
        - "MvRegister"
        - "OrMap"
        - "Rga"
    violation_modes:
      - "A duplicate delta changes visible state."
      - "Two replicas converge to different values after applying the same states in different orders."
      - "A sender-side combined delta is not equivalent to sequential receiver apply."
    detection_signals:
      - type: test
        name: "primitive merge law tests"
        source: "test/lattice/Primitives/CrdtMergeLawTests.cs"
      - type: test
        name: "typed delta apply tests"
        source: "test/lattice.replication/PublicApiContract/PublicReplicationApiContractTests.CrdtDeltas.cs"
      - type: metric
        name: "orleans.lattice.replication.coalesce.deltas_merged"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
    remediation:
      - step: "Write convergent values through typed CRDT accessors when last-writer-wins would lose concurrent updates."
        source: "docs/lattice/state-primitives.md"
      - step: "Dead-letter enrolled replication entries whose wire mode disagrees with the locally resolved mode."
        source: "docs/lattice.replication/replication-apply.md"
    sources:
      - ".github/instructions/primitives.instructions.md"
      - "docs/crdt/readme.md"
      - "docs/lattice/state-primitives.md"
      - "docs/lattice.replication/deltas.md"
  - id: delegated-tenant-access-off-is-inert
    name: "Delegated tenant access administration off is inert"
    description: "With LatticeTenancyOptions.DelegatedAccessAdministrationEnabled false (the default), member entries, group admin entries and tenant-tier rules have no effect, active-tenant validation is the exact-id admin check, the delegated facades refuse with TenantAccessAdministrationDisabledException except posture, and turning the flag off deletes nothing. Tenant group records are kept and still satisfy an operator rule or app role binding that names them through their directory-recorded members, while identity-provider-asserted t/ group claims stay stripped whenever tenancy is registered."
    scope:
      packages:
        - "Orleans.Lattice.Tenancy"
        - "Orleans.Lattice.Auth"
        - "Orleans.Lattice.Membership"
        - "Orleans.Lattice.Api.TenantAdmin"
      components:
        - "DelegatedTenantAccessFlag"
        - "TenancyTenantRuleLayer"
        - "LatticeTenantPolicyEngine"
        - "TenantAccessAdministrationDisabledException"
    violation_modes:
      - "A member or group entry admits a subject while the flag is off."
      - "Turning the flag off also stops stripping asserted t/ group claims (the claim filter must stay active)."
      - "The evaluator consults a tenant-tier rule while the flag is off."
      - "Turning the flag off deletes tenant groups, members or rules."
      - "A snapshot compiled with the flag on keeps honouring member entries after the flag is turned off."
    detection_signals:
      - type: test
        name: "TenantAccessConformanceTests"
        source: "test/lattice.api.tenantadmin/Security/TenantAccessConformanceTests.cs"
      - type: test
        name: "DelegatedAccessStaleSnapshotTests"
        source: "test/lattice.tenancy/DelegatedAccessStaleSnapshotTests.cs"
      - type: test
        name: "LatticeTenantDirectoryAdminFeatureOffIntegrationTests"
        source: "test/lattice.api.tenantadmin/Directory/LatticeTenantDirectoryAdminFeatureOffIntegrationTests.cs"
      - type: test
        name: "TenantLayerAllocationTests"
        source: "test/lattice.auth/TenantLayerAllocationTests.cs"
    remediation:
      - step: "Read TenantAccessPosture.Enabled or AccessModelDescriptor.DelegatedTenantAccessAdministrationEnabled before relying on tenant groups or rules."
        source: "docs/lattice.tenancy/README.md"
    sources:
      - "docs/lattice.tenancy/README.md"
      - "src/lattice.tenancy/LatticeTenancyOptions.cs"
  - id: distributed-lock-fencing
    name: "Distributed lock fencing"
    description: "Every lock grant has a durable, strictly increasing fencing token and stale holders cannot renew, release, or write through lower tokens."
    scope:
      packages:
        - "Orleans.Lattice"
      components:
        - "LatticeLockGrain"
        - "LockAdmissionCore"
        - "LockToken"
    violation_modes:
      - "A fencing token is reused after a crash or reactivation."
      - "An expired holder writes after a later holder receives a higher token."
      - "A timed-out waiter remains in the FIFO queue."
    detection_signals:
      - type: test
        name: "LockAdmissionCoyoteTests"
        source: "test/lattice/BPlusTree/Coyote/LockAdmissionCoyoteTests.cs"
      - type: metric
        name: "orleans.lattice.lock.lease_reclaimed"
        source: "src/lattice/LatticeMetrics.cs"
      - type: status-field
        name: "LockStatus.CurrentFencingToken"
        source: "docs/lattice/distributed-lock.md"
    remediation:
      - step: "Forward the granted fencing token to the guarded resource with every write."
        source: "docs/lattice/distributed-lock.md"
      - step: "Have the guarded resource reject writes carrying a token lower than the highest token it has accepted."
        source: "docs/lattice/distributed-lock.md"
      - step: "Renew periodically for work that outlives a single lease."
        source: "docs/lattice/distributed-lock.md"
    sources:
      - "docs/lattice/distributed-lock.md"
      - "test/lattice/BPlusTree/Coyote/LockAdmissionCoyoteTests.cs"
  - id: explorer-circuit-scope-isolation
    name: "Explorer circuit scoped credentials"
    description: "Explorer authentication, connection, and credential services are scoped per Blazor circuit and are never captured by singletons or hosted services."
    scope:
      packages:
        - "Orleans.Lattice.Explorer.Core"
        - "Orleans.Lattice.Explorer.Web"
        - "Orleans.Lattice.Explorer.Entra"
        - "Orleans.Lattice.Explorer.Entra.Web"
      components:
        - "Explorer web head"
        - "Circuit services"
        - "Security headers middleware"
    violation_modes:
      - "A singleton captures per-user credential state."
      - "One circuit can reuse another operator's auth session."
      - "Security response headers are omitted on the Explorer branch."
      - "A credential clear that cannot send response headers leaves the stored cookie replayable against an endpoint the console was repointed to."
    detection_signals:
      - type: test
        name: "Explorer service lifetime tests"
        source: "test/lattice.explorer/Authentication/ExplorerAuthCircuitIsolationTests.cs"
      - type: health
        name: "security response headers"
        source: ".github/instructions/security.instructions.md"
      - type: test
        name: "CookieCredentialStoreTests"
        source: "test/lattice.explorer/Web/CookieCredentialStoreTests.cs"
    remediation:
      - step: "Register per-user auth, connection, and credential services as scoped."
        source: ".github/instructions/security.instructions.md"
      - step: "Audit new Explorer services so no singleton or hosted service captures the scoped auth or connection graph."
        source: ".github/instructions/security.instructions.md"
      - step: "Emit the Explorer security response headers through middleware on the Explorer branch."
        source: ".github/instructions/security.instructions.md"
      - step: "Revoke the presented cookie value in-process on every ClearAsync and refuse a revoked value in GetAsync, whether or not the delete header could be sent."
        source: "src/lattice.explorer/WebHosting/CookieCredentialStore.cs#CookieCredentialStore"
      - step: "Bind each persisted cookie credential to the endpoint it was minted for and refuse it when the configured endpoint cannot be resolved or differs."
        source: "src/lattice.explorer/WebHosting/CookieCredentialStore.cs#CookieCredentialStore.GetAsync"
    sources:
      - ".github/instructions/security.instructions.md"
      - "src/lattice.explorer/WebHosting/CookieCredentialStore.cs"
  - id: grain-key-storage-safe
    name: "Persistent grain keys are storage safe"
    description: "A persistent grain composite key uses one marked builder that cannot emit storage-unsafe control or URL-forbidden characters."
    scope:
      packages:
        - "Orleans.Lattice"
        - "Orleans.Lattice.Backup"
      components:
        - "Persistent grain key builders"
        - "LatticeCrossTreeReceiverGrain"
        - "BackupScopeKey"
    violation_modes:
      - "A composite persistent key contains a control character or '/', '\\', '#', or '?'."
      - "Two distinct inputs encode to one persistent grain key."
      - "A key-shape change strands existing durable state without a read-migration path."
    detection_signals:
      - type: test
        name: "GrainKeyStorageSafetyContractTestsBase"
        source: "test/lattice/GrainKeyStorageSafetyContractTests.cs"
      - type: exception
        name: "HTTP 400 Invalid URL from storage provider"
        source: ".github/instructions/grains.instructions.md"
    remediation:
      - step: "Compose each persistent composite key in a single static method marked GrainKeyBuilder."
        source: ".github/instructions/grains.instructions.md"
      - step: "Use length-prefixing or another deterministic storage-safe encoding rather than unsafe delimiters."
        source: ".github/instructions/grains.instructions.md"
      - step: "Keep reading the old key shape until the durable state written under it has aged out."
        source: ".github/instructions/grains.instructions.md"
    sources:
      - ".github/instructions/grains.instructions.md"
  - id: grain-storage-etag-fencing
    name: "Grain storage ETag fencing"
    description: "The grain storage provider registered by AddLattice must reject writes that carry a stale ETag; otherwise stale duplicate activations or direct pin writes can overwrite newer durable state while WAL pins retain newer offsets."
    scope:
      packages:
        - "Orleans.Lattice"
      components:
        - "LatticeServiceCollectionExtensions"
        - "LatticeGrainStorageFencingOptions"
        - "GrainStorageFencingCheck"
        - "GrainStorageFencingProbe"
    violation_modes:
      - "The provider accepts a stale ETag write and an older checkpoint overwrites a newer one."
      - "A stale duplicate activation persists grain state during membership churn."
      - "A direct durable WAL pin write from outside a grain overwrites a newer pin row."
    detection_signals:
      - type: source
        name: "GrainStorageFencingProbeResult.Verdict"
        source: "src/lattice/Storage/GrainStorageFencingProbeResult.cs#GrainStorageFencingProbeResult"
      - type: exception
        name: "OrleansConfigurationException"
        source: "src/lattice/Storage/GrainStorageFencingCheck.cs#GrainStorageFencingCheck.RunAsync"
      - type: log
        name: "Lattice grain-storage fencing check"
        source: "src/lattice/Storage/GrainStorageFencingCheck.cs#GrainStorageFencingCheck.RunAsync"
    remediation:
      - step: "Use a grain storage provider that enforces ETags, such as Orleans memory, Azure Table, Azure Blob, Cosmos DB, or ADO.NET storage."
        source: "src/lattice/LatticeServiceCollectionExtensions.cs#LatticeServiceCollectionExtensions.AddLattice"
      - step: "Keep LatticeGrainStorageFencingOptions.Mode at its default, Reject, so silo start fails when the provider accepts a stale ETag; Warn only logs the finding."
        source: "src/lattice/Storage/LatticeGrainStorageFencingMode.cs#LatticeGrainStorageFencingMode.Reject"
      - step: "Leave Disabled only for deliberately non-durable deployments where the probe writes are unwanted."
        source: "src/lattice/Storage/LatticeGrainStorageFencingMode.cs#LatticeGrainStorageFencingMode.Disabled"
    sources:
      - "src/lattice/LatticeServiceCollectionExtensions.cs#LatticeServiceCollectionExtensions.AddLattice"
      - "src/lattice/Storage/LatticeGrainStorageFencingOptions.cs#LatticeGrainStorageFencingOptions"
      - "src/lattice/Storage/GrainStorageFencingCheck.cs#GrainStorageFencingCheck"
      - "src/lattice/Storage/GrainStorageFencingProbe.cs#GrainStorageFencingProbe"
  - id: hlc-monotonic-successor
    name: "Hybrid logical clock successor"
    description: "A local tick or merge returns an HLC that is strictly greater than the event inputs while LWW state compares HLC values without advancing them."
    scope:
      packages:
        - "Orleans.Lattice"
      components:
        - "HybridLogicalClock"
        - "LwwValue"
        - "VersionVector"
    violation_modes:
      - "A merge returns an HLC equal to or lower than one input."
      - "An LWW tie-break depends on replica observation order."
      - "A version vector update regresses a replica component."
    detection_signals:
      - type: test
        name: "HybridLogicalClockTests"
        source: "test/lattice/Primitives/HybridLogicalClockTests.cs"
      - type: test
        name: "VersionVectorTests"
        source: "test/lattice/Primitives/VersionVectorTests.cs"
    remediation:
      - step: "Use HLC merge to mint a successor timestamp for an event."
        source: "docs/lattice/state-primitives.md"
      - step: "Resolve stored LWW values by comparing timestamps and deterministic tie-breakers."
        source: "docs/lattice/state-primitives.md"
      - step: "Merge version vectors by pointwise maximum."
        source: "docs/lattice/state-primitives.md"
    sources:
      - "docs/lattice/state-primitives.md"
      - ".github/instructions/primitives.instructions.md"
  - id: mcp-caller-error-text-sanitized
    name: "MCP caller error text is sanitized"
    description: "Caller-controlled MCP rejection text is classified as a client error or sanitized before echoing or logging, so CR/LF and overlong values cannot forge logs or leak raw input."
    scope:
      packages:
        - "Orleans.Lattice.Api.Mcp"
        - "Orleans.Lattice.Api.Mcp.RepoContext"
      components:
        - "McpToolClientErrors"
        - "CredentialStampingTool"
        - "RepoContextToolInvocationLogger"
    violation_modes:
      - "A caller-supplied argument name, region id, record key, field value, or link target reaches the caller or a log without SanitizeForEcho."
      - "A tool-level McpException is attached to a repo-context warning log, causing raw exception text and stack output to be rendered."
      - "A caller mistake escapes as an unhandled tool exception instead of an MCP error result marked as a client error."
    detection_signals:
      - type: source
        name: "McpToolClientErrors.SanitizeForEcho"
        source: "src/lattice.api.mcp/Tools/McpToolClientErrors.cs#McpToolClientErrors.SanitizeForEcho"
      - type: source
        name: "CredentialStampingTool.ReportClientError"
        source: "src/lattice.api.mcp/Discovery/CredentialStampingTool.cs#CredentialStampingTool.ReportClientError"
    remediation:
      - step: "Classify caller mistakes as MCP client errors (invalid argument, rejected content or not found) so they are sanitized, capped, counted, and returned as MCP error results."
        source: "src/lattice.api.mcp/Tools/McpToolClientErrors.cs#McpToolClientErrors"
      - step: "When logging repo-context tool-level McpException failures before the outer client-error seam runs, log SanitizeForEcho(ex.Message) without attaching the exception."
        source: "src/lattice.api.mcp.repocontext/Logging/RepoContextToolInvocationLogger.cs#RepoContextToolInvocationLogger"
    sources:
      - "src/lattice.api.mcp/Tools/McpToolClientErrors.cs"
      - "src/lattice.api.mcp/Discovery/CredentialStampingTool.cs"
      - "src/lattice.api.mcp.repocontext/Logging/RepoContextToolInvocationLogger.cs"
  - id: mcp-region-catalog-validated-tenant-scope
    name: "MCP region catalog honours only a validated tenant assertion"
    description: "With tenancy active, a tenant-asserted region discovery call is scoped to the asserted tenant only when ITenantContextResolver resolves that same tenant; otherwise it advertises the current region alone with no tenantScope annotation."
    scope:
      packages:
        - "Orleans.Lattice.Api.Mcp"
      components:
        - "LatticeApiMcpRegionCatalog"
        - "ITenantContextResolver"
        - "ITenantRegionVisibilityResolver"
    violation_modes:
      - "An unvalidated lattice-active-tenant header value is used to scope or annotate the region list."
      - "A refused assertion falls back to the full routing topology."
      - "A refused assertion is echoed back as a tenantScope annotation."
    detection_signals:
      - type: test
        name: "MCP region catalog tenant scope tests"
        source: "test/lattice.api.mcp/Remote/LatticeApiMcpRegionCatalogTenantScopeTests.cs"
    remediation:
      - step: "Re-resolve the asserted tenant through ITenantContextResolver and honour it only on an exact match."
        source: "src/lattice.api.mcp/Remote/LatticeApiMcpRegionCatalog.cs#LatticeApiMcpRegionCatalog.ResolveTenantScopeAsync"
      - step: "Treat a missing ITenantContextResolver, a refusal, or a mismatch as a refusal that advertises the current region alone."
        source: "src/lattice.api.mcp/Remote/LatticeApiMcpRegionCatalog.cs#LatticeApiMcpRegionCatalog"
    sources:
      - "src/lattice.api.mcp/Remote/LatticeApiMcpRegionCatalog.cs"
  - id: mcp-telemetry-call-time-capability
    name: "MCP telemetry tools enforce the cluster-wide Telemetry capability at call time"
    description: "Every MCP telemetry tool authorizes LatticeOperation.Telemetry over LatticeScope.ClusterWideTreeId before any backend call, and discovery carries Telemetry only from a cluster-wide Allow rule."
    scope:
      packages:
        - "Orleans.Lattice.Api.Mcp"
        - "Orleans.Lattice.Api.Mcp.Telemetry"
        - "Orleans.Lattice.Api.Telemetry"
      components:
        - "TelemetryToolHandlers"
        - "TelemetryAccessAuthorizer"
        - "AuthAdminMcpPermissionResolver"
    violation_modes:
      - "A telemetry tool runs caller-supplied PromQL after only a discovery-time check."
      - "A tree-scoped Telemetry grant makes the telemetry group discoverable or satisfies a per-tool minimum."
      - "A key-filtered allow is treated as authorizing cluster telemetry."
      - "A capability denial echoes the subject id or the gate reason to the caller."
    detection_signals:
      - type: test
        name: "Telemetry tool capability gate tests"
        source: "test/lattice.api.mcp.telemetry/TelemetryToolCapabilityGateTests.cs"
      - type: test
        name: "Auth-admin MCP permission resolver tests"
        source: "test/lattice.api.mcp/AuthAdminMcpPermissionResolverTests.cs"
    remediation:
      - step: "Open every telemetry tool handler with TelemetryAccessAuthorizer.AuthorizeClusterTelemetryAsync before policy, guardrails, or backend calls."
        source: "src/lattice.api.mcp.telemetry/TelemetryToolHandlers.cs#TelemetryToolHandlers"
      - step: "Register TelemetryAccessAuthorizer from AddTelemetryTools so the gate applies without the transport-neutral facade."
        source: "src/lattice.api.mcp.telemetry/LatticeMcpTelemetryServiceCollectionExtensions.cs#AddTelemetryTools"
      - step: "Mask cluster-wide-only operations out of any rule that is not written at cluster-wide scope during discovery."
        source: "src/lattice.api.mcp/Discovery/AuthAdminMcpPermissionResolver.cs#AuthAdminMcpPermissionResolver.CarriedOperations"
    sources:
      - "src/lattice.api.mcp.telemetry/TelemetryToolHandlers.cs"
      - "src/lattice.api.telemetry/TelemetryAccessAuthorizer.cs"
      - "src/lattice.api.mcp/Discovery/AuthAdminMcpPermissionResolver.cs"
  - id: mcp-tool-authorization-lockstep
    name: "MCP tool authorization lockstep"
    description: "The same MCP authorizer gates both tool advertisement and tool invocation, with only the capabilities meta-tool ungated."
    scope:
      packages:
        - "Orleans.Lattice.Api.Mcp"
        - "Orleans.Lattice.Api.Mcp.RepoContext"
        - "Orleans.Lattice.Api.Mcp.RepoContext.Replication"
        - "Orleans.Lattice.Api.Mcp.Telemetry"
      components:
        - "MCP session configurator"
        - "Credential stamping tool"
        - "DenyAllMcpAuthorizer"
    violation_modes:
      - "A denied tool is hidden from tools/list but callable through tools/call."
      - "A null HttpContext or null authorizer allows a tool invocation."
      - "A second ungated tool is advertised without authorization."
      - "A mutating data tool is advertised to, or invocable by, a caller holding only a Read grant."
      - "A tree-scoped AppInstall grant satisfies a per-tool minimum."
    detection_signals:
      - type: test
        name: "MCP authorization lockstep tests"
        source: "test/lattice.api.mcp/McpToolAuthorizationGateTests.cs"
      - type: test
        name: "DataToolGroupTests"
        source: "test/lattice.api.mcp/Tools/Data/DataToolGroupTests.cs"
      - type: test
        name: "AuthAdminMcpPermissionResolverTests"
        source: "test/lattice.api.mcp/AuthAdminMcpPermissionResolverTests.cs"
    remediation:
      - step: "Route tool advertisement and invocation through one shared lock-step gate."
        source: ".github/instructions/security.instructions.md"
      - step: "Keep DenyAllMcpAuthorizer as the default until a host explicitly opts in."
        source: ".github/instructions/security.instructions.md"
      - step: "Leave lattice_capabilities as the only ungated advertisement."
        source: ".github/instructions/security.instructions.md"
      - step: "Override RequiredOperationsFor in a tool group whose mutating tools must not be reachable on a bare read grant."
        source: "src/lattice.api.mcp/Discovery/ILatticeApiMcpToolGroup.cs#ILatticeApiMcpToolGroup.RequiredOperationsFor"
      - step: "Mask every scopeless capability (Telemetry and AppInstall) out of rules not written at cluster-wide scope during discovery."
        source: "src/lattice.api.mcp/Discovery/AuthAdminMcpPermissionResolver.cs#AuthAdminMcpPermissionResolver.ClusterWideOnlyOperations"
    sources:
      - ".github/instructions/security.instructions.md"
  - id: membership-directory-validation-fail-closed
    name: "Membership directory validation fails closed"
    description: "Membership reference writes validate principal existence and kind before the system-origin write when validation is required and a real directory is available."
    scope:
      packages:
        - "Orleans.Lattice.Membership"
        - "Orleans.Lattice.Api.Auth"
      components:
        - "Identity directory"
        - "Membership reference admin"
        - "LatticeDirectoryValidationException"
    violation_modes:
      - "An unresolvable user or group id is written to membership state."
      - "A user id is accepted where a group id is required or the reverse."
      - "Validation runs after the system-origin write."
    detection_signals:
      - type: metric
        name: "orleans.lattice.membership.directory.search.misses"
        source: "src/lattice.membership/LatticeMembershipMetrics.cs"
      - type: exception
        name: "LatticeDirectoryValidationException"
        source: "src/lattice.membership/LatticeDirectoryValidationException.cs"
      - type: test
        name: "directory validation tests"
        source: "test/lattice.membership/LatticeDirectoryValidationExceptionTests.cs"
    remediation:
      - step: "Authorize, then validate, then perform the system-origin write."
        source: ".github/instructions/security.instructions.md"
      - step: "Reject an unresolvable id or kind mismatch with LatticeDirectoryValidationException before any write."
        source: ".github/instructions/security.instructions.md"
    sources:
      - ".github/instructions/security.instructions.md"
      - "src/lattice.membership/LatticeMembershipMetrics.cs"
  - id: replication-causal-dependency-gate
    name: "Replication causal dependency gate"
    description: "A receiver parks a causal-plus entry until every non-exempt dependency in the entry frontier is met: the exact named write was applied to the tree, or the origin's shipped low watermark passes it and the write is not held unapplied. A per-origin maximum HLC is never treated as meeting a dependency."
    scope:
      packages:
        - "Orleans.Lattice.Replication"
      components:
        - "ReplicationApplier"
        - "Causal apply buffer"
        - "VersionVector"
    violation_modes:
      - "An entry is applied before a causal dependency from another origin is present locally."
      - "A dependency is treated as met because the origin's per-origin maximum HLC is above it, although the named write never arrived (#4586)."
      - "The entry's own-origin diagonal or receiver self-component is not exempted and the buffer deadlocks."
      - "A bounded buffer eviction is silent instead of dead-lettered before durable removal."
    detection_signals:
      - type: metric
        name: "orleans.lattice.replication.apply.causal_violations_blocked"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
      - type: metric
        name: "orleans.lattice.replication.apply.buffered_entries"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
      - type: metric
        name: "orleans.lattice.replication.apply.dependency_wait"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
    remediation:
      - step: "Park entries with unsatisfied causal dependencies in the per-tree bounded causal-apply buffer."
        source: "docs/lattice.replication/replication-apply.md"
      - step: "Drain parked entries after parks, relevant high-water-mark advances, bootstrap handoff, first touch after restart, and each maintenance tick."
        source: "docs/lattice.replication/replication-apply.md"
      - step: "Monitor causal_violations_blocked, buffered_entries, and dependency_wait together."
        source: "docs/lattice.replication/observability.md"
    sources:
      - "docs/lattice.replication/replication-apply.md"
      - "docs/lattice.replication/observability.md"
  - id: replication-change-feed-offset-cursor
    name: "Replication change-feed offset cursor"
    description: "The public change feed resumes from WAL offsets rather than HLC filters so it never skips entries whose HLC order differs from partition order."
    scope:
      packages:
        - "Orleans.Lattice.Replication"
      components:
        - "IChangeFeed"
        - "ChangeFeedCursor"
        - "WalRecord"
    violation_modes:
      - "A consumer resumes by HLC and skips a lower-HLC entry committed later in a partition."
      - "Tombstone reap envelopes are surfaced to a consumer that has no apply rule for them."
      - "CRDT-mode consumers read stripped Value payloads instead of Delta payloads."
      - "A consumer subscribes by logical tree id after a resize or shadow-cutover restore and reads the retired physical log, or nothing after purge, because the feed does not follow aliases."
    detection_signals:
      - type: test
        name: "change feed tests"
        source: "test/lattice.replication/ChangeFeedTests.cs"
      - type: status-field
        name: "ChangeFeedCursor"
        source: "docs/lattice.replication/change-feed.md"
    remediation:
      - step: "Capture GetCurrentCursorAsync and resubscribe from that offset cursor."
        source: "docs/lattice.replication/change-feed.md"
      - step: "Treat equal-HLC ordering as unspecified."
        source: "docs/lattice.replication/change-feed.md"
      - step: "Read WalRecord.Delta for CRDT-mode Set entries whose Value slot is stripped."
        source: "docs/lattice.replication/change-feed.md"
    sources:
      - "docs/lattice.replication/change-feed.md"
  - id: replication-delta-idempotence
    name: "Replication delta idempotence"
    description: "Every typed CRDT delta apply and sender-side delta combine is order-independent, idempotent, and equivalent to sequential receiver apply."
    scope:
      packages:
        - "Orleans.Lattice"
        - "Orleans.Lattice.Replication"
      components:
        - "WalRecord.Delta"
        - "Crdt delta records"
        - "Pre-ship coalescing"
    violation_modes:
      - "A duplicate delta changes state a second time."
      - "A coalesced same-key run loses or double-counts a primitive contribution."
      - "An unregistered OrMap shape is applied as an opaque value instead of faulting."
    detection_signals:
      - type: metric
        name: "orleans.lattice.replication.coalesce.deltas_merged"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
      - type: metric
        name: "orleans.lattice.replication.coalesce.entries_elided"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
      - type: exception
        name: "InvalidOperationException"
        source: "docs/lattice.replication/replication-apply.md"
    remediation:
      - step: "Apply each typed delta through its documented receiver merge rule."
        source: "docs/lattice.replication/deltas.md"
      - step: "Register the concrete OrMap shape at startup before applying OrMap-mode entries."
        source: "docs/lattice.replication/replication-apply.md"
    sources:
      - "docs/lattice.replication/deltas.md"
      - "docs/lattice.replication/replication-apply.md"
  - id: replication-enrollment-mode-gate
    name: "Replication enrollment and mode gate"
    description: "A receiver re-resolves local tree enrollment and merge mode before applying peer data and never trusts the wire classification."
    scope:
      packages:
        - "Orleans.Lattice.Replication"
        - "Orleans.Lattice.Tenancy"
      components:
        - "ReplicationApplier"
        - "ILatticeReplicationContext"
        - "Dead-letter queue"
    violation_modes:
      - "A peer writes a tree that is not locally enrolled."
      - "A peer changes local merge algebra by sending a different wire mode."
      - "A non-enrolled tree is dead-lettered and creates unbounded activations."
      - "A tenant-offline or foreign-tenant record mutates local state."
    detection_signals:
      - type: metric
        name: "orleans.lattice.replication.apply.duration"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
      - type: log
        name: "one-time missing enrollment warning"
        source: "docs/lattice.replication/replication-apply.md"
      - type: status-field
        name: "dead-letter reason mode_mismatch"
        source: "docs/lattice.replication/dead-letter-queue.md"
    remediation:
      - step: "Drop non-enrolled tree entries without dead-lettering them."
        source: "docs/lattice.replication/replication-apply.md"
      - step: "Dead-letter enrolled entries whose wire mode mismatches the locally resolved mode."
        source: "docs/lattice.replication/replication-apply.md"
      - step: "Replay tenant-gated dead-letter entries only after the tenant exists, becomes resident, or is reinstated."
        source: "docs/lattice.replication/replication-apply.md"
    sources:
      - ".github/instructions/security.instructions.md"
      - "docs/lattice.replication/replication-apply.md"
  - id: replication-local-origin-rejection
    name: "Replication local-origin rejection"
    description: "A receiver rejects records whose origin cluster id matches the local cluster to prevent replication loops."
    scope:
      packages:
        - "Orleans.Lattice.Replication"
      components:
        - "ReplicationApplier"
        - "LatticeOriginContext"
        - "Outbound shipper"
    violation_modes:
      - "A hand-built apply path re-applies the receiver's own mutation."
      - "The receiver relies only on the sender-side outbound origin filter."
      - "Local-origin CRDT deltas are folded and re-emitted indefinitely."
    detection_signals:
      - type: metric
        name: "orleans.lattice.replication.apply.duration"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
      - type: test
        name: "replication apply tests"
        source: "test/lattice.replication/ReplicationApplierTests.cs"
    remediation:
      - step: "Return Applied=false for records whose origin cluster id matches the local cluster id."
        source: "docs/lattice.replication/replication-apply.md"
      - step: "Preserve foreign origin through receiver writes with LatticeOriginContext."
        source: "docs/lattice.replication/replication-apply.md"
    sources:
      - "docs/lattice.replication/replication-apply.md"
  - id: replication-peer-origin-binding
    name: "Replication peers act only on their own origin"
    description: "Every replication receiver verb that keys the durable per-origin high-water mark by a body-declared OriginClusterId refuses a missing transport-stamped origin or a value that differs from the body, so the body origin is not a standalone authorization input."
    scope:
      packages:
        - "Orleans.Lattice.Replication.Grpc"
      components:
        - "LatticeReplicationGrpcService"
    violation_modes:
      - "A mesh-secret holder pushes under a third cluster's origin and drives that stream's high-water mark forward, suppressing anti-entropy repair for it."
      - "GetPeerHighWaterMark discloses a third cluster's replication cursor."
      - "A new verb consuming a body-declared origin skips the binding."
    detection_signals:
      - type: test
        name: "LatticeReplicationGrpcServiceEnrollmentTests"
        source: "test/lattice.replication.grpc/LatticeReplicationGrpcServiceEnrollmentTests.cs"
      - type: log
        name: "Refusing replication origin mismatch warning"
        source: "src/lattice.replication.grpc/LatticeReplicationGrpcService.cs#EnsureOriginMatchesCaller"
    remediation:
      - step: "Call EnsureOriginMatchesCaller from every verb that consumes a body-declared OriginClusterId, before reading or advancing the per-origin high-water mark."
        source: "src/lattice.replication.grpc/LatticeReplicationGrpcService.cs#EnsureOriginMatchesCaller"
    sources:
      - "src/lattice.replication.grpc/LatticeReplicationGrpcService.cs"
  - id: replication-peer-status-hides-unauthorized-trees
    name: "Replication peer status hides unauthorized trees"
    description: "Replication peer status reports rows only for trees the caller may manage through the Replication capability."
    scope:
      packages:
        - "Orleans.Lattice.Api.Replication"
      components:
        - "LatticeReplicationStatus"
        - "ReplicationAccessAuthorizer"
    violation_modes:
      - "An unauthorized tree appears in the peer-status report."
      - "An unauthorized tree filter discloses that the tree exists."
      - "A continuation token is issued from a skipped unauthorized row."
    detection_signals:
      - type: source
        name: "LatticeReplicationStatus.GetPeerStatusAsync"
        source: "src/lattice.api.replication/LatticeReplicationStatus.cs#LatticeReplicationStatus.GetPeerStatusAsync"
      - type: source
        name: "ReplicationAccessAuthorizer.IsAuthorizedAsync"
        source: "src/lattice.api.replication/ReplicationAccessAuthorizer.cs#ReplicationAccessAuthorizer.IsAuthorizedAsync"
    remediation:
      - step: "Filter every status row through the replication access check before returning it."
        source: "src/lattice.api.replication/LatticeReplicationStatus.cs#LatticeReplicationStatus.IsVisibleAsync"
      - step: "Return an empty page for an unauthorized tree filter before reading telemetry."
        source: "src/lattice.api.replication/LatticeReplicationStatus.cs#LatticeReplicationStatus.GetPeerStatusAsync"
    sources:
      - "src/lattice.api.replication/LatticeReplicationStatus.cs#LatticeReplicationStatus"
      - "src/lattice.api.replication/ReplicationAccessAuthorizer.cs#ReplicationAccessAuthorizer"
  - id: replication-point-write-no-hlc-floor
    name: "Replication point-write no HLC floor"
    description: "Steady-state receiver dedupe never drops point writes only because their HLC is at or below a per-origin high-water mark or legacy snapshot floor."
    scope:
      packages:
        - "Orleans.Lattice.Replication"
      components:
        - "ReplicationApplier"
        - "TxRegistryHighWaterGrain"
        - "Bootstrap handoff"
    violation_modes:
      - "A genuinely new point write with a source HLC below the running high-water mark is dropped."
      - "A genuinely new point write with a source HLC at or below a legacy snapshot coordinate is dropped."
      - "High-water-mark advance regresses under a lower applied HLC."
    detection_signals:
      - type: metric
        name: "orleans.lattice.replication.apply.fifo_violations"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
      - type: metric
        name: "orleans.lattice.replication.apply.lag"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
      - type: status-field
        name: "per-origin high-water mark"
        source: "docs/lattice.replication/replication-apply.md"
    remediation:
      - step: "Apply point writes regardless of whether their HLC is below the running high-water mark or legacy snapshot coordinate."
        source: "docs/lattice.replication/replication-apply.md"
      - step: "Advance the per-origin high-water mark monotonically after successful point apply."
        source: "docs/lattice.replication/replication-apply.md"
      - step: "Run snapshot bootstrap when incremental replication has fallen off the WAL."
        source: "docs/lattice.replication/snapshot-bootstrap.md"
    sources:
      - "docs/lattice.replication/replication-apply.md"
      - "docs/lattice.replication/observability.md"
      - "docs/lattice.replication/snapshot-bootstrap.md"
  - id: replication-restore-fence-defer
    name: "Replication restore receive fence"
    description: "While a coordinated restore has paused inbound apply for a tree, the receiver defers entries without advancing the sender cursor."
    scope:
      packages:
        - "Orleans.Lattice.Replication"
        - "Orleans.Lattice.Backup"
      components:
        - "ReplicationApplier"
        - "Coordinated restore saga"
        - "Receive fence"
    violation_modes:
      - "A fenced tree applies inbound entries during a restore cutover."
      - "A deferred entry is acknowledged as applied and the sender advances permanently."
      - "A custom applier fails to propagate Deferred through ApplyBatchAsync."
      - "A dead-letter replay the receive fence defers removes the parked entry, which was the write's only copy."
    detection_signals:
      - type: metric
        name: "orleans.lattice.replication.saga.fence.duration"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
      - type: metric
        name: "orleans.lattice.replication.apply.duration"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
      - type: status-field
        name: "Deferred"
        source: "docs/lattice.replication/replication-apply.md"
      - type: test
        name: "LatticeReplicationDeadLettersTests"
        source: "test/lattice.replication/LatticeReplicationDeadLettersTests.cs"
    remediation:
      - step: "Return Applied=false and Deferred=true while the restore receive fence is active."
        source: "docs/lattice.replication/replication-apply.md"
      - step: "Keep the sender cursor unchanged so the entry re-ships after the fence lifts."
        source: "docs/lattice.replication/replication-apply.md"
      - step: "Override ApplyBatchAsync in custom appliers that can return deferred results."
        source: "docs/lattice.replication/replication-apply.md"
      - step: "Leave a dead-letter entry parked when ReplayAsync returns Deferred true, and replay it again once the fence lifts."
        source: "src/lattice.replication/ILatticeReplicationDeadLetters.cs#ILatticeReplicationDeadLetters.ReplayAsync"
    sources:
      - "docs/lattice.replication/replication-apply.md"
      - "docs/lattice.replication/coordinated-restore.md"
      - "docs/lattice.replication/dead-letter-queue.md"
  - id: replication-source-hlc-preservation
    name: "Replication source HLC preservation"
    description: "Receiver apply preserves the authoring cluster's HLC and origin where documented so last-writer-wins and provenance stay deterministic across clusters."
    scope:
      packages:
        - "Orleans.Lattice"
        - "Orleans.Lattice.Replication"
      components:
        - "ReplicationApplier"
        - "WalRecord"
        - "LatticeOriginContext"
        - "LwwValue"
    violation_modes:
      - "A replicated LWW point write is restamped with a local HLC."
      - "A range delete loses its producer issue HLC."
      - "Receiver-side observer emits a foreign-origin mutation as local."
    detection_signals:
      - type: metric
        name: "orleans.lattice.replication.apply.fifo_violations"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
      - type: test
        name: "replication HLC preservation tests"
        source: "test/lattice.replication/ReplicationApplierTests.PreparedNonMonotonicHlc.cs"
      - type: exception
        name: "ArgumentException"
        source: "docs/lattice.replication/replication-apply.md"
    remediation:
      - step: "Persist LwwRegister entries with the supplied source timestamp and origin cluster id verbatim."
        source: "docs/lattice.replication/replication-apply.md"
      - step: "Wrap receiver CRDT folds in a LatticeOriginContext for the source origin."
        source: "docs/lattice.replication/replication-apply.md"
      - step: "Preserve the producer HLC on range delete tombstones."
        source: "docs/lattice.replication/replication-apply.md"
    sources:
      - "docs/lattice.replication/replication-apply.md"
      - "docs/lattice.replication/deltas.md"
  - id: snapshot-consistency
    name: "Snapshot consistency"
    description: "Offline snapshots copy an exact lock-instant state; online snapshots preserve source HLCs and absolute TTL expiry for the entries they copy or mirror, and do not mirror typed CRDT deltas applied to a source shard after it drained."
    scope:
      packages:
        - "Orleans.Lattice"
      components:
        - "TreeSnapshotGrain"
        - "SnapshotLeafGrain"
        - "ShardRootGrain"
    violation_modes:
      - "A destination tree includes a tombstoned key from the source."
      - "An online snapshot drops or double-applies a write racing with drain."
      - "A copied TTL is refreshed instead of preserving its absolute expiry."
      - "A crash loses snapshot phase progress or makes retry non-idempotent."
    detection_signals:
      - type: status-field
        name: "TreeSnapshotStatus"
        source: "src/lattice.api.abstractions/TreeAdmin/Model/TreeSnapshotStatus.cs"
      - type: exception
        name: "InvalidOperationException"
        source: "docs/lattice/snapshots.md"
      - type: metric
        name: "orleans.lattice.coordinator.completed"
        source: "src/lattice/LatticeMetrics.cs"
    remediation:
      - step: "Resume snapshot progress from the last completed persisted phase after a silo restart."
        source: "docs/lattice/snapshots.md"
      - step: "Use deterministic operation ids for retrying destination bulk-load operations."
        source: "docs/lattice/snapshots.md"
      - step: "Reject a snapshot whose destination exists, equals the source, or uses a reserved namespace."
        source: "docs/lattice/snapshots.md"
    sources:
      - "docs/lattice/snapshots.md"
      - "docs/lattice/consistency.md"
      - "docs/lattice/ttl.md"
  - id: split-reshard-shadow-forwarding
    name: "Split and reshard shadow forwarding"
    description: "During a split or reshard, every moved-slot write or prepared mutation is drained, shadow-forwarded, or conservatively retried so ownership changes do not lose or duplicate authority."
    scope:
      packages:
        - "Orleans.Lattice"
      components:
        - "TreeShardSplitGrain"
        - "TreeReshardGrain"
        - "ShardMap"
        - "ShadowedMigrationReadGuard"
    violation_modes:
      - "The registry map flips before the source shard rejects stale moved-slot operations."
      - "Prepared mutations present before the shadow window are not replayed to the target."
      - "A migrated pre-saga value is served while the saga may have committed."
      - "After swap, both source and target are reachable authorities for a moved slot."
    detection_signals:
      - type: metric
        name: "orleans.lattice.split.retroactive_forward.entries"
        source: "src/lattice/LatticeMetrics.cs"
      - type: metric
        name: "orleans.lattice.shard_root.reshard.rejected"
        source: "src/lattice/LatticeMetrics.cs"
      - type: exception
        name: "StaleShardRoutingException"
        source: "src/lattice/BPlusTree/StaleShardRoutingException.cs"
      - type: test
        name: "ReshardMigrationCoyoteTests"
        source: "test/lattice/BPlusTree/Coyote/ReshardMigrationCoyoteTests.cs"
    remediation:
      - step: "Persist coordinator state before side effects and resume from the last persisted phase after a crash."
        source: "docs/lattice/shard-splitting.md"
      - step: "Run the retroactive prepared-mutation sweep before the drain begins."
        source: "docs/lattice/shard-splitting.md"
      - step: "Seal and reject the source for moved slots before updating the registry map."
        source: "docs/lattice/shard-splitting.md"
      - step: "Retry stale-routed calls after refreshing the shard map."
        source: "docs/lattice/shard-splitting.md"
    sources:
      - "docs/lattice/shard-splitting.md"
      - "docs/lattice/online-reshard.md"
      - "docs/lattice/consistency.md"
  - id: subject-relative-scope-bounded
    name: "Subject-relative scopes resolve only to the caller's own segments"
    description: "A {subject} or {group:<prefix>} placeholder matches only a whole delimiter-bounded key segment equal to the caller's own subject id or one of its own groups; an id that is empty or contains the delimiter or U+001F, and the anonymous subject, never match; templates are refused on control-plane trees and a group prefix reaching tenant groups is confined to the scoped tree's tenant."
    scope:
      packages:
        - "Orleans.Lattice.Auth"
      components:
        - "ScopeTemplate"
        - "CompiledTree"
        - "LatticeAuthorizationPolicyStore"
        - "PolicyEvaluator"
    violation_modes:
      - "A placeholder without a following delimiter lets u1 match keys of u10."
      - "A templated rule grants a caller another caller's prefix, or grants the anonymous subject."
      - "A templated allow outranks a literal deny on the same resolved prefix."
      - "A range or existence probe reports a grant the point decision would deny."
      - "A group placeholder reaches another tenant's groups."
    detection_signals:
      - type: test
        name: "TemplatedScopeEvaluationTests"
        source: "test/lattice.auth/TemplatedScopeEvaluationTests.cs"
      - type: test
        name: "TemplatedScopeAuthoringTests"
        source: "test/lattice.auth/TemplatedScopeAuthoringTests.cs"
      - type: test
        name: "ScopeTemplateTests"
        source: "test/lattice.auth/ScopeTemplateTests.cs"
    remediation:
      - step: "Follow every placeholder with a literal delimiter such as '/', and start a tenant-group placeholder prefix with t/{tenant}/ for the scoped tree's tenant."
        source: "docs/lattice.auth/README.md"
    sources:
      - "docs/lattice.auth/README.md"
      - "src/lattice.auth/ScopeTemplate.cs"
  - id: telemetry-metric-allow-list-fail-closed
    name: "Telemetry metric allow-list fails closed"
    description: "PromQL queries are authorized only when their metric-name matcher parses to an exact allowed name."
    scope:
      packages:
        - "Orleans.Lattice.Api.Telemetry"
        - "Orleans.Lattice.Api.Telemetry.Grpc"
        - "Orleans.Lattice.Api.Mcp.Telemetry"
        - "Orleans.Lattice.Api.Mcp.Telemetry.Azure"
      components:
        - "TelemetryMetricAccessPolicy"
        - "PromQlMetricExtractor"
        - "TelemetryQueryAuthorizer"
    violation_modes:
      - "An unparseable or ambiguous __name__ matcher bypasses the allow-list."
      - "A grouping label list scanner treats parentheses in comments or quoted strings as syntax and hides the aggregand selector."
      - "A query catalogue route omits the shared authorizer."
      - "Matcher parsing allocates per label on the steady path."
    detection_signals:
      - type: test
        name: "telemetry authorization tests"
        source: "test/lattice.api.telemetry/TelemetryMetricAccessPolicyTests.cs"
    remediation:
      - step: "Deny unparseable, ambiguous, or non-exact __name__ matchers."
        source: ".github/instructions/security.instructions.md"
      - step: "Skip grouping label parentheses while honoring comments and quoted strings exactly as the main PromQL scan does."
        source: "src/lattice.api.telemetry/PromQlMetricExtractor.cs#PromQlMetricExtractor"
      - step: "Authorize MCP telemetry tools and facade query catalogue entries through TelemetryQueryAuthorizer."
        source: ".github/instructions/security.instructions.md"
    sources:
      - ".github/instructions/security.instructions.md"
  - id: tenant-access-no-isolation-bypass
    name: "Tenant access never bypasses tenant isolation"
    description: "Tenant membership, group-aware admin checks and tenant-tier rules never bypass the tenant gate or the cross-tenant grant protocol; reaching another tenant's trees still needs an active grant, admin-set, member-set and app-binding entries never count when they name another tenant's group, and the reserved default tenant has no tenant groups, members or tenant rules."
    scope:
      packages:
        - "Orleans.Lattice.Tenancy"
        - "Orleans.Lattice.Api.TenantAdmin"
        - "Orleans.Lattice.Apps"
      components:
        - "TenantGateEnforcer"
        - "TenantAccessEntries"
        - "LatticeTenantDirectoryAdmin"
        - "LatticeTenantPolicyAdmin"
    violation_modes:
      - "A tenant member reaches another tenant's tree without an active cross-tenant grant."
      - "An admin-set entry naming another tenant's group admits that group's members."
      - "A delegated access facade accepts the reserved default tenant."
      - "Two concurrent admin-set removals both commit and leave the tenant with no admin entry, or a removal is repaired by a second write that can fail."
      - "A removal stamped behind the slot it supersedes loses the merge while the facade reports the entry removed."
    detection_signals:
      - type: test
        name: "TenantAccessConformanceTests"
        source: "test/lattice.api.tenantadmin/Security/TenantAccessConformanceTests.cs"
      - type: test
        name: "TenantAccessEntriesTests"
        source: "test/lattice.tenancy/TenantAccessEntriesTests.cs"
      - type: test
        name: "LatticeTenantAccessAdminAdminSetConfinementTests"
        source: "test/lattice.api.tenantadmin/Directory/LatticeTenantAccessAdminAdminSetConfinementTests.cs"
      - type: test
        name: "AppRoleGrantEvaluatorTenantConfinementTests"
        source: "test/lattice.apps/Registry/AppRoleGrantEvaluatorTenantConfinementTests.cs"
    remediation:
      - step: "Use the cross-tenant grant protocol to share data between tenants."
        source: "docs/lattice.api.tenantadmin/README.md"
    sources:
      - "docs/lattice.tenancy/README.md"
      - "src/lattice.tenancy/TenantAccessEntries.cs"
  - id: tenant-group-namespace-reserved
    name: "The t/ group namespace is reserved to the tenant tier"
    description: "Only the tenant tier owns group ids starting with t/: the cluster auth facade refuses to create one, and whenever the tenancy add-on is registered, whatever its delegated tenant access administration flag, every identity-provider-asserted t/ group is stripped before group expansion, because operator rules and app role bindings naming a tenant group are honoured whatever the flag."
    scope:
      packages:
        - "Orleans.Lattice.Membership"
        - "Orleans.Lattice.Api.Auth"
        - "Orleans.Lattice.Tenancy"
      components:
        - "ITenantGroupClaimFilter"
        - "TenantGroupClaimFilter"
        - "LatticeAuthAdmin"
    violation_modes:
      - "The cluster auth facade creates a group whose id starts with t/."
      - "A token-asserted, overage or claim-projected t/ group id reaches group expansion on a cluster with tenancy registered, including while the delegated-access flag is off."
      - "The claim filter is made to follow the delegated-access flag, so a token asserting t/{T}/x matches an operator rule or app role binding after a rollback."
      - "A check tests only the well-formed LatticeTenantGroupId shape, so t/default/x or a malformed t/ id slips through."
    detection_signals:
      - type: test
        name: "TenantGroupClaimFilterTests"
        source: "test/lattice.membership/TenantGroupClaimFilterTests.cs"
      - type: test
        name: "MembershipContextTenantGroupClaimFilterTests"
        source: "test/lattice.membership/MembershipContextTenantGroupClaimFilterTests.cs"
      - type: exception
        name: "LatticeTenantOwnedGroupException"
        source: "src/lattice.api.auth/LatticeTenantOwnedGroupException.cs#LatticeTenantOwnedGroupException"
    remediation:
      - step: "Manage tenant groups through ILatticeTenantDirectoryAdmin, which composes t/{tenant}/{name} from the tenant the call names."
        source: "src/lattice.api.abstractions/TenantAdmin/ILatticeTenantDirectoryAdmin.cs#ILatticeTenantDirectoryAdmin"
      - step: "Test the whole t/ prefix (LatticeTenantTrees.SegmentPrefix) when reserving the namespace."
        source: "src/lattice.membership/TenantGroupClaimFilter.cs#TenantGroupClaimFilter"
    sources:
      - "docs/lattice.membership/README.md"
      - "docs/lattice.api.auth/README.md"
  - id: tenant-group-nesting-confined
    name: "Tenant groups stay inside their tenant"
    description: "A tenant group may contain users, groups of the same tenant and cluster groups, but never becomes a member of a cluster group or of another tenant's group; the membership directory refuses such an edge for every caller, system origin included."
    scope:
      packages:
        - "Orleans.Lattice.Membership"
      components:
        - "ILatticeMembershipDirectory"
        - "TenantGroupNesting"
        - "LatticeTenantGroupNestingException"
    violation_modes:
      - "A tenant group is added as a member of a cluster group, extending an operator rule on that group to people a tenant administrator controls."
      - "A tenant group is added to another tenant's group."
      - "A system-origin write skips the nesting check."
    detection_signals:
      - type: test
        name: "TenantGroupNestingTests"
        source: "test/lattice.membership/TenantGroupNestingTests.cs"
      - type: exception
        name: "LatticeTenantGroupNestingException"
        source: "src/lattice.membership/LatticeTenantGroupNestingException.cs#LatticeTenantGroupNestingException"
    remediation:
      - step: "Nest the cluster group inside the tenant group instead; that direction is allowed."
        source: "docs/lattice.membership/README.md"
    sources:
      - "docs/lattice.membership/README.md"
      - "src/lattice.membership/TenantGroupNesting.cs"
  - id: tenant-isolation-namespace
    name: "Tenant namespace isolation"
    description: "Tenant-scoped surfaces compose tree ids under t/{tenant}/ and refuse platform or foreign namespaces unless the access gate authorizes the crossing."
    scope:
      packages:
        - "Orleans.Lattice.Tenancy"
        - "Orleans.Lattice.Api.TenantAdmin"
        - "Orleans.Lattice.Api.TenantAdmin.Grpc"
        - "Orleans.Lattice.Backup"
        - "Orleans.Lattice.Replication"
      components:
        - "LatticeTenantTrees"
        - "Tenant resolver"
        - "Tenant access gate"
    violation_modes:
      - "A non-default tenant creates or writes a sys- namespace tree."
      - "A malformed t/ id resolves to platform ownership and is allowed."
      - "A split-head binding omits the active-tenant bridge and serves the default namespace."
      - "A denied assertion reports a live tenant descriptor."
    detection_signals:
      - type: exception
        name: "LatticeTenantAccessDeniedException"
        source: "src/lattice/LatticeTenantAccessDeniedException.cs"
      - type: test
        name: "tenant isolation tests"
        source: "test/lattice.tenancy/ReplicationTenantIsolationGateTests.cs"
      - type: metric
        name: "orleans.lattice.tenancy.tenants"
        source: "src/lattice.tenancy/LatticeTenantMetrics.cs"
    remediation:
      - step: "Compose unqualified tree names with the active tenant through LatticeTenantTrees."
        source: "docs/lattice.tenancy/README.md"
      - step: "Refuse sys- and malformed t/ namespace access outside system-origin scope."
        source: "docs/lattice.tenancy/README.md"
      - step: "Lift the active-tenant assertion at every split-head transport binding."
        source: "docs/lattice.tenancy/README.md"
    sources:
      - "docs/lattice.tenancy/README.md"
      - ".github/instructions/security.instructions.md"
  - id: tenant-layer-beneath-operator
    name: "Operator verdicts are final over tenant-tier rules"
    description: "A matched operator rule, allow or deny, decides the request; the tenant layer is consulted only when no operator rule matches, only for a tenant-layer tree, and it is the tree owner's layer. Range filters compose the layers per key on operator coverage."
    scope:
      packages:
        - "Orleans.Lattice.Auth"
      components:
        - "PolicyEvaluator"
        - "LatticeDecisionEngine"
        - "ITenantRuleLayer"
    violation_modes:
      - "A tenant key-scoped allow carves a hole in an operator deny."
      - "A tenant deny revokes an operator allow."
      - "A range filter admits a key an operator rule denies or drops a key an operator rule allows."
      - "The tenant layer governs a control-plane, app-owned or default-tenant tree."
    detection_signals:
      - type: test
        name: "TenantAccessConformanceTests"
        source: "test/lattice.api.tenantadmin/Security/TenantAccessConformanceTests.cs"
      - type: test
        name: "TenantLayerEvaluationTests"
        source: "test/lattice.auth/TenantLayerEvaluationTests.cs"
      - type: test
        name: "TenantLayerRangeFilterPropertyTests"
        source: "test/lattice.auth/TenantLayerRangeFilterPropertyTests.cs"
    remediation:
      - step: "Author an operator rule to change a decision the operator layer makes; a tenant rule cannot."
        source: "docs/lattice.auth/tenant-layer.md"
    sources:
      - "docs/lattice.auth/tenant-layer.md"
      - "src/lattice.auth/PolicyEvaluator.cs"
  - id: tenant-quota-admission
    name: "Tenant quota admission"
    description: "Tenant writes and charged reads are admitted against the compiled quota policy after authorization and are refused only at the documented admission seams."
    scope:
      packages:
        - "Orleans.Lattice.Tenancy"
        - "Orleans.Lattice.Api.Data"
        - "Orleans.Lattice.Api.Data.Grpc"
        - "Orleans.Lattice.Backup"
      components:
        - "TenantQuotas"
        - "TenantUsageAccountingOptions"
        - "Tenant rate limiter"
        - "Quota admission gate"
    violation_modes:
      - "A read is charged before the access gate validates the tenant assertion."
      - "A footprint breach refuses reads needed for cleanup."
      - "A tree creation evaluates quota admission twice and charges two rate tokens."
      - "A first usage sample below hysteresis never publishes and leaves admission fail-open forever."
    detection_signals:
      - type: metric
        name: "orleans.lattice.tenancy.usage.bytes"
        source: "src/lattice.tenancy/LatticeTenantMetrics.cs"
      - type: metric
        name: "orleans.lattice.tenancy.overage.keys"
        source: "src/lattice.tenancy/LatticeTenantMetrics.cs"
      - type: exception
        name: "LatticeQuotaExceededException"
        source: "src/lattice/LatticeQuotaExceededException.cs"
    remediation:
      - step: "Charge reads strictly after the access gate authorizes the read."
        source: "docs/lattice.tenancy/README.md"
      - step: "Apply footprint admission to writes and tree creation, not ordinary reads."
        source: "docs/lattice.tenancy/README.md"
      - step: "Treat ops-per-second breaches as transient back-pressure and retry after backoff."
        source: "docs/lattice.tenancy/README.md"
    sources:
      - "docs/lattice.tenancy/README.md"
  - id: tenant-region-residency
    name: "Tenant region residency invariants"
    description: "A tenant's resident regions are non-empty, are a subset of allowed regions, and cannot be revoked while resident; an added region advances automatically from Provisioning through Backfilling and remains non-serving until every tenant tree is live and unfenced and tenant_offline dead letters have replayed, then becomes Online, and a dropped region drains through Offline to Removed."
    scope:
      packages:
        - "Orleans.Lattice.Tenancy"
        - "Orleans.Lattice.Api.TenantAdmin"
        - "Orleans.Lattice.Api.TenantAdmin.Grpc"
        - "Orleans.Lattice.Api.Mcp"
      components:
        - "ILatticeTenantRegionAdmin"
        - "Tenant region status"
    violation_modes:
      - "Residency is set to a region outside the allowed set."
      - "The last resident region is removed."
      - "An allowed region is revoked before the tenant is drained from it."
      - "A non-operator distinguishes unknown tenant from denied tenant."
    detection_signals:
      - type: exception
        name: "TenantRegionNotAllowedException"
        source: "src/lattice.api.abstractions/TenantAdmin/Model/TenantRegionNotAllowedException.cs"
      - type: exception
        name: "TenantLastRegionException"
        source: "src/lattice.api.abstractions/TenantAdmin/Model/TenantLastRegionException.cs"
      - type: exception
        name: "TenantNotFoundException"
        source: "src/lattice.api.abstractions/TenantAdmin/Model/TenantNotFoundException.cs"
      - type: status-field
        name: "TenantRegionStatus"
        source: "docs/lattice.tenancy/README.md"
    remediation:
      - step: "Authorize allowed regions before setting residency into them."
        source: "docs/lattice.tenancy/README.md"
      - step: "Drain residency away from a region before revoking that region."
        source: "docs/lattice.tenancy/README.md"
      - step: "Keep at least one resident region for every tenant."
        source: "docs/lattice.tenancy/README.md"
      - step: "Return the generic authorization-denied shape to non-operator callers for unknown tenants."
        source: "docs/lattice.tenancy/README.md"
    sources:
      - "docs/lattice.tenancy/README.md"
  - id: tenant-rule-confinement
    name: "Tenant-tier rules and tenant-group subjects are confined to their tenant"
    description: "The policy store refuses, for every caller, a tenant-tier rule outside its tenant's tenant-layer trees or tenant-wide scope or outside the data-plane operations, and any rule naming a tenant group on a tree outside that group's tenant (app: rules may also use that tenant's app-owned trees); tenant: ids are written only under system origin."
    scope:
      packages:
        - "Orleans.Lattice.Auth"
        - "Orleans.Lattice.Api.TenantAdmin"
        - "Orleans.Lattice.Apps"
      components:
        - "LatticeAuthorizationPolicyStore"
        - "TenantRuleConfinement"
        - "LatticeTenantRuleIds"
        - "LatticeTenantOwnedRuleException"
    violation_modes:
      - "An operator writes or deletes a tenant: rule id off system origin."
      - "A tenant-tier rule governs another tenant, an app-owned tree, a reserved or sys- tree, or Telemetry, Replication, TreeLifecycle or AppInstall."
      - "A Tree:* or cross-tenant rule names a tenant group."
      - "An app role binding names another tenant group."
    detection_signals:
      - type: test
        name: "TenantAccessConformanceTests"
        source: "test/lattice.api.tenantadmin/Security/TenantAccessConformanceTests.cs"
      - type: test
        name: "LatticeAuthorizationPolicyStoreTenantRuleTests"
        source: "test/lattice.auth/LatticeAuthorizationPolicyStoreTenantRuleTests.cs"
      - type: test
        name: "AppRoleCompilerTests.TenantGroups"
        source: "test/lattice.apps/Compiler/AppRoleCompilerTests.TenantGroups.cs"
      - type: exception
        name: "LatticeTenantOwnedRuleException"
        source: "src/lattice.auth/LatticeTenantOwnedRuleException.cs#LatticeTenantOwnedRuleException"
    remediation:
      - step: "Author tenant-tier rules only through ILatticeTenantPolicyAdmin, which composes the tenant: id and tenant-local trees."
        source: "src/lattice.api.abstractions/TenantAdmin/ILatticeTenantPolicyAdmin.cs#ILatticeTenantPolicyAdmin"
    sources:
      - "docs/lattice.auth/tenant-layer.md"
      - "src/lattice.auth/TenantRuleConfinement.cs"
  - id: tenant-wide-scope-tenant-tier-only
    name: "The tenant-wide scope is tenant-tier only"
    description: "A rule over a t/{tenant}/* sentinel tree is accepted only when its id is tenant:-prefixed and its scope is exactly LatticeScope.TenantWide of that tenant; it never reaches app-owned, system or other-tenant trees, and the data plane refuses user-origin writes to such a tree id."
    scope:
      packages:
        - "Orleans.Lattice"
        - "Orleans.Lattice.Auth"
        - "Orleans.Lattice.Api.Auth"
      components:
        - "LatticeScope"
        - "LatticeAuthorizationPolicyStore"
        - "LatticeAuthAdmin"
    violation_modes:
      - "An operator or app rule uses a t/{tenant}/* scope."
      - "A tenant-wide rule grants access to an app-owned or system tree."
      - "A real tree is created with a /* local name."
    detection_signals:
      - type: test
        name: "LatticeScopeTenantWideTests"
        source: "test/lattice.auth/LatticeScopeTenantWideTests.cs"
      - type: test
        name: "LatticeAuthAdminTenantTierTests.Rules"
        source: "test/lattice.api.auth/LatticeAuthAdminTenantTierTests.Rules.cs"
    remediation:
      - step: "Use LatticeScope.ClusterWide for an operator all-trees rule, and the tenant facade for a tenant-wide rule."
        source: "docs/lattice.auth/tenant-layer.md"
    sources:
      - "docs/lattice.auth/tenant-layer.md"
      - "src/lattice.auth/LatticeScope.cs"
  - id: tombstone-ttl-retention
    name: "Tombstone and TTL retention"
    description: "Expired live entries and tombstones are hidden from user reads but retained through the grace window for convergence before physical compaction."
    scope:
      packages:
        - "Orleans.Lattice"
        - "Orleans.Lattice.Replication"
      components:
        - "BPlusLeafGrain"
        - "TombstoneCompactionGrain"
        - "LeafCacheGrain"
        - "LwwValue"
    violation_modes:
      - "An expired entry is returned by GetAsync, scan, count, cursor, or cache."
      - "A TTL'd CRDT merge shortens expiry instead of using the max-absolute-ticks join."
      - "Replication drops expired entries and loses the HLC needed for convergence."
      - "Compaction reaps before TombstoneGracePeriod and a lagging replica resurrects data."
    detection_signals:
      - type: metric
        name: "orleans.lattice.leaf.tombstones.expired"
        source: "src/lattice/LatticeMetrics.cs"
      - type: metric
        name: "orleans.lattice.compaction.shard.skipped"
        source: "src/lattice/LatticeMetrics.cs"
      - type: test
        name: "TTL and tombstone compaction tests"
        source: "test/lattice/BPlusTree/TtlIntegrationTests.cs"
    remediation:
      - step: "Filter expired entries at every user-facing read path and cache hit."
        source: "docs/lattice/ttl.md"
      - step: "Preserve absolute expiry across replication, replay, snapshots, splits, resize, and merge."
        source: "docs/lattice/ttl.md"
      - step: "Tune TombstoneGracePeriod to at least expected clock drift plus replication delay."
        source: "docs/lattice/ttl.md"
    sources:
      - "docs/lattice/ttl.md"
      - "docs/lattice/tombstone-compaction.md"
      - "docs/lattice/consistency.md"
  - id: tracked-operation-terminal-state
    name: "Tracked operation terminal state is final"
    description: "A tracked operation reaches at most one terminal state; once terminal, completion writes are ignored, progress stops moving it, and later status reads return that terminal record until retention prunes it."
    scope:
      packages:
        - "Orleans.Lattice"
        - "Orleans.Lattice.Api.Abstractions"
      components:
        - "LatticeOperationGrain"
        - "LatticeOperationRunner"
        - "LatticeOperationIndexGrain"
    violation_modes:
      - "A terminal Succeeded, Failed or Cancelled operation later returns Running."
      - "A duplicate start with the same tenant and operation id starts a second runner for the same kind."
      - "A stale completion overwrites a previously recorded terminal outcome."
      - "A lost runner remains Running after the runner silo is dead or the heartbeat lease lapses."
    detection_signals:
      - type: status
        name: "LatticeOperationStatus.State"
        source: "src/lattice.api.abstractions/Operations/Model/LatticeOperationStatus.cs#LatticeOperationStatus.State"
      - type: status
        name: "LatticeOperationStatus.IsTerminal"
        source: "src/lattice.api.abstractions/Operations/Model/LatticeOperationStatus.cs#LatticeOperationStatus.IsTerminal"
      - type: source
        name: "LatticeOperationGrain.CompleteAsync"
        source: "src/lattice/Operations/LatticeOperationGrain.cs#LatticeOperationGrain.CompleteAsync"
    remediation:
      - step: "Use the same caller-chosen operation id when retrying a start after an ambiguous client-side failure."
        source: "src/lattice.api.abstractions/Operations/Model/LatticeOperationHandle.cs#LatticeOperationHandle.Created"
      - step: "Treat Failed after silo loss or heartbeat lapse as terminal and start a new operation only after inspecting the previous status."
        source: "src/lattice/Operations/LatticeOperationGrain.cs#LatticeOperationGrain.DescribeLoss"
      - step: "Keep operation-specific work idempotent under same-id reattachment and do not infer absence once retention can prune the record."
        source: "src/lattice/Operations/LatticeOperationIndexGrain.cs#LatticeOperationIndexGrain.Prune"
    sources:
      - "src/lattice/Operations/LatticeOperationGrain.cs"
      - "src/lattice/Operations/LatticeOperationRunner.cs"
      - "src/lattice.api.abstractions/Operations/Model/LatticeOperationStatus.cs"
  - id: tree-alias-ownership-bounded
    name: "Tree aliasing is bounded by ownership"
    description: "Every alias assignment, including system-origin resize, restore and remediation, is decided by the registered ITreeOwnershipGuard before the registry writes or publishes it, and a denial or guard failure leaves the alias unwritten."
    scope:
      packages:
        - "Orleans.Lattice"
        - "Orleans.Lattice.Apps"
      components:
        - "LatticeRegistryGrain"
        - "ITreeOwnershipGuard"
        - "AppTreeOwnershipGuard"
    violation_modes:
      - "An alias is written or published before the ownership guard decides."
      - "A system-origin resize, restore or remediation alias bypasses the ownership guard."
      - "A default TreeOwnershipDecision is treated as an allow."
      - "A guard failure is swallowed and the alias is written."
      - "An alias lets one install's logical tree read or write a tree another install owns."
    detection_signals:
      - type: exception
        name: "LatticeTreeOwnershipDeniedException"
        source: "src/lattice/LatticeTreeOwnershipDeniedException.cs#LatticeTreeOwnershipDeniedException"
      - type: test
        name: "LatticeRegistryGrainTests.Ownership"
        source: "test/lattice/BPlusTree/Grains/LatticeRegistryGrainTests.Ownership.cs"
      - type: test
        name: "AppTreeOwnershipGuardTests"
        source: "test/lattice.apps/Ownership/AppTreeOwnershipGuardTests.cs"
    remediation:
      - step: "Consult ITreeOwnershipGuard.AuthorizeAliasAsync with the target's registry-read DerivedFrom on every alias assignment, after namespace, target-control and lifecycle checks."
        source: "docs/lattice/tree-registry.md"
      - step: "Return an explicit TreeOwnershipDecision.Allow or Deny from a guard; never rely on the default value."
        source: "src/lattice/TreeOwnershipDecision.cs#TreeOwnershipDecision"
      - step: "Keep guard implementations to point reads; never call registry mutations or range scans from the guard."
        source: "src/lattice/ITreeOwnershipGuard.cs#ITreeOwnershipGuard.AuthorizeAliasAsync"
    sources:
      - "docs/lattice/tree-registry.md"
      - "src/lattice/ITreeOwnershipGuard.cs"
      - "docs/lattice.apps/README.md"
  - id: tree-logical-lifecycle-across-alias
    name: "Logical tree lifecycle across an alias"
    description: "Delete, recover and purge act on the logical tree: on an aliased tree they apply to the pinned live copy only when that copy was derived from the tree and no other logical tree aliases it, and alias-changing operations never overlap a logical delete."
    scope:
      packages:
        - "Orleans.Lattice"
        - "Orleans.Lattice.Api.TreeAdmin"
      components:
        - "TreeDeletionGrain"
        - "LatticeRegistryGrain"
        - "Tree resize, restore and schema remediation coordinators"
    violation_modes:
      - "A delete on an aliased tree marks only the logical id's own shards while reads and writes through the alias keep succeeding."
      - "A delete through one logical name removes an independent tree or a tree another logical tree aliases."
      - "A retry after an ambiguous failure re-resolves the alias and acts on a different target."
      - "A resize, restore or remediation changes the alias while a logical delete is pending."
      - "A resize's retirement of its old copy makes the live tree read as deleted."
    detection_signals:
      - type: test
        name: "TreeDeletionGrainTests.Aliases"
        source: "test/lattice/BPlusTree/Grains/TreeDeletionGrainTests.Aliases.cs"
      - type: test
        name: "TreeResizeAliasLifecycleIntegrationTests.Deletion"
        source: "test/lattice/BPlusTree/TreeResizeAliasLifecycleIntegrationTests.Deletion.cs"
      - type: exception
        name: "InvalidOperationException"
        source: "src/lattice/BPlusTree/ILattice.cs#ILattice.DeleteTreeAsync"
    remediation:
      - step: "Resolve the alias target, require its DerivedFrom to equal the logical tree id and no other logical tree to alias it, and pin it in durable state before any physical effect."
        source: "docs/lattice/tree-registry.md"
      - step: "Hold a durable alias-change reservation keyed by operation id for the whole of a resize, restore or remediation alias change, and refuse a delete while one is held."
        source: "docs/lattice/tree-registry.md"
      - step: "Wait for the alias-changing operation to finish, then retry the delete."
        source: "src/lattice.api.abstractions/TreeAdmin/ILatticeTreeAdmin.cs#ILatticeTreeAdmin.DeleteTreeAsync"
    sources:
      - "docs/lattice/tree-registry.md"
      - "src/lattice/BPlusTree/ILattice.cs"
      - "src/lattice.api.abstractions/TreeAdmin/ILatticeTreeAdmin.cs"
  - id: tree-resize-shadow-swap
    name: "Tree resize shadow swap"
    description: "An online resize drains into a new physical tree, shadow-forwards live writes, fences the old physical tree before the alias swap, atomically swaps the registry alias, and leaves ordinary reads and writes retrying transparently until the alias flip lands; bulk loads and appends are not retried across the rejecting window, so a call made after the swap reaches the destination but one already in flight when the alias swaps lands on the old physical tree and is removed by its purge."
    scope:
      packages:
        - "Orleans.Lattice"
      components:
        - "TreeResizeGrain"
        - "TreeSnapshotGrain"
        - "LatticeRegistryGrain"
    violation_modes:
      - "A write during drain reaches only the old tree and is not captured later."
      - "The destination is bulk-loaded after shadow-forwarded writes populated it."
      - "The alias swap leaves callers observing a stale tree-routing fault."
      - "The first resize purges the logical tree registry entry that now carries the live alias and configuration."
      - "Resize and reshard run concurrently on one tree."
    detection_signals:
      - type: status-field
        name: "TreeResizeStatus"
        source: "src/lattice.api.abstractions/TreeAdmin/Model/TreeResizeStatus.cs"
      - type: exception
        name: "StaleTreeRoutingException"
        source: "src/lattice/BPlusTree/StaleTreeRoutingException.cs"
      - type: exception
        name: "InvalidOperationException"
        source: "docs/lattice/tree-sizing.md"
    remediation:
      - step: "Drain with MergeManyAsync rather than BulkLoadRawAsync when shadow-forwarded writes may already exist."
        source: "docs/lattice/tree-sizing.md"
      - step: "Resume resize from the last completed persisted phase after a silo crash."
        source: "docs/lattice/tree-sizing.md"
      - step: "Undo a resize before the old tree leaves the soft-delete window when rollback is required."
        source: "docs/lattice/tree-sizing.md"
      - step: "When the retired physical tree id is the logical tree id, purge its shards while leaving the logical registry entry and compaction schedule in place."
        source: "src/lattice/BPlusTree/Grains/TreeResizeGrain.cs#TreeResizeGrain"
    sources:
      - "docs/lattice/tree-sizing.md"
      - "docs/lattice/consistency.md"
      - "docs/lattice/ttl.md"
  - id: treeadmin-operation-cancel-before-flip
    name: "Tree-admin WAL-move cancel before flip"
    description: "Cancelling a tracked WAL move before its placement flip leaves the partition on its source provider and unfenced; a tracked tree-admin operation is never resumed after accepting-silo loss."
    scope:
      packages:
        - "Orleans.Lattice.Api.TreeAdmin"
        - "Orleans.Lattice"
      components:
        - "ILatticeTreeAdminOperations"
        - "LatticeOperationStatus"
        - "LatticeOperationRunner"
    violation_modes:
      - "A cancelled WAL move flips the partition placement after cancellation was observed."
      - "A cancelled or failed WAL move leaves the source partition fenced against writes."
      - "A tree-admin operation remains Running after the accepting silo is declared dead."
    detection_signals:
      - type: status
        name: "LatticeOperationStatus.State"
        source: "src/lattice.api.abstractions/Operations/Model/LatticeOperationStatus.cs"
      - type: status
        name: "LatticeOperationStatus.Phase"
        source: "src/lattice.api.abstractions/Operations/Model/LatticeOperationStatus.cs"
    remediation:
      - step: "Inspect the WAL placement after a Cancelled or Failed move and start a new move if it is still needed."
        source: "docs/lattice.api.treeadmin/operations.md"
      - step: "Treat Failed after silo loss as terminal and start a new tracked operation."
        source: "docs/lattice.api.abstractions/operations.md"
    sources:
      - "docs/lattice.api.treeadmin/operations.md"
      - "docs/lattice.api.abstractions/operations.md"
  - id: wal-append-durability-boundary
    name: "WAL append durability boundary"
    description: "A foreground write mutates the in-memory projection only after its WAL partition append succeeds, making the WAL the commit linearization point."
    scope:
      packages:
        - "Orleans.Lattice"
      components:
        - "WalShardGrain"
        - "WalCommitLogWriter"
        - "BPlusLeafGrain"
    violation_modes:
      - "The leaf projection changes after a failed WAL append."
      - "A successful SetAsync lacks a durable WAL record for replay."
      - "Append-failure latch permits later successes to mask an earlier failed window."
    detection_signals:
      - type: metric
        name: "orleans.lattice.leaf.commit.duration"
        source: "src/lattice/LatticeMetrics.cs"
      - type: metric
        name: "orleans.lattice.wal.append_dispatch.timeouts"
        source: "src/lattice/LatticeMetrics.cs"
      - type: exception
        name: "storage exception from WAL append"
        source: "docs/lattice/wal.md"
    remediation:
      - step: "Fault every caller in the failed and later in-flight windows."
        source: "docs/lattice/wal.md"
      - step: "Run ReconcileAsync and reread the provider tail before clearing the sticky failure."
        source: "docs/lattice/wal.md"
      - step: "Request WAL shard deactivation when resync fails so activation-time reconcile reruns."
        source: "docs/lattice/wal.md"
    sources:
      - "docs/lattice/wal.md"
      - "samples/VerifiedWalDurability/README.md"
  - id: wal-gc-consumer-frontier
    name: "WAL GC consumer frontier"
    description: "WAL GC trims only entries admitted by every applicable consumer cursor, causal-stable frontier, durable materializer floor, and blocked-floor pin except when hard wall-clock retention is configured."
    scope:
      packages:
        - "Orleans.Lattice"
        - "Orleans.Lattice.Replication"
      components:
        - "WalGcTrimCore"
        - "IWalCursorRegistry"
        - "ILatticeWalGc"
    violation_modes:
      - "GC trims by the maximum consumer cursor and strands a lagging consumer."
      - "A live buffer pin is ignored and entries still needed by that buffer are removed."
      - "An advisory byte ceiling trims past the safe consumer frontier."
      - "A consumer never registers and later reads a gap without detecting it."
    detection_signals:
      - type: test
        name: "WalGcTrimFloorCoyoteTests"
        source: "test/lattice/BPlusTree/Coyote/WalGcTrimFloorCoyoteTests.cs"
      - type: metric
        name: "orleans.lattice.wal.gc.trim_stop"
        source: "src/lattice/LatticeMetrics.cs"
      - type: metric
        name: "orleans.lattice.wal.gc.passes"
        source: "src/lattice/LatticeMetrics.cs"
      - type: metric
        name: "orleans.lattice.wal.gc.orphan_pin_sweep"
        source: "src/lattice/LatticeMetrics.cs"
      - type: metric
        name: "orleans.lattice.wal.gc.drive_orphan_pin_retirement"
        source: "src/lattice/LatticeMetrics.cs"
      - type: metric
        name: "orleans.lattice.wal.gc.floor_holder_admission"
        source: "src/lattice/LatticeMetrics.cs"
    remediation:
      - step: "Report each consumer cursor monotonically after successfully applying a batch."
        source: "docs/lattice/wal.md"
      - step: "Trim only within the minimum registered consumer frontier and below blocked-floor pins."
        source: "docs/lattice/wal.md"
      - step: "Use bootstrap or projection rebuild when a consumer falls off the retained log."
        source: "docs/lattice.replication/snapshot-bootstrap.md"
      - step: "Use the WAL reclamation read to identify a stranded floor holder before intervening; refuse to retire a durable pin whose consumer id is malformed or ambiguous rather than treating it as safe to remove."
        source: "src/lattice.api.abstractions/TreeAdmin/ILatticeWalReclamation.cs#GetWalReclamationAsync"
    sources:
      - "docs/lattice/wal.md"
      - "docs/lattice/verified-wal.md"
      - "test/lattice/BPlusTree/Coyote/WalGcTrimFloorCoyoteTests.cs"
  - id: wal-offset-contiguity
    name: "WAL offset contiguity"
    description: "Each WAL shard assigns dense, strictly ascending offsets and never hands two concurrent appends the same sequence number."
    scope:
      packages:
        - "Orleans.Lattice"
      components:
        - "WalOffsetAllocationCore"
        - "WalShardGrain"
    violation_modes:
      - "Two concurrent appends receive the same offset."
      - "An offset gap is exposed as durable after a failed flush window."
      - "A shard move admits an append after the move fence is raised."
    detection_signals:
      - type: test
        name: "WalOffsetContiguityCoyoteTests"
        source: "test/lattice/BPlusTree/Coyote/WalOffsetContiguityCoyoteTests.cs"
      - type: test
        name: "WalMoveQuiesceCoyoteTests"
        source: "test/lattice/BPlusTree/Coyote/WalMoveQuiesceCoyoteTests.cs"
      - type: metric
        name: "orleans.lattice.wal.shard.start_flush.calls"
        source: "src/lattice/LatticeMetrics.cs"
    remediation:
      - step: "Keep read-and-advance of the offset counter atomic."
        source: "docs/lattice/verified-wal.md"
      - step: "Pair the move fence check atomically with offset assignment."
        source: "docs/lattice/verified-wal.md"
      - step: "Resync from the provider tail after a flush failure before accepting new appends."
        source: "docs/lattice/wal.md"
    sources:
      - "docs/lattice/verified-wal.md"
      - "docs/lattice/wal.md"
  - id: wal-replay-reconstructability
    name: "WAL replay reconstructability"
    description: "A leaf activation reconstructs its visible projection from the latest durable snapshot plus retained WAL records and refuses activation when the required prefix is gone."
    scope:
      packages:
        - "Orleans.Lattice"
      components:
        - "BPlusLeafGrain"
        - "LeafReplayCoordinatorGrain"
        - "LeafSnapshotStorageGrain"
        - "WalShardGrain"
    violation_modes:
      - "Leaf grain state is treated as a fallback copy of committed values."
      - "Replay applies records outside the leaf's current ownership filter."
      - "A leaf replays only a surviving suffix after falling off the log."
      - "A failed projection-checkpoint persist is advertised as a durable WAL trim floor."
    detection_signals:
      - type: exception
        name: "LeafProjectionStaleException"
        source: "src/lattice/LeafProjectionStaleException.cs"
      - type: metric
        name: "orleans.lattice.leaf.activation_replays_over_budget"
        source: "src/lattice/LatticeMetrics.cs"
      - type: metric
        name: "orleans.lattice.leaf.commit.duration"
        source: "src/lattice/LatticeMetrics.cs"
    remediation:
      - step: "Replay retained WAL tail records from the persisted projection checkpoint."
        source: "docs/lattice/wal.md"
      - step: "Rollback checkpoint fields and restore pending advances when checkpoint PersistAsync throws so the failed advance retries rather than publishing a false durable pin."
        source: "src/lattice/BPlusTree/Grains/BPlusLeafGrain.Projection.cs#BPlusLeafGrain.RollbackCheckpointCommit"
      - step: "Use the WAL key filter and the leaf apply check together during replay."
        source: "docs/lattice/wal.md"
      - step: "Refuse activation with LeafProjectionStaleException when no snapshot covers a trimmed WAL gap."
        source: "docs/lattice/wal.md"
    sources:
      - "docs/lattice/wal.md"
      - "docs/lattice/state-model.md"
      - "docs/lattice/projection-rebuild.md"
  - id: wal-shipping-prefix-hole
    name: "WAL shipping prefix-hole guard"
    description: "A cursor-advancing reader sees only WAL offsets below the durable contiguous tail so an out-of-order flush cannot ship past a prefix hole."
    scope:
      packages:
        - "Orleans.Lattice"
        - "Orleans.Lattice.Replication"
      components:
        - "WalShippingWatermark"
        - "WalShardGrain"
        - "Replication shipper"
        - "View maintainer"
    violation_modes:
      - "A reader advances its cursor past a lower offset whose flush is still in flight."
      - "Out-of-order flush completion exposes a higher window before the lower prefix is durable."
      - "A placement move resumes with duplicate or missing retained offsets."
    detection_signals:
      - type: test
        name: "WalShippingWatermarkCoyoteTests"
        source: "test/lattice/BPlusTree/Coyote/WalShippingWatermarkCoyoteTests.cs"
      - type: test
        name: "WalMoveRedriveCoyoteTests"
        source: "test/lattice/BPlusTree/Coyote/WalMoveRedriveCoyoteTests.cs"
      - type: metric
        name: "orleans.lattice.replication.wal.entries_shipped"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
    remediation:
      - step: "Clamp cursor-advancing readers below the oldest in-flight flush start."
        source: "docs/lattice/verified-wal.md"
      - step: "Resume a redriven WAL move just past the clean prefix already present at the target."
        source: "docs/lattice/verified-wal.md"
      - step: "Use bootstrap when a peer has fallen below the oldest retained log entry."
        source: "docs/lattice.replication/snapshot-bootstrap.md"
    sources:
      - "docs/lattice/verified-wal.md"
      - "docs/lattice/wal.md"
      - "docs/lattice.replication/observability.md"
  - id: wal-trim-watermark-exactness
    name: "WAL trim watermark exactness"
    description: "A WAL storage provider infers its trim watermark only from committed state, so a watermark never covers a batch that is accepted but not yet committed; a reader that sees an offset jump the watermark says was not trimmed re-derives the watermark from storage and re-reads before reading past the range as a hole."
    scope:
      packages:
        - "Orleans.Lattice"
        - "Orleans.Lattice.Storage.AzureTable"
        - "Orleans.Lattice.Replication"
      components:
        - "IWalStorageProvider"
        - "WalShardGrain"
        - "WAL subscriber"
        - "Replication shipper"
    violation_modes:
      - "A provider infers an empty shard's watermark from its highest offset, which counts batches still committing, and caches that batch as trimmed."
      - "A cached watermark above the stored trim point hides committed entries from every read on that silo."
      - "A reader consumes a hidden committed range as a hole, so views miss writes and peers never receive them."
      - "Leaf replay clamps away hidden entries and loses acknowledged writes its snapshot did not hold; leaf replay has no refresh backstop and relies on the watermark being exact."
    detection_signals:
      - type: metric
        name: "orleans.lattice.wal.subscriber.holes_skipped"
        source: "src/lattice/LatticeMetrics.cs"
      - type: metric
        name: "orleans.lattice.wal.subscriber.empty_backlog_reads"
        source: "src/lattice/LatticeMetrics.cs"
      - type: metric
        name: "orleans.lattice.replication.ship.holes_skipped"
        source: "src/lattice.replication/LatticeReplicationMetrics.cs"
      - type: test
        name: "AzureTableWalStorageProviderTrimWatermarkInFlightIntegrationTests"
        source: "test/lattice.storage.azuretable/AzureTableWalStorageProviderTrimWatermarkInFlightIntegrationTests.cs"
      - type: test
        name: "WalLogSubscriberTests"
        source: "test/lattice/Wal/WalLogSubscriberTests.Holes.cs"
    remediation:
      - step: "Infer a watermark only from the committed tail, never from the highest assigned offset."
        source: "docs/lattice/wal.md"
      - step: "On a jump the watermark says was not trimmed, call IWalStorageProvider.RefreshTrimWatermarkAsync through the WAL partition and re-read once; read past only what is still missing."
        source: "docs/lattice/wal.md"
      - step: "After upgrading an Azure Table WAL from 10.0.0-10.2.0, reconcile or rebuild views, re-seed peers, and compare projection digests to find shards that lost writes."
        source: "docs/lattice.storage.azuretable/architecture.md"
    sources:
      - "docs/lattice/wal.md"
      - "docs/lattice/wal-storage-providers.md"
      - "docs/lattice.storage.azuretable/architecture.md"
      - "docs/lattice.replication/observability.md"
